{"input": "Create an instance of Axios [CODESPLIT] function createInstance ( defaultConfig ) { var context = new Axios ( defaultConfig ) ; var instance = bind ( Axios . prototype . request , context ) ; // Copy axios.prototype to instance utils . extend ( instance , Axios . prototype , context ) ; // Copy context to instance utils . extend ( instance , context ) ; return instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A CancelToken is an object that can be used to request cancellation of an operation . [CODESPLIT] function CancelToken ( executor ) { if ( typeof executor !== 'function' ) { throw new TypeError ( 'executor must be a function.' ) ; } var resolvePromise ; this . promise = new Promise ( function promiseExecutor ( resolve ) { resolvePromise = resolve ; } ) ; var token = this ; executor ( function cancel ( message ) { if ( token . reason ) { // Cancellation has already been requested return ; } token . reason = new Cancel ( message ) ; resolvePromise ( token . reason ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if a value is a view on an ArrayBuffer [CODESPLIT] function isArrayBufferView ( val ) { var result ; if ( ( typeof ArrayBuffer !== 'undefined' ) && ( ArrayBuffer . isView ) ) { result = ArrayBuffer . isView ( val ) ; } else { result = ( val ) && ( val . buffer ) && ( val . buffer instanceof ArrayBuffer ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if we re running in a standard browser environment [CODESPLIT] function isStandardBrowserEnv ( ) { if ( typeof navigator !== 'undefined' && ( navigator . product === 'ReactNative' || navigator . product === 'NativeScript' || navigator . product === 'NS' ) ) { return false ; } return ( typeof window !== 'undefined' && typeof document !== 'undefined' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate over an Array or an Object invoking a function for each item . [CODESPLIT] function forEach ( obj , fn ) { // Don't bother if no value provided if ( obj === null || typeof obj === 'undefined' ) { return ; } // Force an array if not already something iterable if ( typeof obj !== 'object' ) { /*eslint no-param-reassign:0*/ obj = [ obj ] ; } if ( isArray ( obj ) ) { // Iterate over array values for ( var i = 0 , l = obj . length ; i < l ; i ++ ) { fn . call ( null , obj [ i ] , i , obj ) ; } } else { // Iterate over object keys for ( var key in obj ) { if ( Object . prototype . hasOwnProperty . call ( obj , key ) ) { fn . call ( null , obj [ key ] , key , obj ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extends object a by mutably adding to it the properties of object b . [CODESPLIT] function extend ( a , b , thisArg ) { forEach ( b , function assignValue ( val , key ) { if ( thisArg && typeof val === 'function' ) { a [ key ] = bind ( val , thisArg ) ; } else { a [ key ] = val ; } } ) ; return a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define a function that fetches the results of an operation ( query / mutation / etc ) and returns its results as a Promise : [CODESPLIT] function fetchQuery ( operation , variables , cacheConfig , uploadables ) { // Because we implement the graphql server, the client must to point to the same host const relayServer = process . browser ? '' : process . env . RELAY_SERVER return fetch ( ` ${ relayServer } ` , { method : 'POST' , headers : { Accept : 'application/json' , 'Content-Type' : 'application/json' } , // Add authentication and other headers here body : JSON . stringify ( { query : operation . text , // GraphQL text from input variables } ) } ) . then ( response => response . json ( ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "konstructor : The redis client constructor method . All redis methods must be promises args : The arguments to pass to the constructor buildNew : is it new konstructor () or just konstructor () ? [CODESPLIT] function retryStrategy ( times ) { if ( times === 1 ) { const error = 'Unable to connect to Redis - please check your Redis config!' if ( process . env . NODE_ENV === 'test' ) { console . error ( error ) } else { api . log ( error , 'error' ) } return 5000 } return Math . min ( times * 50 , maxBackoff ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function writes a minimal package . json file for a compiled package . It defines name main author and license . It also defines types . n . b . types intended for development usage only . [CODESPLIT] function writePackageManifest ( packageName ) { const packagePath = require . resolve ( packageName + '/package.json' ) let { name , main , author , license , types , typings } = require ( packagePath ) if ( ! main ) { main = 'index.js' } let typesFile = types || typings if ( typesFile ) { typesFile = require . resolve ( join ( packageName , typesFile ) ) } const compiledPackagePath = join ( __dirname , ` ${ packageName } ` ) const potentialLicensePath = join ( dirname ( packagePath ) , './LICENSE' ) if ( existsSync ( potentialLicensePath ) ) { this . _ . files . push ( { dir : compiledPackagePath , base : 'LICENSE' , data : readFileSync ( potentialLicensePath , 'utf8' ) } ) } this . _ . files . push ( { dir : compiledPackagePath , base : 'package.json' , data : JSON . stringify ( Object . assign ( { } , { name , main : ` ${ basename ( main , '.' + extname ( main ) ) } ` } , author ? { author } : undefined , license ? { license } : undefined , typesFile ? { types : relative ( compiledPackagePath , typesFile ) } : undefined ) ) + '\\n' } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "smaller version of https : // gist . github . com / igrigorik / a02f2359f3bc50ca7a9c [CODESPLIT] function supportsPreload ( list ) { if ( ! list || ! list . supports ) { return false } try { return list . supports ( 'preload' ) } catch ( e ) { return false } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Based on https : // github . com / webpack / webpack / blob / master / lib / DynamicEntryPlugin . js#L29 - L37 [CODESPLIT] function addEntry ( compilation , context , name , entry ) { return new Promise ( ( resolve , reject ) => { const dep = DynamicEntryPlugin . createDependency ( entry , name ) compilation . addEntry ( context , dep , name , ( err ) => { if ( err ) return reject ( err ) resolve ( ) } ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compilation with warnings ( e . g . ESLint ) . [CODESPLIT] function handleWarnings ( warnings ) { clearOutdatedErrors ( ) // Print warnings to the console. const formatted = formatWebpackMessages ( { warnings : warnings , errors : [ ] } ) if ( typeof console !== 'undefined' && typeof console . warn === 'function' ) { for ( let i = 0 ; i < formatted . warnings . length ; i ++ ) { if ( i === 5 ) { console . warn ( 'There were more warnings in other files.\\n' + 'You can find a complete log in the terminal.' ) break } console . warn ( stripAnsi ( formatted . warnings [ i ] ) ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compilation with errors ( e . g . syntax error or missing modules ) . [CODESPLIT] function handleErrors ( errors ) { clearOutdatedErrors ( ) isFirstCompilation = false hasCompileErrors = true // \"Massage\" webpack messages. var formatted = formatWebpackMessages ( { errors : errors , warnings : [ ] } ) // Only show the first error. ErrorOverlay . reportBuildError ( formatted . errors [ 0 ] ) // Also log them to the console. if ( typeof console !== 'undefined' && typeof console . error === 'function' ) { for ( var i = 0 ; i < formatted . errors . length ; i ++ ) { console . error ( stripAnsi ( formatted . errors [ i ] ) ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle messages from the server . [CODESPLIT] function processMessage ( e ) { const obj = JSON . parse ( e . data ) switch ( obj . action ) { case 'building' : { console . log ( '[HMR] bundle ' + ( obj . name ? \"'\" + obj . name + \"' \" : '' ) + 'rebuilding' ) break } case 'built' : case 'sync' : { clearOutdatedErrors ( ) if ( obj . hash ) { handleAvailableHash ( obj . hash ) } if ( obj . warnings . length > 0 ) { handleWarnings ( obj . warnings ) } if ( obj . errors . length > 0 ) { // When there is a compilation error coming from SSR we have to reload the page on next successful compile if ( obj . action === 'sync' ) { hadRuntimeError = true } handleErrors ( obj . errors ) break } handleSuccess ( ) break } default : { if ( customHmrEventHandler ) { customHmrEventHandler ( obj ) break } break } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to update code on the fly fall back to a hard reload . [CODESPLIT] async function tryApplyUpdates ( onHotUpdateSuccess ) { if ( ! module . hot ) { // HotModuleReplacementPlugin is not in Webpack configuration. console . error ( 'HotModuleReplacementPlugin is not in Webpack configuration.' ) // window.location.reload(); return } if ( ! isUpdateAvailable ( ) || ! canApplyUpdates ( ) ) { return } function handleApplyUpdates ( err , updatedModules ) { if ( err || hadRuntimeError ) { if ( err ) { console . warn ( 'Error while applying updates, reloading page' , err ) } if ( hadRuntimeError ) { console . warn ( 'Had runtime error previously, reloading page' ) } window . location . reload ( ) return } if ( typeof onHotUpdateSuccess === 'function' ) { // Maybe we want to do something. onHotUpdateSuccess ( ) } if ( isUpdateAvailable ( ) ) { // While we were updating, there was a new update! Do it again. tryApplyUpdates ( ) } } // https://webpack.github.io/docs/hot-module-replacement.html#check try { const updatedModules = await module . hot . check ( /* autoApply */ { ignoreUnaccepted : true } ) if ( updatedModules ) { handleApplyUpdates ( null , updatedModules ) } } catch ( err ) { handleApplyUpdates ( err , null ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function reads code updates on the fly and hard reloads the page when it has changed . [CODESPLIT] async function tryApplyUpdates ( ) { if ( ! isUpdateAvailable ( ) || ! canApplyUpdates ( ) ) { return } try { const res = await fetch ( ` ${ hotUpdatePath } ${ curHash } ` ) const data = await res . json ( ) const curPage = page === '/' ? 'index' : page const pageUpdated = Object . keys ( data . c ) . some ( mod => { return ( mod . indexOf ( ` ${ curPage . substr ( 0 , 1 ) === '/' ? curPage : ` ${ curPage } ` } ` ) !== - 1 || mod . indexOf ( ` ${ curPage . substr ( 0 , 1 ) === '/' ? curPage : ` ${ curPage } ` } ` . replace ( / \\/ / g , '\\\\' ) ) !== - 1 ) } ) if ( pageUpdated ) { document . location . reload ( true ) } else { curHash = mostRecentHash } } catch ( err ) { console . error ( 'Error occurred checking for update' , err ) document . location . reload ( true ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleans up webpack error messages . eslint - disable - next - line no - unused - vars [CODESPLIT] function formatMessage ( message , isError ) { let lines = message . split ( '\\n' ) // Strip Webpack-added headers off errors/warnings // https://github.com/webpack/webpack/blob/master/lib/ModuleError.js lines = lines . filter ( line => ! / Module [A-z ]+\\(from / . test ( line ) ) // Transform parsing error into syntax error // TODO: move this to our ESLint formatter? lines = lines . map ( line => { const parsingError = / Line (\\d+):(?:(\\d+):)?\\s*Parsing error: (.+)$ / . exec ( line ) if ( ! parsingError ) { return line } const [ , errorLine , errorColumn , errorMessage ] = parsingError return ` ${ friendlySyntaxErrorLabel } ${ errorMessage } ${ errorLine } ${ errorColumn } ` } ) message = lines . join ( '\\n' ) // Smoosh syntax errors (commonly found in CSS) message = message . replace ( / SyntaxError\\s+\\((\\d+):(\\d+)\\)\\s*(.+?)\\n / g , ` ${ friendlySyntaxErrorLabel } \\n ` ) // Remove columns from ESLint formatter output (we added these for more // accurate syntax errors) message = message . replace ( / Line (\\d+):\\d+: / g , 'Line $1:' ) // Clean up export errors message = message . replace ( / ^.*export '(.+?)' was not found in '(.+?)'.*$ / gm , ` ` ) message = message . replace ( / ^.*export 'default' \\(imported as '(.+?)'\\) was not found in '(.+?)'.*$ / gm , ` ` ) message = message . replace ( / ^.*export '(.+?)' \\(imported as '(.+?)'\\) was not found in '(.+?)'.*$ / gm , ` ` ) lines = message . split ( '\\n' ) // Remove leading newline if ( lines . length > 2 && lines [ 1 ] . trim ( ) === '' ) { lines . splice ( 1 , 1 ) } // Clean up file name lines [ 0 ] = lines [ 0 ] . replace ( / ^(.*) \\d+:\\d+-\\d+$ / , '$1' ) // Cleans up verbose \"module not found\" messages for files and packages. if ( lines [ 1 ] && lines [ 1 ] . indexOf ( 'Module not found: ' ) === 0 ) { lines = [ lines [ 0 ] , lines [ 1 ] . replace ( 'Error: ' , '' ) . replace ( 'Module not found: Cannot find file:' , 'Cannot find file:' ) ] } message = lines . join ( '\\n' ) // Internal stacks are generally useless so we strip them... with the // exception of stacks containing `webpack:` because they're normally // from user code generated by Webpack. For more information see // https://github.com/facebook/create-react-app/pull/1050 message = message . replace ( / ^\\s*at\\s((?!webpack:).)*:\\d+:\\d+[\\s)]*(\\n|$) / gm , '' ) // at ... ...:x:y message = message . replace ( / ^\\s*at\\s<anonymous>(\\n|$) / gm , '' ) // at <anonymous> lines = message . split ( '\\n' ) // Remove duplicated newlines lines = lines . filter ( ( line , index , arr ) => index === 0 || line . trim ( ) !== '' || line . trim ( ) !== arr [ index - 1 ] . trim ( ) ) // Reassemble the message message = lines . join ( '\\n' ) return message . trim ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * eslint no - unused - vars : off [CODESPLIT] function slideNext ( speed = this . params . speed , runCallbacks = true , internal ) { const swiper = this ; const { params , animating } = swiper ; if ( params . loop ) { if ( animating ) return false ; swiper . loopFix ( ) ; // eslint-disable-next-line swiper . _clientLeft = swiper . $wrapperEl [ 0 ] . clientLeft ; return swiper . slideTo ( swiper . activeIndex + params . slidesPerGroup , speed , runCallbacks , internal ) ; } return swiper . slideTo ( swiper . activeIndex + params . slidesPerGroup , speed , runCallbacks , internal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * eslint no - unused - vars : off [CODESPLIT] function slidePrev ( speed = this . params . speed , runCallbacks = true , internal ) { const swiper = this ; const { params , animating , snapGrid , slidesGrid , rtlTranslate , } = swiper ; if ( params . loop ) { if ( animating ) return false ; swiper . loopFix ( ) ; // eslint-disable-next-line swiper . _clientLeft = swiper . $wrapperEl [ 0 ] . clientLeft ; } const translate = rtlTranslate ? swiper . translate : - swiper . translate ; function normalize ( val ) { if ( val < 0 ) return - Math . floor ( Math . abs ( val ) ) ; return Math . floor ( val ) ; } const normalizedTranslate = normalize ( translate ) ; const normalizedSnapGrid = snapGrid . map ( val => normalize ( val ) ) ; const normalizedSlidesGrid = slidesGrid . map ( val => normalize ( val ) ) ; const currentSnap = snapGrid [ normalizedSnapGrid . indexOf ( normalizedTranslate ) ] ; const prevSnap = snapGrid [ normalizedSnapGrid . indexOf ( normalizedTranslate ) - 1 ] ; let prevIndex ; if ( typeof prevSnap !== 'undefined' ) { prevIndex = slidesGrid . indexOf ( prevSnap ) ; if ( prevIndex < 0 ) prevIndex = swiper . activeIndex - 1 ; } return swiper . slideTo ( prevIndex , speed , runCallbacks , internal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Original Name encode and decode logic is in github . com / eosio / eos native . hpp Encode a name ( a base32 string ) to a number . [CODESPLIT] function encodeName ( name ) { var littleEndian = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : true ; if ( typeof name !== \"string\" ) throw new TypeError ( \"name parameter is a required string\" ) ; if ( name . length > 13 ) throw new TypeError ( \"A name can be up to 13 characters long\" ) ; var bitstr = \"\" ; for ( var i = 0 ; i <= 12 ; i ++ ) { // process all 64 bits (even if name is short) var c = i < name . length ? charidx ( name [ i ] ) : 0 ; var bitlen = i < 12 ? 5 : 4 ; var bits = Number ( c ) . toString ( 2 ) ; if ( bits . length > bitlen ) { throw new TypeError ( \"Invalid name \" + name ) ; } bits = \"0\" . repeat ( bitlen - bits . length ) + bits ; bitstr += bits ; } var value = Long . fromString ( bitstr , true , 2 ) ; // convert to LITTLE_ENDIAN var leHex = \"\" ; var bytes = littleEndian ? value . toBytesLE ( ) : value . toBytesBE ( ) ; var _iteratorNormalCompletion = true ; var _didIteratorError = false ; var _iteratorError = undefined ; try { for ( var _iterator = ( 0 , _getIterator3 . default ) ( bytes ) , _step ; ! ( _iteratorNormalCompletion = ( _step = _iterator . next ( ) ) . done ) ; _iteratorNormalCompletion = true ) { var b = _step . value ; var n = Number ( b ) . toString ( 16 ) ; leHex += ( n . length === 1 ? \"0\" : \"\" ) + n ; } } catch ( err ) { _didIteratorError = true ; _iteratorError = err ; } finally { try { if ( ! _iteratorNormalCompletion && _iterator . return ) { _iterator . return ( ) ; } } finally { if ( _didIteratorError ) { throw _iteratorError ; } } } var ulName = Long . fromString ( leHex , true , 16 ) . toString ( ) ; // console.log('encodeName', name, value.toString(), ulName.toString(), JSON.stringify(bitstr.split(/(.....)/).slice(1))) return ulName . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize and validate decimal string ( potentially large values ) . Should avoid internationalization issues if possible but will be safe and throw an error for an invalid number . [CODESPLIT] function UDecimalString ( value ) { assert ( value != null , \"value is required\" ) ; value = value === \"object\" && value . toString ? value . toString ( ) : String ( value ) ; if ( value [ 0 ] === \".\" ) { value = '0' + value ; } var part = value . split ( \".\" ) ; assert ( part . length <= 2 , 'invalid decimal ' + value ) ; assert ( / ^\\d+(,?\\d)*\\d*$ / . test ( part [ 0 ] ) , 'invalid decimal ' + value ) ; if ( part . length === 2 ) { assert ( / ^\\d*$ / . test ( part [ 1 ] ) , 'invalid decimal ' + value ) ; part [ 1 ] = part [ 1 ] . replace ( / 0+$ / , \"\" ) ; // remove suffixing zeros if ( part [ 1 ] === \"\" ) { part . pop ( ) ; } } part [ 0 ] = part [ 0 ] . replace ( / ^0* / , \"\" ) ; // remove leading zeros if ( part [ 0 ] === \"\" ) { part [ 0 ] = \"0\" ; } return part . join ( \".\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure a fixed number of decimal places . Safe for large numbers . [CODESPLIT] function UDecimalPad ( num , precision ) { var value = UDecimalString ( num ) ; assert . equal ( \"number\" , typeof precision === 'undefined' ? 'undefined' : ( 0 , _typeof3 . default ) ( precision ) , \"precision\" ) ; var part = value . split ( \".\" ) ; if ( precision === 0 && part . length === 1 ) { return part [ 0 ] ; } if ( part . length === 1 ) { return part [ 0 ] + '.' + \"0\" . repeat ( precision ) ; } else { var pad = precision - part [ 1 ] . length ; assert ( pad >= 0 , 'decimal \\'' + value + '\\' exceeds precision ' + precision ) ; return part [ 0 ] + '.' + part [ 1 ] + \"0\" . repeat ( pad ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put the decimal place back in its position and return the normalized number string ( with any unnecessary zeros or an unnecessary decimal removed ) . [CODESPLIT] function UDecimalUnimply ( value , precision ) { assert ( value != null , \"value is required\" ) ; value = value === \"object\" && value . toString ? value . toString ( ) : String ( value ) ; assert ( / ^\\d+$ / . test ( value ) , 'invalid whole number ' + value ) ; // Ensure minimum length var pad = precision - value . length ; if ( pad > 0 ) { value = '' + \"0\" . repeat ( pad ) + value ; } var dotIdx = value . length - precision ; value = value . slice ( 0 , dotIdx ) + '.' + value . slice ( dotIdx ) ; return UDecimalString ( value ) ; // Normalize }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@arg { string } assetSymbol - 4 SYM @arg { number } [ precision = null ] - expected precision or mismatch AssertionError [CODESPLIT] function parseAssetSymbol ( assetSymbol ) { var precision = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : null ; assert . equal ( typeof assetSymbol === 'undefined' ? 'undefined' : ( 0 , _typeof3 . default ) ( assetSymbol ) , \"string\" , \"Asset symbol should be string\" ) ; if ( assetSymbol . indexOf ( \",\" ) === - 1 ) { assetSymbol = ',' + assetSymbol ; // null precision } var v = assetSymbol . split ( \",\" ) ; assert ( v . length === 2 , 'Asset symbol \"' + assetSymbol + '\" may have a precision like this: 4,SYM' ) ; var symbolPrecision = v [ 0 ] == \"\" ? null : parseInt ( v [ 0 ] ) ; var symbol = v [ 1 ] ; if ( precision != null ) { assert . equal ( precision , symbolPrecision , \"Asset symbol precision mismatch\" ) ; } else { precision = symbolPrecision ; } if ( precision != null ) { assert . equal ( typeof precision === 'undefined' ? 'undefined' : ( 0 , _typeof3 . default ) ( precision ) , \"number\" , \"precision\" ) ; assert ( precision > - 1 , \"precision must be positive\" ) ; } if ( ! / ^[0-9]+$ / . test ( symbol ) ) { if ( / ^S#[0-9]+$ / . test ( symbol ) ) { symbol = symbol . replace ( \"S#\" , \"\" ) ; } else { throw new Error ( 'Asset symbol should looks like \\'S#{num}\\', but got ' + symbol + '.' ) ; } } assert ( precision <= 18 , \"Precision should be 18 characters or less\" ) ; assert ( symbol . length <= 7 , \"Asset symbol is 7 characters or less\" ) ; return { precision : precision , symbol : symbol } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Encode EVT Address in address . cpp [CODESPLIT] function encodeAddress ( str ) { /* Check avalibility of evt_address */ if ( typeof str !== \"string\" || str . length !== 53 || ! str . startsWith ( \"EVT\" ) ) throw new Error ( \"EVTAddress should be a string with length 53 starts with EVT.\" ) ; str = str . substr ( 3 ) ; if ( str === \"0\" . repeat ( 50 ) ) return Buffer . from ( [ 0 , 0 ] ) ; // 0000 else if ( str [ 0 ] === \"0\" ) return encodeGeneratedAddressToBin ( \"EVT\" + str ) ; // generated address var buf = Buffer . concat ( [ Buffer . from ( [ 1 , 0 ] ) , new Buffer ( base58 . decode ( str ) ) ] ) ; // normal //console.log(buf) return buf . slice ( 0 , buf . length - 4 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Decode EVT Address in address . cpp [CODESPLIT] function decodeAddress ( bytes ) { if ( bytes . length === 2 && bytes . equals ( Buffer . from ( [ 0 , 0 ] ) ) ) return \"EVT\" + \"0\" . repeat ( 50 ) ; // 0000 else if ( bytes . slice ( 0 , 2 ) . equals ( Buffer . from ( [ 2 , 0 ] ) ) ) return decodeGeneratedAddressFromBin ( bytes ) ; // generated address return \"EVT\" + KeyUtils . checkEncode ( bytes . slice ( 2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a buffer representing a segment . Different typeKey has different data type this is the detail : 0 - 20 1 - byte unsigned integer 21 - 40 2 - byte unsigned integer ( BE ) 41 - 90 4 - byte unsigned integer ( BE ) 91 - 155 string 156 - 165 uuid 166 - 180 byte string > 180 remained [CODESPLIT] function createSegment ( typeKey , value ) { // 1-byte unsigned integer if ( typeKey <= 20 ) { return ( new Buffer ( [ typeKey , value ] ) ) ; } // 2-byte unsigned integer if ( typeKey <= 40 ) { let content = new Buffer ( 3 ) ; content . writeUInt8 ( typeKey , 0 ) ; content . writeUInt16BE ( value , 1 ) ; return ( content ) ; } // 4-byte unsigned integer else if ( typeKey <= 90 ) { let content = new Buffer ( 5 ) ; content . writeUInt8 ( typeKey , 0 ) ; content . writeUInt32BE ( value , 1 ) ; return ( content ) ; } // string else if ( typeKey <= 155 ) { let content = Buffer . from ( value ) ; let header = new Buffer ( [ typeKey , content . length ] ) ; return ( Buffer . concat ( [ header , content ] ) ) ; } // uuid else if ( typeKey <= 165 ) { return ( Buffer . concat ( [ new Buffer ( [ typeKey ] ) , value ] ) ) ; } // byte string else if ( typeKey <= 180 ) { let content = value ; let header = new Buffer ( [ typeKey , content . length ] ) ; return ( Buffer . concat ( [ header , content ] ) ) ; } else { throw new Error ( \"typeKey not supported\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a segment and convert it into json . [CODESPLIT] function parseSegment ( buffer , offset ) { let typeKey = buffer [ offset ] ; if ( typeKey <= 20 ) { if ( buffer [ offset + 1 ] == undefined ) throw new Error ( \"ParseError: No value for uint8\" ) ; return { typeKey : typeKey , value : buffer [ offset + 1 ] , bufferLength : 2 } ; } if ( typeKey <= 40 ) { if ( buffer [ offset + 2 ] == undefined ) throw new Error ( \"ParseError: Incomplete value for uint16\" ) ; return { typeKey : typeKey , value : buffer . readUInt16BE ( offset + 1 ) , bufferLength : 3 } ; } else if ( typeKey <= 90 ) { if ( buffer [ offset + 4 ] == undefined ) throw new Error ( \"ParseError: Incomplete value for uint32\" ) ; return { typeKey : typeKey , value : buffer . readUInt32BE ( offset + 1 ) , bufferLength : 5 } ; } else if ( typeKey <= 155 ) { if ( buffer [ offset + 1 ] == undefined ) throw new Error ( \"ParseError: Incomplete length value for string\" ) ; let len = buffer . readUInt8 ( offset + 1 ) ; if ( buffer [ offset + 1 + len ] == undefined ) throw new Error ( \"ParseError: Incomplete value for string\" ) ; let value = buffer . toString ( \"utf8\" , offset + 2 , offset + 2 + len ) ; return { typeKey : typeKey , value : value , bufferLength : 2 + len } ; } else if ( typeKey <= 165 ) { if ( buffer [ offset + 16 ] == undefined ) throw new Error ( \"ParseError: Incomplete value for uuid\" ) ; let len = 16 ; let value = new Buffer ( len ) ; buffer . copy ( value , 0 , offset + 1 , offset + 1 + len ) ; return { typeKey : typeKey , value : value , bufferLength : 1 + len } ; } else if ( typeKey <= 180 ) { if ( buffer [ offset + 1 ] == undefined ) throw new Error ( \"ParseError: Incomplete length value for byte string\" ) ; let len = buffer . readUInt8 ( offset + 1 ) ; if ( buffer [ offset + len + 1 ] == undefined ) throw new Error ( \"ParseError: Incomplete value for byte string\" ) ; let value = new Buffer ( len ) ; buffer . copy ( value , 0 , offset + 2 , offset + 2 + len ) ; return { typeKey : typeKey , value : value , bufferLength : 2 + len } ; } else { throw new Error ( \"typeKey not supported\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a buffer to a array of segments [CODESPLIT] function parseSegments ( buffer ) { if ( buffer . length == 0 ) throw new Error ( \"bad segments stream\" ) ; let pointer = 0 ; let segments = [ ] ; while ( pointer < buffer . length ) { let seg = parseSegment ( buffer , pointer ) ; segments . push ( seg ) ; pointer += seg . bufferLength ; delete seg . bufferLength ; } if ( pointer != buffer . length ) { throw new Error ( \"Bad / incomplete segments\" ) ; } return segments ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a everiToken s QRCode Text [CODESPLIT] function parseQRCode ( text , options ) { if ( text . length < 3 || text . length > 2000 ) throw new Error ( \"Invalid length of EvtLink\" ) ; let textSplited = text . split ( \"_\" ) ; if ( textSplited . length > 2 ) return null ; let rawText ; if ( textSplited [ 0 ] . startsWith ( qrPrefix ) ) { rawText = textSplited [ 0 ] . substr ( qrPrefix . length ) ; } else { rawText = textSplited [ 0 ] ; } // decode segments base42 let segmentsBytes = EvtLink . dec2b ( rawText ) ; if ( segmentsBytes . length < 2 ) throw new Error ( \"no flag in segment\" ) ; let flag = segmentsBytes . readInt16BE ( 0 ) ; if ( ( flag & 1 ) == 0 ) { // check version of EvtLink throw new Error ( \"The EvtLink is invalid or its version is newer than version 1 and is not supported by evtjs yet\" ) ; } let segmentsBytesRaw = new Buffer ( segmentsBytes . length - 2 ) ; segmentsBytes . copy ( segmentsBytesRaw , 0 , 2 , segmentsBytes . length ) ; let publicKeys = [ ] ; let signatures = [ ] ; if ( textSplited [ 1 ] ) { let buf = EvtLink . dec2b ( textSplited [ 1 ] ) ; let i = 0 ; if ( buf . length % 65 !== 0 ) { throw new Error ( \"length of signature is invalid\" ) ; } while ( i * 65 < buf . length ) { let current = new Buffer ( 65 ) ; buf . copy ( current , 0 , i * 65 , i * 65 + 65 ) ; let signature = ecc . Signature . fromBuffer ( current ) ; signatures . push ( signature . toString ( ) ) ; if ( ! options || options . recoverPublicKeys ) { publicKeys . push ( signature . recover ( segmentsBytes ) . toString ( ) ) ; } ++ i ; } } return { flag , segments : parseSegments ( segmentsBytesRaw ) , publicKeys , signatures } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the value of keyProvider [CODESPLIT] async function __calcKeyProvider ( keyProvider ) { if ( ! keyProvider ) { return [ ] ; } // if keyProvider is function if ( keyProvider . apply && keyProvider . call ) { keyProvider = keyProvider ( ) ; } // resolve for Promise keyProvider = await Promise . resolve ( keyProvider ) ; if ( ! Array . isArray ( keyProvider ) ) { keyProvider = [ keyProvider ] ; } for ( let key of keyProvider ) { if ( ! EvtKey . isValidPrivateKey ( key ) ) { throw new Error ( \"Invalid private key\" ) ; } } return keyProvider ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Additional forms of entropy are used . A week random number generator can run out of entropy . This should ensure even the worst random number implementation will be reasonably safe . [CODESPLIT] function random32ByteBuffer ( { cpuEntropyBits = 0 , safe = true } = { } ) { assert . equal ( typeof cpuEntropyBits , \"number\" , \"cpuEntropyBits\" ) ; assert . equal ( typeof safe , \"boolean\" , \"boolean\" ) ; if ( safe ) { assert ( entropyCount >= 128 , \"Call initialize() to add entropy (current: \" + entropyCount + \")\" ) ; } // if(entropyCount > 0) { //     console.log(`Additional private key entropy: ${entropyCount} events`) // } const hash_array = [ ] ; hash_array . push ( randomBytes ( 32 ) ) ; hash_array . push ( Buffer . from ( cpuEntropy ( cpuEntropyBits ) ) ) ; hash_array . push ( externalEntropyArray ) ; hash_array . push ( browserEntropy ( ) ) ; return hash . sha256 ( Buffer . concat ( hash_array ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds entropy . This may be called many times while the amount of data saved is accumulatively reduced to 101 integers . Data is retained in RAM for the life of this module . [CODESPLIT] function addEntropy ( ... ints ) { assert . equal ( externalEntropyArray . length , 101 , \"externalEntropyArray\" ) ; entropyCount += ints . length ; for ( const i of ints ) { const pos = entropyPos ++ % 101 ; const i2 = externalEntropyArray [ pos ] += i ; if ( i2 > 9007199254740991 ) externalEntropyArray [ pos ] = 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This runs in just under 1 second and ensures a minimum of cpuEntropyBits bits of entropy are gathered . [CODESPLIT] function cpuEntropy ( cpuEntropyBits = 128 ) { let collected = [ ] ; let lastCount = null ; let lowEntropySamples = 0 ; while ( collected . length < cpuEntropyBits ) { const count = floatingPointCount ( ) ; if ( lastCount != null ) { const delta = count - lastCount ; if ( Math . abs ( delta ) < 1 ) { lowEntropySamples ++ ; continue ; } // how many bits of entropy were in this sample const bits = Math . floor ( log2 ( Math . abs ( delta ) ) + 1 ) ; if ( bits < 4 ) { if ( bits < 2 ) { lowEntropySamples ++ ; } continue ; } collected . push ( delta ) ; } lastCount = count ; } if ( lowEntropySamples > 10 ) { const pct = Number ( lowEntropySamples / cpuEntropyBits * 100 ) . toFixed ( 2 ) ; // Is this algorithm getting inefficient? console . warn ( ` ${ pct } ` ) ; } return collected ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private Attempt to gather and hash information from the browser s window history and supported mime types . For non - browser environments this simply includes secure random data . In any event the information is re - hashed in a loop for 25 milliseconds seconds . [CODESPLIT] function browserEntropy ( ) { let entropyStr = Array ( randomBytes ( 101 ) ) . join ( ) ; try { entropyStr += ( new Date ( ) ) . toString ( ) + \" \" + window . screen . height + \" \" + window . screen . width + \" \" + window . screen . colorDepth + \" \" + \" \" + window . screen . availHeight + \" \" + window . screen . availWidth + \" \" + window . screen . pixelDepth + navigator . language + \" \" + window . location + \" \" + window . history . length ; for ( let i = 0 , mimeType ; i < navigator . mimeTypes . length ; i ++ ) { mimeType = navigator . mimeTypes [ i ] ; entropyStr += mimeType . description + \" \" + mimeType . type + \" \" + mimeType . suffixes + \" \" ; } } catch ( error ) { //nodejs:ReferenceError: window is not defined entropyStr += hash . sha256 ( ( new Date ( ) ) . toString ( ) ) ; } const b = new Buffer ( entropyStr ) ; entropyStr += b . toString ( \"binary\" ) + \" \" + ( new Date ( ) ) . toString ( ) ; let entropy = entropyStr ; const start_t = Date . now ( ) ; while ( Date . now ( ) - start_t < 25 ) entropy = hash . sha256 ( entropy ) ; return entropy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Spec : http : // localhost : 3002 / steem / @dantheman / how - to - encrypt - a - memo - when - transferring - steem [CODESPLIT] function encrypt ( private_key , public_key , message , nonce = uniqueNonce ( ) ) { return crypt ( private_key , public_key , nonce , message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Spec : http : // localhost : 3002 / steem / @dantheman / how - to - encrypt - a - memo - when - transferring - steem [CODESPLIT] function decrypt ( private_key , public_key , nonce , message , checksum ) { return crypt ( private_key , public_key , nonce , message , checksum ) . message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method does not use a checksum the returned data must be validated some other way . [CODESPLIT] function cryptoJsDecrypt ( message , key , iv ) { assert ( message , \"Missing cipher text\" ) ; message = toBinaryBuffer ( message ) ; const decipher = crypto . createDecipheriv ( \"aes-256-cbc\" , key , iv ) ; // decipher.setAutoPadding(true) message = Buffer . concat ( [ decipher . update ( message ) , decipher . final ( ) ] ) ; return message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method does not use a checksum the returned data must be validated some other way . @arg { string|Buffer } message - plaintext binary format @arg { string<utf8 > |Buffer } key - 256bit @arg { string<utf8 > |Buffer } iv - 128bit [CODESPLIT] function cryptoJsEncrypt ( message , key , iv ) { assert ( message , \"Missing plain text\" ) ; message = toBinaryBuffer ( message ) ; const cipher = crypto . createCipheriv ( \"aes-256-cbc\" , key , iv ) ; // cipher.setAutoPadding(true) message = Buffer . concat ( [ cipher . update ( message ) , cipher . final ( ) ] ) ; return message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ECIES [CODESPLIT] function getSharedSecret ( public_key ) { public_key = PublicKey ( public_key ) ; let KB = public_key . toUncompressed ( ) . toBuffer ( ) ; let KBP = Point . fromAffine ( secp256k1 , BigInteger . fromBuffer ( KB . slice ( 1 , 33 ) ) , // x BigInteger . fromBuffer ( KB . slice ( 33 , 65 ) ) // y ) ; let r = toBuffer ( ) ; let P = KBP . multiply ( BigInteger . fromBuffer ( r ) ) ; let S = P . affineX . toBuffer ( { size : 32 } ) ; // SHA512 used in ECIES return hash . sha512 ( S ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ ** ECIES TODO unit test @arg { string|Object } pubkey wif PublicKey object @return { Buffer } 64 byte shared secret function getSharedSecret ( public_key ) { public_key = PublicKey ( public_key ) . toUncompressed () var P = public_key . Q . multiply ( d ) ; var S = P . affineX . toBuffer ( { size : 32 } ) ; // ECIES adds an extra sha512 return hash . sha512 ( S ) ; } @arg { string } name - child key name . @return { PrivateKey } [CODESPLIT] function getChildKey ( name ) { // console.error('WARNING: getChildKey untested against evtd'); // no evtd impl yet const index = createHash ( \"sha256\" ) . update ( toBuffer ( ) ) . update ( name ) . digest ( ) ; return PrivateKey ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run self - checking code and gather CPU entropy . [CODESPLIT] function initialize ( ) { if ( initialized ) { return ; } unitTest ( ) ; keyUtils . addEntropy ( ... keyUtils . cpuEntropy ( ) ) ; assert ( keyUtils . entropyCount ( ) >= 128 , \"insufficient entropy\" ) ; initialized = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "am1 : use a single mult and divide to get the high bits max digit bits should be 26 because max internal value = 2 * dvalue^2 - 2 * dvalue ( < 2^53 ) [CODESPLIT] function am1 ( i , x , w , j , c , n ) { while ( -- n >= 0 ) { var v = x * this [ i ++ ] + w [ j ] + c c = Math . floor ( v / 0x4000000 ) w [ j ++ ] = v & 0x3ffffff } return c }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "am2 avoids a big mult - and - extract completely . Max digit bits should be < = 30 because we do bitwise ops on values up to 2 * hdvalue^2 - hdvalue - 1 ( < 2^31 ) [CODESPLIT] function am2 ( i , x , w , j , c , n ) { var xl = x & 0x7fff , xh = x >> 15 while ( -- n >= 0 ) { var l = this [ i ] & 0x7fff var h = this [ i ++ ] >> 15 var m = xh * l + h * xl l = xl * l + ( ( m & 0x7fff ) << 15 ) + w [ j ] + ( c & 0x3fffffff ) c = ( l >>> 30 ) + ( m >>> 15 ) + xh * h + ( c >>> 30 ) w [ j ++ ] = l & 0x3fffffff } return c }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( protected ) copy this to r [CODESPLIT] function bnpCopyTo ( r ) { for ( var i = this . t - 1 ; i >= 0 ; -- i ) r [ i ] = this [ i ] r . t = this . t r . s = this . s }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( protected ) return - 1 / this % 2^DB ; useful for Mont . reduction justification : xy == 1 ( mod m ) xy = 1 + km xy ( 2 - xy ) = ( 1 + km ) ( 1 - km ) x [ y ( 2 - xy ) ] = 1 - k^2m^2 x [ y ( 2 - xy ) ] == 1 ( mod m^2 ) if y is 1 / x mod m then y ( 2 - xy ) is 1 / x mod m^2 should reduce x and y ( 2 - xy ) by m^2 at each step to keep size bounded . JS multiply overflows differently from C / C ++ so care is needed here . [CODESPLIT] function bnpInvDigit ( ) { if ( this . t < 1 ) return 0 var x = this [ 0 ] if ( ( x & 1 ) == 0 ) return 0 var y = x & 3 ; // y == 1/x mod 2^2 y = ( y * ( 2 - ( x & 0xf ) * y ) ) & 0xf ; // y == 1/x mod 2^4 y = ( y * ( 2 - ( x & 0xff ) * y ) ) & 0xff ; // y == 1/x mod 2^8 y = ( y * ( 2 - ( ( ( x & 0xffff ) * y ) & 0xffff ) ) ) & 0xffff ; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = ( y * ( 2 - x * y % this . DV ) ) % this . DV ; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return ( y > 0 ) ? this . DV - y : - y }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Montgomery reduction [CODESPLIT] function Montgomery ( m ) { this . m = m this . mp = m . invDigit ( ) this . mpl = this . mp & 0x7fff this . mph = this . mp >> 15 this . um = ( 1 << ( m . DB - 15 ) ) - 1 this . mt2 = 2 * m . t }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "xR mod m [CODESPLIT] function montConvert ( x ) { var r = new BigInteger ( ) x . abs ( ) . dlShiftTo ( this . m . t , r ) r . divRemTo ( this . m , null , r ) if ( x . s < 0 && r . compareTo ( BigInteger . ZERO ) > 0 ) this . m . subTo ( r , r ) return r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "x / R mod m [CODESPLIT] function montRevert ( x ) { var r = new BigInteger ( ) x . copyTo ( r ) this . reduce ( r ) return r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( public ) ~this [CODESPLIT] function bnNot ( ) { var r = new BigInteger ( ) for ( var i = 0 ; i < this . t ; ++ i ) r [ i ] = this . DM & ~ this [ i ] r . t = this . t r . s = ~ this . s return r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( public ) this << n [CODESPLIT] function bnShiftLeft ( n ) { var r = new BigInteger ( ) if ( n < 0 ) this . rShiftTo ( - n , r ) else this . lShiftTo ( n , r ) return r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( public ) this >> n [CODESPLIT] function bnShiftRight ( n ) { var r = new BigInteger ( ) if ( n < 0 ) this . lShiftTo ( - n , r ) else this . rShiftTo ( n , r ) return r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( protected ) this op ( 1<<n ) [CODESPLIT] function bnpChangeBit ( n , op ) { var r = BigInteger . ONE . shiftLeft ( n ) this . bitwiseTo ( r , op , r ) return r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( public ) [ this / a this%a ] [CODESPLIT] function bnDivideAndRemainder ( a ) { var q = new BigInteger ( ) , r = new BigInteger ( ) this . divRemTo ( a , q , r ) return new Array ( q , r ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "x = x mod m ( HAC 14 . 42 ) [CODESPLIT] function barrettReduce ( x ) { var self = this x . drShiftTo ( self . m . t - 1 , self . r2 ) if ( x . t > self . m . t + 1 ) { x . t = self . m . t + 1 x . clamp ( ) } self . mu . multiplyUpperTo ( self . r2 , self . m . t + 1 , self . q3 ) self . m . multiplyLowerTo ( self . q3 , self . m . t + 1 , self . r2 ) while ( x . compareTo ( self . r2 ) < 0 ) x . dAddOffset ( 1 , self . m . t + 1 ) x . subTo ( self . r2 , x ) while ( x . compareTo ( self . m ) >= 0 ) x . subTo ( self . m , x ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( public ) this^e % m ( HAC 14 . 85 ) [CODESPLIT] function bnModPow ( e , m ) { var i = e . bitLength ( ) , k , r = nbv ( 1 ) , z if ( i <= 0 ) return r else if ( i < 18 ) k = 1 else if ( i < 48 ) k = 3 else if ( i < 144 ) k = 4 else if ( i < 768 ) k = 5 else k = 6 if ( i < 8 ) z = new Classic ( m ) else if ( m . isEven ( ) ) z = new Barrett ( m ) else z = new Montgomery ( m ) // precomputation var g = new Array ( ) , n = 3 , k1 = k - 1 , km = ( 1 << k ) - 1 g [ 1 ] = z . convert ( this ) if ( k > 1 ) { var g2 = new BigInteger ( ) z . sqrTo ( g [ 1 ] , g2 ) while ( n <= km ) { g [ n ] = new BigInteger ( ) z . mulTo ( g2 , g [ n - 2 ] , g [ n ] ) n += 2 } } var j = e . t - 1 , w , is1 = true , r2 = new BigInteger ( ) , t i = nbits ( e [ j ] ) - 1 while ( j >= 0 ) { if ( i >= k1 ) w = ( e [ j ] >> ( i - k1 ) ) & km else { w = ( e [ j ] & ( ( 1 << ( i + 1 ) ) - 1 ) ) << ( k1 - i ) if ( j > 0 ) w |= e [ j - 1 ] >> ( this . DB + i - k1 ) } n = k while ( ( w & 1 ) == 0 ) { w >>= 1 -- n } if ( ( i -= n ) < 0 ) { i += this . DB -- j } if ( is1 ) { // ret == 1, don't bother squaring or multiplying it g [ w ] . copyTo ( r ) is1 = false } else { while ( n > 1 ) { z . sqrTo ( r , r2 ) z . sqrTo ( r2 , r ) n -= 2 } if ( n > 0 ) z . sqrTo ( r , r2 ) else { t = r r = r2 r2 = t } z . mulTo ( r2 , g [ w ] , r ) } while ( j >= 0 && ( e [ j ] & ( 1 << i ) ) == 0 ) { z . sqrTo ( r , r2 ) t = r r = r2 r2 = t if ( -- i < 0 ) { i = this . DB - 1 -- j } } } return z . revert ( r ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( public ) gcd ( this a ) ( HAC 14 . 54 ) [CODESPLIT] function bnGCD ( a ) { var x = ( this . s < 0 ) ? this . negate ( ) : this . clone ( ) var y = ( a . s < 0 ) ? a . negate ( ) : a . clone ( ) if ( x . compareTo ( y ) < 0 ) { var t = x x = y y = t } var i = x . getLowestSetBit ( ) , g = y . getLowestSetBit ( ) if ( g < 0 ) return x if ( i < g ) g = i if ( g > 0 ) { x . rShiftTo ( g , x ) y . rShiftTo ( g , y ) } while ( x . signum ( ) > 0 ) { if ( ( i = x . getLowestSetBit ( ) ) > 0 ) x . rShiftTo ( i , x ) if ( ( i = y . getLowestSetBit ( ) ) > 0 ) y . rShiftTo ( i , y ) if ( x . compareTo ( y ) >= 0 ) { x . subTo ( y , x ) x . rShiftTo ( 1 , x ) } else { y . subTo ( x , y ) y . rShiftTo ( 1 , y ) } } if ( g > 0 ) y . lShiftTo ( g , y ) return y }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( protected ) this % n n < 2^26 [CODESPLIT] function bnpModInt ( n ) { if ( n <= 0 ) return 0 var d = this . DV % n , r = ( this . s < 0 ) ? n - 1 : 0 if ( this . t > 0 ) if ( d == 0 ) r = this [ 0 ] % n else for ( var i = this . t - 1 ; i >= 0 ; -- i ) r = ( d * r + this [ i ] ) % n return r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( public ) test primality with certainty > = 1 - . 5^t [CODESPLIT] function bnIsProbablePrime ( t ) { var i , x = this . abs ( ) if ( x . t == 1 && x [ 0 ] <= lowprimes [ lowprimes . length - 1 ] ) { for ( i = 0 ; i < lowprimes . length ; ++ i ) if ( x [ 0 ] == lowprimes [ i ] ) return true return false } if ( x . isEven ( ) ) return false i = 1 while ( i < lowprimes . length ) { var m = lowprimes [ i ] , j = i + 1 while ( j < lowprimes . length && m < lplim ) m *= lowprimes [ j ++ ] m = x . modInt ( m ) while ( i < j ) if ( m % lowprimes [ i ++ ] == 0 ) return false } return x . millerRabin ( t ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verify signed data . [CODESPLIT] function verify ( data , pubkey , encoding = \"utf8\" ) { if ( typeof data === \"string\" ) { data = Buffer . from ( data , encoding ) ; } assert ( Buffer . isBuffer ( data ) , \"data is a required String or Buffer\" ) ; data = hash . sha256 ( data ) ; return verifyHash ( data , pubkey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verify a buffer of exactally 32 bytes in size ( sha256 ( text )) [CODESPLIT] function verifyHash ( dataSha256 , pubkey , encoding = \"hex\" ) { if ( typeof dataSha256 === \"string\" ) { dataSha256 = Buffer . from ( dataSha256 , encoding ) ; } if ( dataSha256 . length !== 32 || ! Buffer . isBuffer ( dataSha256 ) ) throw new Error ( \"dataSha256: 32 bytes required\" ) ; const publicKey = PublicKey ( pubkey ) ; assert ( publicKey , \"pubkey required\" ) ; return ecdsa . verify ( curve , dataSha256 , { r : r , s : s } , publicKey . Q ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recover the public key used to create this signature using full data . [CODESPLIT] function recover ( data , encoding = \"utf8\" ) { if ( typeof data === \"string\" ) { data = Buffer . from ( data , encoding ) ; } assert ( Buffer . isBuffer ( data ) , \"data is a required String or Buffer\" ) ; data = hash . sha256 ( data ) ; return recoverHash ( data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@arg { String|Buffer } dataSha256 - sha256 hash 32 byte buffer or hex string @arg { String } [ encoding = hex ] - dataSha256 encoding ( if string ) [CODESPLIT] function recoverHash ( dataSha256 , encoding = \"hex\" ) { //let time = new Date().valueOf(); if ( typeof dataSha256 === \"string\" ) { dataSha256 = Buffer . from ( dataSha256 , encoding ) ; } if ( dataSha256 . length !== 32 || ! Buffer . isBuffer ( dataSha256 ) ) { throw new Error ( \"dataSha256: 32 byte String or buffer requred\" ) ; } // sign the message if ( secp256k1 != null ) { let buffer = toBuffer ( ) ; //console.log(\"[recoverHash] accelerating supported, length of sign: \" + buffer.length); var ret = PublicKey . fromBuffer ( secp256k1 . recover ( dataSha256 , buffer . slice ( 1 ) , buffer [ 0 ] - 4 - 27 , true ) ) ; //time = (new Date().valueOf()) - time; //console.log(\"[+\" + time + \"ms] recoverHash (c binding)\"); return ret ; } else { //console.log(\"[recoverHash] accelerating not supported\"); const e = BigInteger . fromBuffer ( dataSha256 ) ; let i2 = i ; i2 -= 27 ; i2 = i2 & 3 ; const Q = ecdsa . recoverPubKey ( curve , e , { r , s , i } , i2 ) ; // time = (new Date().valueOf()) - time; //console.log(\"[+\" + time + \"ms] recoverHash\"); return PublicKey . fromPoint ( Q ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Original Name encode and decode logic is in github . com / eosio / eos native . hpp Encode a name ( a base32 string ) to a number . [CODESPLIT] function encodeName ( name , littleEndian = true ) { if ( typeof name !== \"string\" ) throw new TypeError ( \"name parameter is a required string\" ) ; if ( name . length > 13 ) throw new TypeError ( \"A name can be up to 13 characters long\" ) ; let bitstr = \"\" ; for ( let i = 0 ; i <= 12 ; i ++ ) { // process all 64 bits (even if name is short) const c = i < name . length ? charidx ( name [ i ] ) : 0 ; const bitlen = i < 12 ? 5 : 4 ; let bits = Number ( c ) . toString ( 2 ) ; if ( bits . length > bitlen ) { throw new TypeError ( \"Invalid name \" + name ) ; } bits = \"0\" . repeat ( bitlen - bits . length ) + bits ; bitstr += bits ; } const value = Long . fromString ( bitstr , true , 2 ) ; // convert to LITTLE_ENDIAN let leHex = \"\" ; const bytes = littleEndian ? value . toBytesLE ( ) : value . toBytesBE ( ) ; for ( const b of bytes ) { const n = Number ( b ) . toString ( 16 ) ; leHex += ( n . length === 1 ? \"0\" : \"\" ) + n ; } const ulName = Long . fromString ( leHex , true , 16 ) . toString ( ) ; // console.log('encodeName', name, value.toString(), ulName.toString(), JSON.stringify(bitstr.split(/(.....)/).slice(1))) return ulName . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode a name ( a base32 string ) to a number . [CODESPLIT] function encodeName128 ( name ) { if ( typeof name !== 'string' ) throw new TypeError ( 'name parameter is a required string' ) ; if ( name . length > 21 ) throw new TypeError ( 'A name can be up to 21 characters long' ) ; let bitstr = '' ; for ( let i = 0 ; i < 21 ; i ++ ) { // process all 64 bits (even if name is short) const c = i < name . length ? charidx128 ( name [ i ] ) : 0 ; let bits = Number ( c ) . toString ( 2 ) ; if ( bits . length > 6 ) { throw new TypeError ( 'Invalid name ' + name ) ; } bits = '0' . repeat ( 6 - bits . length ) + bits ; bitstr = bits + bitstr ; } let cutSize = 4 ; if ( name . length <= 5 ) { bitstr += \"00\" cutSize = 4 } else if ( name . length <= 10 ) { bitstr += \"01\" cutSize = 8 } else if ( name . length <= 15 ) { bitstr += \"10\" cutSize = 12 } else { bitstr += \"11\" cutSize = 16 } let bn = new BN ( bitstr , 2 ) ; // bn = bn.toTwos(128); return bn . toArrayLike ( Buffer , 'le' , 128 / 8 / 16 * cutSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The authenticate function is called whenever ZAP requires to authenticate for a Context for which this script was selected as the Authentication Method . The function should send any messages that are required to do the authentication and should return a message with an authenticated response so the calling method . NOTE : Any message sent in the function should be obtained using the helper . prepareMessage () method . Parameters : helper - a helper class providing useful methods : prepareMessage () sendAndReceive ( msg ) getHttpSender () paramsValues - the values of the parameters configured in the Session Properties - > Authentication panel . The paramsValues is a map having as keys the parameters names ( as returned by the getRequiredParamsNames () and getOptionalParamsNames () functions below ) credentials - an object containing the credentials values as configured in the Session Properties - > Users panel . The credential values can be obtained via calls to the getParam ( paramName ) method . The param names are the ones returned by the getCredentialsParamsNames () below [CODESPLIT] function authenticate ( helper , paramsValues , credentials ) { print ( \"Authenticating via JavaScript script...\" ) ; var msg = helper . prepareMessage ( ) ; // TODO: Process message to match the authentication needs // Configurations on how the messages are sent/handled: // Set to follow redirects when sending messages (default is false). // helper.getHttpSender().setFollowRedirect(true) // Send message without following redirects (overriding the option previously set). // helper.sendAndReceive(msg, false) // Set the number of maximum redirects followed to 5 (default is 100). Main purpose is to prevent infinite loops. // helper.getHttpSender().setMaxRedirects(5) // Allow circular redirects (default is not allow). Circular redirects happen when a request // redirects to itself, or when a same request was already accessed in a chain of redirects. // helper.getHttpSender().setAllowCircularRedirects(true) helper . sendAndReceive ( msg ) ; return msg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The authenticate function is called whenever ZAP requires to authenticate for a Context for which this script was selected as the Authentication Method . The function should send any messages that are required to do the authentication and should return a message with an authenticated response so the calling method . NOTE : Any message sent in the function should be obtained using the helper . prepareMessage () method . Parameters : helper - a helper class providing useful methods : prepareMessage () sendAndReceive ( msg ) paramsValues - the values of the parameters configured in the Session Properties - > Authentication panel . The paramsValues is a map having as keys the parameters names ( as returned by the getRequiredParamsNames () and getOptionalParamsNames () functions below ) credentials - an object containing the credentials values as configured in the Session Properties - > Users panel . The credential values can be obtained via calls to the getParam ( paramName ) method . The param names are the ones returned by the getCredentialsParamsNames () below [CODESPLIT] function authenticate ( helper , paramsValues , credentials ) { print ( \"Authenticating via JavaScript script...\" ) ; // Make sure any Java classes used explicitly are imported var HttpRequestHeader = Java . type ( \"org.parosproxy.paros.network.HttpRequestHeader\" ) var HttpHeader = Java . type ( \"org.parosproxy.paros.network.HttpHeader\" ) var URI = Java . type ( \"org.apache.commons.httpclient.URI\" ) // Prepare the login request details var requestUri = new URI ( paramsValues . get ( \"Target URL\" ) , false ) ; var requestMethod = HttpRequestHeader . POST ; // Build the request body using the credentials values var extraPostData = paramsValues . get ( \"Extra POST data\" ) ; var requestBody = paramsValues . get ( \"Username field\" ) + \"=\" + encodeURIComponent ( credentials . getParam ( \"Username\" ) ) ; requestBody += \"&\" + paramsValues . get ( \"Password field\" ) + \"=\" + encodeURIComponent ( credentials . getParam ( \"Password\" ) ) ; if ( extraPostData . trim ( ) . length ( ) > 0 ) requestBody += \"&\" + extraPostData . trim ( ) ; // Build the actual message to be sent print ( \"Sending \" + requestMethod + \" request to \" + requestUri + \" with body: \" + requestBody ) ; var msg = helper . prepareMessage ( ) ; msg . setRequestHeader ( new HttpRequestHeader ( requestMethod , requestUri , HttpHeader . HTTP10 ) ) ; msg . setRequestBody ( requestBody ) ; // Send the authentication message and return it helper . sendAndReceive ( msg ) ; print ( \"Received response status code: \" + msg . getResponseHeader ( ) . getStatusCode ( ) ) ; return msg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Targeted scripts can only be invoked by you the user eg via a right - click option on the Sites or History tabs [CODESPLIT] function invokeWith ( msg ) { // Debugging can be done using println like this print ( 'Finding comments in ' + msg . getRequestHeader ( ) . getURI ( ) . toString ( ) ) ; var body = msg . getResponseBody ( ) . toString ( ) // Look for html comments if ( body . indexOf ( '<!--' ) > 0 ) { var o = body . indexOf ( '<!--' ) ; while ( o > 0 ) { var e = body . indexOf ( '-->' , o ) ; print ( \"\\t\" + body . substr ( o , e - o + 3 ) ) o = body . indexOf ( '<!--' , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Passively scans an HTTP message . The scan function will be called for request / response made via ZAP actual messages depend on the function appliesToHistoryType defined below . [CODESPLIT] function scan ( ps , msg , src ) { // Test the request and/or response here if ( true ) { // Change to a test which detects the vulnerability // raiseAlert(risk, int confidence, String name, String description, String uri,  //\t\tString param, String attack, String otherInfo, String solution, String evidence,  //\t\tint cweId, int wascId, HttpMessage msg) // risk: 0: info, 1: low, 2: medium, 3: high // confidence: 0: falsePositive, 1: low, 2: medium, 3: high, 4: confirmed ps . raiseAlert ( 1 , 1 , 'Passive Vulnerability title' , 'Full description' , msg . getRequestHeader ( ) . getURI ( ) . toString ( ) , 'The param' , 'Your attack' , 'Any other info' , 'The solution' , '' , 'References' , 0 , 0 , msg ) ; //addTag(String tag) ps . addTag ( 'tag' ) } // Raise less reliable alert (that is, prone to false positives) when in LOW alert threshold // Expected values: \"LOW\", \"MEDIUM\", \"HIGH\" if ( ps . getAlertThreshold ( ) == \"LOW\" ) { // ... } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The authenticate function is called whenever ZAP requires to authenticate for a Context for which this script was selected as the Authentication Method . The function should send any messages that are required to do the authentication and should return a message with an authenticated response so the calling method . NOTE : Any message sent in the function should be obtained using the helper . prepareMessage () method . Parameters : helper - a helper class providing useful methods : prepareMessage () sendAndReceive ( msg ) paramsValues - the values of the parameters configured in the Session Properties - > Authentication panel . The paramsValues is a map having as keys the parameters names ( as returned by the getRequiredParamsNames () and getOptionalParamsNames () functions below ) credentials - an object containing the credentials values as configured in the Session Properties - > Users panel . The credential values can be obtained via calls to the getParam ( paramName ) method . The param names are the ones returned by the getCredentialsParamsNames () below [CODESPLIT] function authenticate ( helper , paramsValues , credentials ) { print ( \"Wordpress Authenticating via JavaScript script...\" ) ; // Make sure any Java classes used explicitly are imported var HttpRequestHeader = Java . type ( \"org.parosproxy.paros.network.HttpRequestHeader\" ) var HttpHeader = Java . type ( \"org.parosproxy.paros.network.HttpHeader\" ) var URI = Java . type ( \"org.apache.commons.httpclient.URI\" ) var Cookie = Java . type ( \"org.apache.commons.httpclient.Cookie\" ) // Prepare the login request details var domain = paramsValues . get ( \"Domain\" ) ; var path = paramsValues . get ( \"Path\" ) ; print ( \"Logging in to domain \" + domain + \" and path \" + path ) ; var requestUri = new URI ( \"http://\" + domain + path + \"wp-login.php\" , false ) ; var requestMethod = HttpRequestHeader . POST ; // Build the request body using the credentials values var requestBody = \"log=\" + encodeURIComponent ( credentials . getParam ( \"Username\" ) ) ; requestBody = requestBody + \"&pwd=\" + encodeURIComponent ( credentials . getParam ( \"Password\" ) ) ; requestBody = requestBody + \"&rememberme=forever&wp-submit=Log+In&testcookie=1\" ; // Add the proper cookie to the header var requestHeader = new HttpRequestHeader ( requestMethod , requestUri , HttpHeader . HTTP10 ) ; requestHeader . setHeader ( HttpHeader . COOKIE , \"wordpress_test_cookie=WP+Cookie+check\" ) ; // Build the actual message to be sent print ( \"Sending \" + requestMethod + \" request to \" + requestUri + \" with body: \" + requestBody ) ; var msg = helper . prepareMessage ( ) ; msg . setRequestHeader ( requestHeader ) ; msg . setRequestBody ( requestBody ) ; // Send the authentication message and return it helper . sendAndReceive ( msg ) ; print ( \"Received response status code for authentication request: \" + msg . getResponseHeader ( ) . getStatusCode ( ) ) ; // The path Wordpress sets on the session cookies is illegal according to the standard. The web browsers ignore this and use the cookies anyway, but the Apache Commons HttpClient used in ZAP really cares about this (probably the only one who does it) and simply ignores the \"invalid\" cookies [0] , [1],so we must make sure we MANUALLY add the response cookies if ( path != \"/\" && path . charAt ( path . length ( ) - 1 ) == '/' ) { path = path . substring ( 0 , path . length ( ) - 1 ) ; } print ( \"Cleaned cookie path: \" + path ) ; var cookies = msg . getResponseHeader ( ) . getCookieParams ( ) ; var state = helper . getCorrespondingHttpState ( ) ; for ( var iterator = cookies . iterator ( ) ; iterator . hasNext ( ) ; ) { var cookie = iterator . next ( ) ; print ( \"Manually adding cookie: \" + cookie . getName ( ) + \" = \" + cookie . getValue ( ) ) ; state . addCookie ( new Cookie ( domain , cookie . getName ( ) , cookie . getValue ( ) , path , 999999 , false ) ) ; } return msg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A set of fields can appear grouped together . [CODESPLIT] function FormGroup ( props ) { const { children , className , grouped , inline , unstackable , widths } = props const classes = cx ( useKeyOnly ( grouped , 'grouped' ) , useKeyOnly ( inline , 'inline' ) , useKeyOnly ( unstackable , 'unstackable' ) , useWidthProp ( widths , null , true ) , 'fields' , className , ) const rest = getUnhandledProps ( FormGroup , props ) const ElementType = getElementType ( FormGroup , props ) return ( < ElementType { ... rest } className = { classes } > \n       { children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A loader alerts a user to wait for an activity to complete . [CODESPLIT] function Loader ( props ) { const { active , children , className , content , disabled , indeterminate , inline , inverted , size , } = props const classes = cx ( 'ui' , size , useKeyOnly ( active , 'active' ) , useKeyOnly ( disabled , 'disabled' ) , useKeyOnly ( indeterminate , 'indeterminate' ) , useKeyOnly ( inverted , 'inverted' ) , useKeyOnly ( children || content , 'text' ) , useKeyOrValueAndKey ( inline , 'inline' ) , 'loader' , className , ) const rest = getUnhandledProps ( Loader , props ) const ElementType = getElementType ( Loader , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sugar for <Form . Field control = { TextArea } / > . [CODESPLIT] function FormTextArea ( props ) { const { control } = props const rest = getUnhandledProps ( FormTextArea , props ) const ElementType = getElementType ( FormTextArea , props ) return < ElementType { ... rest } control = { control } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sugar for <Form . Field control = { Select } / > . [CODESPLIT] function FormSelect ( props ) { const { control , options } = props const rest = getUnhandledProps ( FormSelect , props ) const ElementType = getElementType ( FormSelect , props ) return < ElementType { ... rest } control = { control } options = { options } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An item can contain content . [CODESPLIT] function ItemContent ( props ) { const { children , className , content , description , extra , header , meta , verticalAlign } = props const classes = cx ( useVerticalAlignProp ( verticalAlign ) , 'content' , className ) const rest = getUnhandledProps ( ItemContent , props ) const ElementType = getElementType ( ItemContent , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { ItemHeader . create ( header , { autoGenerateKey : false } ) } \n       { ItemMeta . create ( meta , { autoGenerateKey : false } ) } \n       { ItemDescription . create ( description , { autoGenerateKey : false } ) } \n       { ItemExtra . create ( extra , { autoGenerateKey : false } ) } \n       { content } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A table displays a collections of data grouped into rows . [CODESPLIT] function Table ( props ) { const { attached , basic , celled , children , className , collapsing , color , columns , compact , definition , fixed , footerRow , headerRow , headerRows , inverted , padded , renderBodyRow , selectable , singleLine , size , sortable , stackable , striped , structured , tableData , textAlign , unstackable , verticalAlign , } = props const classes = cx ( 'ui' , color , size , useKeyOnly ( celled , 'celled' ) , useKeyOnly ( collapsing , 'collapsing' ) , useKeyOnly ( definition , 'definition' ) , useKeyOnly ( fixed , 'fixed' ) , useKeyOnly ( inverted , 'inverted' ) , useKeyOnly ( selectable , 'selectable' ) , useKeyOnly ( singleLine , 'single line' ) , useKeyOnly ( sortable , 'sortable' ) , useKeyOnly ( stackable , 'stackable' ) , useKeyOnly ( striped , 'striped' ) , useKeyOnly ( structured , 'structured' ) , useKeyOnly ( unstackable , 'unstackable' ) , useKeyOrValueAndKey ( attached , 'attached' ) , useKeyOrValueAndKey ( basic , 'basic' ) , useKeyOrValueAndKey ( compact , 'compact' ) , useKeyOrValueAndKey ( padded , 'padded' ) , useTextAlignProp ( textAlign ) , useVerticalAlignProp ( verticalAlign ) , useWidthProp ( columns , 'column' ) , 'table' , className , ) const rest = getUnhandledProps ( Table , props ) const ElementType = getElementType ( Table , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } const hasHeaderRows = headerRow || headerRows const headerShorthandOptions = { defaultProps : { cellAs : 'th' } } const headerElement = hasHeaderRows && ( < TableHeader > \n       { TableRow . create ( headerRow , headerShorthandOptions ) } \n       { _ . map ( headerRows , ( data ) => TableRow . create ( data , headerShorthandOptions ) ) } \n     < / TableHeader > ) return ( < ElementType { ... rest } className = { classes } > \n       { headerElement } \n       < TableBody > \n         { renderBodyRow && _ . map ( tableData , ( data , index ) => TableRow . create ( renderBodyRow ( data , index ) ) ) } \n       < / TableBody > \n       { footerRow && < TableFooter > { TableRow . create ( footerRow ) } < / TableFooter > } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A rail is used to show accompanying content outside the boundaries of the main view of a site . [CODESPLIT] function Rail ( props ) { const { attached , children , className , close , content , dividing , internal , position , size , } = props const classes = cx ( 'ui' , position , size , useKeyOnly ( attached , 'attached' ) , useKeyOnly ( dividing , 'dividing' ) , useKeyOnly ( internal , 'internal' ) , useKeyOrValueAndKey ( close , 'close' ) , 'rail' , className , ) const rest = getUnhandledProps ( Rail , props ) const ElementType = getElementType ( Rail , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Buttons can be grouped . [CODESPLIT] function ButtonGroup ( props ) { const { attached , basic , buttons , children , className , color , compact , content , floated , fluid , icon , inverted , labeled , negative , positive , primary , secondary , size , toggle , vertical , widths , } = props const classes = cx ( 'ui' , color , size , useKeyOnly ( basic , 'basic' ) , useKeyOnly ( compact , 'compact' ) , useKeyOnly ( fluid , 'fluid' ) , useKeyOnly ( icon , 'icon' ) , useKeyOnly ( inverted , 'inverted' ) , useKeyOnly ( labeled , 'labeled' ) , useKeyOnly ( negative , 'negative' ) , useKeyOnly ( positive , 'positive' ) , useKeyOnly ( primary , 'primary' ) , useKeyOnly ( secondary , 'secondary' ) , useKeyOnly ( toggle , 'toggle' ) , useKeyOnly ( vertical , 'vertical' ) , useKeyOrValueAndKey ( attached , 'attached' ) , useValueAndKey ( floated , 'floated' ) , useWidthProp ( widths ) , 'buttons' , className , ) const rest = getUnhandledProps ( ButtonGroup , props ) const ElementType = getElementType ( ButtonGroup , props ) if ( _ . isNil ( buttons ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { childrenUtils . isNil ( children ) ? content : children } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { _ . map ( buttons , button => Button . create ( button ) ) } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A row sub - component for Grid . [CODESPLIT] function GridRow ( props ) { const { centered , children , className , color , columns , divided , only , reversed , stretched , textAlign , verticalAlign , } = props const classes = cx ( color , useKeyOnly ( centered , 'centered' ) , useKeyOnly ( divided , 'divided' ) , useKeyOnly ( stretched , 'stretched' ) , useMultipleProp ( only , 'only' ) , useMultipleProp ( reversed , 'reversed' ) , useTextAlignProp ( textAlign ) , useVerticalAlignProp ( verticalAlign ) , useWidthProp ( columns , 'column' , true ) , 'row' , className , ) const rest = getUnhandledProps ( GridRow , props ) const ElementType = getElementType ( GridRow , props ) return ( < ElementType { ... rest } className = { classes } > \n       { children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A field is a form element containing a label and an input . [CODESPLIT] function FormField ( props ) { const { children , className , content , control , disabled , error , inline , label , required , type , width , } = props const classes = cx ( useKeyOnly ( disabled , 'disabled' ) , useKeyOnly ( error , 'error' ) , useKeyOnly ( inline , 'inline' ) , useKeyOnly ( required , 'required' ) , useWidthProp ( width , 'wide' ) , 'field' , className , ) const rest = getUnhandledProps ( FormField , props ) const ElementType = getElementType ( FormField , props ) // ---------------------------------------- // No Control // ---------------------------------------- if ( _ . isNil ( control ) ) { if ( _ . isNil ( label ) ) { return ( < ElementType { ... rest } className = { classes } > \n           { childrenUtils . isNil ( children ) ? content : children } \n         < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n         { createHTMLLabel ( label , { autoGenerateKey : false } ) } \n       < / ElementType > ) } // ---------------------------------------- // Checkbox/Radio Control // ---------------------------------------- const controlProps = { ... rest , content , children , disabled , required , type } // wrap HTML checkboxes/radios in the label if ( control === 'input' && ( type === 'checkbox' || type === 'radio' ) ) { return ( < ElementType className = { classes } > \n         < label > \n           { createElement ( control , controlProps ) }   { label } \n         < / label > \n       < / ElementType > ) } // pass label prop to controls that support it if ( control === Checkbox || control === Radio ) { return ( < ElementType className = { classes } > \n         { createElement ( control , { ... controlProps , label } ) } \n       < / ElementType > ) } // ---------------------------------------- // Other Control // ---------------------------------------- return ( < ElementType className = { classes } > \n       { createHTMLLabel ( label , { defaultProps : { htmlFor : _ . get ( controlProps , 'id' ) } , autoGenerateKey : false , } ) } \n       { createElement ( control , controlProps ) } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A card can contain blocks of content or extra content meant to be formatted separately from the main content . [CODESPLIT] function CardContent ( props ) { const { children , className , content , description , extra , header , meta , textAlign } = props const classes = cx ( useKeyOnly ( extra , 'extra' ) , useTextAlignProp ( textAlign ) , 'content' , className ) const rest = getUnhandledProps ( CardContent , props ) const ElementType = getElementType ( CardContent , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } if ( ! childrenUtils . isNil ( content ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { content } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { createShorthand ( CardHeader , val => ( { content : val } ) , header , { autoGenerateKey : false } ) } \n       { createShorthand ( CardMeta , val => ( { content : val } ) , meta , { autoGenerateKey : false } ) } \n       { createShorthand ( CardDescription , val => ( { content : val } ) , description , { autoGenerateKey : false , } ) } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An item view presents large collections of site content for display . [CODESPLIT] function Item ( props ) { const { children , className , content , description , extra , header , image , meta } = props const classes = cx ( 'item' , className ) const rest = getUnhandledProps ( Item , props ) const ElementType = getElementType ( Item , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { ItemImage . create ( image , { autoGenerateKey : false } ) } \n\n       < ItemContent content = { content } description = { description } extra = { extra } header = { header } meta = { meta } / > \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A comment can contain an image or avatar . [CODESPLIT] function CommentAvatar ( props ) { const { className , src } = props const classes = cx ( 'avatar' , className ) const rest = getUnhandledProps ( CommentAvatar , props ) const [ imageProps , rootProps ] = partitionHTMLProps ( rest , { htmlProps : htmlImageProps } ) const ElementType = getElementType ( CommentAvatar , props ) return ( < ElementType { ... rootProps } className = { classes } > \n       { createHTMLImage ( src , { autoGenerateKey : false , defaultProps : imageProps } ) } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A statistic can contain a label to help provide context for the presented value . [CODESPLIT] function StatisticLabel ( props ) { const { children , className , content } = props const classes = cx ( 'label' , className ) const rest = getUnhandledProps ( StatisticLabel , props ) const ElementType = getElementType ( StatisticLabel , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A Radio is sugar for <Checkbox radio / > . Useful for exclusive groups of sliders or toggles . [CODESPLIT] function Radio ( props ) { const { slider , toggle , type } = props const rest = getUnhandledProps ( Radio , props ) // const ElementType = getElementType(Radio, props) // radio, slider, toggle are exclusive // use an undefined radio if slider or toggle are present const radio = ! ( slider || toggle ) || undefined return < Checkbox { ... rest } type = { type } radio = { radio } slider = { slider } toggle = { toggle } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sugar for <Form . Field control = { Checkbox } / > . [CODESPLIT] function FormCheckbox ( props ) { const { control } = props const rest = getUnhandledProps ( FormCheckbox , props ) const ElementType = getElementType ( FormCheckbox , props ) return < ElementType { ... rest } control = { control } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A feed can contain a meta . [CODESPLIT] function FeedMeta ( props ) { const { children , className , content , like } = props const classes = cx ( 'meta' , className ) const rest = getUnhandledProps ( FeedMeta , props ) const ElementType = getElementType ( FeedMeta , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { createShorthand ( FeedLike , val => ( { content : val } ) , like , { autoGenerateKey : false } ) } \n       { content } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A container limits content to a maximum width . [CODESPLIT] function Container ( props ) { const { children , className , content , fluid , text , textAlign } = props const classes = cx ( 'ui' , useKeyOnly ( text , 'text' ) , useKeyOnly ( fluid , 'fluid' ) , useTextAlignProp ( textAlign ) , 'container' , className , ) const rest = getUnhandledProps ( Container , props ) const ElementType = getElementType ( Container , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A set of steps . [CODESPLIT] function StepGroup ( props ) { const { attached , children , className , content , fluid , items , ordered , size , stackable , unstackable , vertical , widths , } = props const classes = cx ( 'ui' , size , useKeyOnly ( fluid , 'fluid' ) , useKeyOnly ( ordered , 'ordered' ) , useKeyOnly ( unstackable , 'unstackable' ) , useKeyOnly ( vertical , 'vertical' ) , useKeyOrValueAndKey ( attached , 'attached' ) , useValueAndKey ( stackable , 'stackable' ) , useWidthProp ( widths ) , 'steps' , className , ) const rest = getUnhandledProps ( StepGroup , props ) const ElementType = getElementType ( StepGroup , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } if ( ! childrenUtils . isNil ( content ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { content } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { _ . map ( items , item => Step . create ( item ) ) } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A divider visually segments content into groups . [CODESPLIT] function Divider ( props ) { const { children , className , clearing , content , fitted , hidden , horizontal , inverted , section , vertical , } = props const classes = cx ( 'ui' , useKeyOnly ( clearing , 'clearing' ) , useKeyOnly ( fitted , 'fitted' ) , useKeyOnly ( hidden , 'hidden' ) , useKeyOnly ( horizontal , 'horizontal' ) , useKeyOnly ( inverted , 'inverted' ) , useKeyOnly ( section , 'section' ) , useKeyOnly ( vertical , 'vertical' ) , 'divider' , className , ) const rest = getUnhandledProps ( Divider , props ) const ElementType = getElementType ( Divider , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A header provides a short summary of content [CODESPLIT] function Header ( props ) { const { attached , block , children , className , color , content , disabled , dividing , floated , icon , image , inverted , size , sub , subheader , textAlign , } = props const classes = cx ( 'ui' , color , size , useKeyOnly ( block , 'block' ) , useKeyOnly ( disabled , 'disabled' ) , useKeyOnly ( dividing , 'dividing' ) , useValueAndKey ( floated , 'floated' ) , useKeyOnly ( icon === true , 'icon' ) , useKeyOnly ( image === true , 'image' ) , useKeyOnly ( inverted , 'inverted' ) , useKeyOnly ( sub , 'sub' ) , useKeyOrValueAndKey ( attached , 'attached' ) , useTextAlignProp ( textAlign ) , 'header' , className , ) const rest = getUnhandledProps ( Header , props ) const ElementType = getElementType ( Header , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } const iconElement = Icon . create ( icon , { autoGenerateKey : false } ) const imageElement = Image . create ( image , { autoGenerateKey : false } ) const subheaderElement = HeaderSubheader . create ( subheader , { autoGenerateKey : false } ) if ( iconElement || imageElement ) { return ( < ElementType { ... rest } className = { classes } > \n         { iconElement || imageElement } \n         { ( content || subheaderElement ) && ( < HeaderContent > \n             { content } \n             { subheaderElement } \n           < / HeaderContent > ) } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { content } \n       { subheaderElement } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A grid is used to harmonize negative space in a layout . [CODESPLIT] function Grid ( props ) { const { celled , centered , children , className , columns , container , divided , doubling , inverted , padded , relaxed , reversed , stackable , stretched , textAlign , verticalAlign , } = props const classes = cx ( 'ui' , useKeyOnly ( centered , 'centered' ) , useKeyOnly ( container , 'container' ) , useKeyOnly ( doubling , 'doubling' ) , useKeyOnly ( inverted , 'inverted' ) , useKeyOnly ( stackable , 'stackable' ) , useKeyOnly ( stretched , 'stretched' ) , useKeyOrValueAndKey ( celled , 'celled' ) , useKeyOrValueAndKey ( divided , 'divided' ) , useKeyOrValueAndKey ( padded , 'padded' ) , useKeyOrValueAndKey ( relaxed , 'relaxed' ) , useMultipleProp ( reversed , 'reversed' ) , useTextAlignProp ( textAlign ) , useVerticalAlignProp ( verticalAlign ) , useWidthProp ( columns , 'column' , true ) , 'grid' , className , ) const rest = getUnhandledProps ( Grid , props ) const ElementType = getElementType ( Grid , props ) return ( < ElementType { ... rest } className = { classes } > \n       { children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A breadcrumb is used to show hierarchy between content . [CODESPLIT] function Breadcrumb ( props ) { const { children , className , divider , icon , sections , size } = props const classes = cx ( 'ui' , size , 'breadcrumb' , className ) const rest = getUnhandledProps ( Breadcrumb , props ) const ElementType = getElementType ( Breadcrumb , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } const childElements = [ ] _ . each ( sections , ( section , index ) => { // section const breadcrumbElement = BreadcrumbSection . create ( section ) childElements . push ( breadcrumbElement ) // divider if ( index !== sections . length - 1 ) { const key = ` ${ breadcrumbElement . key } ` || JSON . stringify ( section ) childElements . push ( BreadcrumbDivider . create ( { content : divider , icon , key } ) ) } } ) return ( < ElementType { ... rest } className = { classes } > \n       { childElements } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sugar for <Form . Field control = { Dropdown } / > . [CODESPLIT] function FormDropdown ( props ) { const { control } = props const rest = getUnhandledProps ( FormDropdown , props ) const ElementType = getElementType ( FormDropdown , props ) return < ElementType { ... rest } control = { control } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A card can contain a description with one or more paragraphs . [CODESPLIT] function CardDescription ( props ) { const { children , className , content , textAlign } = props const classes = cx ( useTextAlignProp ( textAlign ) , 'description' , className ) const rest = getUnhandledProps ( CardDescription , props ) const ElementType = getElementType ( CardDescription , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A group of items . [CODESPLIT] function ItemGroup ( props ) { const { children , className , content , divided , items , link , relaxed , unstackable } = props const classes = cx ( 'ui' , useKeyOnly ( divided , 'divided' ) , useKeyOnly ( link , 'link' ) , useKeyOnly ( unstackable , 'unstackable' ) , useKeyOrValueAndKey ( relaxed , 'relaxed' ) , 'items' , className , ) const rest = getUnhandledProps ( ItemGroup , props ) const ElementType = getElementType ( ItemGroup , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } if ( ! childrenUtils . isNil ( content ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { content } \n       < / ElementType > ) } const itemsJSX = _ . map ( items , ( item ) => { const { childKey , ... itemProps } = item const finalKey = childKey || [ itemProps . content , itemProps . description , itemProps . header , itemProps . meta ] . join ( '-' ) return < Item { ... itemProps } key = { finalKey } / > } ) return ( < ElementType { ... rest } className = { classes } > \n       { itemsJSX } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A column sub - component for Grid . [CODESPLIT] function GridColumn ( props ) { const { children , className , computer , color , floated , largeScreen , mobile , only , stretched , tablet , textAlign , verticalAlign , widescreen , width , } = props const classes = cx ( color , useKeyOnly ( stretched , 'stretched' ) , useMultipleProp ( only , 'only' ) , useTextAlignProp ( textAlign ) , useValueAndKey ( floated , 'floated' ) , useVerticalAlignProp ( verticalAlign ) , useWidthProp ( computer , 'wide computer' ) , useWidthProp ( largeScreen , 'wide large screen' ) , useWidthProp ( mobile , 'wide mobile' ) , useWidthProp ( tablet , 'wide tablet' ) , useWidthProp ( widescreen , 'wide widescreen' ) , useWidthProp ( width , 'wide' ) , 'column' , className , ) const rest = getUnhandledProps ( GridColumn , props ) const ElementType = getElementType ( GridColumn , props ) return ( < ElementType { ... rest } className = { classes } > \n       { children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An item can contain an image . [CODESPLIT] function ItemImage ( props ) { const { size } = props const rest = getUnhandledProps ( ItemImage , props ) return < Image { ... rest } size = { size } ui = { ! ! size } wrapped / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A group of cards . [CODESPLIT] function CardGroup ( props ) { const { centered , children , className , content , doubling , items , itemsPerRow , stackable , textAlign , } = props const classes = cx ( 'ui' , useKeyOnly ( centered , 'centered' ) , useKeyOnly ( doubling , 'doubling' ) , useKeyOnly ( stackable , 'stackable' ) , useTextAlignProp ( textAlign ) , useWidthProp ( itemsPerRow ) , 'cards' , className , ) const rest = getUnhandledProps ( CardGroup , props ) const ElementType = getElementType ( CardGroup , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } if ( ! childrenUtils . isNil ( content ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { content } \n       < / ElementType > ) } const itemsJSX = _ . map ( items , ( item ) => { const key = item . key || [ item . header , item . description ] . join ( '-' ) return < Card key = { key } { ... item } / > } ) return ( < ElementType { ... rest } className = { classes } > \n       { itemsJSX } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A table can have rows . [CODESPLIT] function TableRow ( props ) { const { active , cellAs , cells , children , className , disabled , error , negative , positive , textAlign , verticalAlign , warning , } = props const classes = cx ( useKeyOnly ( active , 'active' ) , useKeyOnly ( disabled , 'disabled' ) , useKeyOnly ( error , 'error' ) , useKeyOnly ( negative , 'negative' ) , useKeyOnly ( positive , 'positive' ) , useKeyOnly ( warning , 'warning' ) , useTextAlignProp ( textAlign ) , useVerticalAlignProp ( verticalAlign ) , className , ) const rest = getUnhandledProps ( TableRow , props ) const ElementType = getElementType ( TableRow , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { _ . map ( cells , cell => TableCell . create ( cell , { defaultProps : { as : cellAs } } ) ) } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sugar for <Form . Field control = { Button } / > . [CODESPLIT] function FormButton ( props ) { const { control } = props const rest = getUnhandledProps ( FormButton , props ) const ElementType = getElementType ( FormButton , props ) return < ElementType { ... rest } control = { control } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This component exposes a prop that supports functional and createRef () API and returns the DOM node of both functional and class component children . [CODESPLIT] function Ref ( props ) { const { children , innerRef } = props const child = React . Children . only ( children ) const ElementType = isForwardRef ( child ) ? RefForward : RefFindNode return < ElementType innerRef = { innerRef } > { child } < / ElementType > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A feed contains an event . [CODESPLIT] function FeedEvent ( props ) { const { content , children , className , date , extraImages , extraText , image , icon , meta , summary , } = props const classes = cx ( 'event' , className ) const rest = getUnhandledProps ( FeedEvent , props ) const ElementType = getElementType ( FeedEvent , props ) const hasContentProp = content || date || extraImages || extraText || meta || summary const contentProps = { content , date , extraImages , extraText , meta , summary } return ( < ElementType { ... rest } className = { classes } > \n       { createShorthand ( FeedLabel , val => ( { icon : val } ) , icon , { autoGenerateKey : false } ) } \n       { createShorthand ( FeedLabel , val => ( { image : val } ) , image , { autoGenerateKey : false } ) } \n       { hasContentProp && < FeedContent { ... contentProps } / > } \n       { children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A tab pane holds the content of a tab . [CODESPLIT] function TabPane ( props ) { const { active , children , className , content , loading } = props const classes = cx ( useKeyOnly ( active , 'active' ) , useKeyOnly ( loading , 'loading' ) , 'tab' , className ) const rest = getUnhandledProps ( TabPane , props ) const ElementType = getElementType ( TabPane , props ) const calculatedDefaultProps = { } if ( ElementType === Segment ) { calculatedDefaultProps . attached = 'bottom' } return ( < ElementType { ... calculatedDefaultProps } { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A list item can contain a content . [CODESPLIT] function ListContent ( props ) { const { children , className , content , description , floated , header , verticalAlign } = props const classes = cx ( useValueAndKey ( floated , 'floated' ) , useVerticalAlignProp ( verticalAlign ) , 'content' , className , ) const rest = getUnhandledProps ( ListContent , props ) const ElementType = getElementType ( ListContent , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { ListHeader . create ( header ) } \n       { ListDescription . create ( description ) } \n       { content } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Button groups can contain conditionals . [CODESPLIT] function ButtonOr ( props ) { const { className , text } = props const classes = cx ( 'or' , className ) const rest = getUnhandledProps ( ButtonOr , props ) const ElementType = getElementType ( ButtonOr , props ) return < ElementType { ... rest } className = { classes } data-text = { text } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A table row can have cells . [CODESPLIT] function TableCell ( props ) { const { active , children , className , collapsing , content , disabled , error , icon , negative , positive , selectable , singleLine , textAlign , verticalAlign , warning , width , } = props const classes = cx ( useKeyOnly ( active , 'active' ) , useKeyOnly ( collapsing , 'collapsing' ) , useKeyOnly ( disabled , 'disabled' ) , useKeyOnly ( error , 'error' ) , useKeyOnly ( negative , 'negative' ) , useKeyOnly ( positive , 'positive' ) , useKeyOnly ( selectable , 'selectable' ) , useKeyOnly ( singleLine , 'single line' ) , useKeyOnly ( warning , 'warning' ) , useTextAlignProp ( textAlign ) , useVerticalAlignProp ( verticalAlign ) , useWidthProp ( width , 'wide' ) , className , ) const rest = getUnhandledProps ( TableCell , props ) const ElementType = getElementType ( TableCell , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { Icon . create ( icon ) } \n       { content } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A divider sub - component for Breadcrumb component . [CODESPLIT] function BreadcrumbDivider ( props ) { const { children , className , content , icon } = props const classes = cx ( 'divider' , className ) const rest = getUnhandledProps ( BreadcrumbDivider , props ) const ElementType = getElementType ( BreadcrumbDivider , props ) if ( ! _ . isNil ( icon ) ) { return Icon . create ( icon , { defaultProps : { ... rest , className : classes } , autoGenerateKey : false , } ) } if ( ! _ . isNil ( content ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { content } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? '/' : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A message can contain a list of items . [CODESPLIT] function MessageList ( props ) { const { children , className , items } = props const classes = cx ( 'list' , className ) const rest = getUnhandledProps ( MessageList , props ) const ElementType = getElementType ( MessageList , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? _ . map ( items , MessageItem . create ) : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A table can have a footer . [CODESPLIT] function TableFooter ( props ) { const { as } = props const rest = getUnhandledProps ( TableFooter , props ) return < TableHeader { ... rest } as = { as } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Comments can be grouped . [CODESPLIT] function CommentGroup ( props ) { const { className , children , collapsed , content , minimal , size , threaded } = props const classes = cx ( 'ui' , size , useKeyOnly ( collapsed , 'collapsed' ) , useKeyOnly ( minimal , 'minimal' ) , useKeyOnly ( threaded , 'threaded' ) , 'comments' , className , ) const rest = getUnhandledProps ( CommentGroup , props ) const ElementType = getElementType ( CommentGroup , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A reveal displays additional content in place of previous content when activated . [CODESPLIT] function Reveal ( props ) { const { active , animated , children , className , content , disabled , instant } = props const classes = cx ( 'ui' , animated , useKeyOnly ( active , 'active' ) , useKeyOnly ( disabled , 'disabled' ) , useKeyOnly ( instant , 'instant' ) , 'reveal' , className , ) const rest = getUnhandledProps ( Reveal , props ) const ElementType = getElementType ( Reveal , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A segment is used to create a grouping of related content . [CODESPLIT] function Segment ( props ) { const { attached , basic , children , circular , className , clearing , color , compact , content , disabled , floated , inverted , loading , placeholder , padded , piled , raised , secondary , size , stacked , tertiary , textAlign , vertical , } = props const classes = cx ( 'ui' , color , size , useKeyOnly ( basic , 'basic' ) , useKeyOnly ( circular , 'circular' ) , useKeyOnly ( clearing , 'clearing' ) , useKeyOnly ( compact , 'compact' ) , useKeyOnly ( disabled , 'disabled' ) , useKeyOnly ( inverted , 'inverted' ) , useKeyOnly ( loading , 'loading' ) , useKeyOnly ( placeholder , 'placeholder' ) , useKeyOnly ( piled , 'piled' ) , useKeyOnly ( raised , 'raised' ) , useKeyOnly ( secondary , 'secondary' ) , useKeyOnly ( stacked , 'stacked' ) , useKeyOnly ( tertiary , 'tertiary' ) , useKeyOnly ( vertical , 'vertical' ) , useKeyOrValueAndKey ( attached , 'attached' ) , useKeyOrValueAndKey ( padded , 'padded' ) , useTextAlignProp ( textAlign ) , useValueAndKey ( floated , 'floated' ) , 'segment' , className , ) const rest = getUnhandledProps ( Segment , props ) const ElementType = getElementType ( Segment , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sugar for <Form . Field control = { Input } / > . [CODESPLIT] function FormInput ( props ) { const { control } = props const rest = getUnhandledProps ( FormInput , props ) const ElementType = getElementType ( FormInput , props ) return < ElementType { ... rest } control = { control } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A placeholder can contain have lines of text . [CODESPLIT] function PlaceholderLine ( props ) { const { className , length } = props const classes = cx ( 'line' , length , className ) const rest = getUnhandledProps ( PlaceholderLine , props ) const ElementType = getElementType ( PlaceholderLine , props ) return < ElementType { ... rest } className = { classes } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A content sub - component for the Reveal . [CODESPLIT] function RevealContent ( props ) { const { children , className , content , hidden , visible } = props const classes = cx ( 'ui' , useKeyOnly ( hidden , 'hidden' ) , useKeyOnly ( visible , 'visible' ) , 'content' , className , ) const rest = getUnhandledProps ( RevealContent , props ) const ElementType = getElementType ( RevealContent , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A feed can contain a like element . [CODESPLIT] function FeedLike ( props ) { const { children , className , content , icon } = props const classes = cx ( 'like' , className ) const rest = getUnhandledProps ( FeedLike , props ) const ElementType = getElementType ( FeedLike , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { Icon . create ( icon , { autoGenerateKey : false } ) } \n       { content } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A placeholder is used to reserve splace for content that soon will appear in a layout . [CODESPLIT] function Placeholder ( props ) { const { children , className , content , fluid , inverted } = props const classes = cx ( 'ui' , useKeyOnly ( fluid , 'fluid' ) , useKeyOnly ( inverted , 'inverted' ) , 'placeholder' , className , ) const rest = getUnhandledProps ( Placeholder , props ) const ElementType = getElementType ( Placeholder , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An accordion allows users to toggle the display of sections of content . [CODESPLIT] function Accordion ( props ) { const { className , fluid , inverted , styled } = props const classes = cx ( 'ui' , useKeyOnly ( fluid , 'fluid' ) , useKeyOnly ( inverted , 'inverted' ) , useKeyOnly ( styled , 'styled' ) , className , ) const rest = getUnhandledProps ( Accordion , props ) return < AccordionAccordion { ... rest } className = { classes } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A placeholder can contain an image . [CODESPLIT] function PlaceholderImage ( props ) { const { className , square , rectangular } = props const classes = cx ( useKeyOnly ( square , 'square' ) , useKeyOnly ( rectangular , 'rectangular' ) , 'image' , className , ) const rest = getUnhandledProps ( PlaceholderImage , props ) const ElementType = getElementType ( PlaceholderImage , props ) return < ElementType { ... rest } className = { classes } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A dropdown menu can contain a menu . [CODESPLIT] function DropdownMenu ( props ) { const { children , className , content , direction , open , scrolling } = props const classes = cx ( direction , useKeyOnly ( open , 'visible' ) , useKeyOnly ( scrolling , 'scrolling' ) , 'menu transition' , className , ) const rest = getUnhandledProps ( DropdownMenu , props ) const ElementType = getElementType ( DropdownMenu , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A list item can contain an icon . [CODESPLIT] function ListIcon ( props ) { const { className , verticalAlign } = props const classes = cx ( useVerticalAlignProp ( verticalAlign ) , className ) const rest = getUnhandledProps ( ListIcon , props ) return < Icon { ... rest } className = { classes } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An ad displays third - party promotional content . [CODESPLIT] function Advertisement ( props ) { const { centered , children , className , content , test , unit } = props const classes = cx ( 'ui' , unit , useKeyOnly ( centered , 'centered' ) , useKeyOnly ( test , 'test' ) , 'ad' , className , ) const rest = getUnhandledProps ( Advertisement , props ) const ElementType = getElementType ( Advertisement , props ) return ( < ElementType { ... rest } className = { classes } data-text = { test } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A group of statistics . [CODESPLIT] function StatisticGroup ( props ) { const { children , className , color , content , horizontal , inverted , items , size , widths } = props const classes = cx ( 'ui' , color , size , useKeyOnly ( horizontal , 'horizontal' ) , useKeyOnly ( inverted , 'inverted' ) , useWidthProp ( widths ) , 'statistics' , className , ) const rest = getUnhandledProps ( StatisticGroup , props ) const ElementType = getElementType ( StatisticGroup , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } if ( ! childrenUtils . isNil ( content ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { content } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { _ . map ( items , item => Statistic . create ( item ) ) } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A statistic emphasizes the current value of an attribute . [CODESPLIT] function Statistic ( props ) { const { children , className , color , content , floated , horizontal , inverted , label , size , text , value , } = props const classes = cx ( 'ui' , color , size , useValueAndKey ( floated , 'floated' ) , useKeyOnly ( horizontal , 'horizontal' ) , useKeyOnly ( inverted , 'inverted' ) , 'statistic' , className , ) const rest = getUnhandledProps ( Statistic , props ) const ElementType = getElementType ( Statistic , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } if ( ! childrenUtils . isNil ( content ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { content } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { StatisticValue . create ( value , { defaultProps : { text } , autoGenerateKey : false , } ) } \n       { StatisticLabel . create ( label , { autoGenerateKey : false } ) } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a createElement () type based on the props of the Component . Useful for calculating what type a component should render as . [CODESPLIT] function getElementType ( Component , props , getDefault ) { const { defaultProps = { } } = Component // ---------------------------------------- // user defined \"as\" element type if ( props . as && props . as !== defaultProps . as ) return props . as // ---------------------------------------- // computed default element type if ( getDefault ) { const computedDefault = getDefault ( ) if ( computedDefault ) return computedDefault } // ---------------------------------------- // infer anchor links if ( props . href ) return 'a' // ---------------------------------------- // use defaultProp or 'div' return defaultProps . as || 'div' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A group of segments can be formatted to appear together . [CODESPLIT] function SegmentGroup ( props ) { const { children , className , compact , content , horizontal , piled , raised , size , stacked } = props const classes = cx ( 'ui' , size , useKeyOnly ( compact , 'compact' ) , useKeyOnly ( horizontal , 'horizontal' ) , useKeyOnly ( piled , 'piled' ) , useKeyOnly ( raised , 'raised' ) , useKeyOnly ( stacked , 'stacked' ) , 'segments' , className , ) const rest = getUnhandledProps ( SegmentGroup , props ) const ElementType = getElementType ( SegmentGroup , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A table can have a header cell . [CODESPLIT] function TableHeaderCell ( props ) { const { as , className , sorted } = props const classes = cx ( useValueAndKey ( sorted , 'sorted' ) , className ) const rest = getUnhandledProps ( TableHeaderCell , props ) return < TableCell { ... rest } as = { as } className = { classes } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A feed presents user activity chronologically . [CODESPLIT] function Feed ( props ) { const { children , className , events , size } = props const classes = cx ( 'ui' , size , 'feed' , className ) const rest = getUnhandledProps ( Feed , props ) const ElementType = getElementType ( Feed , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } const eventElements = _ . map ( events , ( eventProps ) => { const { childKey , date , meta , summary , ... eventData } = eventProps const finalKey = childKey || [ date , meta , summary ] . join ( '-' ) return < FeedEvent date = { date } key = { finalKey } meta = { meta } summary = { summary } { ... eventData } / > } ) return ( < ElementType { ... rest } className = { classes } > \n       { eventElements } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A label can be grouped . [CODESPLIT] function LabelGroup ( props ) { const { children , circular , className , color , content , size , tag } = props const classes = cx ( 'ui' , color , size , useKeyOnly ( circular , 'circular' ) , useKeyOnly ( tag , 'tag' ) , 'labels' , className , ) const rest = getUnhandledProps ( LabelGroup , props ) const ElementType = getElementType ( LabelGroup , props ) return ( < ElementType { ... rest } className = { classes } > \n       { childrenUtils . isNil ( children ) ? content : children } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A feed can contain an extra content . [CODESPLIT] function FeedExtra ( props ) { const { children , className , content , images , text } = props const classes = cx ( useKeyOnly ( images , 'images' ) , useKeyOnly ( content || text , 'text' ) , 'extra' , className , ) const rest = getUnhandledProps ( FeedExtra , props ) const ElementType = getElementType ( FeedExtra , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } // TODO need a \"collection factory\" to handle creating multiple image elements and their keys const imageElements = _ . map ( images , ( image , index ) => { const key = [ index , image ] . join ( '-' ) return createHTMLImage ( image , { key } ) } ) return ( < ElementType { ... rest } className = { classes } > \n       { content } \n       { imageElements } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A dropdown menu can contain dividers to separate related content . [CODESPLIT] function DropdownDivider ( props ) { const { className } = props const classes = cx ( 'divider' , className ) const rest = getUnhandledProps ( DropdownDivider , props ) const ElementType = getElementType ( DropdownDivider , props ) return < ElementType { ... rest } className = { classes } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A feed can contain a summary . [CODESPLIT] function FeedSummary ( props ) { const { children , className , content , date , user } = props const classes = cx ( 'summary' , className ) const rest = getUnhandledProps ( FeedSummary , props ) const ElementType = getElementType ( FeedSummary , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { createShorthand ( FeedUser , val => ( { content : val } ) , user , { autoGenerateKey : false } ) } \n       { content } \n       { createShorthand ( FeedDate , val => ( { content : val } ) , date , { autoGenerateKey : false } ) } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A step can contain a content . [CODESPLIT] function StepContent ( props ) { const { children , className , content , description , title } = props const classes = cx ( 'content' , className ) const rest = getUnhandledProps ( StepContent , props ) const ElementType = getElementType ( StepContent , props ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } if ( ! childrenUtils . isNil ( content ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { content } \n       < / ElementType > ) } return ( < ElementType { ... rest } className = { classes } > \n       { StepTitle . create ( title , { autoGenerateKey : false } ) } \n       { StepDescription . create ( description , { autoGenerateKey : false } ) } \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sugar for <Form . Field control = { Radio } / > . [CODESPLIT] function FormRadio ( props ) { const { control } = props const rest = getUnhandledProps ( FormRadio , props ) const ElementType = getElementType ( FormRadio , props ) return < ElementType { ... rest } control = { control } / > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An image is a graphic representation of something . [CODESPLIT] function Image ( props ) { const { avatar , bordered , centered , children , circular , className , content , dimmer , disabled , floated , fluid , hidden , href , inline , label , rounded , size , spaced , verticalAlign , wrapped , ui , } = props const classes = cx ( useKeyOnly ( ui , 'ui' ) , size , useKeyOnly ( avatar , 'avatar' ) , useKeyOnly ( bordered , 'bordered' ) , useKeyOnly ( circular , 'circular' ) , useKeyOnly ( centered , 'centered' ) , useKeyOnly ( disabled , 'disabled' ) , useKeyOnly ( fluid , 'fluid' ) , useKeyOnly ( hidden , 'hidden' ) , useKeyOnly ( inline , 'inline' ) , useKeyOnly ( rounded , 'rounded' ) , useKeyOrValueAndKey ( spaced , 'spaced' ) , useValueAndKey ( floated , 'floated' ) , useVerticalAlignProp ( verticalAlign , 'aligned' ) , 'image' , className , ) const rest = getUnhandledProps ( Image , props ) const [ imgTagProps , rootProps ] = partitionHTMLProps ( rest , { htmlProps : htmlImageProps } ) const ElementType = getElementType ( Image , props , ( ) => { if ( ! _ . isNil ( dimmer ) || ! _ . isNil ( label ) || ! _ . isNil ( wrapped ) || ! childrenUtils . isNil ( children ) ) { return 'div' } } ) if ( ! childrenUtils . isNil ( children ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { children } \n       < / ElementType > ) } if ( ! childrenUtils . isNil ( content ) ) { return ( < ElementType { ... rest } className = { classes } > \n         { content } \n       < / ElementType > ) } if ( ElementType === 'img' ) { return < ElementType { ... rootProps } { ... imgTagProps } className = { classes } / > } return ( < ElementType { ... rootProps } className = { classes } href = { href } > \n       { Dimmer . create ( dimmer , { autoGenerateKey : false } ) } \n       { Label . create ( label , { autoGenerateKey : false } ) } \n       < img { ... imgTagProps } / > \n     < / ElementType > ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Description [CODESPLIT] function ( width , height ) { var canvas = document . createElement ( 'canvas' ) ; canvas . width = width ; canvas . height = height ; canvas . oncontextmenu = function ( ) { return false ; } ; canvas . onselectstart = function ( ) { return false ; } ; return canvas ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the pixel ratio of the canvas . [CODESPLIT] function ( canvas ) { var context = canvas . getContext ( '2d' ) , devicePixelRatio = window . devicePixelRatio || 1 , backingStorePixelRatio = context . webkitBackingStorePixelRatio || context . mozBackingStorePixelRatio || context . msBackingStorePixelRatio || context . oBackingStorePixelRatio || context . backingStorePixelRatio || 1 ; return devicePixelRatio / backingStorePixelRatio ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the requested texture ( an Image ) via its path [CODESPLIT] function ( render , imagePath ) { var image = render . textures [ imagePath ] ; if ( image ) return image ; image = render . textures [ imagePath ] = new Image ( ) ; image . src = imagePath ; return image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies the background to the canvas using CSS . [CODESPLIT] function ( render , background ) { var cssBackground = background ; if ( / (jpg|gif|png)$ / . test ( background ) ) cssBackground = 'url(' + background + ')' ; render . canvas . style . background = cssBackground ; render . canvas . style . backgroundSize = \"contain\" ; render . currentBackground = background ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a body sprite [CODESPLIT] function ( render , body ) { var bodyRender = body . render , texturePath = bodyRender . sprite . texture , texture = _getTexture ( render , texturePath ) , sprite = new PIXI . Sprite ( texture ) ; sprite . anchor . x = body . render . sprite . xOffset ; sprite . anchor . y = body . render . sprite . yOffset ; return sprite ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a body primitive [CODESPLIT] function ( render , body ) { var bodyRender = body . render , options = render . options , primitive = new PIXI . Graphics ( ) , fillStyle = Common . colorToNumber ( bodyRender . fillStyle ) , strokeStyle = Common . colorToNumber ( bodyRender . strokeStyle ) , strokeStyleIndicator = Common . colorToNumber ( bodyRender . strokeStyle ) , strokeStyleWireframe = Common . colorToNumber ( '#bbb' ) , strokeStyleWireframeIndicator = Common . colorToNumber ( '#CD5C5C' ) , part ; primitive . clear ( ) ; // handle compound parts for ( var k = body . parts . length > 1 ? 1 : 0 ; k < body . parts . length ; k ++ ) { part = body . parts [ k ] ; if ( ! options . wireframes ) { primitive . beginFill ( fillStyle , 1 ) ; primitive . lineStyle ( bodyRender . lineWidth , strokeStyle , 1 ) ; } else { primitive . beginFill ( 0 , 0 ) ; primitive . lineStyle ( 1 , strokeStyleWireframe , 1 ) ; } primitive . moveTo ( part . vertices [ 0 ] . x - body . position . x , part . vertices [ 0 ] . y - body . position . y ) ; for ( var j = 1 ; j < part . vertices . length ; j ++ ) { primitive . lineTo ( part . vertices [ j ] . x - body . position . x , part . vertices [ j ] . y - body . position . y ) ; } primitive . lineTo ( part . vertices [ 0 ] . x - body . position . x , part . vertices [ 0 ] . y - body . position . y ) ; primitive . endFill ( ) ; // angle indicator if ( options . showAngleIndicator || options . showAxes ) { primitive . beginFill ( 0 , 0 ) ; if ( options . wireframes ) { primitive . lineStyle ( 1 , strokeStyleWireframeIndicator , 1 ) ; } else { primitive . lineStyle ( 1 , strokeStyleIndicator ) ; } primitive . moveTo ( part . position . x - body . position . x , part . position . y - body . position . y ) ; primitive . lineTo ( ( ( part . vertices [ 0 ] . x + part . vertices [ part . vertices . length - 1 ] . x ) / 2 - body . position . x ) , ( ( part . vertices [ 0 ] . y + part . vertices [ part . vertices . length - 1 ] . y ) / 2 - body . position . y ) ) ; primitive . endFill ( ) ; } } return primitive ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the requested texture ( a PIXI . Texture ) via its path [CODESPLIT] function ( render , imagePath ) { var texture = render . textures [ imagePath ] ; if ( ! texture ) texture = render . textures [ imagePath ] = PIXI . Texture . fromImage ( imagePath ) ; return texture ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialises body properties . [CODESPLIT] function ( body , options ) { options = options || { } ; // init required properties (order is important) Body . set ( body , { bounds : body . bounds || Bounds . create ( body . vertices ) , positionPrev : body . positionPrev || Vector . clone ( body . position ) , anglePrev : body . anglePrev || body . angle , vertices : body . vertices , parts : body . parts || [ body ] , isStatic : body . isStatic , isSleeping : body . isSleeping , parent : body . parent || body } ) ; Vertices . rotate ( body . vertices , body . angle , body . position ) ; Axes . rotate ( body . axes , body . angle ) ; Bounds . update ( body . bounds , body . vertices , body . velocity ) ; // allow options to override the automatically calculated properties Body . set ( body , { axes : options . axes || body . axes , area : options . area || body . area , mass : options . mass || body . mass , inertia : options . inertia || body . inertia } ) ; // render properties var defaultFillStyle = ( body . isStatic ? '#2e2b44' : Common . choose ( [ '#006BA6' , '#0496FF' , '#FFBC42' , '#D81159' , '#8F2D56' ] ) ) , defaultStrokeStyle = '#000' ; body . render . fillStyle = body . render . fillStyle || defaultFillStyle ; body . render . strokeStyle = body . render . strokeStyle || defaultStrokeStyle ; body . render . sprite . xOffset += - ( body . bounds . min . x - body . position . x ) / ( body . bounds . max . x - body . bounds . min . x ) ; body . render . sprite . yOffset += - ( body . bounds . min . y - body . position . y ) / ( body . bounds . max . y - body . bounds . min . y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dynamically creates pages in the static website [CODESPLIT] async function createPages ( { actions , graphql } ) { const retrieveMarkdownPages = ( ) => graphql ( ` ` ) const exampleTemplate = path . resolve ( ` ` ) const docTemplate = path . resolve ( ` ` ) const result = await retrieveMarkdownPages ( ) if ( result . errors ) { console . error ( 'graphql error' , result . errors ) throw new Error ( 'Error invoking graphql for pages' ) } result . data . allMarkdownRemark . edges . forEach ( ( { node } ) => { const { frontmatter : { path : pagePath } , } = node const category = ( pagePath || '/' ) . split ( '/' ) . filter ( t => ! ! t ) [ 0 ] const isExample = category === 'examples' console . log ( ` ${ pagePath } ${ category } ` ) actions . createPage ( { path : pagePath , component : isExample ? exampleTemplate : docTemplate , context : { } , // additional data can be passed via context } ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#parse - a - month - string [CODESPLIT] function parseMonthString ( str ) { const matches = monthRe . exec ( str ) ; if ( ! matches ) { return null ; } const year = Number ( matches [ 1 ] ) ; if ( year <= 0 ) { return null ; } const month = Number ( matches [ 2 ] ) ; if ( month < 1 || month > 12 ) { return null ; } return { year , month } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#parse - a - date - string [CODESPLIT] function parseDateString ( str ) { const matches = dateRe . exec ( str ) ; if ( ! matches ) { return null ; } const year = Number ( matches [ 1 ] ) ; if ( year <= 0 ) { return null ; } const month = Number ( matches [ 2 ] ) ; if ( month < 1 || month > 12 ) { return null ; } const day = Number ( matches [ 3 ] ) ; if ( day < 1 || day > numberOfDaysInMonthOfYear ( month , year ) ) { return null ; } return { year , month , day } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#parse - a - yearless - date - string [CODESPLIT] function parseYearlessDateString ( str ) { const matches = yearlessDateRe . exec ( str ) ; if ( ! matches ) { return null ; } const month = Number ( matches [ 1 ] ) ; if ( month < 1 || month > 12 ) { return null ; } const day = Number ( matches [ 2 ] ) ; if ( day < 1 || day > numberOfDaysInMonthOfYear ( month , 4 ) ) { return null ; } return { month , day } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#parse - a - time - string [CODESPLIT] function parseTimeString ( str ) { const matches = timeRe . exec ( str ) ; if ( ! matches ) { return null ; } const hour = Number ( matches [ 1 ] ) ; if ( hour < 0 || hour > 23 ) { return null ; } const minute = Number ( matches [ 2 ] ) ; if ( minute < 0 || minute > 59 ) { return null ; } const second = matches [ 3 ] !== undefined ? Math . trunc ( Number ( matches [ 3 ] ) ) : 0 ; if ( second < 0 || second >= 60 ) { return null ; } const millisecond = matches [ 4 ] !== undefined ? Number ( matches [ 4 ] ) : 0 ; return { hour , minute , second , millisecond } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#parse - a - local - date - and - time - string [CODESPLIT] function parseLocalDateAndTimeString ( str , normalized = false ) { let separatorIdx = str . indexOf ( \"T\" ) ; if ( separatorIdx < 0 && ! normalized ) { separatorIdx = str . indexOf ( \" \" ) ; } if ( separatorIdx < 0 ) { return null ; } const date = parseDateString ( str . slice ( 0 , separatorIdx ) ) ; if ( date === null ) { return null ; } const time = parseTimeString ( str . slice ( separatorIdx + 1 ) ) ; if ( time === null ) { return null ; } return { date , time } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#week - number - of - the - last - day https : // stackoverflow . com / a / 18538272 / 1937836 [CODESPLIT] function weekNumberOfLastDay ( year ) { const jan1 = new Date ( year , 0 ) ; return jan1 . getDay ( ) === 4 || ( isLeapYear ( year ) && jan1 . getDay ( ) === 3 ) ? 53 : 52 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // html . spec . whatwg . org / multipage / common - microsyntaxes . html#parse - a - week - string [CODESPLIT] function parseWeekString ( str ) { const matches = weekRe . exec ( str ) ; if ( ! matches ) { return null ; } const year = Number ( matches [ 1 ] ) ; if ( year <= 0 ) { return null ; } const week = Number ( matches [ 2 ] ) ; if ( week < 1 || week > weekNumberOfLastDay ( year ) ) { return null ; } return { year , week } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We need to wrap the methods that receive an image or canvas object ( luckily always as the first argument ) so that these objects can be unwrapped an the expected types passed . [CODESPLIT] function wrapNodeCanvasMethod ( ctx , name ) { const prev = ctx [ name ] ; ctx [ name ] = function ( image ) { const impl = idlUtils . implForWrapper ( image ) ; if ( impl ) { arguments [ 0 ] = impl . _image || impl . _canvas ; } return prev . apply ( ctx , arguments ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NOTE : per https : // heycam . github . io / webidl / #Global all properties on the Window object must be own - properties . That is why we assign everything inside of the constructor instead of using a shared prototype . You can verify this in e . g . Firefox or Internet Explorer which do a good job with Web IDL compliance . [CODESPLIT] function Window ( options ) { EventTarget . setup ( this ) ; const rawPerformance = new RawPerformance ( ) ; const windowInitialized = rawPerformance . now ( ) ; const window = this ; mixin ( window , WindowEventHandlersImpl . prototype ) ; mixin ( window , GlobalEventHandlersImpl . prototype ) ; this . _initGlobalEvents ( ) ; ///// INTERFACES FROM THE DOM // TODO: consider a mode of some sort where these are not shared between all DOM instances // It'd be very memory-expensive in most cases, though. for ( const name in dom ) { Object . defineProperty ( window , name , { enumerable : false , configurable : true , writable : true , value : dom [ name ] } ) ; } ///// PRIVATE DATA PROPERTIES this . _resourceLoader = options . resourceLoader ; // vm initialization is deferred until script processing is activated this . _globalProxy = this ; Object . defineProperty ( idlUtils . implForWrapper ( this ) , idlUtils . wrapperSymbol , { get : ( ) => this . _globalProxy } ) ; let timers = Object . create ( null ) ; let animationFrameCallbacks = Object . create ( null ) ; // List options explicitly to be clear which are passed through this . _document = Document . create ( [ ] , { options : { parsingMode : options . parsingMode , contentType : options . contentType , encoding : options . encoding , cookieJar : options . cookieJar , url : options . url , lastModified : options . lastModified , referrer : options . referrer , concurrentNodeIterators : options . concurrentNodeIterators , parseOptions : options . parseOptions , defaultView : this . _globalProxy , global : this } } ) ; // https://html.spec.whatwg.org/#session-history this . _sessionHistory = new SessionHistory ( { document : idlUtils . implForWrapper ( this . _document ) , url : idlUtils . implForWrapper ( this . _document ) . _URL , stateObject : null } , this ) ; this . _virtualConsole = options . virtualConsole ; this . _runScripts = options . runScripts ; if ( this . _runScripts === \"outside-only\" || this . _runScripts === \"dangerously\" ) { contextifyWindow ( this ) ; } // Set up the window as if it's a top level window. // If it's not, then references will be corrected by frame/iframe code. this . _parent = this . _top = this . _globalProxy ; this . _frameElement = null ; // This implements window.frames.length, since window.frames returns a // self reference to the window object.  This value is incremented in the // HTMLFrameElement implementation. this . _length = 0 ; this . _pretendToBeVisual = options . pretendToBeVisual ; this . _storageQuota = options . storageQuota ; // Some properties (such as localStorage and sessionStorage) share data // between windows in the same origin. This object is intended // to contain such data. if ( options . commonForOrigin && options . commonForOrigin [ this . _document . origin ] ) { this . _commonForOrigin = options . commonForOrigin ; } else { this . _commonForOrigin = { [ this . _document . origin ] : { localStorageArea : new Map ( ) , sessionStorageArea : new Map ( ) , windowsInSameOrigin : [ this ] } } ; } this . _currentOriginData = this . _commonForOrigin [ this . _document . origin ] ; ///// WEB STORAGE this . _localStorage = Storage . create ( [ ] , { associatedWindow : this , storageArea : this . _currentOriginData . localStorageArea , type : \"localStorage\" , url : this . _document . documentURI , storageQuota : this . _storageQuota } ) ; this . _sessionStorage = Storage . create ( [ ] , { associatedWindow : this , storageArea : this . _currentOriginData . sessionStorageArea , type : \"sessionStorage\" , url : this . _document . documentURI , storageQuota : this . _storageQuota } ) ; ///// GETTERS const locationbar = BarProp . create ( ) ; const menubar = BarProp . create ( ) ; const personalbar = BarProp . create ( ) ; const scrollbars = BarProp . create ( ) ; const statusbar = BarProp . create ( ) ; const toolbar = BarProp . create ( ) ; const external = External . create ( ) ; const navigator = Navigator . create ( [ ] , { userAgent : this . _resourceLoader . _userAgent } ) ; const performance = Performance . create ( [ ] , { rawPerformance } ) ; const screen = Screen . create ( ) ; define ( this , { get length ( ) { return window . _length ; } , get window ( ) { return window . _globalProxy ; } , get frameElement ( ) { return idlUtils . wrapperForImpl ( window . _frameElement ) ; } , get frames ( ) { return window . _globalProxy ; } , get self ( ) { return window . _globalProxy ; } , get parent ( ) { return window . _parent ; } , get top ( ) { return window . _top ; } , get document ( ) { return window . _document ; } , get external ( ) { return external ; } , get location ( ) { return idlUtils . wrapperForImpl ( idlUtils . implForWrapper ( window . _document ) . _location ) ; } , get history ( ) { return idlUtils . wrapperForImpl ( idlUtils . implForWrapper ( window . _document ) . _history ) ; } , get navigator ( ) { return navigator ; } , get locationbar ( ) { return locationbar ; } , get menubar ( ) { return menubar ; } , get personalbar ( ) { return personalbar ; } , get scrollbars ( ) { return scrollbars ; } , get statusbar ( ) { return statusbar ; } , get toolbar ( ) { return toolbar ; } , get performance ( ) { return performance ; } , get screen ( ) { return screen ; } , get localStorage ( ) { if ( this . _document . origin === \"null\" ) { throw new DOMException ( \"localStorage is not available for opaque origins\" , \"SecurityError\" ) ; } return this . _localStorage ; } , get sessionStorage ( ) { if ( this . _document . origin === \"null\" ) { throw new DOMException ( \"sessionStorage is not available for opaque origins\" , \"SecurityError\" ) ; } return this . _sessionStorage ; } } ) ; namedPropertiesWindow . initializeWindow ( this , this . _globalProxy ) ; ///// METHODS for [ImplicitThis] hack // See https://lists.w3.org/Archives/Public/public-script-coord/2015JanMar/0109.html this . addEventListener = this . addEventListener . bind ( this ) ; this . removeEventListener = this . removeEventListener . bind ( this ) ; this . dispatchEvent = this . dispatchEvent . bind ( this ) ; ///// METHODS let latestTimerId = 0 ; let latestAnimationFrameCallbackId = 0 ; this . setTimeout = function ( fn , ms ) { const args = [ ] ; for ( let i = 2 ; i < arguments . length ; ++ i ) { args [ i - 2 ] = arguments [ i ] ; } return startTimer ( window , setTimeout , clearTimeout , ++ latestTimerId , fn , ms , timers , args ) ; } ; this . setInterval = function ( fn , ms ) { const args = [ ] ; for ( let i = 2 ; i < arguments . length ; ++ i ) { args [ i - 2 ] = arguments [ i ] ; } return startTimer ( window , setInterval , clearInterval , ++ latestTimerId , fn , ms , timers , args ) ; } ; this . clearInterval = stopTimer . bind ( this , timers ) ; this . clearTimeout = stopTimer . bind ( this , timers ) ; if ( this . _pretendToBeVisual ) { this . requestAnimationFrame = fn => { const timestamp = rawPerformance . now ( ) - windowInitialized ; const fps = 1000 / 60 ; return startTimer ( window , setTimeout , clearTimeout , ++ latestAnimationFrameCallbackId , fn , fps , animationFrameCallbacks , [ timestamp ] ) ; } ; this . cancelAnimationFrame = stopTimer . bind ( this , animationFrameCallbacks ) ; } this . __stopAllTimers = function ( ) { stopAllTimers ( timers ) ; stopAllTimers ( animationFrameCallbacks ) ; latestTimerId = 0 ; latestAnimationFrameCallbackId = 0 ; timers = Object . create ( null ) ; animationFrameCallbacks = Object . create ( null ) ; } ; function Option ( text , value , defaultSelected , selected ) { if ( text === undefined ) { text = \"\" ; } text = webIDLConversions . DOMString ( text ) ; if ( value !== undefined ) { value = webIDLConversions . DOMString ( value ) ; } defaultSelected = webIDLConversions . boolean ( defaultSelected ) ; selected = webIDLConversions . boolean ( selected ) ; const option = window . _document . createElement ( \"option\" ) ; const impl = idlUtils . implForWrapper ( option ) ; if ( text !== \"\" ) { impl . text = text ; } if ( value !== undefined ) { impl . setAttributeNS ( null , \"value\" , value ) ; } if ( defaultSelected ) { impl . setAttributeNS ( null , \"selected\" , \"\" ) ; } impl . _selectedness = selected ; return option ; } Object . defineProperty ( Option , \"prototype\" , { value : this . HTMLOptionElement . prototype , configurable : false , enumerable : false , writable : false } ) ; Object . defineProperty ( window , \"Option\" , { value : Option , configurable : true , enumerable : false , writable : true } ) ; function Image ( ) { const img = window . _document . createElement ( \"img\" ) ; const impl = idlUtils . implForWrapper ( img ) ; if ( arguments . length > 0 ) { impl . setAttributeNS ( null , \"width\" , String ( arguments [ 0 ] ) ) ; } if ( arguments . length > 1 ) { impl . setAttributeNS ( null , \"height\" , String ( arguments [ 1 ] ) ) ; } return img ; } Object . defineProperty ( Image , \"prototype\" , { value : this . HTMLImageElement . prototype , configurable : false , enumerable : false , writable : false } ) ; Object . defineProperty ( window , \"Image\" , { value : Image , configurable : true , enumerable : false , writable : true } ) ; function Audio ( src ) { const audio = window . _document . createElement ( \"audio\" ) ; const impl = idlUtils . implForWrapper ( audio ) ; impl . setAttributeNS ( null , \"preload\" , \"auto\" ) ; if ( src !== undefined ) { impl . setAttributeNS ( null , \"src\" , String ( src ) ) ; } return audio ; } Object . defineProperty ( Audio , \"prototype\" , { value : this . HTMLAudioElement . prototype , configurable : false , enumerable : false , writable : false } ) ; Object . defineProperty ( window , \"Audio\" , { value : Audio , configurable : true , enumerable : false , writable : true } ) ; this . postMessage = postMessage ; this . atob = function ( str ) { const result = atob ( str ) ; if ( result === null ) { throw new DOMException ( \"The string to be decoded contains invalid characters.\" , \"InvalidCharacterError\" ) ; } return result ; } ; this . btoa = function ( str ) { const result = btoa ( str ) ; if ( result === null ) { throw new DOMException ( \"The string to be encoded contains invalid characters.\" , \"InvalidCharacterError\" ) ; } return result ; } ; this . FileReader = createFileReader ( { window : this } ) . interface ; this . WebSocket = createWebSocket ( { window : this } ) . interface ; const AbortSignalWrapper = createAbortSignal ( { window : this } ) ; this . AbortSignal = AbortSignalWrapper . interface ; this . AbortController = createAbortController ( { AbortSignal : AbortSignalWrapper } ) . interface ; this . XMLHttpRequest = createXMLHttpRequest ( this ) ; // TODO: necessary for Blob and FileReader due to different-globals weirdness; investigate how to avoid this. this . ArrayBuffer = ArrayBuffer ; this . Int8Array = Int8Array ; this . Uint8Array = Uint8Array ; this . Uint8ClampedArray = Uint8ClampedArray ; this . Int16Array = Int16Array ; this . Uint16Array = Uint16Array ; this . Int32Array = Int32Array ; this . Uint32Array = Uint32Array ; this . Float32Array = Float32Array ; this . Float64Array = Float64Array ; this . stop = function ( ) { const manager = idlUtils . implForWrapper ( this . _document ) . _requestManager ; if ( manager ) { manager . close ( ) ; } } ; this . close = function ( ) { // Recursively close child frame windows, then ourselves. const currentWindow = this ; ( function windowCleaner ( windowToClean ) { for ( let i = 0 ; i < windowToClean . length ; i ++ ) { windowCleaner ( windowToClean [ i ] ) ; } // We\"re already in our own window.close(). if ( windowToClean !== currentWindow ) { windowToClean . close ( ) ; } } ( this ) ) ; // Clear out all listeners. Any in-flight or upcoming events should not get delivered. idlUtils . implForWrapper ( this ) . _eventListeners = Object . create ( null ) ; if ( this . _document ) { if ( this . _document . body ) { this . _document . body . innerHTML = \"\" ; } if ( this . _document . close ) { // It's especially important to clear out the listeners here because document.close() causes a \"load\" event to // fire. idlUtils . implForWrapper ( this . _document ) . _eventListeners = Object . create ( null ) ; this . _document . close ( ) ; } const doc = idlUtils . implForWrapper ( this . _document ) ; if ( doc . _requestManager ) { doc . _requestManager . close ( ) ; } delete this . _document ; } this . __stopAllTimers ( ) ; WebSocketImpl . cleanUpWindow ( this ) ; } ; this . getComputedStyle = function ( elt ) { elt = Element . convert ( elt ) ; const declaration = new CSSStyleDeclaration ( ) ; const { forEach , indexOf } = Array . prototype ; const { style } = elt ; function setPropertiesFromRule ( rule ) { if ( ! rule . selectorText ) { return ; } const cssSelectorSplitRe = / ((?:[^,\"']|\"[^\"]*\"|'[^']*')+) / ; const selectors = rule . selectorText . split ( cssSelectorSplitRe ) ; let matched = false ; for ( const selectorText of selectors ) { if ( selectorText !== \"\" && selectorText !== \",\" && ! matched && matchesDontThrow ( elt , selectorText ) ) { matched = true ; forEach . call ( rule . style , property => { declaration . setProperty ( property , rule . style . getPropertyValue ( property ) , rule . style . getPropertyPriority ( property ) ) ; } ) ; } } } function readStylesFromStyleSheet ( sheet ) { forEach . call ( sheet . cssRules , rule => { if ( rule . media ) { if ( indexOf . call ( rule . media , \"screen\" ) !== - 1 ) { forEach . call ( rule . cssRules , setPropertiesFromRule ) ; } } else { setPropertiesFromRule ( rule ) ; } } ) ; } if ( ! parsedDefaultStyleSheet ) { parsedDefaultStyleSheet = cssom . parse ( defaultStyleSheet ) ; } readStylesFromStyleSheet ( parsedDefaultStyleSheet ) ; forEach . call ( elt . ownerDocument . styleSheets , readStylesFromStyleSheet ) ; forEach . call ( style , property => { declaration . setProperty ( property , style . getPropertyValue ( property ) , style . getPropertyPriority ( property ) ) ; } ) ; return declaration ; } ; // The captureEvents() and releaseEvents() methods must do nothing this . captureEvents = function ( ) { } ; this . releaseEvents = function ( ) { } ; ///// PUBLIC DATA PROPERTIES (TODO: should be getters) function wrapConsoleMethod ( method ) { return ( ... args ) => { window . _virtualConsole . emit ( method , ... args ) ; } ; } this . console = { assert : wrapConsoleMethod ( \"assert\" ) , clear : wrapConsoleMethod ( \"clear\" ) , count : wrapConsoleMethod ( \"count\" ) , countReset : wrapConsoleMethod ( \"countReset\" ) , debug : wrapConsoleMethod ( \"debug\" ) , dir : wrapConsoleMethod ( \"dir\" ) , dirxml : wrapConsoleMethod ( \"dirxml\" ) , error : wrapConsoleMethod ( \"error\" ) , group : wrapConsoleMethod ( \"group\" ) , groupCollapsed : wrapConsoleMethod ( \"groupCollapsed\" ) , groupEnd : wrapConsoleMethod ( \"groupEnd\" ) , info : wrapConsoleMethod ( \"info\" ) , log : wrapConsoleMethod ( \"log\" ) , table : wrapConsoleMethod ( \"table\" ) , time : wrapConsoleMethod ( \"time\" ) , timeEnd : wrapConsoleMethod ( \"timeEnd\" ) , trace : wrapConsoleMethod ( \"trace\" ) , warn : wrapConsoleMethod ( \"warn\" ) } ; function notImplementedMethod ( name ) { return function ( ) { notImplemented ( name , window ) ; } ; } define ( this , { name : \"\" , status : \"\" , devicePixelRatio : 1 , innerWidth : 1024 , innerHeight : 768 , outerWidth : 1024 , outerHeight : 768 , pageXOffset : 0 , pageYOffset : 0 , screenX : 0 , screenLeft : 0 , screenY : 0 , screenTop : 0 , scrollX : 0 , scrollY : 0 , alert : notImplementedMethod ( \"window.alert\" ) , blur : notImplementedMethod ( \"window.blur\" ) , confirm : notImplementedMethod ( \"window.confirm\" ) , focus : notImplementedMethod ( \"window.focus\" ) , moveBy : notImplementedMethod ( \"window.moveBy\" ) , moveTo : notImplementedMethod ( \"window.moveTo\" ) , open : notImplementedMethod ( \"window.open\" ) , print : notImplementedMethod ( \"window.print\" ) , prompt : notImplementedMethod ( \"window.prompt\" ) , resizeBy : notImplementedMethod ( \"window.resizeBy\" ) , resizeTo : notImplementedMethod ( \"window.resizeTo\" ) , scroll : notImplementedMethod ( \"window.scroll\" ) , scrollBy : notImplementedMethod ( \"window.scrollBy\" ) , scrollTo : notImplementedMethod ( \"window.scrollTo\" ) } ) ; ///// INITIALIZATION process . nextTick ( ( ) => { if ( ! window . document ) { return ; // window might've been closed already } if ( window . document . readyState === \"complete\" ) { fireAnEvent ( \"load\" , window , undefined , { } , window . document ) ; } else { window . document . addEventListener ( \"load\" , ( ) => { fireAnEvent ( \"load\" , window , undefined , { } , window . document ) ; if ( ! idlUtils . implForWrapper ( window . _document ) . _pageShowingFlag ) { idlUtils . implForWrapper ( window . _document ) . _pageShowingFlag = true ; fireAnEvent ( \"pageshow\" , window , PageTransitionEvent , { persisted : false } , window . document ) ; } } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #concept - tree - host - including - inclusive - ancestor [CODESPLIT] function isHostInclusiveAncestor ( nodeImplA , nodeImplB ) { for ( const ancestor of domSymbolTree . ancestorsIterator ( nodeImplB ) ) { if ( ancestor === nodeImplA ) { return true ; } } const rootImplB = getRoot ( nodeImplB ) ; if ( rootImplB . _host ) { return isHostInclusiveAncestor ( nodeImplA , rootImplB . _host ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Until webidl2js gains support for checking for Window this would have to do . [CODESPLIT] function isWindow ( val ) { if ( typeof val !== \"object\" ) { return false ; } const wrapper = idlUtils . wrapperForImpl ( val ) ; if ( typeof wrapper === \"object\" ) { return wrapper === wrapper . _globalProxy ; } // `val` may be either impl or wrapper currently, because webidl2js currently unwraps Window objects (and their global // proxies) to their underlying EventTargetImpl during conversion, which is not what we want. But at the same time, // some internal usage call this constructor with the actual global proxy. return isWindow ( idlUtils . implForWrapper ( val ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return a request client object or an event emitter matching the same behaviour for unsupported protocols the callback should be called with a request response object or an event emitter matching the same behaviour too [CODESPLIT] function createClient ( xhr ) { const flag = xhr [ xhrSymbols . flag ] ; const properties = xhr [ xhrSymbols . properties ] ; const urlObj = new URL ( flag . uri ) ; const uri = urlObj . href ; const ucMethod = flag . method . toUpperCase ( ) ; const { requestManager } = flag ; if ( urlObj . protocol === \"file:\" ) { const response = new EventEmitter ( ) ; response . statusCode = 200 ; response . rawHeaders = [ ] ; response . headers = { } ; response . request = { uri : urlObj } ; const filePath = urlObj . pathname . replace ( / ^file:\\/\\/ / , \"\" ) . replace ( / ^\\/([a-z]):\\/ / i , \"$1:/\" ) . replace ( / %20 / g , \" \" ) ; const client = new EventEmitter ( ) ; const readableStream = fs . createReadStream ( filePath , { encoding : null } ) ; readableStream . on ( \"data\" , chunk => { response . emit ( \"data\" , chunk ) ; client . emit ( \"data\" , chunk ) ; } ) ; readableStream . on ( \"end\" , ( ) => { response . emit ( \"end\" ) ; client . emit ( \"end\" ) ; } ) ; readableStream . on ( \"error\" , err => { client . emit ( \"error\" , err ) ; } ) ; client . abort = function ( ) { readableStream . destroy ( ) ; client . emit ( \"abort\" ) ; } ; if ( requestManager ) { const req = { abort ( ) { properties . abortError = true ; xhr . abort ( ) ; } } ; requestManager . add ( req ) ; const rmReq = requestManager . remove . bind ( requestManager , req ) ; client . on ( \"abort\" , rmReq ) ; client . on ( \"error\" , rmReq ) ; client . on ( \"end\" , rmReq ) ; } process . nextTick ( ( ) => client . emit ( \"response\" , response ) ) ; return client ; } if ( urlObj . protocol === \"data:\" ) { const response = new EventEmitter ( ) ; response . request = { uri : urlObj } ; const client = new EventEmitter ( ) ; let buffer ; try { const parsed = parseDataURL ( uri ) ; const contentType = parsed . mimeType . toString ( ) ; buffer = parsed . body ; response . statusCode = 200 ; response . rawHeaders = [ \"Content-Type\" , contentType ] ; response . headers = { \"content-type\" : contentType } ; } catch ( err ) { process . nextTick ( ( ) => client . emit ( \"error\" , err ) ) ; return client ; } client . abort = ( ) => { // do nothing } ; process . nextTick ( ( ) => { client . emit ( \"response\" , response ) ; process . nextTick ( ( ) => { response . emit ( \"data\" , buffer ) ; client . emit ( \"data\" , buffer ) ; response . emit ( \"end\" ) ; client . emit ( \"end\" ) ; } ) ; } ) ; return client ; } const requestHeaders = { } ; for ( const header in flag . requestHeaders ) { requestHeaders [ header ] = flag . requestHeaders [ header ] ; } if ( getRequestHeader ( flag . requestHeaders , \"referer\" ) === null ) { requestHeaders . Referer = flag . referrer ; } if ( getRequestHeader ( flag . requestHeaders , \"user-agent\" ) === null ) { requestHeaders [ \"User-Agent\" ] = flag . userAgent ; } if ( getRequestHeader ( flag . requestHeaders , \"accept-language\" ) === null ) { requestHeaders [ \"Accept-Language\" ] = \"en\" ; } if ( getRequestHeader ( flag . requestHeaders , \"accept\" ) === null ) { requestHeaders . Accept = \"*/*\" ; } const crossOrigin = flag . origin !== urlObj . origin ; if ( crossOrigin ) { requestHeaders . Origin = flag . origin ; } const options = { uri , method : flag . method , headers : requestHeaders , gzip : true , maxRedirects : 21 , followAllRedirects : true , encoding : null , strictSSL : flag . strictSSL , proxy : flag . proxy , forever : true } ; if ( flag . auth ) { options . auth = { user : flag . auth . user || \"\" , pass : flag . auth . pass || \"\" , sendImmediately : false } ; } if ( flag . cookieJar && ( ! crossOrigin || flag . withCredentials ) ) { options . jar = wrapCookieJarForRequest ( flag . cookieJar ) ; } const { body } = flag ; const hasBody = body !== undefined && body !== null && body !== \"\" && ! ( ucMethod === \"HEAD\" || ucMethod === \"GET\" ) ; if ( hasBody && ! flag . formData ) { options . body = body ; } if ( hasBody && getRequestHeader ( flag . requestHeaders , \"content-type\" ) === null ) { requestHeaders [ \"Content-Type\" ] = \"text/plain;charset=UTF-8\" ; } function doRequest ( ) { try { const client = request ( options ) ; if ( hasBody && flag . formData ) { const form = client . form ( ) ; for ( const entry of body ) { form . append ( entry . name , entry . value , entry . options ) ; } } return client ; } catch ( e ) { const client = new EventEmitter ( ) ; process . nextTick ( ( ) => client . emit ( \"error\" , e ) ) ; return client ; } } let client ; const nonSimpleHeaders = Object . keys ( flag . requestHeaders ) . filter ( header => ! simpleHeaders . has ( header . toLowerCase ( ) ) ) ; if ( crossOrigin && ( ! simpleMethods . has ( ucMethod ) || nonSimpleHeaders . length > 0 || properties . uploadListener ) ) { client = new EventEmitter ( ) ; const preflightRequestHeaders = [ ] ; for ( const header in requestHeaders ) { // the only existing request headers the cors spec allows on the preflight request are Origin and Referrer const lcHeader = header . toLowerCase ( ) ; if ( lcHeader === \"origin\" || lcHeader === \"referrer\" ) { preflightRequestHeaders [ header ] = requestHeaders [ header ] ; } } preflightRequestHeaders [ \"Access-Control-Request-Method\" ] = flag . method ; if ( nonSimpleHeaders . length > 0 ) { preflightRequestHeaders [ \"Access-Control-Request-Headers\" ] = nonSimpleHeaders . join ( \", \" ) ; } preflightRequestHeaders [ \"User-Agent\" ] = flag . userAgent ; flag . preflight = true ; const preflightOptions = { uri , method : \"OPTIONS\" , headers : preflightRequestHeaders , followRedirect : false , encoding : null , pool : flag . pool , strictSSL : flag . strictSSL , proxy : flag . proxy , forever : true } ; const preflightClient = request ( preflightOptions ) ; preflightClient . on ( \"response\" , resp => { // don't send the real request if the preflight request returned an error if ( resp . statusCode < 200 || resp . statusCode > 299 ) { client . emit ( \"error\" , new Error ( \"Response for preflight has invalid HTTP status code \" + resp . statusCode ) ) ; return ; } // don't send the real request if we aren't allowed to use the headers if ( ! validCORSPreflightHeaders ( xhr , resp , flag , properties ) ) { setResponseToNetworkError ( xhr ) ; return ; } const realClient = doRequest ( ) ; realClient . on ( \"response\" , res => { for ( const header in resp . headers ) { if ( preflightHeaders . has ( header ) ) { res . headers [ header ] = Object . prototype . hasOwnProperty . call ( res . headers , header ) ? mergeHeaders ( res . headers [ header ] , resp . headers [ header ] ) : resp . headers [ header ] ; } } client . emit ( \"response\" , res ) ; } ) ; realClient . on ( \"data\" , chunk => client . emit ( \"data\" , chunk ) ) ; realClient . on ( \"end\" , ( ) => client . emit ( \"end\" ) ) ; realClient . on ( \"abort\" , ( ) => client . emit ( \"abort\" ) ) ; realClient . on ( \"request\" , req => { client . headers = realClient . headers ; client . emit ( \"request\" , req ) ; } ) ; realClient . on ( \"redirect\" , ( ) => { client . response = realClient . response ; client . emit ( \"redirect\" ) ; } ) ; realClient . on ( \"error\" , err => client . emit ( \"error\" , err ) ) ; client . abort = ( ) => { realClient . abort ( ) ; } ; } ) ; preflightClient . on ( \"error\" , err => client . emit ( \"error\" , err ) ) ; client . abort = ( ) => { preflightClient . abort ( ) ; } ; } else { client = doRequest ( ) ; } if ( requestManager ) { const req = { abort ( ) { properties . abortError = true ; xhr . abort ( ) ; } } ; requestManager . add ( req ) ; const rmReq = requestManager . remove . bind ( requestManager , req ) ; client . on ( \"abort\" , rmReq ) ; client . on ( \"error\" , rmReq ) ; client . on ( \"end\" , rmReq ) ; } return client ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // w3c . github . io / DOM - Parsing / #dfn - fragment - parsing - algorithm [CODESPLIT] function parseFragment ( markup , contextElement ) { const { _parsingMode } = contextElement . _ownerDocument ; let parseAlgorithm ; if ( _parsingMode === \"html\" ) { parseAlgorithm = htmlParser . parseFragment ; } else if ( _parsingMode === \"xml\" ) { parseAlgorithm = xmlParser . parseFragment ; } // Note: HTML and XML fragment parsing algorithm already return a document fragments; no need to do steps 3 and 4 return parseAlgorithm ( markup , contextElement ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * eslint - disable no - console / * eslint - disable no - invalid - this [CODESPLIT] function onError ( event ) { const bench = event . target ; console . error ( \"Error in benchmark\" , bench . name , \":\" , bench . error ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // html . spec . whatwg . org / multipage / webappapis . html#report - the - error Omits script parameter and any check for muted errors . Takes target as an EventTarget impl . Takes error object message and location as params unlike the spec . Returns whether the event was handled or not . [CODESPLIT] function reportAnError ( line , col , target , errorObject , message , location ) { if ( target [ errorReportingMode ] ) { return false ; } target [ errorReportingMode ] = true ; const event = createAnEvent ( \"error\" , ErrorEvent , { cancelable : true , message , filename : location , lineno : line , colno : col , error : errorObject } ) ; try { target . _dispatch ( event ) ; } finally { target [ errorReportingMode ] = false ; return event . defaultPrevented ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // html . spec . whatwg . org / multipage / links . html#link - type - stylesheet [CODESPLIT] function maybeFetchAndProcess ( el ) { if ( ! isExternalResourceLink ( el ) ) { return ; } // Browsing-context connected if ( ! el . isConnected || ! el . _ownerDocument . _defaultView ) { return ; } fetchAndProcess ( el ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // html . spec . whatwg . org / multipage / semantics . html#default - fetch - and - process - the - linked - resource TODO : refactor into general link - fetching like the spec . [CODESPLIT] function fetchAndProcess ( el ) { const href = el . getAttributeNS ( null , \"href\" ) ; if ( href === null || href === \"\" ) { return ; } const url = parseURLToResultingURLRecord ( href , el . _ownerDocument ) ; if ( url === null ) { return ; } // TODO handle crossorigin=\"\", nonce, integrity=\"\", referrerpolicy=\"\" const serialized = whatwgURL . serializeURL ( url ) ; fetchStylesheet ( el , serialized ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #concept - slotable [CODESPLIT] function isSlotable ( nodeImpl ) { return nodeImpl && ( nodeImpl . nodeType === NODE_TYPE . ELEMENT_NODE || nodeImpl . nodeType === NODE_TYPE . TEXT_NODE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #concept - shadow - including - inclusive - ancestor [CODESPLIT] function isShadowInclusiveAncestor ( ancestor , node ) { while ( isNode ( node ) ) { if ( node === ancestor ) { return true ; } if ( isShadowRoot ( node ) ) { node = node . host ; } else { node = domSymbolTree . parent ( node ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #retarget [CODESPLIT] function retarget ( a , b ) { while ( true ) { if ( ! isNode ( a ) ) { return a ; } const aRoot = getRoot ( a ) ; if ( ! isShadowRoot ( aRoot ) || ( isNode ( b ) && isShadowInclusiveAncestor ( aRoot , b ) ) ) { return a ; } a = getRoot ( a ) . host ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #concept - shadow - including - root [CODESPLIT] function shadowIncludingRoot ( node ) { const root = getRoot ( node ) ; return isShadowRoot ( root ) ? shadowIncludingRoot ( root . host ) : root ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #assign - slotables [CODESPLIT] function assignSlotable ( slot ) { const slotables = findSlotable ( slot ) ; let shouldFireSlotChange = false ; if ( slotables . length !== slot . _assignedNodes . length ) { shouldFireSlotChange = true ; } else { for ( let i = 0 ; i < slotables . length ; i ++ ) { if ( slotables [ i ] !== slot . _assignedNodes [ i ] ) { shouldFireSlotChange = true ; break ; } } } if ( shouldFireSlotChange ) { signalSlotChange ( slot ) ; } slot . _assignedNodes = slotables ; for ( const slotable of slotables ) { slotable . _assignedSlot = slot ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #assign - slotables - for - a - tree [CODESPLIT] function assignSlotableForTree ( root ) { for ( const slot of domSymbolTree . treeIterator ( root ) ) { if ( isSlot ( slot ) ) { assignSlotable ( slot ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #find - slotables [CODESPLIT] function findSlotable ( slot ) { const result = [ ] ; const root = getRoot ( slot ) ; if ( ! isShadowRoot ( root ) ) { return result ; } for ( const slotable of domSymbolTree . treeIterator ( root . host ) ) { const foundSlot = findSlot ( slotable ) ; if ( foundSlot === slot ) { result . push ( slotable ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #find - flattened - slotables [CODESPLIT] function findFlattenedSlotables ( slot ) { const result = [ ] ; const root = getRoot ( slot ) ; if ( ! isShadowRoot ( root ) ) { return result ; } const slotables = findSlotable ( slot ) ; if ( slotables . length === 0 ) { for ( const child of domSymbolTree . childrenIterator ( slot ) ) { if ( isSlotable ( child ) ) { slotables . push ( child ) ; } } } for ( const node of slotables ) { if ( isSlot ( node ) && isShadowRoot ( getRoot ( node ) ) ) { const temporaryResult = findFlattenedSlotables ( node ) ; result . push ( ... temporaryResult ) ; } else { result . push ( node ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #find - a - slot [CODESPLIT] function findSlot ( slotable , openFlag ) { const { parentNode : parent } = slotable ; if ( ! parent ) { return null ; } const shadow = parent . _shadowRoot ; if ( ! shadow || ( openFlag && shadow . mode !== \"open\" ) ) { return null ; } for ( const child of domSymbolTree . treeIterator ( shadow ) ) { if ( isSlot ( child ) && child . name === slotable . _slotableName ) { return child ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #signal - a - slot - change [CODESPLIT] function signalSlotChange ( slot ) { if ( ! signalSlotList . some ( entry => entry === slot ) ) { signalSlotList . push ( slot ) ; } queueMutationObserverMicrotask ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // html . spec . whatwg . org / #scroll - to - fragid [CODESPLIT] function navigateToFragment ( window , newURL , flags ) { const document = idlUtils . implForWrapper ( window . _document ) ; window . _sessionHistory . clearHistoryTraversalTasks ( ) ; if ( ! flags . replacement ) { // handling replacement=true here deviates from spec, but matches real browser behaviour // see https://github.com/whatwg/html/issues/2796 for spec bug window . _sessionHistory . removeAllEntriesAfterCurrentEntry ( ) ; } const newEntry = { document , url : newURL } ; window . _sessionHistory . addEntryAfterCurrentEntry ( newEntry ) ; window . _sessionHistory . traverseHistory ( newEntry , { nonBlockingEvents : true , replacement : flags . replacement } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #concept - event - listener - invoke [CODESPLIT] function invokeEventListeners ( tuple , eventImpl ) { const tupleIndex = eventImpl . _path . indexOf ( tuple ) ; for ( let i = tupleIndex ; i >= 0 ; i -- ) { const t = eventImpl . _path [ i ] ; if ( t . target ) { eventImpl . target = t . target ; break ; } } eventImpl . relatedTarget = idlUtils . wrapperForImpl ( tuple . relatedTarget ) ; if ( eventImpl . _stopPropagationFlag ) { return ; } eventImpl . currentTarget = idlUtils . wrapperForImpl ( tuple . item ) ; const listeners = tuple . item . _eventListeners ; innerInvokeEventListeners ( eventImpl , listeners ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #concept - event - listener - inner - invoke [CODESPLIT] function innerInvokeEventListeners ( eventImpl , listeners ) { let found = false ; const { type , target } = eventImpl ; const wrapper = idlUtils . wrapperForImpl ( target ) ; if ( ! listeners || ! listeners [ type ] ) { return found ; } // Copy event listeners before iterating since the list can be modified during the iteration. const handlers = listeners [ type ] . slice ( ) ; for ( let i = 0 ; i < handlers . length ; i ++ ) { const listener = handlers [ i ] ; const { capture , once , passive } = listener . options ; // Check if the event listener has been removed since the listeners has been cloned. if ( ! listeners [ type ] . includes ( listener ) ) { continue ; } found = true ; if ( ( eventImpl . eventPhase === Event . CAPTURING_PHASE && ! capture ) || ( eventImpl . eventPhase === Event . BUBBLING_PHASE && capture ) ) { continue ; } if ( once ) { listeners [ type ] . splice ( listeners [ type ] . indexOf ( listener ) , 1 ) ; } if ( passive ) { eventImpl . _inPassiveListenerFlag = true ; } try { if ( typeof listener . callback === \"object\" ) { if ( typeof listener . callback . handleEvent === \"function\" ) { listener . callback . handleEvent ( idlUtils . wrapperForImpl ( eventImpl ) ) ; } } else { listener . callback . call ( eventImpl . currentTarget , idlUtils . wrapperForImpl ( eventImpl ) ) ; } } catch ( e ) { let window = null ; if ( wrapper && wrapper . _document ) { // Triggered by Window window = wrapper ; } else if ( target . _ownerDocument ) { // Triggered by most webidl2js'ed instances window = target . _ownerDocument . _defaultView ; } else if ( wrapper . _ownerDocument ) { // Currently triggered by XHR and some other non-webidl2js things window = wrapper . _ownerDocument . _defaultView ; } if ( window ) { reportException ( window , e ) ; } // Errors in window-less documents just get swallowed... can you think of anything better? } eventImpl . _inPassiveListenerFlag = false ; if ( eventImpl . _stopImmediatePropagationFlag ) { return found ; } } return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize the event listeners options argument in order to get always a valid options object [CODESPLIT] function normalizeEventHandlerOptions ( options , defaultBoolKeys ) { const returnValue = { } ; // no need to go further here if ( typeof options === \"boolean\" || options === null || typeof options === \"undefined\" ) { returnValue . capture = Boolean ( options ) ; return returnValue ; } // non objects options so we typecast its value as \"capture\" value if ( typeof options !== \"object\" ) { returnValue . capture = Boolean ( options ) ; // at this point we don't need to loop the \"capture\" key anymore defaultBoolKeys = defaultBoolKeys . filter ( k => k !== \"capture\" ) ; } for ( const key of defaultBoolKeys ) { returnValue [ key ] = Boolean ( options [ key ] ) ; } return returnValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #concept - event - path - append [CODESPLIT] function appendToEventPath ( eventImpl , target , targetOverride , relatedTarget , touchTargets , slotInClosedTree ) { const itemInShadowTree = isNode ( target ) && isShadowRoot ( getRoot ( target ) ) ; const rootOfClosedTree = isShadowRoot ( target ) && target . mode === \"closed\" ; eventImpl . _path . push ( { item : target , itemInShadowTree , target : targetOverride , relatedTarget , touchTargets , rootOfClosedTree , slotInClosedTree } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #queue - a - mutation - record [CODESPLIT] function queueMutationRecord ( type , target , name , namespace , oldValue , addedNodes , removedNodes , previousSibling , nextSibling ) { const interestedObservers = new Map ( ) ; const nodes = domSymbolTree . ancestorsToArray ( target ) ; for ( const node of nodes ) { for ( const registered of node . _registeredObserverList ) { const { options , observer : mo } = registered ; if ( ! ( node !== target && options . subtree === false ) && ! ( type === MUTATION_TYPE . ATTRIBUTES && options . attributes !== true ) && ! ( type === MUTATION_TYPE . ATTRIBUTES && options . attributeFilter && ! options . attributeFilter . some ( value => value === name || value === namespace ) ) && ! ( type === MUTATION_TYPE . CHARACTER_DATA && options . characterData !== true ) && ! ( type === MUTATION_TYPE . CHILD_LIST && options . childList === false ) ) { if ( ! interestedObservers . has ( mo ) ) { interestedObservers . set ( mo , null ) ; } if ( ( type === MUTATION_TYPE . ATTRIBUTES && options . attributeOldValue === true ) || ( type === MUTATION_TYPE . CHARACTER_DATA && options . characterDataOldValue === true ) ) { interestedObservers . set ( mo , oldValue ) ; } } } } for ( const [ observer , mappedOldValue ] of interestedObservers . entries ( ) ) { const record = MutationRecord . createImpl ( [ ] , { type , target , attributeName : name , attributeNamespace : namespace , oldValue : mappedOldValue , addedNodes , removedNodes , previousSibling , nextSibling } ) ; observer . _recordQueue . push ( record ) ; activeMutationObservers . add ( observer ) ; } queueMutationObserverMicrotask ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #queue - a - tree - mutation - record [CODESPLIT] function queueTreeMutationRecord ( target , addedNodes , removedNodes , previousSibling , nextSibling ) { queueMutationRecord ( MUTATION_TYPE . CHILD_LIST , target , null , null , null , addedNodes , removedNodes , previousSibling , nextSibling ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #queue - an - attribute - mutation - record [CODESPLIT] function queueAttributeMutationRecord ( target , name , namespace , oldValue ) { queueMutationRecord ( MUTATION_TYPE . ATTRIBUTES , target , name , namespace , oldValue , [ ] , [ ] , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #notify - mutation - observers [CODESPLIT] function notifyMutationObservers ( ) { mutationObserverMicrotaskQueueFlag = false ; const notifyList = [ ... activeMutationObservers ] . sort ( ( a , b ) => a . _id - b . _id ) ; activeMutationObservers . clear ( ) ; const signalList = [ ... signalSlotList ] ; signalSlotList . splice ( 0 , signalSlotList . length ) ; for ( const mo of notifyList ) { const records = [ ... mo . _recordQueue ] ; mo . _recordQueue = [ ] ; for ( const node of mo . _nodeList ) { node . _registeredObserverList = node . _registeredObserverList . filter ( registeredObserver => { return registeredObserver . source !== mo ; } ) ; if ( records . length ) { try { mo . _callback ( records . map ( idlUtils . wrapperForImpl ) , idlUtils . wrapperForImpl ( mo ) ) ; } catch ( e ) { const { target } = records [ 0 ] ; const window = target . _ownerDocument . _defaultView ; reportException ( window , e ) ; } } } } for ( const slot of signalList ) { const slotChangeEvent = Event . createImpl ( [ \"slotchange\" , { bubbles : true } ] , { isTrusted : true } ) ; slot . _dispatch ( slotChangeEvent ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // drafts . csswg . org / cssom / #add - a - css - style - sheet [CODESPLIT] function addStylesheet ( sheet , elementImpl ) { elementImpl . _ownerDocument . styleSheets . push ( sheet ) ; // Set the association explicitly; in the spec it's implicit. elementImpl . sheet = sheet ; // TODO: title and disabled stuff }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO this is actually really messed up and overwrites the sheet on elementImpl Tracking in https : // github . com / tmpvar / jsdom / issues / 2124 [CODESPLIT] function scanForImportRules ( elementImpl , cssRules , baseURL ) { if ( ! cssRules ) { return ; } for ( let i = 0 ; i < cssRules . length ; ++ i ) { if ( cssRules [ i ] . cssRules ) { // @media rule: keep searching inside it. scanForImportRules ( elementImpl , cssRules [ i ] . cssRules , baseURL ) ; } else if ( cssRules [ i ] . href ) { // @import rule: fetch the resource and evaluate it. // See http://dev.w3.org/csswg/cssom/#css-import-rule //     If loading of the style sheet fails its cssRules list is simply //     empty. I.e. an @import rule always has an associated style sheet. const parsed = whatwgURL . parseURL ( cssRules [ i ] . href , { baseURL } ) ; if ( parsed === null ) { const window = elementImpl . _ownerDocument . _defaultView ; if ( window ) { const error = new Error ( ` ${ cssRules [ i ] . href } ` + ` ${ whatwgURL . serializeURL ( baseURL ) } ` ) ; error . type = \"css @import URL parsing\" ; window . _virtualConsole . emit ( \"jsdomError\" , error ) ; } } else { fetchStylesheetInternal ( elementImpl , whatwgURL . serializeURL ( parsed ) , parsed ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Necessary because Date . UTC () treats year within [ 0 99 ] as [ 1900 1999 ] . [CODESPLIT] function getUTCMs ( year , month = 1 , day = 1 , hour = 0 , minute = 0 , second = 0 , millisecond = 0 ) { if ( year > 99 || year < 0 ) { return Date . UTC ( year , month - 1 , day , hour , minute , second , millisecond ) ; } const d = new Date ( 0 ) ; d . setUTCFullYear ( year ) ; d . setUTCMonth ( month - 1 ) ; d . setUTCDate ( day ) ; d . setUTCHours ( hour ) ; d . setUTCMinutes ( minute ) ; d . setUTCSeconds ( second , millisecond ) ; return d . valueOf ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generate SUMMARY . md by config . json [CODESPLIT] function sammary ( ) { const nodeFn = function ( { parentPaths , lang , item , isDir , result } ) { const navTitle = generateNavTitle ( { parentPaths , item , sign : isDir ? '-' : '*' , lang } ) ; result . push ( navTitle ) ; } ; langs . forEach ( dir => { const SUMMARY = 'SUMMARY.md' ; const targetFile = path . join ( docsDir , ` ${ dir } ${ SUMMARY } ` ) ; const result = walk ( { catalog : docConfig . catalog , lang : dir , result : [ ] , parentPaths : [ ] , fn : nodeFn } ) ; if ( result && result . length ) { result . unshift ( '# whistle\\n' ) ; fs . writeFileSync ( targetFile , result . join ( '\\n' ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "如果超过最大缓存数，清理如下请求数据： 1 . 已经请求结束且结束时间超过10秒 2 . 请求#1前面的未结束且未被ui读取过的请求 [CODESPLIT] function clearCache ( ) { var overflow = frames . length - MAX_FRAMES_LENGTH ; overflow > 0 && frames . splice ( 0 , overflow + 60 ) ; var len = ids . length ; if ( len <= MAX_LENGTH ) { return ; } var now = Date . now ( ) ; var _ids = [ ] ; var preserveLen = len ; overflow = - 1 ; if ( len >= OVERFLOW_LENGTH ) { overflow = len - MAX_CACHE_SIZE ; preserveLen = len - PRESERVE_LEN ; } for ( var i = 0 ; i < len ; i ++ ) { var id = ids [ i ] ; var curData = reqData [ id ] ; if ( i > overflow && ( i >= preserveLen || ( curData . endTime ? now - curData . endTime < CACHE_TIME : now - curData . startTime < CACHE_TIMEOUT ) ) ) { if ( curData . endTime && curData . abort ) { delete curData . abort ; } _ids . push ( id ) ; } else { delete reqData [ id ] ; } } ids = _ids ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "options : { startTime : timestamp || timestamp + - + count count : 获取新数据的数量 ids : 请未结束的id列表 } [CODESPLIT] function formatFilter ( filter , clientIp ) { if ( ! filter . url && ! filter . name && ! filter . value && ! filter . ip ) { return ; } var url = util . trimStr ( filter . url ) . toLowerCase ( ) ; var name = util . trimStr ( filter . name ) . toLowerCase ( ) ; var value = util . trimStr ( filter . value ) . toLowerCase ( ) ; var ip = util . trimStr ( filter . ip ) ; var list = [ ] ; if ( ip === 'self' ) { ip = clientIp ; } else if ( ip && ! net . isIP ( ip ) ) { ip . split ( ',' ) . forEach ( function ( item ) { item = item . trim ( ) ; if ( item === 'self' ) { item = clientIp ; } if ( net . isIP ( item ) && list . indexOf ( item ) === - 1 ) { list . push ( item ) ; } } ) ; ip = null ; } var result ; if ( url ) { result = { } ; result . url = url ; } if ( name && value ) { result = result || { } ; result . name = name ; result . value = value ; } if ( ip ) { result = result || { } ; result . ip = ip ; } if ( list . length ) { result = result || { } ; result . ipList = list . slice ( 0 , 16 ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rules [CODESPLIT] function resolveInlineValues ( str ) { str = str && str . replace ( CONTROL_RE , '' ) . trim ( ) ; if ( ! str || str . indexOf ( '```' ) === - 1 ) { return str ; } return str . replace ( MULTI_LINE_VALUE_RE , function ( _ , __ , key , value ) { inlineValues = inlineValues || { } ; if ( ! inlineValues [ key ] ) { inlineValues [ key ] = value ; } return '' ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * eslint no - console : off [CODESPLIT] function ( message , filename , lineno , colno , error ) { if ( error ) { wConsole . error ( getErrorStack ( error , message ) ) ; } else { wConsole . error ( 'Error: ' + message + '(' + filename + ':' + lineno + ':' + ( colno || 0 ) + ')' + getPageInfo ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders nested values ( eg . objects arrays lists etc . ) [CODESPLIT] function renderChildNodes ( props , from , to ) { var nodeType = props . nodeType , data = props . data , collectionLimit = props . collectionLimit , circularCache = props . circularCache , keyPath = props . keyPath , postprocessValue = props . postprocessValue , sortObjectKeys = props . sortObjectKeys ; var childNodes = [ ] ; ( 0 , _getCollectionEntries2 [ 'default' ] ) ( nodeType , data , sortObjectKeys , collectionLimit , from , to ) . forEach ( function ( entry ) { if ( entry . to ) { childNodes . push ( _react2 [ 'default' ] . createElement ( _ItemRange2 [ 'default' ] , ( 0 , _extends3 [ 'default' ] ) ( { } , props , { key : 'ItemRange--' + entry . from + '-' + entry . to , from : entry . from , to : entry . to , renderChildNodes : renderChildNodes } ) ) ) ; } else { var key = entry . key , value = entry . value ; var isCircular = circularCache . indexOf ( value ) !== - 1 ; var node = _react2 [ 'default' ] . createElement ( _JSONNode2 [ 'default' ] , ( 0 , _extends3 [ 'default' ] ) ( { } , props , { postprocessValue : postprocessValue , collectionLimit : collectionLimit } , { key : 'Node--' + key , keyPath : [ key ] . concat ( keyPath ) , value : postprocessValue ( value ) , circularCache : [ ] . concat ( circularCache , [ value ] ) , isCircular : isCircular , hideRoot : false } ) ) ; if ( node !== false ) { childNodes . push ( node ) ; } } } ) ; return childNodes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the n Items string for this node generating and caching it if it hasn t been created yet . [CODESPLIT] function createItemString ( data , limit ) { var count = 0 ; var hasMore = false ; if ( ( 0 , _isSafeInteger2 [ 'default' ] ) ( data . size ) ) { count = data . size ; } else { for ( var _iterator = data , _isArray = Array . isArray ( _iterator ) , _i = 0 , _iterator = _isArray ? _iterator : ( 0 , _getIterator3 [ 'default' ] ) ( _iterator ) ; ; ) { var _ref ; if ( _isArray ) { if ( _i >= _iterator . length ) break ; _ref = _iterator [ _i ++ ] ; } else { _i = _iterator . next ( ) ; if ( _i . done ) break ; _ref = _i . value ; } var entry = _ref ; // eslint-disable-line no-unused-vars if ( limit && count + 1 > limit ) { hasMore = true ; break ; } count += 1 ; } } return '' + ( hasMore ? '>' : '' ) + count + ' ' + ( count !== 1 ? 'entries' : 'entry' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures <JSONNestedNode > to render an iterable [CODESPLIT] function JSONIterableNode ( _ref2 ) { var props = ( 0 , _objectWithoutProperties3 [ 'default' ] ) ( _ref2 , [ ] ) ; return _react2 [ 'default' ] . createElement ( _JSONNestedNode2 [ 'default' ] , ( 0 , _extends3 [ 'default' ] ) ( { } , props , { nodeType : 'Iterable' , nodeTypeIndicator : '()' , createItemString : createItemString } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "first : xxxx xxxx? xxx?xxxx second : ?xxx xxx?xxxx [CODESPLIT] function join ( first , second ) { if ( ! first || ! second ) { return first + second ; } var firstIndex = first . indexOf ( '?' ) ; var secondIndex = second . indexOf ( '?' ) ; var firstQuery = '' ; var secondQuery = '' ; if ( firstIndex != - 1 ) { firstQuery = first . substring ( firstIndex ) ; first = first . substring ( 0 , firstIndex ) ; } if ( secondIndex != - 1 ) { secondQuery = second . substring ( secondIndex ) ; second = second . substring ( 0 , secondIndex ) ; } var query = firstQuery && secondQuery ? firstQuery + secondQuery . substring ( 1 ) : ( firstQuery || secondQuery ) ; if ( second ) { var lastIndex = first . length - 1 ; var startWithSep = isPathSeparator ( second [ 0 ] ) ; if ( isPathSeparator ( first [ lastIndex ] ) ) { first = startWithSep ? first . substring ( 0 , lastIndex ) + second : first + second ; } else { first = first + ( startWithSep ? '' : '/' ) + second ; } } return WEB_PROTOCOL_RE . test ( first ) ? formatUrl ( first + query ) : first + query ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "处理请求数据 [CODESPLIT] function handleReq ( req , data ) { var method = util . getMethod ( data . method || req . method ) ; req . method = method ; req . timeout = parseInt ( data . timeout , 10 ) ; extend ( req . headers , data . headers ) ; if ( typeof data . charset == 'string' ) { var type = req . headers [ 'content-type' ] ; var charset = '; charset=' + data . charset ; if ( typeof type == 'string' ) { req . headers [ 'content-type' ] = type . split ( ';' ) [ 0 ] + charset ; } else { req . headers [ 'content-type' ] = charset ; } } else { delete data . charset ; } if ( ! util . hasRequestBody ( method ) ) { delete data . top ; delete data . bottom ; delete data . body ; delete req . headers [ 'content-length' ] ; } else if ( data . top || data . bottom || data . body ) { delete req . headers [ 'content-length' ] ; } util . isWhistleTransformData ( data ) && req . addZipTransform ( new WhistleTransform ( data ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "构造函数 / 实例初始化 Constructor / instance initialization [CODESPLIT] function ( id , options ) { options = options || { } ; if ( typeof id === \"object\" ) { options = id ; } var _this = this ; var classPrefix = this . classPrefix = editormd . classPrefix ; var settings = this . settings = $ . extend ( true , editormd . defaults , options ) ; id = ( typeof id === \"object\" ) ? settings . id : id ; var editor = this . editor = $ ( \"#\" + id ) ; this . id = id ; this . lang = settings . lang ; var classNames = this . classNames = { textarea : { html : classPrefix + \"html-textarea\" , markdown : classPrefix + \"markdown-textarea\" } } ; settings . pluginPath = ( settings . pluginPath === \"\" ) ? settings . path + \"../plugins/\" : settings . pluginPath ; this . state . watching = ( settings . watch ) ? true : false ; if ( ! editor . hasClass ( \"editormd\" ) ) { editor . addClass ( \"editormd\" ) ; } editor . css ( { width : ( typeof settings . width === \"number\" ) ? settings . width + \"px\" : settings . width , height : ( typeof settings . height === \"number\" ) ? settings . height + \"px\" : settings . height } ) ; if ( settings . autoHeight ) { editor . css ( \"height\" , \"auto\" ) ; } var markdownTextarea = this . markdownTextarea = editor . children ( \"textarea\" ) ; if ( markdownTextarea . length < 1 ) { editor . append ( \"<textarea></textarea>\" ) ; markdownTextarea = this . markdownTextarea = editor . children ( \"textarea\" ) ; } markdownTextarea . addClass ( classNames . textarea . markdown ) . attr ( \"placeholder\" , settings . placeholder ) ; if ( typeof markdownTextarea . attr ( \"name\" ) === \"undefined\" || markdownTextarea . attr ( \"name\" ) === \"\" ) { markdownTextarea . attr ( \"name\" , ( settings . name !== \"\" ) ? settings . name : id + \"-markdown-doc\" ) ; } var appendElements = [ ( ! settings . readOnly ) ? \"<a href=\\\"javascript:;\\\" class=\\\"fa fa-close \" + classPrefix + \"preview-close-btn\\\"></a>\" : \"\" , ( ( settings . saveHTMLToTextarea ) ? \"<textarea class=\\\"\" + classNames . textarea . html + \"\\\" name=\\\"\" + id + \"-html-code\\\"></textarea>\" : \"\" ) , \"<div class=\\\"\" + classPrefix + \"preview\\\"><div class=\\\"markdown-body \" + classPrefix + \"preview-container\\\"></div></div>\" , \"<div class=\\\"\" + classPrefix + \"container-mask\\\" style=\\\"display:block;\\\"></div>\" , \"<div class=\\\"\" + classPrefix + \"mask\\\"></div>\" ] . join ( \"\\n\" ) ; editor . append ( appendElements ) . addClass ( classPrefix + \"vertical\" ) ; if ( settings . theme !== \"\" ) { editor . addClass ( classPrefix + \"theme-\" + settings . theme ) ; } this . mask = editor . children ( \".\" + classPrefix + \"mask\" ) ; this . containerMask = editor . children ( \".\" + classPrefix + \"container-mask\" ) ; if ( settings . markdown !== \"\" ) { markdownTextarea . val ( settings . markdown ) ; } if ( settings . appendMarkdown !== \"\" ) { markdownTextarea . val ( markdownTextarea . val ( ) + settings . appendMarkdown ) ; } this . htmlTextarea = editor . children ( \".\" + classNames . textarea . html ) ; this . preview = editor . children ( \".\" + classPrefix + \"preview\" ) ; this . previewContainer = this . preview . children ( \".\" + classPrefix + \"preview-container\" ) ; if ( settings . previewTheme !== \"\" ) { this . preview . addClass ( classPrefix + \"preview-theme-\" + settings . previewTheme ) ; } if ( typeof define === \"function\" && define . amd ) { if ( typeof katex !== \"undefined\" ) { editormd . $katex = katex ; } if ( settings . searchReplace && ! settings . readOnly ) { editormd . loadCSS ( settings . path + \"codemirror/addon/dialog/dialog\" ) ; editormd . loadCSS ( settings . path + \"codemirror/addon/search/matchesonscrollbar\" ) ; } } if ( ( typeof define === \"function\" && define . amd ) || ! settings . autoLoadModules ) { if ( typeof CodeMirror !== \"undefined\" ) { editormd . $CodeMirror = CodeMirror ; } if ( typeof marked !== \"undefined\" ) { editormd . $marked = marked ; } this . setCodeMirror ( ) . setToolbar ( ) . loadedDisplay ( ) ; } else { this . loadQueues ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "所需组件加载队列 Required components loading queue [CODESPLIT] function ( ) { var _this = this ; var settings = this . settings ; var loadPath = settings . path ; var loadFlowChartOrSequenceDiagram = function ( ) { if ( editormd . isIE8 ) { _this . loadedDisplay ( ) ; return ; } if ( settings . flowChart || settings . sequenceDiagram ) { editormd . loadScript ( loadPath + \"raphael.min\" , function ( ) { editormd . loadScript ( loadPath + \"underscore.min\" , function ( ) { if ( ! settings . flowChart && settings . sequenceDiagram ) { editormd . loadScript ( loadPath + \"sequence-diagram.min\" , function ( ) { _this . loadedDisplay ( ) ; } ) ; } else if ( settings . flowChart && ! settings . sequenceDiagram ) { editormd . loadScript ( loadPath + \"flowchart.min\" , function ( ) { editormd . loadScript ( loadPath + \"jquery.flowchart.min\" , function ( ) { _this . loadedDisplay ( ) ; } ) ; } ) ; } else if ( settings . flowChart && settings . sequenceDiagram ) { editormd . loadScript ( loadPath + \"flowchart.min\" , function ( ) { editormd . loadScript ( loadPath + \"jquery.flowchart.min\" , function ( ) { editormd . loadScript ( loadPath + \"sequence-diagram.min\" , function ( ) { _this . loadedDisplay ( ) ; } ) ; } ) ; } ) ; } } ) ; } ) ; } else { _this . loadedDisplay ( ) ; } } ; editormd . loadCSS ( loadPath + \"codemirror/codemirror.min\" ) ; if ( settings . searchReplace && ! settings . readOnly ) { editormd . loadCSS ( loadPath + \"codemirror/addon/dialog/dialog\" ) ; editormd . loadCSS ( loadPath + \"codemirror/addon/search/matchesonscrollbar\" ) ; } if ( settings . codeFold ) { editormd . loadCSS ( loadPath + \"codemirror/addon/fold/foldgutter\" ) ; } editormd . loadScript ( loadPath + \"codemirror/codemirror.min\" , function ( ) { editormd . $CodeMirror = CodeMirror ; editormd . loadScript ( loadPath + \"codemirror/modes.min\" , function ( ) { editormd . loadScript ( loadPath + \"codemirror/addons.min\" , function ( ) { _this . setCodeMirror ( ) ; if ( settings . mode !== \"gfm\" && settings . mode !== \"markdown\" ) { _this . loadedDisplay ( ) ; return false ; } _this . setToolbar ( ) ; editormd . loadScript ( loadPath + \"marked.min\" , function ( ) { editormd . $marked = marked ; if ( settings . previewCodeHighlight ) { editormd . loadScript ( loadPath + \"prettify.min\" , function ( ) { loadFlowChartOrSequenceDiagram ( ) ; } ) ; } else { loadFlowChartOrSequenceDiagram ( ) ; } } ) ; } ) ; } ) ; } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置 Editor . md 的整体主题，主要是工具栏 Setting Editor . md theme [CODESPLIT] function ( theme ) { var editor = this . editor ; var oldTheme = this . settings . theme ; var themePrefix = this . classPrefix + \"theme-\" ; editor . removeClass ( themePrefix + oldTheme ) . addClass ( themePrefix + theme ) ; this . settings . theme = theme ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置 CodeMirror（编辑区）的主题 Setting CodeMirror ( Editor area ) theme [CODESPLIT] function ( theme ) { var settings = this . settings ; settings . editorTheme = theme ; if ( theme !== \"default\" ) { editormd . loadCSS ( settings . path + \"codemirror/theme/\" + settings . editorTheme ) ; } this . cm . setOption ( \"theme\" , theme ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置 Editor . md 的主题 Setting Editor . md theme [CODESPLIT] function ( theme ) { var preview = this . preview ; var oldTheme = this . settings . previewTheme ; var themePrefix = this . classPrefix + \"preview-theme-\" ; preview . removeClass ( themePrefix + oldTheme ) . addClass ( themePrefix + theme ) ; this . settings . previewTheme = theme ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "配置和初始化CodeMirror组件 CodeMirror initialization [CODESPLIT] function ( ) { var settings = this . settings ; var editor = this . editor ; if ( settings . editorTheme !== \"default\" ) { editormd . loadCSS ( settings . path + \"codemirror/theme/\" + settings . editorTheme ) ; } var codeMirrorConfig = { mode : settings . mode , theme : settings . editorTheme , tabSize : settings . tabSize , dragDrop : false , autofocus : settings . autoFocus , autoCloseTags : settings . autoCloseTags , readOnly : ( settings . readOnly ) ? \"nocursor\" : false , indentUnit : settings . indentUnit , lineNumbers : settings . lineNumbers , lineWrapping : settings . lineWrapping , extraKeys : { \"Ctrl-Q\" : function ( cm ) { cm . foldCode ( cm . getCursor ( ) ) ; } } , foldGutter : settings . codeFold , gutters : [ \"CodeMirror-linenumbers\" , \"CodeMirror-foldgutter\" ] , matchBrackets : settings . matchBrackets , indentWithTabs : settings . indentWithTabs , styleActiveLine : settings . styleActiveLine , styleSelectedText : settings . styleSelectedText , autoCloseBrackets : settings . autoCloseBrackets , showTrailingSpace : settings . showTrailingSpace , highlightSelectionMatches : ( ( ! settings . matchWordHighlight ) ? false : { showToken : ( settings . matchWordHighlight === \"onselected\" ) ? false : / \\w / } ) } ; this . codeEditor = this . cm = editormd . $CodeMirror . fromTextArea ( this . markdownTextarea [ 0 ] , codeMirrorConfig ) ; this . codeMirror = this . cmElement = editor . children ( \".CodeMirror\" ) ; if ( settings . value !== \"\" ) { this . cm . setValue ( settings . value ) ; } this . codeMirror . css ( { fontSize : settings . fontSize , width : ( ! settings . watch ) ? \"100%\" : \"50%\" } ) ; if ( settings . autoHeight ) { this . codeMirror . css ( \"height\" , \"auto\" ) ; this . cm . setOption ( \"viewportMargin\" , Infinity ) ; } if ( ! settings . lineNumbers ) { this . codeMirror . find ( \".CodeMirror-gutters\" ) . css ( \"border-right\" , \"none\" ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "跳转到指定的行 Goto CodeMirror line [CODESPLIT] function ( line ) { var settings = this . settings ; if ( ! settings . gotoLine ) { return this ; } var cm = this . cm ; var editor = this . editor ; var count = cm . lineCount ( ) ; var preview = this . preview ; if ( typeof line === \"string\" ) { if ( line === \"last\" ) { line = count ; } if ( line === \"first\" ) { line = 1 ; } } if ( typeof line !== \"number\" ) { alert ( \"Error: The line number must be an integer.\" ) ; return this ; } line = parseInt ( line ) - 1 ; if ( line > count ) { alert ( \"Error: The line number range 1-\" + count ) ; return this ; } cm . setCursor ( { line : line , ch : 0 } ) ; var scrollInfo = cm . getScrollInfo ( ) ; var clientHeight = scrollInfo . clientHeight ; var coords = cm . charCoords ( { line : line , ch : 0 } , \"local\" ) ; cm . scrollTo ( null , ( coords . top + coords . bottom - clientHeight ) / 2 ) ; if ( settings . watch ) { var cmScroll = this . codeMirror . find ( \".CodeMirror-scroll\" ) [ 0 ] ; var height = $ ( cmScroll ) . height ( ) ; var scrollTop = cmScroll . scrollTop ; var percent = ( scrollTop / cmScroll . scrollHeight ) ; if ( scrollTop === 0 ) { preview . scrollTop ( 0 ) ; } else if ( scrollTop + height >= cmScroll . scrollHeight - 16 ) { preview . scrollTop ( preview [ 0 ] . scrollHeight ) ; } else { preview . scrollTop ( preview [ 0 ] . scrollHeight * percent ) ; } } cm . focus ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "扩展当前实例对象，可同时设置多个或者只设置一个 Extend editormd instance object can mutil setting . [CODESPLIT] function ( ) { if ( typeof arguments [ 1 ] !== \"undefined\" ) { if ( typeof arguments [ 1 ] === \"function\" ) { arguments [ 1 ] = $ . proxy ( arguments [ 1 ] , this ) ; } this [ arguments [ 0 ] ] = arguments [ 1 ] ; } if ( typeof arguments [ 0 ] === \"object\" && typeof arguments [ 0 ] . length === \"undefined\" ) { $ . extend ( true , this , arguments [ 0 ] ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "重新配置 Resetting editor options [CODESPLIT] function ( key , value ) { var settings = this . settings ; if ( typeof key === \"object\" ) { settings = $ . extend ( true , settings , key ) ; } if ( typeof key === \"string\" ) { settings [ key ] = value ; } this . settings = settings ; this . recreate ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "注册事件处理方法 Bind editor event handle [CODESPLIT] function ( eventType , callback ) { var settings = this . settings ; if ( typeof settings [ \"on\" + eventType ] !== \"undefined\" ) { settings [ \"on\" + eventType ] = $ . proxy ( callback , this ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "显示工具栏 Display toolbar [CODESPLIT] function ( callback ) { var settings = this . settings ; if ( settings . readOnly ) { return this ; } if ( settings . toolbar && ( this . toolbar . length < 1 || this . toolbar . find ( \".\" + this . classPrefix + \"menu\" ) . html ( ) === \"\" ) ) { this . setToolbar ( ) ; } settings . toolbar = true ; this . toolbar . show ( ) ; this . resize ( ) ; $ . proxy ( callback || function ( ) { } , this ) ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "隐藏工具栏 Hide toolbar [CODESPLIT] function ( callback ) { var settings = this . settings ; settings . toolbar = false ; this . toolbar . hide ( ) ; this . resize ( ) ; $ . proxy ( callback || function ( ) { } , this ) ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "页面滚动时工具栏的固定定位 Set toolbar in window scroll auto fixed position [CODESPLIT] function ( fixed ) { var state = this . state ; var editor = this . editor ; var toolbar = this . toolbar ; var settings = this . settings ; if ( typeof fixed !== \"undefined\" ) { settings . toolbarAutoFixed = fixed ; } var autoFixedHandle = function ( ) { var $window = $ ( window ) ; var top = $window . scrollTop ( ) ; if ( ! settings . toolbarAutoFixed ) { return false ; } if ( top - editor . offset ( ) . top > 10 && top < editor . height ( ) ) { toolbar . css ( { position : \"fixed\" , width : editor . width ( ) + \"px\" , left : ( $window . width ( ) - editor . width ( ) ) / 2 + \"px\" } ) ; } else { toolbar . css ( { position : \"absolute\" , width : \"100%\" , left : 0 } ) ; } } ; if ( ! state . fullscreen && ! state . preview && settings . toolbar && settings . toolbarAutoFixed ) { $ ( window ) . bind ( \"scroll\" , autoFixedHandle ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "配置和初始化工具栏 Set toolbar and Initialization [CODESPLIT] function ( ) { var settings = this . settings ; if ( settings . readOnly ) { return this ; } var editor = this . editor ; var preview = this . preview ; var classPrefix = this . classPrefix ; var toolbar = this . toolbar = editor . children ( \".\" + classPrefix + \"toolbar\" ) ; if ( settings . toolbar && toolbar . length < 1 ) { var toolbarHTML = \"<div class=\\\"\" + classPrefix + \"toolbar\\\"><div class=\\\"\" + classPrefix + \"toolbar-container\\\"><ul class=\\\"\" + classPrefix + \"menu\\\"></ul></div></div>\" ; editor . append ( toolbarHTML ) ; toolbar = this . toolbar = editor . children ( \".\" + classPrefix + \"toolbar\" ) ; } if ( ! settings . toolbar ) { toolbar . hide ( ) ; return this ; } toolbar . show ( ) ; var icons = ( typeof settings . toolbarIcons === \"function\" ) ? settings . toolbarIcons ( ) : ( ( typeof settings . toolbarIcons === \"string\" ) ? editormd . toolbarModes [ settings . toolbarIcons ] : settings . toolbarIcons ) ; var toolbarMenu = toolbar . find ( \".\" + this . classPrefix + \"menu\" ) , menu = \"\" ; var pullRight = false ; for ( var i = 0 , len = icons . length ; i < len ; i ++ ) { var name = icons [ i ] ; if ( name === \"||\" ) { pullRight = true ; } else if ( name === \"|\" ) { menu += \"<li class=\\\"divider\\\" unselectable=\\\"on\\\">|</li>\" ; } else { var isHeader = ( / h(\\d) / . test ( name ) ) ; var index = name ; if ( name === \"watch\" && ! settings . watch ) { index = \"unwatch\" ; } var title = settings . lang . toolbar [ index ] ; var iconTexts = settings . toolbarIconTexts [ index ] ; var iconClass = settings . toolbarIconsClass [ index ] ; title = ( typeof title === \"undefined\" ) ? \"\" : title ; iconTexts = ( typeof iconTexts === \"undefined\" ) ? \"\" : iconTexts ; iconClass = ( typeof iconClass === \"undefined\" ) ? \"\" : iconClass ; var menuItem = pullRight ? \"<li class=\\\"pull-right\\\">\" : \"<li>\" ; if ( typeof settings . toolbarCustomIcons [ name ] !== \"undefined\" && typeof settings . toolbarCustomIcons [ name ] !== \"function\" ) { menuItem += settings . toolbarCustomIcons [ name ] ; } else { menuItem += \"<a href=\\\"javascript:;\\\" title=\\\"\" + title + \"\\\" unselectable=\\\"on\\\">\" ; menuItem += \"<i class=\\\"fa \" + iconClass + \"\\\" name=\\\"\" + name + \"\\\" unselectable=\\\"on\\\">\" + ( ( isHeader ) ? name . toUpperCase ( ) : ( ( iconClass === \"\" ) ? iconTexts : \"\" ) ) + \"</i>\" ; menuItem += \"</a>\" ; } menuItem += \"</li>\" ; menu = pullRight ? menuItem + menu : menu + menuItem ; } } toolbarMenu . html ( menu ) ; toolbarMenu . find ( \"[title=\\\"Lowercase\\\"]\" ) . attr ( \"title\" , settings . lang . toolbar . lowercase ) ; toolbarMenu . find ( \"[title=\\\"ucwords\\\"]\" ) . attr ( \"title\" , settings . lang . toolbar . ucwords ) ; this . setToolbarHandler ( ) ; this . setToolbarAutoFixed ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "工具栏图标事件处理器 Bind toolbar icons event handle [CODESPLIT] function ( ) { var _this = this ; var settings = this . settings ; if ( ! settings . toolbar || settings . readOnly ) { return this ; } var toolbar = this . toolbar ; var cm = this . cm ; var classPrefix = this . classPrefix ; var toolbarIcons = this . toolbarIcons = toolbar . find ( \".\" + classPrefix + \"menu > li > a\" ) ; var toolbarIconHandlers = this . getToolbarHandles ( ) ; toolbarIcons . bind ( editormd . mouseOrTouch ( \"click\" , \"touchend\" ) , function ( event ) { var icon = $ ( this ) . children ( \".fa\" ) ; var name = icon . attr ( \"name\" ) ; var cursor = cm . getCursor ( ) ; var selection = cm . getSelection ( ) ; if ( name === \"\" ) { return ; } _this . activeIcon = icon ; if ( typeof toolbarIconHandlers [ name ] !== \"undefined\" ) { $ . proxy ( toolbarIconHandlers [ name ] , _this ) ( cm ) ; } else { if ( typeof settings . toolbarHandlers [ name ] !== \"undefined\" ) { $ . proxy ( settings . toolbarHandlers [ name ] , _this ) ( cm , icon , cursor , selection ) ; } } if ( name !== \"link\" && name !== \"reference-link\" && name !== \"image\" && name !== \"code-block\" && name !== \"preformatted-text\" && name !== \"watch\" && name !== \"preview\" && name !== \"search\" && name !== \"fullscreen\" && name !== \"info\" ) { cm . focus ( ) ; } return false ; } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "创建关于Editor . md的对话框 Create about Editor . md dialog [CODESPLIT] function ( ) { var _this = this ; var editor = this . editor ; var classPrefix = this . classPrefix ; var infoDialogHTML = [ \"<div class=\\\"\" + classPrefix + \"dialog \" + classPrefix + \"dialog-info\\\" style=\\\"\\\">\" , \"<div class=\\\"\" + classPrefix + \"dialog-container\\\">\" , \"<h1><i class=\\\"editormd-logo editormd-logo-lg editormd-logo-color\\\"></i> \" + editormd . title + \"<small>v\" + editormd . version + \"</small></h1>\" , \"<p>\" + this . lang . description + \"</p>\" , \"<p style=\\\"margin: 10px 0 20px 0;\\\"><a href=\\\"\" + editormd . homePage + \"\\\" target=\\\"_blank\\\">\" + editormd . homePage + \" <i class=\\\"fa fa-external-link\\\"></i></a></p>\" , \"<p style=\\\"font-size: 0.85em;\\\">Copyright &copy; 2015 <a href=\\\"https://github.com/pandao\\\" target=\\\"_blank\\\" class=\\\"hover-link\\\">Pandao</a>, The <a href=\\\"https://github.com/pandao/editor.md/blob/master/LICENSE\\\" target=\\\"_blank\\\" class=\\\"hover-link\\\">MIT</a> License.</p>\" , \"</div>\" , \"<a href=\\\"javascript:;\\\" class=\\\"fa fa-close \" + classPrefix + \"dialog-close\\\"></a>\" , \"</div>\" ] . join ( \"\\n\" ) ; editor . append ( infoDialogHTML ) ; var infoDialog = this . infoDialog = editor . children ( \".\" + classPrefix + \"dialog-info\" ) ; infoDialog . find ( \".\" + classPrefix + \"dialog-close\" ) . bind ( editormd . mouseOrTouch ( \"click\" , \"touchend\" ) , function ( ) { _this . hideInfoDialog ( ) ; } ) ; infoDialog . css ( \"border\" , ( editormd . isIE8 ) ? \"1px solid #ddd\" : \"\" ) . css ( \"z-index\" , editormd . dialogZindex ) . show ( ) ; this . infoDialogPosition ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "关于Editor . md对话居中定位 Editor . md dialog position handle [CODESPLIT] function ( ) { var infoDialog = this . infoDialog ; var _infoDialogPosition = function ( ) { infoDialog . css ( { top : ( $ ( window ) . height ( ) - infoDialog . height ( ) ) / 2 + \"px\" , left : ( $ ( window ) . width ( ) - infoDialog . width ( ) ) / 2 + \"px\" } ) ; } ; _infoDialogPosition ( ) ; $ ( window ) . resize ( _infoDialogPosition ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "显示关于Editor . md Display about Editor . md dialog [CODESPLIT] function ( ) { $ ( \"html,body\" ) . css ( \"overflow-x\" , \"hidden\" ) ; var _this = this ; var editor = this . editor ; var settings = this . settings ; var infoDialog = this . infoDialog = editor . children ( \".\" + this . classPrefix + \"dialog-info\" ) ; if ( infoDialog . length < 1 ) { this . createInfoDialog ( ) ; } this . lockScreen ( true ) ; this . mask . css ( { opacity : settings . dialogMaskOpacity , backgroundColor : settings . dialogMaskBgColor } ) . show ( ) ; infoDialog . css ( \"z-index\" , editormd . dialogZindex ) . show ( ) ; this . infoDialogPosition ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "编辑器界面重建，用于动态语言包或模块加载等 Recreate editor [CODESPLIT] function ( ) { var _this = this ; var editor = this . editor ; var settings = this . settings ; this . codeMirror . remove ( ) ; this . setCodeMirror ( ) ; if ( ! settings . readOnly ) { if ( editor . find ( \".editormd-dialog\" ) . length > 0 ) { editor . find ( \".editormd-dialog\" ) . remove ( ) ; } if ( settings . toolbar ) { this . getToolbarHandles ( ) ; this . setToolbar ( ) ; } } this . loadedDisplay ( true ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "高亮预览HTML的pre代码部分 highlight of preview codes [CODESPLIT] function ( ) { var settings = this . settings ; var previewContainer = this . previewContainer ; if ( settings . previewCodeHighlight ) { previewContainer . find ( \"pre\" ) . addClass ( \"prettyprint linenums\" ) ; if ( typeof prettyPrint !== \"undefined\" ) { prettyPrint ( ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解析TeX ( KaTeX ) 科学公式 TeX ( KaTeX ) Renderer [CODESPLIT] function ( ) { if ( timer === null ) { return this ; } this . previewContainer . find ( \".\" + editormd . classNames . tex ) . each ( function ( ) { var tex = $ ( this ) ; editormd . $katex . render ( tex . text ( ) , tex [ 0 ] ) ; tex . find ( \".katex\" ) . css ( \"font-size\" , \"1.6em\" ) ; } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解析和渲染流程图及时序图 FlowChart and SequenceDiagram Renderer [CODESPLIT] function ( ) { var $this = this ; var settings = this . settings ; var previewContainer = this . previewContainer ; if ( editormd . isIE8 ) { return this ; } if ( settings . flowChart ) { if ( flowchartTimer === null ) { return this ; } previewContainer . find ( \".flowchart\" ) . flowChart ( ) ; } if ( settings . sequenceDiagram ) { previewContainer . find ( \".sequence-diagram\" ) . sequenceDiagram ( { theme : \"simple\" } ) ; } var preview = $this . preview ; var codeMirror = $this . codeMirror ; var codeView = codeMirror . find ( \".CodeMirror-scroll\" ) ; var height = codeView . height ( ) ; var scrollTop = codeView . scrollTop ( ) ; var percent = ( scrollTop / codeView [ 0 ] . scrollHeight ) ; var tocHeight = 0 ; preview . find ( \".markdown-toc-list\" ) . each ( function ( ) { tocHeight += $ ( this ) . height ( ) ; } ) ; var tocMenuHeight = preview . find ( \".editormd-toc-menu\" ) . height ( ) ; tocMenuHeight = ( ! tocMenuHeight ) ? 0 : tocMenuHeight ; if ( scrollTop === 0 ) { preview . scrollTop ( 0 ) ; } else if ( scrollTop + height >= codeView [ 0 ] . scrollHeight - 16 ) { preview . scrollTop ( preview [ 0 ] . scrollHeight ) ; } else { preview . scrollTop ( ( preview [ 0 ] . scrollHeight + tocHeight + tocMenuHeight ) * percent ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "注册键盘快捷键处理 Register CodeMirror keyMaps ( keyboard shortcuts ) . [CODESPLIT] function ( keyMap ) { var _this = this ; var cm = this . cm ; var settings = this . settings ; var toolbarHandlers = editormd . toolbarHandlers ; var disabledKeyMaps = settings . disabledKeyMaps ; keyMap = keyMap || null ; if ( keyMap ) { for ( var i in keyMap ) { if ( $ . inArray ( i , disabledKeyMaps ) < 0 ) { var map = { } ; map [ i ] = keyMap [ i ] ; cm . addKeyMap ( keyMap ) ; } } } else { for ( var k in editormd . keyMaps ) { var _keyMap = editormd . keyMaps [ k ] ; var handle = ( typeof _keyMap === \"string\" ) ? $ . proxy ( toolbarHandlers [ _keyMap ] , _this ) : $ . proxy ( _keyMap , _this ) ; if ( $ . inArray ( k , [ \"F9\" , \"F10\" , \"F11\" ] ) < 0 && $ . inArray ( k , disabledKeyMaps ) < 0 ) { var _map = { } ; _map [ k ] = handle ; cm . addKeyMap ( _map ) ; } } $ ( window ) . keydown ( function ( event ) { var keymaps = { \"120\" : \"F9\" , \"121\" : \"F10\" , \"122\" : \"F11\" } ; if ( $ . inArray ( keymaps [ event . keyCode ] , disabledKeyMaps ) < 0 ) { switch ( event . keyCode ) { case 120 : $ . proxy ( toolbarHandlers [ \"watch\" ] , _this ) ( ) ; return false ; break ; case 121 : $ . proxy ( toolbarHandlers [ \"preview\" ] , _this ) ( ) ; return false ; break ; case 122 : $ . proxy ( toolbarHandlers [ \"fullscreen\" ] , _this ) ( ) ; return false ; break ; default : break ; } } } ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "绑定同步滚动 [CODESPLIT] function ( ) { var _this = this ; var preview = this . preview ; var settings = this . settings ; var codeMirror = this . codeMirror ; var mouseOrTouch = editormd . mouseOrTouch ; if ( ! settings . syncScrolling ) { return this ; } var cmBindScroll = function ( ) { codeMirror . find ( \".CodeMirror-scroll\" ) . bind ( mouseOrTouch ( \"scroll\" , \"touchmove\" ) , function ( event ) { var height = $ ( this ) . height ( ) ; var scrollTop = $ ( this ) . scrollTop ( ) ; var percent = ( scrollTop / $ ( this ) [ 0 ] . scrollHeight ) ; var tocHeight = 0 ; preview . find ( \".markdown-toc-list\" ) . each ( function ( ) { tocHeight += $ ( this ) . height ( ) ; } ) ; var tocMenuHeight = preview . find ( \".editormd-toc-menu\" ) . height ( ) ; tocMenuHeight = ( ! tocMenuHeight ) ? 0 : tocMenuHeight ; if ( scrollTop === 0 ) { preview . scrollTop ( 0 ) ; } else if ( scrollTop + height >= $ ( this ) [ 0 ] . scrollHeight - 16 ) { preview . scrollTop ( preview [ 0 ] . scrollHeight ) ; } else { preview . scrollTop ( ( preview [ 0 ] . scrollHeight + tocHeight + tocMenuHeight ) * percent ) ; } $ . proxy ( settings . onscroll , _this ) ( event ) ; } ) ; } ; var cmUnbindScroll = function ( ) { codeMirror . find ( \".CodeMirror-scroll\" ) . unbind ( mouseOrTouch ( \"scroll\" , \"touchmove\" ) ) ; } ; var previewBindScroll = function ( ) { preview . bind ( mouseOrTouch ( \"scroll\" , \"touchmove\" ) , function ( event ) { var height = $ ( this ) . height ( ) ; var scrollTop = $ ( this ) . scrollTop ( ) ; var percent = ( scrollTop / $ ( this ) [ 0 ] . scrollHeight ) ; var codeView = codeMirror . find ( \".CodeMirror-scroll\" ) ; if ( scrollTop === 0 ) { codeView . scrollTop ( 0 ) ; } else if ( scrollTop + height >= $ ( this ) [ 0 ] . scrollHeight ) { codeView . scrollTop ( codeView [ 0 ] . scrollHeight ) ; } else { codeView . scrollTop ( codeView [ 0 ] . scrollHeight * percent ) ; } $ . proxy ( settings . onpreviewscroll , _this ) ( event ) ; } ) ; } ; var previewUnbindScroll = function ( ) { preview . unbind ( mouseOrTouch ( \"scroll\" , \"touchmove\" ) ) ; } ; codeMirror . bind ( { mouseover : cmBindScroll , mouseout : cmUnbindScroll , touchstart : cmBindScroll , touchend : cmUnbindScroll } ) ; if ( settings . syncScrolling === \"single\" ) { return this ; } preview . bind ( { mouseover : previewBindScroll , mouseout : previewUnbindScroll , touchstart : previewBindScroll , touchend : previewUnbindScroll } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加载队列完成之后的显示处理 Display handle of the module queues loaded after . [CODESPLIT] function ( recreate ) { recreate = recreate || false ; var _this = this ; var editor = this . editor ; var preview = this . preview ; var settings = this . settings ; this . containerMask . hide ( ) ; this . save ( ) ; if ( settings . watch ) { preview . show ( ) ; } editor . data ( \"oldWidth\" , editor . width ( ) ) . data ( \"oldHeight\" , editor . height ( ) ) ; // 为了兼容Zepto\r this . resize ( ) ; this . registerKeyMaps ( ) ; $ ( window ) . resize ( function ( ) { _this . resize ( ) ; } ) ; this . bindScrollEvent ( ) . bindChangeEvent ( ) ; if ( ! recreate ) { $ . proxy ( settings . onload , this ) ( ) ; } this . state . loaded = true ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "调整编辑器的尺寸和布局 Resize editor layout [CODESPLIT] function ( width , height ) { width = width || null ; height = height || null ; var state = this . state ; var editor = this . editor ; var preview = this . preview ; var toolbar = this . toolbar ; var settings = this . settings ; var codeMirror = this . codeMirror ; if ( width ) { editor . css ( \"width\" , ( typeof width === \"number\" ) ? width + \"px\" : width ) ; } if ( settings . autoHeight && ! state . fullscreen && ! state . preview ) { editor . css ( \"height\" , \"auto\" ) ; codeMirror . css ( \"height\" , \"auto\" ) ; } else { if ( height ) { editor . css ( \"height\" , ( typeof height === \"number\" ) ? height + \"px\" : height ) ; } if ( state . fullscreen ) { editor . height ( $ ( window ) . height ( ) ) ; } if ( settings . toolbar && ! settings . readOnly ) { codeMirror . css ( \"margin-top\" , toolbar . height ( ) + 1 ) . height ( editor . height ( ) - toolbar . height ( ) ) ; } else { codeMirror . css ( \"margin-top\" , 0 ) . height ( editor . height ( ) ) ; } } if ( settings . watch ) { codeMirror . width ( editor . width ( ) / 2 ) ; preview . width ( ( ! state . preview ) ? editor . width ( ) / 2 : editor . width ( ) ) ; this . previewContainer . css ( \"padding\" , settings . autoHeight ? \"20px 20px 50px 40px\" : \"20px\" ) ; if ( settings . toolbar && ! settings . readOnly ) { preview . css ( \"top\" , toolbar . height ( ) + 1 ) ; } else { preview . css ( \"top\" , 0 ) ; } if ( settings . autoHeight && ! state . fullscreen && ! state . preview ) { preview . height ( \"\" ) ; } else { var previewHeight = ( settings . toolbar && ! settings . readOnly ) ? editor . height ( ) - toolbar . height ( ) : editor . height ( ) ; preview . height ( previewHeight ) ; } } else { codeMirror . width ( editor . width ( ) ) ; preview . hide ( ) ; } if ( state . loaded ) { $ . proxy ( settings . onresize , this ) ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解析和保存Markdown代码 Parse & Saving Markdown source code [CODESPLIT] function ( ) { if ( timer === null ) { return this ; } var _this = this ; var state = this . state ; var settings = this . settings ; var cm = this . cm ; var cmValue = cm . getValue ( ) ; var previewContainer = this . previewContainer ; if ( settings . mode !== \"gfm\" && settings . mode !== \"markdown\" ) { this . markdownTextarea . val ( cmValue ) ; return this ; } var marked = editormd . $marked ; var markdownToC = this . markdownToC = [ ] ; var rendererOptions = this . markedRendererOptions = { toc : settings . toc , tocm : settings . tocm , tocStartLevel : settings . tocStartLevel , pageBreak : settings . pageBreak , taskList : settings . taskList , emoji : settings . emoji , tex : settings . tex , atLink : settings . atLink , // for @link\r emailLink : settings . emailLink , // for mail address auto link\r flowChart : settings . flowChart , sequenceDiagram : settings . sequenceDiagram , previewCodeHighlight : settings . previewCodeHighlight , } ; var markedOptions = this . markedOptions = { renderer : editormd . markedRenderer ( markdownToC , rendererOptions ) , gfm : true , tables : true , breaks : true , pedantic : false , sanitize : ( settings . htmlDecode ) ? false : true , // 关闭忽略HTML标签，即开启识别HTML标签，默认为false\r smartLists : true , smartypants : true } ; marked . setOptions ( markedOptions ) ; var newMarkdownDoc = editormd . $marked ( cmValue , markedOptions ) ; //console.info(\"cmValue\", cmValue, newMarkdownDoc);\r newMarkdownDoc = editormd . filterHTMLTags ( newMarkdownDoc , settings . htmlDecode ) ; //console.error(\"cmValue\", cmValue, newMarkdownDoc);\r this . markdownTextarea . text ( cmValue ) ; cm . save ( ) ; if ( settings . saveHTMLToTextarea ) { this . htmlTextarea . text ( newMarkdownDoc ) ; } if ( settings . watch || ( ! settings . watch && state . preview ) ) { previewContainer . html ( newMarkdownDoc ) ; this . previewCodeHighlight ( ) ; if ( settings . toc ) { var tocContainer = ( settings . tocContainer === \"\" ) ? previewContainer : $ ( settings . tocContainer ) ; var tocMenu = tocContainer . find ( \".\" + this . classPrefix + \"toc-menu\" ) ; tocContainer . attr ( \"previewContainer\" , ( settings . tocContainer === \"\" ) ? \"true\" : \"false\" ) ; if ( settings . tocContainer !== \"\" && tocMenu . length > 0 ) { tocMenu . remove ( ) ; } editormd . markdownToCRenderer ( markdownToC , tocContainer , settings . tocDropdown , settings . tocStartLevel ) ; if ( settings . tocDropdown || tocContainer . find ( \".\" + this . classPrefix + \"toc-menu\" ) . length > 0 ) { editormd . tocDropdownMenu ( tocContainer , ( settings . tocTitle !== \"\" ) ? settings . tocTitle : this . lang . tocTitle ) ; } if ( settings . tocContainer !== \"\" ) { previewContainer . find ( \".markdown-toc\" ) . css ( \"border\" , \"none\" ) ; } } if ( settings . tex ) { if ( ! editormd . kaTeXLoaded && settings . autoLoadModules ) { editormd . loadKaTeX ( function ( ) { editormd . $katex = katex ; editormd . kaTeXLoaded = true ; _this . katexRender ( ) ; } ) ; } else { editormd . $katex = katex ; this . katexRender ( ) ; } } if ( settings . flowChart || settings . sequenceDiagram ) { flowchartTimer = setTimeout ( function ( ) { clearTimeout ( flowchartTimer ) ; _this . flowChartAndSequenceDiagramRender ( ) ; flowchartTimer = null ; } , 10 ) ; } if ( state . loaded ) { $ . proxy ( settings . onchange , this ) ( ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "追加markdown append Markdown to editor [CODESPLIT] function ( md ) { var settings = this . settings ; var cm = this . cm ; cm . setValue ( cm . getValue ( ) + md ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "开启实时预览 Enable real - time watching [CODESPLIT] function ( callback ) { var settings = this . settings ; if ( $ . inArray ( settings . mode , [ \"gfm\" , \"markdown\" ] ) < 0 ) { return this ; } this . state . watching = settings . watch = true ; this . preview . show ( ) ; if ( this . toolbar ) { var watchIcon = settings . toolbarIconsClass . watch ; var unWatchIcon = settings . toolbarIconsClass . unwatch ; var icon = this . toolbar . find ( \".fa[name=watch]\" ) ; icon . parent ( ) . attr ( \"title\" , settings . lang . toolbar . watch ) ; icon . removeClass ( unWatchIcon ) . addClass ( watchIcon ) ; } this . codeMirror . css ( \"border-right\" , \"1px solid #ddd\" ) . width ( this . editor . width ( ) / 2 ) ; timer = 0 ; this . save ( ) . resize ( ) ; if ( ! settings . onwatch ) { settings . onwatch = callback || function ( ) { } ; } $ . proxy ( settings . onwatch , this ) ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "关闭实时预览 Disable real - time watching [CODESPLIT] function ( callback ) { var settings = this . settings ; this . state . watching = settings . watch = false ; this . preview . hide ( ) ; if ( this . toolbar ) { var watchIcon = settings . toolbarIconsClass . watch ; var unWatchIcon = settings . toolbarIconsClass . unwatch ; var icon = this . toolbar . find ( \".fa[name=watch]\" ) ; icon . parent ( ) . attr ( \"title\" , settings . lang . toolbar . unwatch ) ; icon . removeClass ( watchIcon ) . addClass ( unWatchIcon ) ; } this . codeMirror . css ( \"border-right\" , \"none\" ) . width ( this . editor . width ( ) ) ; this . resize ( ) ; if ( ! settings . onunwatch ) { settings . onunwatch = callback || function ( ) { } ; } $ . proxy ( settings . onunwatch , this ) ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "隐藏编辑器部分，只预览HTML Enter preview html state [CODESPLIT] function ( ) { var _this = this ; var editor = this . editor ; var preview = this . preview ; var toolbar = this . toolbar ; var settings = this . settings ; var codeMirror = this . codeMirror ; var previewContainer = this . previewContainer ; if ( $ . inArray ( settings . mode , [ \"gfm\" , \"markdown\" ] ) < 0 ) { return this ; } if ( settings . toolbar && toolbar ) { toolbar . toggle ( ) ; toolbar . find ( \".fa[name=preview]\" ) . toggleClass ( \"active\" ) ; } codeMirror . toggle ( ) ; var escHandle = function ( event ) { if ( event . shiftKey && event . keyCode === 27 ) { _this . previewed ( ) ; } } ; if ( codeMirror . css ( \"display\" ) === \"none\" ) // 为了兼容Zepto，而不使用codeMirror.is(\":hidden\")\r { this . state . preview = true ; if ( this . state . fullscreen ) { preview . css ( \"background\" , \"#fff\" ) ; } editor . find ( \".\" + this . classPrefix + \"preview-close-btn\" ) . show ( ) . bind ( editormd . mouseOrTouch ( \"click\" , \"touchend\" ) , function ( ) { _this . previewed ( ) ; } ) ; if ( ! settings . watch ) { this . save ( ) ; } else { previewContainer . css ( \"padding\" , \"\" ) ; } previewContainer . addClass ( this . classPrefix + \"preview-active\" ) ; preview . show ( ) . css ( { position : \"\" , top : 0 , width : editor . width ( ) , height : ( settings . autoHeight && ! this . state . fullscreen ) ? \"auto\" : editor . height ( ) } ) ; if ( this . state . loaded ) { $ . proxy ( settings . onpreviewing , this ) ( ) ; } $ ( window ) . bind ( \"keyup\" , escHandle ) ; } else { $ ( window ) . unbind ( \"keyup\" , escHandle ) ; this . previewed ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "显示编辑器部分，退出只预览HTML Exit preview html state [CODESPLIT] function ( ) { var editor = this . editor ; var preview = this . preview ; var toolbar = this . toolbar ; var settings = this . settings ; var previewContainer = this . previewContainer ; var previewCloseBtn = editor . find ( \".\" + this . classPrefix + \"preview-close-btn\" ) ; this . state . preview = false ; this . codeMirror . show ( ) ; if ( settings . toolbar ) { toolbar . show ( ) ; } preview [ ( settings . watch ) ? \"show\" : \"hide\" ] ( ) ; previewCloseBtn . hide ( ) . unbind ( editormd . mouseOrTouch ( \"click\" , \"touchend\" ) ) ; previewContainer . removeClass ( this . classPrefix + \"preview-active\" ) ; if ( settings . watch ) { previewContainer . css ( \"padding\" , \"20px\" ) ; } preview . css ( { background : null , position : \"absolute\" , width : editor . width ( ) / 2 , height : ( settings . autoHeight && ! this . state . fullscreen ) ? \"auto\" : editor . height ( ) - toolbar . height ( ) , top : ( settings . toolbar ) ? toolbar . height ( ) : 0 } ) ; if ( this . state . loaded ) { $ . proxy ( settings . onpreviewed , this ) ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "编辑器全屏显示 Fullscreen show [CODESPLIT] function ( ) { var _this = this ; var state = this . state ; var editor = this . editor ; var preview = this . preview ; var toolbar = this . toolbar ; var settings = this . settings ; var fullscreenClass = this . classPrefix + \"fullscreen\" ; if ( toolbar ) { toolbar . find ( \".fa[name=fullscreen]\" ) . parent ( ) . toggleClass ( \"active\" ) ; } var escHandle = function ( event ) { if ( ! event . shiftKey && event . keyCode === 27 ) { if ( state . fullscreen ) { _this . fullscreenExit ( ) ; } } } ; if ( ! editor . hasClass ( fullscreenClass ) ) { state . fullscreen = true ; $ ( \"html,body\" ) . css ( \"overflow\" , \"hidden\" ) ; editor . css ( { width : $ ( window ) . width ( ) , height : $ ( window ) . height ( ) } ) . addClass ( fullscreenClass ) ; this . resize ( ) ; $ . proxy ( settings . onfullscreen , this ) ( ) ; $ ( window ) . bind ( \"keyup\" , escHandle ) ; } else { $ ( window ) . unbind ( \"keyup\" , escHandle ) ; this . fullscreenExit ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "编辑器退出全屏显示 Exit fullscreen state [CODESPLIT] function ( ) { var editor = this . editor ; var settings = this . settings ; var toolbar = this . toolbar ; var fullscreenClass = this . classPrefix + \"fullscreen\" ; this . state . fullscreen = false ; if ( toolbar ) { toolbar . find ( \".fa[name=fullscreen]\" ) . parent ( ) . removeClass ( \"active\" ) ; } $ ( \"html,body\" ) . css ( \"overflow\" , \"\" ) ; editor . css ( { width : editor . data ( \"oldWidth\" ) , height : editor . data ( \"oldHeight\" ) } ) . removeClass ( fullscreenClass ) ; this . resize ( ) ; $ . proxy ( settings . onfullscreenExit , this ) ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加载并执行插件 Load and execute the plugin [CODESPLIT] function ( name , path ) { var _this = this ; var cm = this . cm ; var settings = this . settings ; path = settings . pluginPath + path ; if ( typeof define === \"function\" ) { if ( typeof this [ name ] === \"undefined\" ) { alert ( \"Error: \" + name + \" plugin is not found, you are not load this plugin.\" ) ; return this ; } this [ name ] ( cm ) ; return this ; } if ( $ . inArray ( path , editormd . loadFiles . plugin ) < 0 ) { editormd . loadPlugin ( path , function ( ) { editormd . loadPlugins [ name ] = _this [ name ] ; _this [ name ] ( cm ) ; } ) ; } else { $ . proxy ( editormd . loadPlugins [ name ] , this ) ( cm ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "搜索替换 Search & replace [CODESPLIT] function ( command ) { var settings = this . settings ; if ( ! settings . searchReplace ) { alert ( \"Error: settings.searchReplace == false\" ) ; return this ; } if ( ! settings . readOnly ) { this . cm . execCommand ( command || \"find\" ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Succinct definitions of keyword token types [CODESPLIT] function kw ( name , options = { } ) { options . keyword = name return keywords [ name ] = new TokenType ( name , options ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This has a complexity linear to the value of the code . The assumption is that looking up astral identifier characters is rare . [CODESPLIT] function isInAstralSet ( code , set ) { let pos = 0x10000 for ( let i = 0 ; i < set . length ; i += 2 ) { pos += set [ i ] if ( pos > code ) return false pos += set [ i + 1 ] if ( pos >= code ) return true } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform token names to formats expected by Sassdoc for descriptions and aliases [CODESPLIT] function transformMetadata ( metadata ) { const namesRegEx = new RegExp ( metadata . tokens . map ( token => token . name ) . join ( '|' ) , 'g' ) ; const replaceMap = { } ; metadata . tokens . map ( token => { replaceMap [ token . name ] = formatTokenName ( token . name ) ; } ) ; metadata . tokens . forEach ( ( token , i ) => { // interactive01 to `$interactive-01` if ( token . role ) { token . role . forEach ( ( role , j ) => { metadata . tokens [ i ] . role [ j ] = role . replace ( namesRegEx , match => { return '`$' + replaceMap [ match ] + '`' ; } ) ; } ) ; } // brand01 to brand-01 if ( token . alias ) { token . alias = formatTokenName ( token . alias ) ; } } ) ; return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rough heuristic used to find the package name for a given file . Idea is to move upwards looking for directories that have a package . json file . Once we find one we report back the name from that file . [CODESPLIT] async function findPackageFor ( filepath ) { let directory = filepath ; while ( directory !== '/' ) { const directoryToSearch = path . dirname ( directory ) ; const files = await fs . readdir ( directoryToSearch ) ; if ( files . indexOf ( 'package.json' ) !== - 1 ) { const packageJson = await fs . readJson ( path . join ( directoryToSearch , 'package.json' ) ) ; return packageJson . name ; } directory = path . resolve ( directory , '..' ) ; } throw new Error ( ` ${ filepath } ` ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copyright IBM Corp . 2016 2018 [CODESPLIT] function svgToggleClass ( svg , name , forceAdd ) { const list = svg . getAttribute ( 'class' ) . trim ( ) . split ( / \\s+ / ) ; const uniqueList = Object . keys ( list . reduce ( ( o , item ) => Object . assign ( o , { [ item ] : 1 } ) , { } ) ) ; const index = uniqueList . indexOf ( name ) ; const found = index >= 0 ; const add = forceAdd === undefined ? ! found : forceAdd ; if ( found === ! add ) { if ( add ) { uniqueList . push ( name ) ; } else { uniqueList . splice ( index , 1 ) ; } svg . setAttribute ( 'class' , uniqueList . join ( ' ' ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inspired by Vue CLI : https : // github . com / vuejs / vue - cli / blob / 31e1b4995edef3d2079da654deedffe002a1d689 / packages / %40vue / cli / bin / vue . js#L172 [CODESPLIT] function cleanArgs ( command ) { return command . options . reduce ( ( acc , option ) => { // TODO: add case for reserved words from commander, like options // Add case for mapping `--foo-bar` to `fooBar` const key = option . long . replace ( / ^-- / , '' ) . split ( '-' ) . map ( ( word , i ) => { if ( i === 0 ) { return word ; } return word [ 0 ] . toUpperCase ( ) + word . slice ( 1 ) ; } ) . join ( '' ) ; // If an option is not present and Command has a method with the same name // it should not be copied if ( typeof command [ key ] !== 'function' ) { return { ... acc , [ key ] : command [ key ] , } ; } return acc ; } , { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copyright IBM Corp . 2018 2018 [CODESPLIT] async function flatMapAsync ( source , mapFn ) { const results = await Promise . all ( source . map ( mapFn ) ) ; return results . reduce ( ( acc , result ) => acc . concat ( result ) , [ ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a JSON file of documented Sass items [CODESPLIT] async function createJson ( sourceDir , config ) { config = config || { } ; return sassdoc . parse ( sourceDir , config ) . then ( data => { return data ; } , err => { console . error ( err ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove duplicate objects in require and usedBy arrays . Array objects have name and type properties sometimes nested in a context object . [CODESPLIT] function dedupeArray ( arr ) { return arr . reduce ( ( p , item ) => { const type = item . type || item . context . type ; const name = item . name || item . context . name ; const id = [ type , name ] . join ( '|' ) ; if ( p . temp . indexOf ( id ) === - 1 ) { p . out . push ( item ) ; p . temp . push ( id ) ; } return p ; } , { temp : [ ] , out : [ ] } ) . out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create GitHub - flavored markdown anchor link [CODESPLIT] function createAnchorLink ( name , heading ) { const anchorLink = heading . toLowerCase ( ) . replace ( /   / g , '-' ) . replace ( / [`~!@#$%^&*()+=<>?,./:;\"'|{}\\[\\]\\\\–—]/g,  ' ' )   . replace ( / [　。？！，、；：“”【】（）〔〕［］﹃﹄“”‘’﹁﹂—…－～《》〈〉「」]/g,    '' ) ; return ` ${ name } ${ anchorLink } ` ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create markdown for Sassdoc item ( function mixin placeholder variable ) [CODESPLIT] function createMarkdownItem ( item ) { let str = '' ; if ( ! item . context ) return '' ; let status = item . access === 'public' ? '✅' : ' ';  if ( item . deprecated || item . deprecated === '' ) { status += '⚠️';  } // Name str += ` \\n \\n ${ status } ${ createUniqueName ( item . context . name , item . context . type ) } ` ; // Description if ( item . description ) { str += ` \\n \\n ${ item . description . trim ( ) } ` ; } // Value (variables) if ( item . context . value ) { str += ` \\` \\` \\` ${ item . context . name } ${ item . context . value } \\` \\` \\` ` ; } // Code (mixins) if ( item . context . code ) { let paramStr = '' ; if ( item . parameter ) { item . parameter . forEach ( param => { if ( paramStr ) paramStr += ` ` ; paramStr += ` ${ param . name } ` ; if ( param . default ) paramStr += ` ${ param . default } ` ; } ) ; } str += ` \\` \\` \\` ${ item . context . type } ${ item . context . name } ${ paramStr } ${ item . context . code } \\` \\` \\` ` ; } // Parameters if ( item . parameter && item . parameter . length ) { str += ` ` ; item . parameter . forEach ( param => { const paramType = param . type ? ` \\` ${ param . type . replace ( / \\| / g , ` \\\\ ` ) } \\` ` : '—';  const paramDefault = param . default ? ` \\` ${ param . default } \\` ` : '—';  const row = ` \\n \\` ${ param . name } \\` ${ param . description || '—'}  | pa ramType}  | pa ramDefault}  |   str += row ; } ) ; } // Example if ( item . example && item . example . length ) { str += ` \\n \\n ` ; if ( item . example [ 0 ] . description ) { str += ` ${ item . example [ 0 ] . description } ` ; } str += ` \\` \\` \\` ${ item . example [ 0 ] . type } ${ item . example [ 0 ] . code } \\` \\` \\` ` ; } // Bullets const metadata = [ ] ; const groupName = createGroupName ( item . group ) ; metadata . push ( { key : 'Group' , value : createAnchorLink ( groupName , groupName ) , } ) ; if ( item . return ) { metadata . push ( { key : 'Returns' , value : ` \\` ${ item . return . type } \\` ${ item . return . description || '' } ` , } ) ; } if ( item . type ) { metadata . push ( { key : 'Type' , value : ` \\` ${ item . type } \\` ` , } ) ; } if ( item . alias ) { metadata . push ( { key : 'Alias' , value : ` \\` ${ item . alias } \\` ` , } ) ; } if ( item . aliased ) { let subbullets = '' ; item . aliased . forEach ( aliased => { subbullets += ` \\n \\` ${ aliased } \\` ` ; } ) ; metadata . push ( { key : 'Aliased' , value : subbullets , } ) ; } if ( item . content ) { metadata . push ( { key : 'Content' , value : item . content , } ) ; } if ( item . require && item . require . length ) { let subbullets = '' ; dedupeArray ( item . require ) . forEach ( requires => { subbullets += ` \\n ${ createAnchorLink ( ` ${ requires . name } ${ requires . type } ` , createUniqueName ( requires . name , requires . type ) ) } ` ; } ) ; metadata . push ( { key : 'Requires' , value : subbullets , } ) ; } if ( item . usedBy && item . usedBy . length ) { let subbullets = '' ; dedupeArray ( item . usedBy ) . forEach ( usedBy => { subbullets += ` \\n ${ createAnchorLink ( ` ${ usedBy . context . name } ${ usedBy . context . type } ` , createUniqueName ( usedBy . context . name , usedBy . context . type ) ) } ` ; } ) ; metadata . push ( { key : 'Used by' , value : subbullets , } ) ; } // if (item.since && item.since.length) { //   metadata.push({ //     key: 'Since', //     value: item.since[0].version, //   }); // } if ( item . link && item . link . length ) { let subbullets = '' ; item . link . forEach ( link => { subbullets += ` \\n ${ link . caption || 'Link' } ${ link . url } ` ; } ) ; metadata . push ( { key : 'Links' , value : subbullets , } ) ; } if ( item . deprecated || item . deprecated === '' ) { metadata . push ( { key : 'Deprecated' , value : item . deprecated || 'This may not be available in future releases' , } ) ; } if ( metadata . length ) { str += '\\n' ; metadata . forEach ( meta => { str += ` \\n ${ meta . key } ${ meta . value } ` ; } ) ; } return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a markdown file of documented Sass items [CODESPLIT] async function createMarkdown ( sourceDir , config ) { config = config || { } ; return sassdoc . parse ( sourceDir , config ) . then ( data => { let markdownFile = '' ; const documentedItems = data . filter ( ( item , index ) => item . access === 'public' || item . access === 'private' ) ; markdownFile += ` ` ; let currentGroup = '' ; documentedItems . forEach ( item => { const itemGroup = createGroupName ( item . group ) ; if ( itemGroup !== currentGroup ) { markdownFile += ` \\n \\n ${ itemGroup } ` ; currentGroup = itemGroup ; } markdownFile += createMarkdownItem ( item ) ; } ) ; return prettier . format ( toc . insert ( markdownFile , { slugify } ) , prettierOptions ) ; } , err => { console . error ( err ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The goal here is to create a top - level build folder with content to be displayed in the gh - pages branch . Specifically we want packages available at : packages / <package - name > / examples / <example - name > to be mirrored over in the build folder at : build / <package - name > / examples / <example - name > . [CODESPLIT] async function main ( ) { reporter . info ( 'Building examples...' ) ; await fs . remove ( BUILD_DIR ) ; await fs . ensureDir ( BUILD_DIR ) ; const packageNames = await fs . readdir ( PACKAGES_DIR ) ; const packages = await Promise . all ( packageNames . map ( async name => { // Verify that each file that we read from the packages directory is // actually a folder. Typically used to catch `.DS_store` files that // accidentally appear when opening with MacOS Finder const filepath = path . join ( PACKAGES_DIR , name ) ; const stat = await fs . lstat ( filepath ) ; const descriptor = { filepath , name , } ; if ( ! stat . isDirectory ( ) ) { throw new Error ( ` ${ name } ${ filepath } ` ) ; } // Try and figure out if the package has an examples directory, if not // then we can skip it const examplesDir = path . join ( filepath , 'examples' ) ; if ( ! ( await fs . pathExists ( examplesDir ) ) ) { return descriptor ; } const examples = ( await fs . readdir ( examplesDir ) ) . filter ( example => { return example !== '.yarnrc' && ! IGNORE_EXAMPLE_DIRS . has ( example ) ; } ) ; return { ... descriptor , examples : examples . map ( name => ( { filepath : path . join ( examplesDir , name ) , name , } ) ) , } ; } ) ) ; const packagesWithExamples = packages . filter ( pkg => Array . isArray ( pkg . examples ) && pkg . examples . length !== 0 ) ; await Promise . all ( packagesWithExamples . map ( async pkg => { reporter . info ( ` \\` ${ pkg . name } \\` ` ) ; const { examples , filepath , name } = pkg ; const packageDir = path . join ( BUILD_DIR , name , 'examples' ) ; await fs . ensureDir ( packageDir ) ; await Promise . all ( examples . map ( async example => { reporter . info ( ` \\` ${ example . name } \\` \\` ${ pkg . name } \\` ` ) ; const exampleDir = path . join ( packageDir , example . name ) ; const exampleBuildDir = path . join ( example . filepath , 'build' ) ; const packageJsonPath = path . join ( example . filepath , 'package.json' ) ; const packageJson = await fs . readJson ( packageJsonPath ) ; await fs . ensureDir ( exampleDir ) ; if ( packageJson . scripts . build ) { spawn . sync ( 'yarn' , [ 'install' ] , { stdio : 'ignore' , cwd : example . filepath , } ) ; spawn . sync ( 'yarn' , [ 'build' ] , { stdio : 'ignore' , cwd : example . filepath , } ) ; } if ( await fs . pathExists ( exampleBuildDir ) ) { await fs . copy ( exampleBuildDir , exampleDir ) ; return ; } await fs . copy ( example . filepath , exampleDir , { filter ( src , dest ) { const relativePath = path . relative ( example . filepath , src ) ; if ( relativePath . includes ( 'node_modules' ) ) { return false ; } if ( relativePath [ 0 ] === '.' ) { return false ; } return true ; } , } ) ; reporter . success ( ` \\` ${ example . name } \\` \\` ${ pkg . name } \\` ` ) ; } ) ) ; reporter . success ( ` \\` ${ pkg . name } \\` ` ) ; } ) ) ; const links = packagesWithExamples . reduce ( ( html , pkg ) => { const links = pkg . examples . reduce ( ( acc , example ) => { const href = ` ${ pkg . name } ${ example . name } ` ; return acc + ` ${ href } ${ example . name } ` ; } , '' ) ; return ( html + '\\n' + ` ${ pkg . name } ${ links } ` ) ; } , '' ) ; const indexFile = ` ${ links } ` ; await fs . writeFile ( path . join ( BUILD_DIR , 'index.html' ) , indexFile ) ; // Copy icons over, useful for adding download links await fs . copy ( path . resolve ( __dirname , '../packages/icons/svg' ) , path . join ( BUILD_DIR , 'icons/svg' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this . options create - component mix - in creates prototype chain so that options given in constructor argument wins over the one defined in static options property Flatpickr wants flat structure of object instead [CODESPLIT] function flattenOptions ( options ) { const o = { } ; // eslint-disable-next-line guard-for-in, no-restricted-syntax for ( const key in options ) { o [ key ] = options [ key ] ; } return o ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append list item [CODESPLIT] function append ( str , prefix = '' ) { const item = document . createElement ( 'li' ) ; item . textContent = prefix + str ; list . appendChild ( item ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorting method for multires nodes . [CODESPLIT] function multiresNodeSort ( a , b ) { // Base tiles are always first if ( a . level == 1 && b . level != 1 ) { return - 1 ; } if ( b . level == 1 && a . level != 1 ) { return 1 ; } // Higher timestamp first return b . timestamp - a . timestamp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorting method for multires node rendering . [CODESPLIT] function multiresNodeRenderSort ( a , b ) { // Lower zoom levels first if ( a . level != b . level ) { return a . level - b . level ; } // Lower distance from center first return a . diff - b . diff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws multires nodes . [CODESPLIT] function multiresDraw ( ) { if ( ! program . drawInProgress ) { program . drawInProgress = true ; gl . clear ( gl . COLOR_BUFFER_BIT ) ; for ( var i = 0 ; i < program . currentNodes . length ; i ++ ) { if ( program . currentNodes [ i ] . textureLoaded > 1 ) { //var color = program.currentNodes[i].color; //gl.uniform4f(program.colorUniform, color[0], color[1], color[2], 1.0); // Bind vertex buffer and pass vertices to WebGL gl . bindBuffer ( gl . ARRAY_BUFFER , cubeVertBuf ) ; gl . bufferData ( gl . ARRAY_BUFFER , new Float32Array ( program . currentNodes [ i ] . vertices ) , gl . STATIC_DRAW ) ; gl . vertexAttribPointer ( program . vertPosLocation , 3 , gl . FLOAT , false , 0 , 0 ) ; // Prep for texture gl . bindBuffer ( gl . ARRAY_BUFFER , cubeVertTexCoordBuf ) ; gl . vertexAttribPointer ( program . texCoordLocation , 2 , gl . FLOAT , false , 0 , 0 ) ; // Bind texture and draw tile gl . bindTexture ( gl . TEXTURE_2D , program . currentNodes [ i ] . texture ) ; // Bind program.currentNodes[i].texture to TEXTURE0 gl . drawElements ( gl . TRIANGLES , 6 , gl . UNSIGNED_SHORT , 0 ) ; } } program . drawInProgress = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new multires node . [CODESPLIT] function MultiresNode ( vertices , side , level , x , y , path ) { this . vertices = vertices ; this . side = side ; this . level = level ; this . x = x ; this . y = y ; this . path = path . replace ( '%s' , side ) . replace ( '%l' , level ) . replace ( '%x' , x ) . replace ( '%y' , y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rotates a 3x3 matrix . [CODESPLIT] function rotateMatrix ( m , angle , axis ) { var s = Math . sin ( angle ) ; var c = Math . cos ( angle ) ; if ( axis == 'x' ) { return [ m [ 0 ] , c * m [ 1 ] + s * m [ 2 ] , c * m [ 2 ] - s * m [ 1 ] , m [ 3 ] , c * m [ 4 ] + s * m [ 5 ] , c * m [ 5 ] - s * m [ 4 ] , m [ 6 ] , c * m [ 7 ] + s * m [ 8 ] , c * m [ 8 ] - s * m [ 7 ] ] ; } if ( axis == 'y' ) { return [ c * m [ 0 ] - s * m [ 2 ] , m [ 1 ] , c * m [ 2 ] + s * m [ 0 ] , c * m [ 3 ] - s * m [ 5 ] , m [ 4 ] , c * m [ 5 ] + s * m [ 3 ] , c * m [ 6 ] - s * m [ 8 ] , m [ 7 ] , c * m [ 8 ] + s * m [ 6 ] ] ; } if ( axis == 'z' ) { return [ c * m [ 0 ] + s * m [ 1 ] , c * m [ 1 ] - s * m [ 0 ] , m [ 2 ] , c * m [ 3 ] + s * m [ 4 ] , c * m [ 4 ] - s * m [ 3 ] , m [ 5 ] , c * m [ 6 ] + s * m [ 7 ] , c * m [ 7 ] - s * m [ 6 ] , m [ 8 ] ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turns a 3x3 matrix into a 4x4 matrix . [CODESPLIT] function makeMatrix4 ( m ) { return [ m [ 0 ] , m [ 1 ] , m [ 2 ] , 0 , m [ 3 ] , m [ 4 ] , m [ 5 ] , 0 , m [ 6 ] , m [ 7 ] , m [ 8 ] , 0 , 0 , 0 , 0 , 1 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a perspective matrix . [CODESPLIT] function makePersp ( hfov , aspect , znear , zfar ) { var fovy = 2 * Math . atan ( Math . tan ( hfov / 2 ) * gl . drawingBufferHeight / gl . drawingBufferWidth ) ; var f = 1 / Math . tan ( fovy / 2 ) ; return [ f / aspect , 0 , 0 , 0 , 0 , f , 0 , 0 , 0 , 0 , ( zfar + znear ) / ( znear - zfar ) , ( 2 * zfar * znear ) / ( znear - zfar ) , 0 , 0 , - 1 , 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes a loaded texture image into a WebGL texture . [CODESPLIT] function processLoadedTexture ( img , tex ) { gl . bindTexture ( gl . TEXTURE_2D , tex ) ; gl . texImage2D ( gl . TEXTURE_2D , 0 , gl . RGB , gl . RGB , gl . UNSIGNED_BYTE , img ) ; gl . texParameteri ( gl . TEXTURE_2D , gl . TEXTURE_MAG_FILTER , gl . LINEAR ) ; gl . texParameteri ( gl . TEXTURE_2D , gl . TEXTURE_MIN_FILTER , gl . LINEAR ) ; gl . texParameteri ( gl . TEXTURE_2D , gl . TEXTURE_WRAP_S , gl . CLAMP_TO_EDGE ) ; gl . texParameteri ( gl . TEXTURE_2D , gl . TEXTURE_WRAP_T , gl . CLAMP_TO_EDGE ) ; gl . bindTexture ( gl . TEXTURE_2D , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads image and creates texture for a multires node / tile . [CODESPLIT] function processNextTile ( node ) { loadTexture ( node , encodeURI ( node . path + '.' + image . extension ) , function ( texture , loaded ) { node . texture = texture ; node . textureLoaded = loaded ? 2 : 1 ; } , globalParams . crossOrigin ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds and applies optimal multires zoom level . [CODESPLIT] function checkZoom ( hfov ) { // Find optimal level var newLevel = 1 ; while ( newLevel < image . maxLevel && gl . drawingBufferWidth > image . tileResolution * Math . pow ( 2 , newLevel - 1 ) * Math . tan ( hfov / 2 ) * 0.707 ) { newLevel ++ ; } // Apply change program . level = newLevel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rotates perspective matrix . [CODESPLIT] function rotatePersp ( p , r ) { return [ p [ 0 ] * r [ 0 ] , p [ 0 ] * r [ 1 ] , p [ 0 ] * r [ 2 ] , 0 , p [ 5 ] * r [ 4 ] , p [ 5 ] * r [ 5 ] , p [ 5 ] * r [ 6 ] , 0 , p [ 10 ] * r [ 8 ] , p [ 10 ] * r [ 9 ] , p [ 10 ] * r [ 10 ] , p [ 11 ] , - r [ 8 ] , - r [ 9 ] , - r [ 10 ] , 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies rotated perspective matrix to a 3 - vector ( last element is inverted ) . [CODESPLIT] function applyRotPerspToVec ( m , v ) { return [ m [ 0 ] * v [ 0 ] + m [ 1 ] * v [ 1 ] + m [ 2 ] * v [ 2 ] , m [ 4 ] * v [ 0 ] + m [ 5 ] * v [ 1 ] + m [ 6 ] * v [ 2 ] , m [ 11 ] + m [ 8 ] * v [ 0 ] + m [ 9 ] * v [ 1 ] + m [ 10 ] * v [ 2 ] , 1 / ( m [ 12 ] * v [ 0 ] + m [ 13 ] * v [ 1 ] + m [ 14 ] * v [ 2 ] ) ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a vertex is visible . [CODESPLIT] function checkInView ( m , v ) { var vpp = applyRotPerspToVec ( m , v ) ; var winX = vpp [ 0 ] * vpp [ 3 ] ; var winY = vpp [ 1 ] * vpp [ 3 ] ; var winZ = vpp [ 2 ] * vpp [ 3 ] ; var ret = [ 0 , 0 , 0 ] ; if ( winX < - 1 ) ret [ 0 ] = - 1 ; if ( winX > 1 ) ret [ 0 ] = 1 ; if ( winY < - 1 ) ret [ 1 ] = - 1 ; if ( winY > 1 ) ret [ 1 ] = 1 ; if ( winZ < - 1 || winZ > 1 ) ret [ 2 ] = 1 ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a square ( tile ) is visible . [CODESPLIT] function checkSquareInView ( m , v ) { var check1 = checkInView ( m , v . slice ( 0 , 3 ) ) ; var check2 = checkInView ( m , v . slice ( 3 , 6 ) ) ; var check3 = checkInView ( m , v . slice ( 6 , 9 ) ) ; var check4 = checkInView ( m , v . slice ( 9 , 12 ) ) ; var testX = check1 [ 0 ] + check2 [ 0 ] + check3 [ 0 ] + check4 [ 0 ] ; if ( testX == - 4 || testX == 4 ) return false ; var testY = check1 [ 1 ] + check2 [ 1 ] + check3 [ 1 ] + check4 [ 1 ] ; if ( testY == - 4 || testY == 4 ) return false ; var testZ = check1 [ 2 ] + check2 [ 2 ] + check3 [ 2 ] + check4 [ 2 ] ; return testZ != 4 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "On iOS ( iPhone 5c iOS 10 . 3 ) this WebGL error occurs when the canvas is too big . Unfortuately there s no way to test for this beforehand so we reduce the canvas size if this error is thrown . [CODESPLIT] function handleWebGLError1286 ( ) { console . log ( 'Reducing canvas size due to error 1286!' ) ; canvas . width = Math . round ( canvas . width / 2 ) ; canvas . height = Math . round ( canvas . height / 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes viewer . [CODESPLIT] function init ( ) { // Display an error for IE 9 as it doesn't work but also doesn't otherwise // show an error (older versions don't work at all) // Based on: http://stackoverflow.com/a/10965203 var div = document . createElement ( \"div\" ) ; div . innerHTML = \"<!--[if lte IE 9]><i></i><![endif]-->\" ; if ( div . getElementsByTagName ( \"i\" ) . length == 1 ) { anError ( ) ; return ; } origHfov = config . hfov ; origPitch = config . pitch ; var i , p ; if ( config . type == 'cubemap' ) { panoImage = [ ] ; for ( i = 0 ; i < 6 ; i ++ ) { panoImage . push ( new Image ( ) ) ; panoImage [ i ] . crossOrigin = config . crossOrigin ; } infoDisplay . load . lbox . style . display = 'block' ; infoDisplay . load . lbar . style . display = 'none' ; } else if ( config . type == 'multires' ) { var c = JSON . parse ( JSON . stringify ( config . multiRes ) ) ; // Deep copy // Avoid \"undefined\" in path, check (optional) multiRes.basePath, too // Use only multiRes.basePath if it's an absolute URL if ( config . basePath && config . multiRes . basePath && ! ( / ^(?:[a-z]+:)?\\/\\/ / i . test ( config . multiRes . basePath ) ) ) { c . basePath = config . basePath + config . multiRes . basePath ; } else if ( config . multiRes . basePath ) { c . basePath = config . multiRes . basePath ; } else if ( config . basePath ) { c . basePath = config . basePath ; } panoImage = c ; } else { if ( config . dynamic === true ) { panoImage = config . panorama ; } else { if ( config . panorama === undefined ) { anError ( config . strings . noPanoramaError ) ; return ; } panoImage = new Image ( ) ; } } // Configure image loading if ( config . type == 'cubemap' ) { // Quick loading counter for synchronous loading var itemsToLoad = 6 ; var onLoad = function ( ) { itemsToLoad -- ; if ( itemsToLoad === 0 ) { onImageLoad ( ) ; } } ; var onError = function ( e ) { var a = document . createElement ( 'a' ) ; a . href = e . target . src ; a . textContent = a . href ; anError ( config . strings . fileAccessError . replace ( '%s' , a . outerHTML ) ) ; } ; for ( i = 0 ; i < panoImage . length ; i ++ ) { p = config . cubeMap [ i ] ; if ( p == \"null\" ) { // support partial cubemap image with explicitly empty faces console . log ( 'Will use background instead of missing cubemap face ' + i ) ; onLoad ( ) ; } else { if ( config . basePath && ! absoluteURL ( p ) ) { p = config . basePath + p ; } panoImage [ i ] . onload = onLoad ; panoImage [ i ] . onerror = onError ; panoImage [ i ] . src = sanitizeURL ( p ) ; } } } else if ( config . type == 'multires' ) { onImageLoad ( ) ; } else { p = '' ; if ( config . basePath ) { p = config . basePath ; } if ( config . dynamic !== true ) { // Still image p = absoluteURL ( config . panorama ) ? config . panorama : p + config . panorama ; panoImage . onload = function ( ) { window . URL . revokeObjectURL ( this . src ) ; // Clean up onImageLoad ( ) ; } ; var xhr = new XMLHttpRequest ( ) ; xhr . onloadend = function ( ) { if ( xhr . status != 200 ) { // Display error if image can't be loaded var a = document . createElement ( 'a' ) ; a . href = p ; a . textContent = a . href ; anError ( config . strings . fileAccessError . replace ( '%s' , a . outerHTML ) ) ; } var img = this . response ; parseGPanoXMP ( img ) ; infoDisplay . load . msg . innerHTML = '' ; } ; xhr . onprogress = function ( e ) { if ( e . lengthComputable ) { // Display progress var percent = e . loaded / e . total * 100 ; infoDisplay . load . lbarFill . style . width = percent + '%' ; var unit , numerator , denominator ; if ( e . total > 1e6 ) { unit = 'MB' ; numerator = ( e . loaded / 1e6 ) . toFixed ( 2 ) ; denominator = ( e . total / 1e6 ) . toFixed ( 2 ) ; } else if ( e . total > 1e3 ) { unit = 'kB' ; numerator = ( e . loaded / 1e3 ) . toFixed ( 1 ) ; denominator = ( e . total / 1e3 ) . toFixed ( 1 ) ; } else { unit = 'B' ; numerator = e . loaded ; denominator = e . total ; } infoDisplay . load . msg . innerHTML = numerator + ' / ' + denominator + ' ' + unit ; } else { // Display loading spinner infoDisplay . load . lbox . style . display = 'block' ; infoDisplay . load . lbar . style . display = 'none' ; } } ; try { xhr . open ( 'GET' , p , true ) ; } catch ( e ) { // Malformed URL anError ( config . strings . malformedURLError ) ; } xhr . responseType = 'blob' ; xhr . setRequestHeader ( 'Accept' , 'image/*,*/*;q=0.9' ) ; xhr . withCredentials = config . crossOrigin === 'use-credentials' ; xhr . send ( ) ; } } if ( config . draggable ) uiContainer . classList . add ( 'pnlm-grab' ) ; uiContainer . classList . remove ( 'pnlm-grabbing' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create renderer and initialize event listeners once image is loaded . [CODESPLIT] function onImageLoad ( ) { if ( ! renderer ) renderer = new libpannellum . renderer ( renderContainer ) ; // Only add event listeners once if ( ! listenersAdded ) { listenersAdded = true ; dragFix . addEventListener ( 'mousedown' , onDocumentMouseDown , false ) ; document . addEventListener ( 'mousemove' , onDocumentMouseMove , false ) ; document . addEventListener ( 'mouseup' , onDocumentMouseUp , false ) ; if ( config . mouseZoom ) { uiContainer . addEventListener ( 'mousewheel' , onDocumentMouseWheel , false ) ; uiContainer . addEventListener ( 'DOMMouseScroll' , onDocumentMouseWheel , false ) ; } if ( config . doubleClickZoom ) { dragFix . addEventListener ( 'dblclick' , onDocumentDoubleClick , false ) ; } container . addEventListener ( 'mozfullscreenchange' , onFullScreenChange , false ) ; container . addEventListener ( 'webkitfullscreenchange' , onFullScreenChange , false ) ; container . addEventListener ( 'msfullscreenchange' , onFullScreenChange , false ) ; container . addEventListener ( 'fullscreenchange' , onFullScreenChange , false ) ; window . addEventListener ( 'resize' , onDocumentResize , false ) ; window . addEventListener ( 'orientationchange' , onDocumentResize , false ) ; if ( ! config . disableKeyboardCtrl ) { container . addEventListener ( 'keydown' , onDocumentKeyPress , false ) ; container . addEventListener ( 'keyup' , onDocumentKeyUp , false ) ; container . addEventListener ( 'blur' , clearKeys , false ) ; } document . addEventListener ( 'mouseleave' , onDocumentMouseUp , false ) ; if ( document . documentElement . style . pointerAction === '' && document . documentElement . style . touchAction === '' ) { dragFix . addEventListener ( 'pointerdown' , onDocumentPointerDown , false ) ; dragFix . addEventListener ( 'pointermove' , onDocumentPointerMove , false ) ; dragFix . addEventListener ( 'pointerup' , onDocumentPointerUp , false ) ; dragFix . addEventListener ( 'pointerleave' , onDocumentPointerUp , false ) ; } else { dragFix . addEventListener ( 'touchstart' , onDocumentTouchStart , false ) ; dragFix . addEventListener ( 'touchmove' , onDocumentTouchMove , false ) ; dragFix . addEventListener ( 'touchend' , onDocumentTouchEnd , false ) ; } // Deal with MS pointer events if ( window . navigator . pointerEnabled ) container . style . touchAction = 'none' ; } renderInit ( ) ; setHfov ( config . hfov ) ; // possibly adapt hfov after configuration and canvas is complete; prevents empty space on top or bottom by zomming out too much setTimeout ( function ( ) { isTimedOut = true ; } , 500 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the requested tag from the XMP data [CODESPLIT] function ( tag ) { var result ; if ( xmpData . indexOf ( tag + '=\"' ) >= 0 ) { result = xmpData . substring ( xmpData . indexOf ( tag + '=\"' ) + tag . length + 2 ) ; result = result . substring ( 0 , result . indexOf ( '\"' ) ) ; } else if ( xmpData . indexOf ( tag + '>' ) >= 0 ) { result = xmpData . substring ( xmpData . indexOf ( tag + '>' ) + tag . length + 1 ) ; result = result . substring ( 0 , result . indexOf ( '<' ) ) ; } if ( result !== undefined ) { return Number ( result ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Displays an error message . [CODESPLIT] function anError ( errorMsg ) { if ( errorMsg === undefined ) errorMsg = config . strings . genericWebGLError ; infoDisplay . errorMsg . innerHTML = '<p>' + errorMsg + '</p>' ; controls . load . style . display = 'none' ; infoDisplay . load . box . style . display = 'none' ; infoDisplay . errorMsg . style . display = 'table' ; error = true ; renderContainer . style . display = 'none' ; fireEvent ( 'error' , errorMsg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hides error message display . [CODESPLIT] function clearError ( ) { if ( error ) { infoDisplay . load . box . style . display = 'none' ; infoDisplay . errorMsg . style . display = 'none' ; error = false ; fireEvent ( 'errorcleared' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Displays about message . [CODESPLIT] function aboutMessage ( event ) { var pos = mousePosition ( event ) ; aboutMsg . style . left = pos . x + 'px' ; aboutMsg . style . top = pos . y + 'px' ; clearTimeout ( aboutMessage . t1 ) ; clearTimeout ( aboutMessage . t2 ) ; aboutMsg . style . display = 'block' ; aboutMsg . style . opacity = 1 ; aboutMessage . t1 = setTimeout ( function ( ) { aboutMsg . style . opacity = 0 ; } , 2000 ) ; aboutMessage . t2 = setTimeout ( function ( ) { aboutMsg . style . display = 'none' ; } , 2500 ) ; event . preventDefault ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate mouse position relative to top left of viewer container . [CODESPLIT] function mousePosition ( event ) { var bounds = container . getBoundingClientRect ( ) ; var pos = { } ; // pageX / pageY needed for iOS pos . x = ( event . clientX || event . pageX ) - bounds . left ; pos . y = ( event . clientY || event . pageY ) - bounds . top ; return pos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for mouse clicks . Initializes panning . Prints center and click location coordinates when hot spot debugging is enabled . [CODESPLIT] function onDocumentMouseDown ( event ) { // Override default action event . preventDefault ( ) ; // But not all of it container . focus ( ) ; // Only do something if the panorama is loaded if ( ! loaded || ! config . draggable ) { return ; } // Calculate mouse position relative to top left of viewer container var pos = mousePosition ( event ) ; // Log pitch / yaw of mouse click when debugging / placing hot spots if ( config . hotSpotDebug ) { var coords = mouseEventToCoords ( event ) ; console . log ( 'Pitch: ' + coords [ 0 ] + ', Yaw: ' + coords [ 1 ] + ', Center Pitch: ' + config . pitch + ', Center Yaw: ' + config . yaw + ', HFOV: ' + config . hfov ) ; } // Turn off auto-rotation if enabled stopAnimation ( ) ; stopOrientation ( ) ; config . roll = 0 ; speed . hfov = 0 ; isUserInteracting = true ; latestInteraction = Date . now ( ) ; onPointerDownPointerX = pos . x ; onPointerDownPointerY = pos . y ; onPointerDownYaw = config . yaw ; onPointerDownPitch = config . pitch ; uiContainer . classList . add ( 'pnlm-grabbing' ) ; uiContainer . classList . remove ( 'pnlm-grab' ) ; fireEvent ( 'mousedown' , event ) ; animateInit ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for double clicks . Zooms in at clicked location [CODESPLIT] function onDocumentDoubleClick ( event ) { if ( config . minHfov === config . hfov ) { _this . setHfov ( origHfov , 1000 ) ; } else { var coords = mouseEventToCoords ( event ) ; _this . lookAt ( coords [ 0 ] , coords [ 1 ] , config . minHfov , 1000 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate panorama pitch and yaw from location of mouse event . [CODESPLIT] function mouseEventToCoords ( event ) { var pos = mousePosition ( event ) ; var canvas = renderer . getCanvas ( ) ; var canvasWidth = canvas . clientWidth , canvasHeight = canvas . clientHeight ; var x = pos . x / canvasWidth * 2 - 1 ; var y = ( 1 - pos . y / canvasHeight * 2 ) * canvasHeight / canvasWidth ; var focal = 1 / Math . tan ( config . hfov * Math . PI / 360 ) ; var s = Math . sin ( config . pitch * Math . PI / 180 ) ; var c = Math . cos ( config . pitch * Math . PI / 180 ) ; var a = focal * c - y * s ; var root = Math . sqrt ( x * x + a * a ) ; var pitch = Math . atan ( ( y * c + focal * s ) / root ) * 180 / Math . PI ; var yaw = Math . atan2 ( x / root , a / root ) * 180 / Math . PI + config . yaw ; if ( yaw < - 180 ) yaw += 360 ; if ( yaw > 180 ) yaw -= 360 ; return [ pitch , yaw ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for mouse moves . Pans center of view . [CODESPLIT] function onDocumentMouseMove ( event ) { if ( isUserInteracting && loaded ) { latestInteraction = Date . now ( ) ; var canvas = renderer . getCanvas ( ) ; var canvasWidth = canvas . clientWidth , canvasHeight = canvas . clientHeight ; var pos = mousePosition ( event ) ; //TODO: This still isn't quite right var yaw = ( ( Math . atan ( onPointerDownPointerX / canvasWidth * 2 - 1 ) - Math . atan ( pos . x / canvasWidth * 2 - 1 ) ) * 180 / Math . PI * config . hfov / 90 ) + onPointerDownYaw ; speed . yaw = ( yaw - config . yaw ) % 360 * 0.2 ; config . yaw = yaw ; var vfov = 2 * Math . atan ( Math . tan ( config . hfov / 360 * Math . PI ) * canvasHeight / canvasWidth ) * 180 / Math . PI ; var pitch = ( ( Math . atan ( pos . y / canvasHeight * 2 - 1 ) - Math . atan ( onPointerDownPointerY / canvasHeight * 2 - 1 ) ) * 180 / Math . PI * vfov / 90 ) + onPointerDownPitch ; speed . pitch = ( pitch - config . pitch ) * 0.2 ; config . pitch = pitch ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for mouse up events . Stops panning . [CODESPLIT] function onDocumentMouseUp ( event ) { if ( ! isUserInteracting ) { return ; } isUserInteracting = false ; if ( Date . now ( ) - latestInteraction > 15 ) { // Prevents jump when user rapidly moves mouse, stops, and then // releases the mouse button speed . pitch = speed . yaw = 0 ; } uiContainer . classList . add ( 'pnlm-grab' ) ; uiContainer . classList . remove ( 'pnlm-grabbing' ) ; latestInteraction = Date . now ( ) ; fireEvent ( 'mouseup' , event ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for touches . Initializes panning if one touch or zooming if two touches . [CODESPLIT] function onDocumentTouchStart ( event ) { // Only do something if the panorama is loaded if ( ! loaded || ! config . draggable ) { return ; } // Turn off auto-rotation if enabled stopAnimation ( ) ; stopOrientation ( ) ; config . roll = 0 ; speed . hfov = 0 ; // Calculate touch position relative to top left of viewer container var pos0 = mousePosition ( event . targetTouches [ 0 ] ) ; onPointerDownPointerX = pos0 . x ; onPointerDownPointerY = pos0 . y ; if ( event . targetTouches . length == 2 ) { // Down pointer is the center of the two fingers var pos1 = mousePosition ( event . targetTouches [ 1 ] ) ; onPointerDownPointerX += ( pos1 . x - pos0 . x ) * 0.5 ; onPointerDownPointerY += ( pos1 . y - pos0 . y ) * 0.5 ; onPointerDownPointerDist = Math . sqrt ( ( pos0 . x - pos1 . x ) * ( pos0 . x - pos1 . x ) + ( pos0 . y - pos1 . y ) * ( pos0 . y - pos1 . y ) ) ; } isUserInteracting = true ; latestInteraction = Date . now ( ) ; onPointerDownYaw = config . yaw ; onPointerDownPitch = config . pitch ; fireEvent ( 'touchstart' , event ) ; animateInit ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for touch movements . Pans center of view if one touch or adjusts zoom if two touches . [CODESPLIT] function onDocumentTouchMove ( event ) { if ( ! config . draggable ) { return ; } // Override default action event . preventDefault ( ) ; if ( loaded ) { latestInteraction = Date . now ( ) ; } if ( isUserInteracting && loaded ) { var pos0 = mousePosition ( event . targetTouches [ 0 ] ) ; var clientX = pos0 . x ; var clientY = pos0 . y ; if ( event . targetTouches . length == 2 && onPointerDownPointerDist != - 1 ) { var pos1 = mousePosition ( event . targetTouches [ 1 ] ) ; clientX += ( pos1 . x - pos0 . x ) * 0.5 ; clientY += ( pos1 . y - pos0 . y ) * 0.5 ; var clientDist = Math . sqrt ( ( pos0 . x - pos1 . x ) * ( pos0 . x - pos1 . x ) + ( pos0 . y - pos1 . y ) * ( pos0 . y - pos1 . y ) ) ; setHfov ( config . hfov + ( onPointerDownPointerDist - clientDist ) * 0.1 ) ; onPointerDownPointerDist = clientDist ; } // The smaller the config.hfov value (the more zoomed-in the user is), the faster // yaw/pitch are perceived to change on one-finger touchmove (panning) events and vice versa. // To improve usability at both small and large zoom levels (config.hfov values) // we introduce a dynamic pan speed coefficient. // // Currently this seems to *roughly* keep initial drag/pan start position close to // the user's finger while panning regardless of zoom level / config.hfov value. var touchmovePanSpeedCoeff = ( config . hfov / 360 ) * config . touchPanSpeedCoeffFactor ; var yaw = ( onPointerDownPointerX - clientX ) * touchmovePanSpeedCoeff + onPointerDownYaw ; speed . yaw = ( yaw - config . yaw ) % 360 * 0.2 ; config . yaw = yaw ; var pitch = ( clientY - onPointerDownPointerY ) * touchmovePanSpeedCoeff + onPointerDownPitch ; speed . pitch = ( pitch - config . pitch ) * 0.2 ; config . pitch = pitch ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for end of touches . Stops panning and / or zooming . [CODESPLIT] function onDocumentTouchEnd ( ) { isUserInteracting = false ; if ( Date . now ( ) - latestInteraction > 150 ) { speed . pitch = speed . yaw = 0 ; } onPointerDownPointerDist = - 1 ; latestInteraction = Date . now ( ) ; fireEvent ( 'touchend' , event ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for touch starts in IE / Edge . [CODESPLIT] function onDocumentPointerDown ( event ) { if ( event . pointerType == 'touch' ) { pointerIDs . push ( event . pointerId ) ; pointerCoordinates . push ( { clientX : event . clientX , clientY : event . clientY } ) ; event . targetTouches = pointerCoordinates ; onDocumentTouchStart ( event ) ; event . preventDefault ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for touch moves in IE / Edge . [CODESPLIT] function onDocumentPointerMove ( event ) { if ( event . pointerType == 'touch' ) { for ( var i = 0 ; i < pointerIDs . length ; i ++ ) { if ( event . pointerId == pointerIDs [ i ] ) { pointerCoordinates [ i ] . clientX = event . clientX ; pointerCoordinates [ i ] . clientY = event . clientY ; event . targetTouches = pointerCoordinates ; onDocumentTouchMove ( event ) ; event . preventDefault ( ) ; return ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for touch ends in IE / Edge . [CODESPLIT] function onDocumentPointerUp ( event ) { if ( event . pointerType == 'touch' ) { var defined = false ; for ( var i = 0 ; i < pointerIDs . length ; i ++ ) { if ( event . pointerId == pointerIDs [ i ] ) pointerIDs [ i ] = undefined ; if ( pointerIDs [ i ] ) defined = true ; } if ( ! defined ) { pointerIDs = [ ] ; pointerCoordinates = [ ] ; onDocumentTouchEnd ( ) ; } event . preventDefault ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for mouse wheel . Changes zoom . [CODESPLIT] function onDocumentMouseWheel ( event ) { // Only do something if the panorama is loaded and mouse wheel zoom is enabled if ( ! loaded || ( config . mouseZoom == 'fullscreenonly' && ! fullscreenActive ) ) { return ; } event . preventDefault ( ) ; // Turn off auto-rotation if enabled stopAnimation ( ) ; latestInteraction = Date . now ( ) ; if ( event . wheelDeltaY ) { // WebKit setHfov ( config . hfov - event . wheelDeltaY * 0.05 ) ; speed . hfov = event . wheelDelta < 0 ? 1 : - 1 ; } else if ( event . wheelDelta ) { // Opera / Explorer 9 setHfov ( config . hfov - event . wheelDelta * 0.05 ) ; speed . hfov = event . wheelDelta < 0 ? 1 : - 1 ; } else if ( event . detail ) { // Firefox setHfov ( config . hfov + event . detail * 1.5 ) ; speed . hfov = event . detail > 0 ? 1 : - 1 ; } animateInit ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for key presses . Updates list of currently pressed keys . [CODESPLIT] function onDocumentKeyPress ( event ) { // Turn off auto-rotation if enabled stopAnimation ( ) ; latestInteraction = Date . now ( ) ; stopOrientation ( ) ; config . roll = 0 ; // Record key pressed var keynumber = event . which || event . keycode ; // Override default action for keys that are used if ( config . capturedKeyNumbers . indexOf ( keynumber ) < 0 ) return ; event . preventDefault ( ) ; // If escape key is pressed if ( keynumber == 27 ) { // If in fullscreen mode if ( fullscreenActive ) { toggleFullscreen ( ) ; } } else { // Change key changeKey ( keynumber , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for key releases . Updates list of currently pressed keys . [CODESPLIT] function onDocumentKeyUp ( event ) { // Record key pressed var keynumber = event . which || event . keycode ; // Override default action for keys that are used if ( config . capturedKeyNumbers . indexOf ( keynumber ) < 0 ) return ; event . preventDefault ( ) ; // Change key changeKey ( keynumber , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates list of currently pressed keys . [CODESPLIT] function changeKey ( keynumber , value ) { var keyChanged = false ; switch ( keynumber ) { // If minus key is released case 109 : case 189 : case 17 : case 173 : if ( keysDown [ 0 ] != value ) { keyChanged = true ; } keysDown [ 0 ] = value ; break ; // If plus key is released case 107 : case 187 : case 16 : case 61 : if ( keysDown [ 1 ] != value ) { keyChanged = true ; } keysDown [ 1 ] = value ; break ; // If up arrow is released case 38 : if ( keysDown [ 2 ] != value ) { keyChanged = true ; } keysDown [ 2 ] = value ; break ; // If \"w\" is released case 87 : if ( keysDown [ 6 ] != value ) { keyChanged = true ; } keysDown [ 6 ] = value ; break ; // If down arrow is released case 40 : if ( keysDown [ 3 ] != value ) { keyChanged = true ; } keysDown [ 3 ] = value ; break ; // If \"s\" is released case 83 : if ( keysDown [ 7 ] != value ) { keyChanged = true ; } keysDown [ 7 ] = value ; break ; // If left arrow is released case 37 : if ( keysDown [ 4 ] != value ) { keyChanged = true ; } keysDown [ 4 ] = value ; break ; // If \"a\" is released case 65 : if ( keysDown [ 8 ] != value ) { keyChanged = true ; } keysDown [ 8 ] = value ; break ; // If right arrow is released case 39 : if ( keysDown [ 5 ] != value ) { keyChanged = true ; } keysDown [ 5 ] = value ; break ; // If \"d\" is released case 68 : if ( keysDown [ 9 ] != value ) { keyChanged = true ; } keysDown [ 9 ] = value ; } if ( keyChanged && value ) { if ( typeof performance !== 'undefined' && performance . now ( ) ) { prevTime = performance . now ( ) ; } else { prevTime = Date . now ( ) ; } animateInit ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pans and / or zooms panorama based on currently pressed keys . Also handles panorama inertia and auto rotation . [CODESPLIT] function keyRepeat ( ) { // Only do something if the panorama is loaded if ( ! loaded ) { return ; } var isKeyDown = false ; var prevPitch = config . pitch ; var prevYaw = config . yaw ; var prevZoom = config . hfov ; var newTime ; if ( typeof performance !== 'undefined' && performance . now ( ) ) { newTime = performance . now ( ) ; } else { newTime = Date . now ( ) ; } if ( prevTime === undefined ) { prevTime = newTime ; } var diff = ( newTime - prevTime ) * config . hfov / 1700 ; diff = Math . min ( diff , 1.0 ) ; // If minus key is down if ( keysDown [ 0 ] && config . keyboardZoom === true ) { setHfov ( config . hfov + ( speed . hfov * 0.8 + 0.5 ) * diff ) ; isKeyDown = true ; } // If plus key is down if ( keysDown [ 1 ] && config . keyboardZoom === true ) { setHfov ( config . hfov + ( speed . hfov * 0.8 - 0.2 ) * diff ) ; isKeyDown = true ; } // If up arrow or \"w\" is down if ( keysDown [ 2 ] || keysDown [ 6 ] ) { // Pan up config . pitch += ( speed . pitch * 0.8 + 0.2 ) * diff ; isKeyDown = true ; } // If down arrow or \"s\" is down if ( keysDown [ 3 ] || keysDown [ 7 ] ) { // Pan down config . pitch += ( speed . pitch * 0.8 - 0.2 ) * diff ; isKeyDown = true ; } // If left arrow or \"a\" is down if ( keysDown [ 4 ] || keysDown [ 8 ] ) { // Pan left config . yaw += ( speed . yaw * 0.8 - 0.2 ) * diff ; isKeyDown = true ; } // If right arrow or \"d\" is down if ( keysDown [ 5 ] || keysDown [ 9 ] ) { // Pan right config . yaw += ( speed . yaw * 0.8 + 0.2 ) * diff ; isKeyDown = true ; } if ( isKeyDown ) latestInteraction = Date . now ( ) ; // If auto-rotate var inactivityInterval = Date . now ( ) - latestInteraction ; if ( config . autoRotate ) { // Pan if ( newTime - prevTime > 0.001 ) { var timeDiff = ( newTime - prevTime ) / 1000 ; var yawDiff = ( speed . yaw / timeDiff * diff - config . autoRotate * 0.2 ) * timeDiff yawDiff = ( - config . autoRotate > 0 ? 1 : - 1 ) * Math . min ( Math . abs ( config . autoRotate * timeDiff ) , Math . abs ( yawDiff ) ) ; config . yaw += yawDiff ; } // Deal with stopping auto rotation after a set delay if ( config . autoRotateStopDelay ) { config . autoRotateStopDelay -= newTime - prevTime ; if ( config . autoRotateStopDelay <= 0 ) { config . autoRotateStopDelay = false ; autoRotateSpeed = config . autoRotate ; config . autoRotate = 0 ; } } } // Animated moves if ( animatedMove . pitch ) { animateMove ( 'pitch' ) ; prevPitch = config . pitch ; } if ( animatedMove . yaw ) { animateMove ( 'yaw' ) ; prevYaw = config . yaw ; } if ( animatedMove . hfov ) { animateMove ( 'hfov' ) ; prevZoom = config . hfov ; } // \"Inertia\" if ( diff > 0 && ! config . autoRotate ) { // \"Friction\" var slowDownFactor = 1 - config . friction ; // Yaw if ( ! keysDown [ 4 ] && ! keysDown [ 5 ] && ! keysDown [ 8 ] && ! keysDown [ 9 ] && ! animatedMove . yaw ) { config . yaw += speed . yaw * diff * slowDownFactor ; } // Pitch if ( ! keysDown [ 2 ] && ! keysDown [ 3 ] && ! keysDown [ 6 ] && ! keysDown [ 7 ] && ! animatedMove . pitch ) { config . pitch += speed . pitch * diff * slowDownFactor ; } // Zoom if ( ! keysDown [ 0 ] && ! keysDown [ 1 ] && ! animatedMove . hfov ) { setHfov ( config . hfov + speed . hfov * diff * slowDownFactor ) ; } } prevTime = newTime ; if ( diff > 0 ) { speed . yaw = speed . yaw * 0.8 + ( config . yaw - prevYaw ) / diff * 0.2 ; speed . pitch = speed . pitch * 0.8 + ( config . pitch - prevPitch ) / diff * 0.2 ; speed . hfov = speed . hfov * 0.8 + ( config . hfov - prevZoom ) / diff * 0.2 ; // Limit speed var maxSpeed = config . autoRotate ? Math . abs ( config . autoRotate ) : 5 ; speed . yaw = Math . min ( maxSpeed , Math . max ( speed . yaw , - maxSpeed ) ) ; speed . pitch = Math . min ( maxSpeed , Math . max ( speed . pitch , - maxSpeed ) ) ; speed . hfov = Math . min ( maxSpeed , Math . max ( speed . hfov , - maxSpeed ) ) ; } // Stop movement if opposite controls are pressed if ( keysDown [ 0 ] && keysDown [ 1 ] ) { speed . hfov = 0 ; } if ( ( keysDown [ 2 ] || keysDown [ 6 ] ) && ( keysDown [ 3 ] || keysDown [ 7 ] ) ) { speed . pitch = 0 ; } if ( ( keysDown [ 4 ] || keysDown [ 8 ] ) && ( keysDown [ 5 ] || keysDown [ 9 ] ) ) { speed . yaw = 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Animates moves . [CODESPLIT] function animateMove ( axis ) { var t = animatedMove [ axis ] ; var normTime = Math . min ( 1 , Math . max ( ( Date . now ( ) - t . startTime ) / 1000 / ( t . duration / 1000 ) , 0 ) ) ; var result = t . startPosition + config . animationTimingFunction ( normTime ) * ( t . endPosition - t . startPosition ) ; if ( ( t . endPosition > t . startPosition && result >= t . endPosition ) || ( t . endPosition < t . startPosition && result <= t . endPosition ) || t . endPosition === t . startPosition ) { result = t . endPosition ; speed [ axis ] = 0 ; delete animatedMove [ axis ] ; } config [ axis ] = result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Animates view using requestAnimationFrame to trigger rendering . [CODESPLIT] function animate ( ) { render ( ) ; if ( autoRotateStart ) clearTimeout ( autoRotateStart ) ; if ( isUserInteracting || orientation === true ) { requestAnimationFrame ( animate ) ; } else if ( keysDown [ 0 ] || keysDown [ 1 ] || keysDown [ 2 ] || keysDown [ 3 ] || keysDown [ 4 ] || keysDown [ 5 ] || keysDown [ 6 ] || keysDown [ 7 ] || keysDown [ 8 ] || keysDown [ 9 ] || config . autoRotate || animatedMove . pitch || animatedMove . yaw || animatedMove . hfov || Math . abs ( speed . yaw ) > 0.01 || Math . abs ( speed . pitch ) > 0.01 || Math . abs ( speed . hfov ) > 0.01 ) { keyRepeat ( ) ; if ( config . autoRotateInactivityDelay >= 0 && autoRotateSpeed && Date . now ( ) - latestInteraction > config . autoRotateInactivityDelay && ! config . autoRotate ) { config . autoRotate = autoRotateSpeed ; _this . lookAt ( origPitch , undefined , origHfov , 3000 ) ; } requestAnimationFrame ( animate ) ; } else if ( renderer && ( renderer . isLoading ( ) || ( config . dynamic === true && update ) ) ) { requestAnimationFrame ( animate ) ; } else { fireEvent ( 'animatefinished' , { pitch : _this . getPitch ( ) , yaw : _this . getYaw ( ) , hfov : _this . getHfov ( ) } ) ; animating = false ; prevTime = undefined ; var autoRotateStartTime = config . autoRotateInactivityDelay - ( Date . now ( ) - latestInteraction ) ; if ( autoRotateStartTime > 0 ) { autoRotateStart = setTimeout ( function ( ) { config . autoRotate = autoRotateSpeed ; _this . lookAt ( origPitch , undefined , origHfov , 3000 ) ; animateInit ( ) ; } , autoRotateStartTime ) ; } else if ( config . autoRotateInactivityDelay >= 0 && autoRotateSpeed ) { config . autoRotate = autoRotateSpeed ; _this . lookAt ( origPitch , undefined , origHfov , 3000 ) ; animateInit ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders panorama view . [CODESPLIT] function render ( ) { var tmpyaw ; if ( loaded ) { // Keep a tmp value of yaw for autoRotate comparison later tmpyaw = config . yaw ; // Optionally avoid showing background (empty space) on left or right by adapting min/max yaw var hoffcut = 0 , voffcut = 0 ; if ( config . avoidShowingBackground ) { var canvas = renderer . getCanvas ( ) , hfov2 = config . hfov / 2 , vfov2 = Math . atan2 ( Math . tan ( hfov2 / 180 * Math . PI ) , ( canvas . width / canvas . height ) ) * 180 / Math . PI , transposed = config . vaov > config . haov ; if ( transposed ) { voffcut = vfov2 * ( 1 - Math . min ( Math . cos ( ( config . pitch - hfov2 ) / 180 * Math . PI ) , Math . cos ( ( config . pitch + hfov2 ) / 180 * Math . PI ) ) ) ; } else { hoffcut = hfov2 * ( 1 - Math . min ( Math . cos ( ( config . pitch - vfov2 ) / 180 * Math . PI ) , Math . cos ( ( config . pitch + vfov2 ) / 180 * Math . PI ) ) ) ; } } // Ensure the yaw is within min and max allowed var yawRange = config . maxYaw - config . minYaw , minYaw = - 180 , maxYaw = 180 ; if ( yawRange < 360 ) { minYaw = config . minYaw + config . hfov / 2 + hoffcut ; maxYaw = config . maxYaw - config . hfov / 2 - hoffcut ; if ( yawRange < config . hfov ) { // Lock yaw to average of min and max yaw when both can be seen at once minYaw = maxYaw = ( minYaw + maxYaw ) / 2 ; } config . yaw = Math . max ( minYaw , Math . min ( maxYaw , config . yaw ) ) ; } if ( config . yaw > 180 ) { config . yaw -= 360 ; } else if ( config . yaw < - 180 ) { config . yaw += 360 ; } // Check if we autoRotate in a limited by min and max yaw // If so reverse direction if ( config . autoRotate !== false && tmpyaw != config . yaw && prevTime !== undefined ) { // this condition prevents changing the direction initially config . autoRotate *= - 1 ; } // Ensure the calculated pitch is within min and max allowed var canvas = renderer . getCanvas ( ) ; var vfov = 2 * Math . atan ( Math . tan ( config . hfov / 180 * Math . PI * 0.5 ) / ( canvas . width / canvas . height ) ) / Math . PI * 180 ; var minPitch = config . minPitch + vfov / 2 , maxPitch = config . maxPitch - vfov / 2 ; var pitchRange = config . maxPitch - config . minPitch ; if ( pitchRange < vfov ) { // Lock pitch to average of min and max pitch when both can be seen at once minPitch = maxPitch = ( minPitch + maxPitch ) / 2 ; } if ( isNaN ( minPitch ) ) minPitch = - 90 ; if ( isNaN ( maxPitch ) ) maxPitch = 90 ; config . pitch = Math . max ( minPitch , Math . min ( maxPitch , config . pitch ) ) ; renderer . render ( config . pitch * Math . PI / 180 , config . yaw * Math . PI / 180 , config . hfov * Math . PI / 180 , { roll : config . roll * Math . PI / 180 } ) ; renderHotSpots ( ) ; // Update compass if ( config . compass ) { compass . style . transform = 'rotate(' + ( - config . yaw - config . northOffset ) + 'deg)' ; compass . style . webkitTransform = 'rotate(' + ( - config . yaw - config . northOffset ) + 'deg)' ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts device orientation API Tait - Bryan angles to a quaternion . [CODESPLIT] function taitBryanToQuaternion ( alpha , beta , gamma ) { var r = [ beta ? beta * Math . PI / 180 / 2 : 0 , gamma ? gamma * Math . PI / 180 / 2 : 0 , alpha ? alpha * Math . PI / 180 / 2 : 0 ] ; var c = [ Math . cos ( r [ 0 ] ) , Math . cos ( r [ 1 ] ) , Math . cos ( r [ 2 ] ) ] , s = [ Math . sin ( r [ 0 ] ) , Math . sin ( r [ 1 ] ) , Math . sin ( r [ 2 ] ) ] ; return new Quaternion ( c [ 0 ] * c [ 1 ] * c [ 2 ] - s [ 0 ] * s [ 1 ] * s [ 2 ] , s [ 0 ] * c [ 1 ] * c [ 2 ] - c [ 0 ] * s [ 1 ] * s [ 2 ] , c [ 0 ] * s [ 1 ] * c [ 2 ] + s [ 0 ] * c [ 1 ] * s [ 2 ] , c [ 0 ] * c [ 1 ] * s [ 2 ] + s [ 0 ] * s [ 1 ] * c [ 2 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes current device orientation quaternion from device orientation API Tait - Bryan angles . [CODESPLIT] function computeQuaternion ( alpha , beta , gamma ) { // Convert Tait-Bryan angles to quaternion var quaternion = taitBryanToQuaternion ( alpha , beta , gamma ) ; // Apply world transform quaternion = quaternion . multiply ( new Quaternion ( Math . sqrt ( 0.5 ) , - Math . sqrt ( 0.5 ) , 0 , 0 ) ) ; // Apply screen transform var angle = window . orientation ? - window . orientation * Math . PI / 180 / 2 : 0 ; return quaternion . multiply ( new Quaternion ( Math . cos ( angle ) , 0 , - Math . sin ( angle ) , 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for device orientation API . Controls pointing . [CODESPLIT] function orientationListener ( e ) { var q = computeQuaternion ( e . alpha , e . beta , e . gamma ) . toEulerAngles ( ) ; if ( typeof ( orientation ) == 'number' && orientation < 10 ) { // This kludge is necessary because iOS sometimes provides a few stale // device orientation events when the listener is removed and then // readded. Thus, we skip the first 10 events to prevent this from // causing problems. orientation += 1 ; } else if ( orientation === 10 ) { // Record starting yaw to prevent jumping orientationYawOffset = q [ 2 ] / Math . PI * 180 + config . yaw ; orientation = true ; requestAnimationFrame ( animate ) ; } else { config . pitch = q [ 0 ] / Math . PI * 180 ; config . roll = - q [ 1 ] / Math . PI * 180 ; config . yaw = - q [ 2 ] / Math . PI * 180 + orientationYawOffset ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes renderer . [CODESPLIT] function renderInit ( ) { try { var params = { } ; if ( config . horizonPitch !== undefined ) params . horizonPitch = config . horizonPitch * Math . PI / 180 ; if ( config . horizonRoll !== undefined ) params . horizonRoll = config . horizonRoll * Math . PI / 180 ; if ( config . backgroundColor !== undefined ) params . backgroundColor = config . backgroundColor ; renderer . init ( panoImage , config . type , config . dynamic , config . haov * Math . PI / 180 , config . vaov * Math . PI / 180 , config . vOffset * Math . PI / 180 , renderInitCallback , params ) ; if ( config . dynamic !== true ) { // Allow image to be garbage collected panoImage = undefined ; } } catch ( event ) { // Panorama not loaded // Display error if there is a bad texture if ( event . type == 'webgl error' || event . type == 'no webgl' ) { anError ( ) ; } else if ( event . type == 'webgl size error' ) { anError ( config . strings . textureSizeError . replace ( '%s' , event . width ) . replace ( '%s' , event . maxWidth ) ) ; } else { anError ( config . strings . unknownError ) ; throw event ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggered when render initialization finishes . Handles fading between scenes as well as showing the compass and hotspots and hiding the loading display . [CODESPLIT] function renderInitCallback ( ) { // Fade if specified if ( config . sceneFadeDuration && renderer . fadeImg !== undefined ) { renderer . fadeImg . style . opacity = 0 ; // Remove image var fadeImg = renderer . fadeImg ; delete renderer . fadeImg ; setTimeout ( function ( ) { renderContainer . removeChild ( fadeImg ) ; fireEvent ( 'scenechangefadedone' ) ; } , config . sceneFadeDuration ) ; } // Show compass if applicable if ( config . compass ) { compass . style . display = 'inline' ; } else { compass . style . display = 'none' ; } // Show hotspots createHotSpots ( ) ; // Hide loading display infoDisplay . load . box . style . display = 'none' ; if ( preview !== undefined ) { renderContainer . removeChild ( preview ) ; preview = undefined ; } loaded = true ; fireEvent ( 'load' ) ; animateInit ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates hot spot element for the current scene . [CODESPLIT] function createHotSpot ( hs ) { // Make sure hot spot pitch and yaw are numbers hs . pitch = Number ( hs . pitch ) || 0 ; hs . yaw = Number ( hs . yaw ) || 0 ; var div = document . createElement ( 'div' ) ; div . className = 'pnlm-hotspot-base' if ( hs . cssClass ) div . className += ' ' + hs . cssClass ; else div . className += ' pnlm-hotspot pnlm-sprite pnlm-' + escapeHTML ( hs . type ) ; var span = document . createElement ( 'span' ) ; if ( hs . text ) span . innerHTML = escapeHTML ( hs . text ) ; var a ; if ( hs . video ) { var video = document . createElement ( 'video' ) , p = hs . video ; if ( config . basePath && ! absoluteURL ( p ) ) p = config . basePath + p ; video . src = sanitizeURL ( p ) ; video . controls = true ; video . style . width = hs . width + 'px' ; renderContainer . appendChild ( div ) ; span . appendChild ( video ) ; } else if ( hs . image ) { var p = hs . image ; if ( config . basePath && ! absoluteURL ( p ) ) p = config . basePath + p ; a = document . createElement ( 'a' ) ; a . href = sanitizeURL ( hs . URL ? hs . URL : p ) ; a . target = '_blank' ; span . appendChild ( a ) ; var image = document . createElement ( 'img' ) ; image . src = sanitizeURL ( p ) ; image . style . width = hs . width + 'px' ; image . style . paddingTop = '5px' ; renderContainer . appendChild ( div ) ; a . appendChild ( image ) ; span . style . maxWidth = 'initial' ; } else if ( hs . URL ) { a = document . createElement ( 'a' ) ; a . href = sanitizeURL ( hs . URL ) ; if ( hs . attributes ) { for ( var key in hs . attributes ) { a . setAttribute ( key , hs . attributes [ key ] ) ; } } else { a . target = '_blank' ; } renderContainer . appendChild ( a ) ; div . className += ' pnlm-pointer' ; span . className += ' pnlm-pointer' ; a . appendChild ( div ) ; } else { if ( hs . sceneId ) { div . onclick = div . ontouchend = function ( ) { if ( ! div . clicked ) { div . clicked = true ; loadScene ( hs . sceneId , hs . targetPitch , hs . targetYaw , hs . targetHfov ) ; } return false ; } ; div . className += ' pnlm-pointer' ; span . className += ' pnlm-pointer' ; } renderContainer . appendChild ( div ) ; } if ( hs . createTooltipFunc ) { hs . createTooltipFunc ( div , hs . createTooltipArgs ) ; } else if ( hs . text || hs . video || hs . image ) { div . classList . add ( 'pnlm-tooltip' ) ; div . appendChild ( span ) ; span . style . width = span . scrollWidth - 20 + 'px' ; span . style . marginLeft = - ( span . scrollWidth - div . offsetWidth ) / 2 + 'px' ; span . style . marginTop = - span . scrollHeight - 12 + 'px' ; } if ( hs . clickHandlerFunc ) { div . addEventListener ( 'click' , function ( e ) { hs . clickHandlerFunc ( e , hs . clickHandlerArgs ) ; } , 'false' ) ; div . className += ' pnlm-pointer' ; span . className += ' pnlm-pointer' ; } hs . div = div ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates hot spot elements for the current scene . [CODESPLIT] function createHotSpots ( ) { if ( hotspotsCreated ) return ; if ( ! config . hotSpots ) { config . hotSpots = [ ] ; } else { // Sort by pitch so tooltip is never obscured by another hot spot config . hotSpots = config . hotSpots . sort ( function ( a , b ) { return a . pitch < b . pitch ; } ) ; config . hotSpots . forEach ( createHotSpot ) ; } hotspotsCreated = true ; renderHotSpots ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Destroys currently created hot spot elements . [CODESPLIT] function destroyHotSpots ( ) { var hs = config . hotSpots ; hotspotsCreated = false ; delete config . hotSpots ; if ( hs ) { for ( var i = 0 ; i < hs . length ; i ++ ) { var current = hs [ i ] . div ; if ( current ) { while ( current . parentNode && current . parentNode != renderContainer ) { current = current . parentNode ; } renderContainer . removeChild ( current ) ; } delete hs [ i ] . div ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders hot spot updating its position and visibility . [CODESPLIT] function renderHotSpot ( hs ) { var hsPitchSin = Math . sin ( hs . pitch * Math . PI / 180 ) , hsPitchCos = Math . cos ( hs . pitch * Math . PI / 180 ) , configPitchSin = Math . sin ( config . pitch * Math . PI / 180 ) , configPitchCos = Math . cos ( config . pitch * Math . PI / 180 ) , yawCos = Math . cos ( ( - hs . yaw + config . yaw ) * Math . PI / 180 ) ; var z = hsPitchSin * configPitchSin + hsPitchCos * yawCos * configPitchCos ; if ( ( hs . yaw <= 90 && hs . yaw > - 90 && z <= 0 ) || ( ( hs . yaw > 90 || hs . yaw <= - 90 ) && z <= 0 ) ) { hs . div . style . visibility = 'hidden' ; } else { var yawSin = Math . sin ( ( - hs . yaw + config . yaw ) * Math . PI / 180 ) , hfovTan = Math . tan ( config . hfov * Math . PI / 360 ) ; hs . div . style . visibility = 'visible' ; // Subpixel rendering doesn't work in Firefox // https://bugzilla.mozilla.org/show_bug.cgi?id=739176 var canvas = renderer . getCanvas ( ) , canvasWidth = canvas . clientWidth , canvasHeight = canvas . clientHeight ; var coord = [ - canvasWidth / hfovTan * yawSin * hsPitchCos / z / 2 , - canvasWidth / hfovTan * ( hsPitchSin * configPitchCos - hsPitchCos * yawCos * configPitchSin ) / z / 2 ] ; // Apply roll var rollSin = Math . sin ( config . roll * Math . PI / 180 ) , rollCos = Math . cos ( config . roll * Math . PI / 180 ) ; coord = [ coord [ 0 ] * rollCos - coord [ 1 ] * rollSin , coord [ 0 ] * rollSin + coord [ 1 ] * rollCos ] ; // Apply transform coord [ 0 ] += ( canvasWidth - hs . div . offsetWidth ) / 2 ; coord [ 1 ] += ( canvasHeight - hs . div . offsetHeight ) / 2 ; var transform = 'translate(' + coord [ 0 ] + 'px, ' + coord [ 1 ] + 'px) translateZ(9999px) rotate(' + config . roll + 'deg)' ; hs . div . style . webkitTransform = transform ; hs . div . style . MozTransform = transform ; hs . div . style . transform = transform ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges a scene configuration into the current configuration . [CODESPLIT] function mergeConfig ( sceneId ) { config = { } ; var k , s ; var photoSphereExcludes = [ 'haov' , 'vaov' , 'vOffset' , 'northOffset' , 'horizonPitch' , 'horizonRoll' ] ; specifiedPhotoSphereExcludes = [ ] ; // Merge default config for ( k in defaultConfig ) { if ( defaultConfig . hasOwnProperty ( k ) ) { config [ k ] = defaultConfig [ k ] ; } } // Merge default scene config for ( k in initialConfig . default ) { if ( initialConfig . default . hasOwnProperty ( k ) ) { if ( k == 'strings' ) { for ( s in initialConfig . default . strings ) { if ( initialConfig . default . strings . hasOwnProperty ( s ) ) { config . strings [ s ] = escapeHTML ( initialConfig . default . strings [ s ] ) ; } } } else { config [ k ] = initialConfig . default [ k ] ; if ( photoSphereExcludes . indexOf ( k ) >= 0 ) { specifiedPhotoSphereExcludes . push ( k ) ; } } } } // Merge current scene config if ( ( sceneId !== null ) && ( sceneId !== '' ) && ( initialConfig . scenes ) && ( initialConfig . scenes [ sceneId ] ) ) { var scene = initialConfig . scenes [ sceneId ] ; for ( k in scene ) { if ( scene . hasOwnProperty ( k ) ) { if ( k == 'strings' ) { for ( s in scene . strings ) { if ( scene . strings . hasOwnProperty ( s ) ) { config . strings [ s ] = escapeHTML ( scene . strings [ s ] ) ; } } } else { config [ k ] = scene [ k ] ; if ( photoSphereExcludes . indexOf ( k ) >= 0 ) { specifiedPhotoSphereExcludes . push ( k ) ; } } } } config . scene = sceneId ; } // Merge initial config for ( k in initialConfig ) { if ( initialConfig . hasOwnProperty ( k ) ) { if ( k == 'strings' ) { for ( s in initialConfig . strings ) { if ( initialConfig . strings . hasOwnProperty ( s ) ) { config . strings [ s ] = escapeHTML ( initialConfig . strings [ s ] ) ; } } } else { config [ k ] = initialConfig [ k ] ; if ( photoSphereExcludes . indexOf ( k ) >= 0 ) { specifiedPhotoSphereExcludes . push ( k ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes configuration options . [CODESPLIT] function processOptions ( isPreview ) { isPreview = isPreview ? isPreview : false ; // Process preview first so it always loads before the browser hits its // maximum number of connections to a server as can happen with cubic // panoramas if ( isPreview && 'preview' in config ) { var p = config . preview ; if ( config . basePath && ! absoluteURL ( p ) ) p = config . basePath + p ; preview = document . createElement ( 'div' ) ; preview . className = 'pnlm-preview-img' ; preview . style . backgroundImage = \"url('\" + sanitizeURLForCss ( p ) + \"')\" ; renderContainer . appendChild ( preview ) ; } // Handle different preview values var title = config . title , author = config . author ; if ( isPreview ) { if ( 'previewTitle' in config ) config . title = config . previewTitle ; if ( 'previewAuthor' in config ) config . author = config . previewAuthor ; } // Reset title / author display if ( ! config . hasOwnProperty ( 'title' ) ) infoDisplay . title . innerHTML = '' ; if ( ! config . hasOwnProperty ( 'author' ) ) infoDisplay . author . innerHTML = '' ; if ( ! config . hasOwnProperty ( 'title' ) && ! config . hasOwnProperty ( 'author' ) ) infoDisplay . container . style . display = 'none' ; // Fill in load button label and loading box text controls . load . innerHTML = '<p>' + config . strings . loadButtonLabel + '</p>' ; infoDisplay . load . boxp . innerHTML = config . strings . loadingLabel ; // Process other options for ( var key in config ) { if ( config . hasOwnProperty ( key ) ) { switch ( key ) { case 'title' : infoDisplay . title . innerHTML = escapeHTML ( config [ key ] ) ; infoDisplay . container . style . display = 'inline' ; break ; case 'author' : infoDisplay . author . innerHTML = config . strings . bylineLabel . replace ( '%s' , escapeHTML ( config [ key ] ) ) ; infoDisplay . container . style . display = 'inline' ; break ; case 'fallback' : var link = document . createElement ( 'a' ) ; link . href = sanitizeURL ( config [ key ] ) ; link . target = '_blank' ; link . textContent = 'Click here to view this panorama in an alternative viewer.' ; var message = document . createElement ( 'p' ) ; message . textContent = 'Your browser does not support WebGL.' message . appendChild ( document . createElement ( 'br' ) ) ; message . appendChild ( link ) ; infoDisplay . errorMsg . innerHTML = '' ; // Removes all children nodes infoDisplay . errorMsg . appendChild ( message ) ; break ; case 'hfov' : setHfov ( Number ( config [ key ] ) ) ; break ; case 'autoLoad' : if ( config [ key ] === true && renderer === undefined ) { // Show loading box infoDisplay . load . box . style . display = 'inline' ; // Hide load button controls . load . style . display = 'none' ; // Initialize init ( ) ; } break ; case 'showZoomCtrl' : if ( config [ key ] && config . showControls != false ) { // Show zoom controls controls . zoom . style . display = 'block' ; } else { // Hide zoom controls controls . zoom . style . display = 'none' ; } break ; case 'showFullscreenCtrl' : if ( config [ key ] && config . showControls != false && ( 'fullscreen' in document || 'mozFullScreen' in document || 'webkitIsFullScreen' in document || 'msFullscreenElement' in document ) ) { // Show fullscreen control controls . fullscreen . style . display = 'block' ; } else { // Hide fullscreen control controls . fullscreen . style . display = 'none' ; } break ; case 'hotSpotDebug' : if ( config [ key ] ) hotSpotDebugIndicator . style . display = 'block' ; else hotSpotDebugIndicator . style . display = 'none' ; break ; case 'showControls' : if ( ! config [ key ] ) { controls . orientation . style . display = 'none' ; controls . zoom . style . display = 'none' ; controls . fullscreen . style . display = 'none' ; } break ; case 'orientationOnByDefault' : if ( config [ key ] ) { if ( orientationSupport === undefined ) startOrientationIfSupported = true ; else if ( orientationSupport === true ) startOrientation ( ) ; } break ; } } } if ( isPreview ) { // Restore original values if changed for preview if ( title ) config . title = title ; else delete config . title ; if ( author ) config . author = author ; else delete config . author ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Toggles fullscreen mode . [CODESPLIT] function toggleFullscreen ( ) { if ( loaded && ! error ) { if ( ! fullscreenActive ) { try { if ( container . requestFullscreen ) { container . requestFullscreen ( ) ; } else if ( container . mozRequestFullScreen ) { container . mozRequestFullScreen ( ) ; } else if ( container . msRequestFullscreen ) { container . msRequestFullscreen ( ) ; } else { container . webkitRequestFullScreen ( ) ; } } catch ( event ) { // Fullscreen doesn't work } } else { if ( document . exitFullscreen ) { document . exitFullscreen ( ) ; } else if ( document . mozCancelFullScreen ) { document . mozCancelFullScreen ( ) ; } else if ( document . webkitCancelFullScreen ) { document . webkitCancelFullScreen ( ) ; } else if ( document . msExitFullscreen ) { document . msExitFullscreen ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for fullscreen changes . [CODESPLIT] function onFullScreenChange ( resize ) { if ( document . fullscreenElement || document . fullscreen || document . mozFullScreen || document . webkitIsFullScreen || document . msFullscreenElement ) { controls . fullscreen . classList . add ( 'pnlm-fullscreen-toggle-button-active' ) ; fullscreenActive = true ; } else { controls . fullscreen . classList . remove ( 'pnlm-fullscreen-toggle-button-active' ) ; fullscreenActive = false ; } if ( resize !== 'resize' ) fireEvent ( 'fullscreenchange' , fullscreenActive ) ; // Resize renderer (deal with browser quirks and fixes #155) renderer . resize ( ) ; setHfov ( config . hfov ) ; animateInit ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clamps horzontal field of view to viewer s limits . [CODESPLIT] function constrainHfov ( hfov ) { // Keep field of view within bounds var minHfov = config . minHfov ; if ( config . type == 'multires' && renderer && config . multiResMinHfov ) { minHfov = Math . min ( minHfov , renderer . getCanvas ( ) . width / ( config . multiRes . cubeResolution / 90 * 0.9 ) ) ; } if ( minHfov > config . maxHfov ) { // Don't change view if bounds don't make sense console . log ( 'HFOV bounds do not make sense (minHfov > maxHfov).' ) return config . hfov ; } var newHfov = config . hfov ; if ( hfov < minHfov ) { newHfov = minHfov ; } else if ( hfov > config . maxHfov ) { newHfov = config . maxHfov ; } else { newHfov = hfov ; } // Optionally avoid showing background (empty space) on top or bottom by adapting newHfov if ( config . avoidShowingBackground && renderer ) { var canvas = renderer . getCanvas ( ) ; newHfov = Math . min ( newHfov , Math . atan ( Math . tan ( ( config . maxPitch - config . minPitch ) / 360 * Math . PI ) / canvas . height * canvas . width ) * 360 / Math . PI ) ; } return newHfov ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops auto rotation and animated moves . [CODESPLIT] function stopAnimation ( ) { animatedMove = { } ; autoRotateSpeed = config . autoRotate ? config . autoRotate : autoRotateSpeed ; config . autoRotate = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads panorama . [CODESPLIT] function load ( ) { // Since WebGL error handling is very general, first we clear any error box // since it is a new scene and the error from previous maybe because of lacking // memory etc and not because of a lack of WebGL support etc clearError ( ) ; loaded = false ; controls . load . style . display = 'none' ; infoDisplay . load . box . style . display = 'inline' ; init ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads scene . [CODESPLIT] function loadScene ( sceneId , targetPitch , targetYaw , targetHfov , fadeDone ) { loaded = false ; animatedMove = { } ; // Set up fade if specified var fadeImg , workingPitch , workingYaw , workingHfov ; if ( config . sceneFadeDuration && ! fadeDone ) { var data = renderer . render ( config . pitch * Math . PI / 180 , config . yaw * Math . PI / 180 , config . hfov * Math . PI / 180 , { returnImage : true } ) ; if ( data !== undefined ) { fadeImg = new Image ( ) ; fadeImg . className = 'pnlm-fade-img' ; fadeImg . style . transition = 'opacity ' + ( config . sceneFadeDuration / 1000 ) + 's' ; fadeImg . style . width = '100%' ; fadeImg . style . height = '100%' ; fadeImg . onload = function ( ) { loadScene ( sceneId , targetPitch , targetYaw , targetHfov , true ) ; } ; fadeImg . src = data ; renderContainer . appendChild ( fadeImg ) ; renderer . fadeImg = fadeImg ; return ; } } // Set new pointing if ( targetPitch === 'same' ) { workingPitch = config . pitch ; } else { workingPitch = targetPitch ; } if ( targetYaw === 'same' ) { workingYaw = config . yaw ; } else if ( targetYaw === 'sameAzimuth' ) { workingYaw = config . yaw + ( config . northOffset || 0 ) - ( initialConfig . scenes [ sceneId ] . northOffset || 0 ) ; } else { workingYaw = targetYaw ; } if ( targetHfov === 'same' ) { workingHfov = config . hfov ; } else { workingHfov = targetHfov ; } // Destroy hot spots from previous scene destroyHotSpots ( ) ; // Create the new config for the scene mergeConfig ( sceneId ) ; // Stop motion speed . yaw = speed . pitch = speed . hfov = 0 ; // Reload scene processOptions ( ) ; if ( workingPitch !== undefined ) { config . pitch = workingPitch ; } if ( workingYaw !== undefined ) { config . yaw = workingYaw ; } if ( workingHfov !== undefined ) { config . hfov = workingHfov ; } fireEvent ( 'scenechange' , sceneId ) ; load ( ) ; // Properly handle switching to dynamic scenes update = config . dynamicUpdate === true ; if ( config . dynamic ) { panoImage = config . panorama ; onImageLoad ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop using device orientation . [CODESPLIT] function stopOrientation ( ) { window . removeEventListener ( 'deviceorientation' , orientationListener ) ; controls . orientation . classList . remove ( 'pnlm-orientation-button-active' ) ; orientation = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escapes HTML string ( to mitigate possible DOM XSS attacks ) . [CODESPLIT] function escapeHTML ( s ) { if ( ! initialConfig . escapeHTML ) return String ( s ) . split ( '\\n' ) . join ( '<br>' ) ; return String ( s ) . split ( / & / g ) . join ( '&amp;' ) . split ( '\"' ) . join ( '&quot;' ) . split ( \"'\" ) . join ( '&#39;' ) . split ( '<' ) . join ( '&lt;' ) . split ( '>' ) . join ( '&gt;' ) . split ( '/' ) . join ( '&#x2f;' ) . split ( '\\n' ) . join ( '<br>' ) ; // Allow line breaks }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fire listeners attached to specified event . [CODESPLIT] function fireEvent ( type ) { if ( type in externalEventListeners ) { // Reverse iteration is useful, if event listener is removed inside its definition for ( var i = externalEventListeners [ type ] . length ; i > 0 ; i -- ) { externalEventListeners [ type ] [ externalEventListeners [ type ] . length - i ] . apply ( null , [ ] . slice . call ( arguments , 1 ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits for the latchFunction to return true before proceeding to the next block . [CODESPLIT] function ( latchFunction , optional_timeoutMessage , optional_timeout ) { jasmine . getEnv ( ) . currentSpec . waitsFor . apply ( jasmine . getEnv ( ) . currentSpec , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function OAuthError ( messageOrError , properties ) { var message = messageOrError instanceof Error ? messageOrError . message : messageOrError ; var error = messageOrError instanceof Error ? messageOrError : null ; if ( _ . isEmpty ( properties ) ) { properties = { } ; } _ . defaults ( properties , { code : 500 } ) ; if ( error ) { properties . inner = error ; } if ( _ . isEmpty ( message ) ) { message = statuses [ properties . code ] ; } this . code = this . status = this . statusCode = properties . code ; this . message = message ; for ( var key in properties ) { if ( key !== 'code' ) { this [ key ] = properties [ key ] ; } } Error . captureStackTrace ( this , OAuthError ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function AuthorizationCodeGrantType ( options ) { options = options || { } ; if ( ! options . model ) { throw new InvalidArgumentError ( 'Missing parameter: `model`' ) ; } if ( ! options . model . getAuthorizationCode ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `getAuthorizationCode()`' ) ; } if ( ! options . model . revokeAuthorizationCode ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `revokeAuthorizationCode()`' ) ; } if ( ! options . model . saveToken ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `saveToken()`' ) ; } AbstractGrantType . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function PasswordGrantType ( options ) { options = options || { } ; if ( ! options . model ) { throw new InvalidArgumentError ( 'Missing parameter: `model`' ) ; } if ( ! options . model . getUser ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `getUser()`' ) ; } if ( ! options . model . saveToken ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `saveToken()`' ) ; } AbstractGrantType . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function TokenHandler ( options ) { options = options || { } ; if ( ! options . accessTokenLifetime ) { throw new InvalidArgumentError ( 'Missing parameter: `accessTokenLifetime`' ) ; } if ( ! options . model ) { throw new InvalidArgumentError ( 'Missing parameter: `model`' ) ; } if ( ! options . refreshTokenLifetime ) { throw new InvalidArgumentError ( 'Missing parameter: `refreshTokenLifetime`' ) ; } if ( ! options . model . getClient ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `getClient()`' ) ; } this . accessTokenLifetime = options . accessTokenLifetime ; this . grantTypes = _ . assign ( { } , grantTypes , options . extendedGrantTypes ) ; this . model = options . model ; this . refreshTokenLifetime = options . refreshTokenLifetime ; this . allowExtendedTokenAttributes = options . allowExtendedTokenAttributes ; this . requireClientAuthentication = options . requireClientAuthentication || { } ; this . alwaysIssueNewRefreshToken = options . alwaysIssueNewRefreshToken !== false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function AbstractGrantType ( options ) { options = options || { } ; if ( ! options . accessTokenLifetime ) { throw new InvalidArgumentError ( 'Missing parameter: `accessTokenLifetime`' ) ; } if ( ! options . model ) { throw new InvalidArgumentError ( 'Missing parameter: `model`' ) ; } this . accessTokenLifetime = options . accessTokenLifetime ; this . model = options . model ; this . refreshTokenLifetime = options . refreshTokenLifetime ; this . alwaysIssueNewRefreshToken = options . alwaysIssueNewRefreshToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function AuthenticateHandler ( options ) { options = options || { } ; if ( ! options . model ) { throw new InvalidArgumentError ( 'Missing parameter: `model`' ) ; } if ( ! options . model . getAccessToken ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `getAccessToken()`' ) ; } if ( options . scope && undefined === options . addAcceptedScopesHeader ) { throw new InvalidArgumentError ( 'Missing parameter: `addAcceptedScopesHeader`' ) ; } if ( options . scope && undefined === options . addAuthorizedScopesHeader ) { throw new InvalidArgumentError ( 'Missing parameter: `addAuthorizedScopesHeader`' ) ; } if ( options . scope && ! options . model . verifyScope ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `verifyScope()`' ) ; } this . addAcceptedScopesHeader = options . addAcceptedScopesHeader ; this . addAuthorizedScopesHeader = options . addAuthorizedScopesHeader ; this . allowBearerTokensInQueryString = options . allowBearerTokensInQueryString ; this . model = options . model ; this . scope = options . scope ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function InvalidArgumentError ( message , properties ) { properties = _ . assign ( { code : 500 , name : 'invalid_argument' } , properties ) ; OAuthError . call ( this , message , properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function RefreshTokenGrantType ( options ) { options = options || { } ; if ( ! options . model ) { throw new InvalidArgumentError ( 'Missing parameter: `model`' ) ; } if ( ! options . model . getRefreshToken ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `getRefreshToken()`' ) ; } if ( ! options . model . revokeToken ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `revokeToken()`' ) ; } if ( ! options . model . saveToken ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `saveToken()`' ) ; } AbstractGrantType . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function Request ( options ) { options = options || { } ; if ( ! options . headers ) { throw new InvalidArgumentError ( 'Missing parameter: `headers`' ) ; } if ( ! options . method ) { throw new InvalidArgumentError ( 'Missing parameter: `method`' ) ; } if ( ! options . query ) { throw new InvalidArgumentError ( 'Missing parameter: `query`' ) ; } this . body = options . body || { } ; this . headers = { } ; this . method = options . method ; this . query = options . query ; // Store the headers in lower case. for ( var field in options . headers ) { if ( options . headers . hasOwnProperty ( field ) ) { this . headers [ field . toLowerCase ( ) ] = options . headers [ field ] ; } } // Store additional properties of the request object passed in for ( var property in options ) { if ( options . hasOwnProperty ( property ) && ! this [ property ] ) { this [ property ] = options [ property ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function AuthorizeHandler ( options ) { options = options || { } ; if ( options . authenticateHandler && ! options . authenticateHandler . handle ) { throw new InvalidArgumentError ( 'Invalid argument: authenticateHandler does not implement `handle()`' ) ; } if ( ! options . authorizationCodeLifetime ) { throw new InvalidArgumentError ( 'Missing parameter: `authorizationCodeLifetime`' ) ; } if ( ! options . model ) { throw new InvalidArgumentError ( 'Missing parameter: `model`' ) ; } if ( ! options . model . getClient ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `getClient()`' ) ; } if ( ! options . model . saveAuthorizationCode ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `saveAuthorizationCode()`' ) ; } this . allowEmptyState = options . allowEmptyState ; this . authenticateHandler = options . authenticateHandler || new AuthenticateHandler ( options ) ; this . authorizationCodeLifetime = options . authorizationCodeLifetime ; this . model = options . model ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function ClientCredentialsGrantType ( options ) { options = options || { } ; if ( ! options . model ) { throw new InvalidArgumentError ( 'Missing parameter: `model`' ) ; } if ( ! options . model . getUserFromClient ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `getUserFromClient()`' ) ; } if ( ! options . model . saveToken ) { throw new InvalidArgumentError ( 'Invalid argument: model does not implement `saveToken()`' ) ; } AbstractGrantType . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function BearerTokenType ( accessToken , accessTokenLifetime , refreshToken , scope , customAttributes ) { if ( ! accessToken ) { throw new InvalidArgumentError ( 'Missing parameter: `accessToken`' ) ; } this . accessToken = accessToken ; this . accessTokenLifetime = accessTokenLifetime ; this . refreshToken = refreshToken ; this . scope = scope ; if ( customAttributes ) { this . customAttributes = customAttributes ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor . [CODESPLIT] function Response ( options ) { options = options || { } ; this . body = options . body || { } ; this . headers = { } ; this . status = 200 ; // Store the headers in lower case. for ( var field in options . headers ) { if ( options . headers . hasOwnProperty ( field ) ) { this . headers [ field . toLowerCase ( ) ] = options . headers [ field ] ; } } // Store additional properties of the response object passed in for ( var property in options ) { if ( options . hasOwnProperty ( property ) && ! this [ property ] ) { this [ property ] = options [ property ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Static binding in function closure needed for import hooks to stick to builtin cache even if module is overriden in sys . modules $sys = $B . imported [ sys ] ; [ Import spec ] [ PEP 302 ] Brython import machinery [CODESPLIT] function import_hooks ( mod_name , _path , from_stdlib ) { var _meta_path = $B . meta_path . slice ( ) , _sys_modules = $B . imported , _loader , spec if ( from_stdlib == \"static\" ) { // No use trying anything else than stdlib finders var ix = _meta_path . indexOf ( $B . finders [ \"path\" ] ) if ( ix > - 1 ) { _meta_path . splice ( ix , 1 ) } } else if ( from_stdlib == \"VFS\" ) { var keys = [ \"path\" , \"stdlib_static\" ] keys . forEach ( function ( key ) { var ix = _meta_path . indexOf ( $B . finders [ key ] ) if ( ix > - 1 ) { _meta_path . splice ( ix , 1 ) } } ) } for ( var i = 0 , len = _meta_path . length ; i < len ; i ++ ) { var _finder = _meta_path [ i ] , find_spec = $B . $getattr ( _finder , \"find_spec\" , _b_ . None ) if ( find_spec == _b_ . None ) { // If find_spec is not defined for the meta path, try the legacy // method find_module() var find_module = $B . $getattr ( _finder , \"find_module\" , _b_ . None ) if ( find_module !== _b_ . None ) { _loader = find_module ( mod_name , _path ) // The loader has a method load_module() var load_module = $B . $getattr ( _loader , \"load_module\" ) module = $B . $call ( load_module ) ( mod_name ) _sys_modules [ mod_name ] = module return module } } else { spec = find_spec ( mod_name , _path , undefined ) if ( ! $B . is_none ( spec ) ) { module = $B . imported [ spec . name ] if ( module !== undefined ) { // If module of same name is already in imports, return it return _sys_modules [ spec . name ] = module } _loader = _b_ . getattr ( spec , \"loader\" , _b_ . None ) break } } } if ( _loader === undefined ) { // No import spec found var exc = _b_ . ImportError . $factory ( \"No module named \" + mod_name ) exc . name = mod_name throw exc } // Import spec represents a match if ( $B . is_none ( module ) ) { var _spec_name = _b_ . getattr ( spec , \"name\" ) // Create module object if ( ! $B . is_none ( _loader ) ) { var create_module = _b_ . getattr ( _loader , \"create_module\" , _b_ . None ) if ( ! $B . is_none ( create_module ) ) { module = $B . $call ( create_module ) ( spec ) } } if ( module === undefined ) { throw _b_ . ImportError . $factory ( mod_name ) } if ( $B . is_none ( module ) ) { // FIXME : Initialize __doc__ and __package__ module = $B . module . $factory ( mod_name ) var mod_desc = _b_ . getattr ( spec , \"origin\" ) if ( _b_ . getattr ( spec , \"has_location\" ) ) { mod_desc = \"from '\" + mod_desc + \"'\" } else { mod_desc = \"(\" + mod_desc + \")\" } } } module . __name__ = _spec_name module . __loader__ = _loader module . __package__ = _b_ . getattr ( spec , \"parent\" , \"\" ) module . __spec__ = spec var locs = _b_ . getattr ( spec , \"submodule_search_locations\" ) // Brython-specific var if ( module . $is_package = ! $B . is_none ( locs ) ) { module . __path__ = locs } if ( _b_ . getattr ( spec , \"has_location\" ) ) { module . __file__ = _b_ . getattr ( spec , \"origin\" ) $B . $py_module_path [ module . __name__ ] = module . __file__ } var cached = _b_ . getattr ( spec , \"cached\" ) if ( ! $B . is_none ( cached ) ) { module . __cached__ = cached } if ( $B . is_none ( _loader ) ) { if ( ! $B . is_none ( locs ) ) { _sys_modules [ _spec_name ] = module } else { throw _b_ . ImportError . $factory ( mod_name ) } } else { var exec_module = _b_ . getattr ( _loader , \"exec_module\" , _b_ . None ) if ( $B . is_none ( exec_module ) ) { // FIXME : Remove !!! Backwards compat in CPython module = _b_ . getattr ( _loader , \"load_module\" ) ( _spec_name ) } else { _sys_modules [ _spec_name ] = module try { exec_module ( module ) } catch ( e ) { delete _sys_modules [ _spec_name ] throw e } } } return _sys_modules [ _spec_name ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cross - browser utility functions [CODESPLIT] function $getMouseOffset ( target , ev ) { ev = ev || _window . event ; var docPos = $getPosition ( target ) ; var mousePos = $mouseCoords ( ev ) ; return { x : mousePos . x - docPos . x , y : mousePos . y - docPos . y } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Code to store / restore local namespace In generators the namespace is stored in an attribute of the generator function until the iterator is exhausted so that it can be restored in the next iteration [CODESPLIT] function jscode_namespace ( iter_name , action , parent_id ) { var _clean = '' ; if ( action === 'store' ) { _clean = ' = {}' } var res = 'for(var attr in this.blocks){' + 'eval(\"var \" + attr + \" = this.blocks[attr]\")' + '};' + 'var $locals_' + iter_name + ' = this.env' + _clean + ', ' + '$local_name = \"' + iter_name + '\", ' + '$locals = $locals_' + iter_name + ';' if ( parent_id ) { res += '$locals.$parent = $locals_' + parent_id . replace ( / \\. / g , \"_\" ) + ';' } return res }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "converts val to float and sets precision if missing [CODESPLIT] function ( val , flags ) { number_check ( val ) if ( ! flags . precision ) { if ( ! flags . decimal_point ) { flags . precision = 6 } else { flags . precision = 0 } } else { flags . precision = parseInt ( flags . precision , 10 ) validate_precision ( flags . precision ) } return parseFloat ( val ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gG [CODESPLIT] function ( val , upper , flags ) { val = _float_helper ( val , flags ) , v = val . toString ( ) , v_len = v . length , dot_idx = v . indexOf ( '.' ) if ( dot_idx < 0 ) { dot_idx = v_len } if ( val < 1 && val > - 1 ) { var zeros = leading_zeros . exec ( v ) , numzeros if ( zeros ) { numzeros = zeros [ 1 ] . length } else { numzeros = 0 } if ( numzeros >= 4 ) { val = format_sign ( val , flags ) + format_float_precision ( val , upper , flags , _floating_g_exp_helper ) if ( ! flags . alternate ) { var trl = trailing_zeros . exec ( val ) if ( trl ) { val = trl [ 1 ] . replace ( trailing_dot , \"\" ) + trl [ 3 ] // remove trailing } } else { if ( flags . precision <= 1 ) { val = val [ 0 ] + \".\" + val . substring ( 1 ) } } return format_padding ( val , flags ) } flags . precision = ( flags . precision || 0 ) + numzeros return format_padding ( format_sign ( val , flags ) + format_float_precision ( val , upper , flags , function ( val , precision ) { return val . toFixed ( min ( precision , v_len - dot_idx ) + numzeros ) } ) , flags ) } if ( dot_idx > flags . precision ) { val = format_sign ( val , flags ) + format_float_precision ( val , upper , flags , _floating_g_exp_helper ) if ( ! flags . alternate ) { var trl = trailing_zeros . exec ( val ) if ( trl ) { val = trl [ 1 ] . replace ( trailing_dot , \"\" ) + trl [ 3 ] // remove trailing } } else { if ( flags . precision <= 1 ) { val = val [ 0 ] + \".\" + val . substring ( 1 ) } } return format_padding ( val , flags ) } return format_padding ( format_sign ( val , flags ) + format_float_precision ( val , upper , flags , function ( val , precision ) { if ( ! flags . decimal_point ) { precision = min ( v_len - 1 , 6 ) } else if ( precision > v_len ) { if ( ! flags . alternate ) { precision = v_len } } if ( precision < dot_idx ) { precision = dot_idx } return val . toFixed ( precision - dot_idx ) } ) , flags ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "fF [CODESPLIT] function ( val , upper , flags ) { val = _float_helper ( val , flags ) return format_padding ( format_sign ( val , flags ) + format_float_precision ( val , upper , flags , function ( val , precision , flags ) { val = val . toFixed ( precision ) if ( precision === 0 && flags . alternate ) { val += '.' } return val } ) , flags ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eE [CODESPLIT] function ( val , upper , flags ) { val = _float_helper ( val , flags ) return format_padding ( format_sign ( val , flags ) + format_float_precision ( val , upper , flags , _floating_exp_helper ) , flags ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "spec may contain nested replacement fields In this case evaluate them using the positional or keyword arguments passed to format () [CODESPLIT] function replace_nested ( name , key ) { if ( / \\d+ / . exec ( key ) ) { // If key is numeric, search in positional // arguments return _b_ . tuple . __getitem__ ( $ . $args , parseInt ( key ) ) } else { // Else try in keyword arguments return _b_ . dict . __getitem__ ( $ . $kw , key ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "code for operands & | ^ [CODESPLIT] function ( self , other ) { if ( _b_ . isinstance ( other , int ) ) { if ( other . __class__ === $B . long_int ) { return $B . long_int . __sub__ ( $B . long_int . $factory ( self ) , $B . long_int . $factory ( other ) ) } other = int_value ( other ) if ( self > $B . max_int32 || self < $B . min_int32 || other > $B . max_int32 || other < $B . min_int32 ) { return $B . long_int . __sub__ ( $B . long_int . $factory ( self ) , $B . long_int . $factory ( other ) ) } return self - other } if ( _b_ . isinstance ( other , _b_ . bool ) ) { return self - other } var rsub = $B . $getattr ( other , \"__rsub__\" , _b_ . None ) if ( rsub !== _b_ . None ) { return rsub ( self ) } $err ( \"-\" , other ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "code for + and - [CODESPLIT] function ( self , other ) { if ( _b_ . isinstance ( other , int ) ) { other = int_value ( other ) if ( typeof other == \"number\" ) { var res = self . valueOf ( ) - other . valueOf ( ) if ( res > $B . min_int && res < $B . max_int ) { return res } else { return $B . long_int . __sub__ ( $B . long_int . $factory ( self ) , $B . long_int . $factory ( other ) ) } } else if ( typeof other == \"boolean\" ) { return other ? self - 1 : self } else { return $B . long_int . __sub__ ( $B . long_int . $factory ( self ) , $B . long_int . $factory ( other ) ) } } if ( _b_ . isinstance ( other , _b_ . float ) ) { return new Number ( self - other ) } if ( _b_ . isinstance ( other , _b_ . complex ) ) { return $B . make_complex ( self - other . $real , - other . $imag ) } if ( _b_ . isinstance ( other , _b_ . bool ) ) { var bool_value = 0 ; if ( other . valueOf ( ) ) { bool_value = 1 } return self - bool_value } if ( _b_ . isinstance ( other , _b_ . complex ) ) { return $B . make_complex ( self . valueOf ( ) - other . $real , other . $imag ) } var rsub = $B . $getattr ( other , \"__rsub__\" , _b_ . None ) if ( rsub !== _b_ . None ) { return rsub ( self ) } throw $err ( \"-\" , other ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "comparison methods [CODESPLIT] function ( self , other ) { if ( other . __class__ === $B . long_int ) { return $B . long_int . __lt__ ( other , $B . long_int . $factory ( self ) ) } if ( _b_ . isinstance ( other , int ) ) { other = int_value ( other ) return self . valueOf ( ) > other . valueOf ( ) } else if ( _b_ . isinstance ( other , _b_ . float ) ) { return self . valueOf ( ) > other . valueOf ( ) } else if ( _b_ . isinstance ( other , _b_ . bool ) ) { return self . valueOf ( ) > _b_ . bool . __hash__ ( other ) } if ( _b_ . hasattr ( other , \"__int__\" ) || _b_ . hasattr ( other , \"__index__\" ) ) { return int . __gt__ ( self , $B . $GetInt ( other ) ) } return _b_ . NotImplemented }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function loop () takes the first task in the tasks list and processes it . The function executed in loop () may itself call loop () . [CODESPLIT] function loop ( ) { if ( tasks . length == 0 ) { // No more tasks to process. idb_cx . result . close ( ) return } var task = tasks . shift ( ) var func = task [ 0 ] , arg = task [ 1 ] if ( func == \"execute\" ) { try { eval ( arg ) } catch ( err ) { if ( $B . debug > 1 ) { console . log ( err ) for ( var attr in err ) { console . log ( attr + ' : ' , err [ attr ] ) } } // If the error was not caught by the Python runtime, build an // instance of a Python exception if ( err . $py_error === undefined ) { console . log ( 'Javascript error' , err ) //console.log(js) //for(var attr in $err){console.log(attr+': '+$err[attr])} err = _b_ . RuntimeError ( err + '' ) } // Print the error traceback on the standard error stream var name = err . __name__ , trace = _b_ . getattr ( err , 'info' ) if ( name == 'SyntaxError' || name == 'IndentationError' ) { var offset = err . args [ 3 ] trace += '\\n    ' + ' ' . repeat ( offset ) + '^' + '\\n' + name + ': ' + err . args [ 0 ] } else { trace += '\\n' + name + ': ' + err . args } try { _b_ . getattr ( $B . stderr , 'write' ) ( trace ) } catch ( print_exc_err ) { console . log ( trace ) } // Throw the error to stop execution throw err } loop ( ) } else { func ( arg ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "operations [CODESPLIT] function ( self , other ) { if ( isinstance ( other , _b_ . int ) ) { if ( typeof other == \"boolean\" ) { return other ? self - 1 : self } else if ( other . __class__ === $B . long_int ) { return float . $factory ( self - parseInt ( other . value ) ) } else { return float . $factory ( self - other ) } } if ( isinstance ( other , float ) ) { return float . $factory ( self - other ) } if ( isinstance ( other , _b_ . bool ) ) { var bool_value = 0 if ( other . valueOf ( ) ) { bool_value = 1 } return float . $factory ( self - bool_value ) } if ( isinstance ( other , _b_ . complex ) ) { return $B . make_complex ( self - other . $real , - other . $imag ) } if ( hasattr ( other , \"__rsub__\" ) ) { return getattr ( other , \"__rsub__\" ) ( self ) } $err ( \"-\" , other ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "comparison methods [CODESPLIT] function ( self , other ) { if ( isinstance ( other , _b_ . int ) ) { if ( other . __class__ === $B . long_int ) { return self > parseInt ( other . value ) } return self > other . valueOf ( ) } if ( isinstance ( other , float ) ) { return self > other } if ( isinstance ( other , _b_ . bool ) ) { return self . valueOf ( ) > _b_ . bool . __hash__ ( other ) } if ( hasattr ( other , \"__int__\" ) || hasattr ( other , \"__index__\" ) ) { return _b_ . int . __gt__ ( self , $B . $GetInt ( other ) ) } // See if other has the opposite operator, eg <= for > var inv_op = getattr ( other , \"__le__\" , None ) if ( inv_op !== None ) { return inv_op ( self ) } throw _b_ . TypeError . $factory ( \"unorderable types: float() > \" + $B . class_name ( other ) + \"()\" ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eval () ( built in function ) [CODESPLIT] function $$eval ( src , _globals , _locals ) { if ( _globals === undefined ) { _globals = _b_ . None } if ( _locals === undefined ) { _locals = _b_ . None } var current_frame = $B . frames_stack [ $B . frames_stack . length - 1 ] if ( current_frame !== undefined ) { var current_locals_id = current_frame [ 0 ] . replace ( / \\. / , '_' ) , current_globals_id = current_frame [ 2 ] . replace ( / \\. / , '_' ) } var stack_len = $B . frames_stack . length var is_exec = arguments [ 3 ] == 'exec' if ( src . __class__ === code ) { is_exec = src . mode == \"exec\" src = src . source } else if ( typeof src !== 'string' ) { throw _b_ . TypeError . $factory ( \"eval() arg 1 must be a string, bytes \" + \"or code object\" ) } // code will be run in a specific block var globals_id = '$exec_' + $B . UUID ( ) , locals_id = '$exec_' + $B . UUID ( ) , parent_scope if ( _globals === _b_ . None ) { if ( current_locals_id == current_globals_id ) { locals_id = globals_id } var local_scope = { module : locals_id , id : locals_id , binding : { } , bindings : { } } for ( var attr in current_frame [ 1 ] ) { local_scope . binding [ attr ] = true local_scope . bindings [ attr ] = true } var global_scope = { module : globals_id , id : globals_id , binding : { } , bindings : { } } for ( var attr in current_frame [ 3 ] ) { global_scope . binding [ attr ] = true global_scope . bindings [ attr ] = true } local_scope . parent_block = global_scope global_scope . parent_block = $B . builtins_scope parent_scope = local_scope // restore parent scope object eval ( \"$locals_\" + parent_scope . id + \" = current_frame[1]\" ) } else { // If a _globals dictionary is provided, set or reuse its attribute // globals_id if ( _globals . __class__ != _b_ . dict ) { throw _b_ . TypeError . $factory ( \"exec() globals must be a dict, not \" + _globals . __class__ . $infos . __name__ ) } _globals . globals_id = _globals . globals_id || globals_id globals_id = _globals . globals_id if ( _locals === _globals || _locals === _b_ . None ) { locals_id = globals_id parent_scope = $B . builtins_scope } else { // The parent block of locals must be set to globals var grandparent_scope = { id : globals_id , parent_block : $B . builtins_scope , binding : { } } parent_scope = { id : locals_id , parent_block : grandparent_scope , binding : { } } for ( var attr in _globals . $string_dict ) { grandparent_scope . binding [ attr ] = true } for ( var attr in _locals . $string_dict ) { parent_scope . binding [ attr ] = true } } } // set module path $B . $py_module_path [ globals_id ] = $B . $py_module_path [ current_globals_id ] // Initialise the object for block namespaces eval ( 'var $locals_' + globals_id + ' = {}\\nvar $locals_' + locals_id + ' = {}' ) // Initialise block globals if ( _globals === _b_ . None ) { var gobj = current_frame [ 3 ] , ex = 'var $locals_' + globals_id + ' = gobj;' eval ( ex ) // needed for generators for ( var attr in gobj ) { if ( ( ! attr . startsWith ( \"$\" ) ) || attr . startsWith ( '$$' ) ) { eval ( \"$locals_\" + globals_id + \"[attr] = gobj[attr]\" ) } } } else { if ( _globals . $jsobj ) { var items = _globals . $jsobj } else { var items = _globals . $string_dict } eval ( \"$locals_\" + globals_id + \" = _globals.$string_dict\" ) for ( var item in items ) { var item1 = $B . to_alias ( item ) try { eval ( '$locals_' + globals_id + '[\"' + item1 + '\"] = items[item]' ) } catch ( err ) { console . log ( err ) console . log ( 'error setting' , item ) break } } } // Initialise block locals if ( _locals === _b_ . None ) { if ( _globals !== _b_ . None ) { eval ( 'var $locals_' + locals_id + ' = $locals_' + globals_id ) } else { var lobj = current_frame [ 1 ] , ex = '' for ( var attr in current_frame [ 1 ] ) { if ( attr . startsWith ( \"$\" ) && ! attr . startsWith ( \"$$\" ) ) { continue } ex += '$locals_' + locals_id + '[\"' + attr + '\"] = current_frame[1][\"' + attr + '\"];' eval ( ex ) } } } else { if ( _locals . $jsobj ) { var items = _locals . $jsobj } else { var items = _locals . $string_dict } for ( var item in items ) { var item1 = $B . to_alias ( item ) try { eval ( '$locals_' + locals_id + '[\"' + item + '\"] = items.' + item ) } catch ( err ) { console . log ( err ) console . log ( 'error setting' , item ) break } } } eval ( \"$locals_\" + locals_id + \".$src = src\" ) var root = $B . py2js ( src , globals_id , locals_id , parent_scope ) , js , gns , lns if ( _globals !== _b_ . None && _locals == _b_ . None ) { for ( var attr in _globals . $string_dict ) { root . binding [ attr ] = true } } try { // The result of py2js ends with // try{ //     (block code) //     $B.leave_frame($local_name) // }catch(err){ //     $B.leave_frame($local_name) //     throw err // } var try_node = root . children [ root . children . length - 2 ] , instr = try_node . children [ try_node . children . length - 2 ] // type of the last instruction in (block code) var type = instr . context . tree [ 0 ] . type // If the Python function is eval(), not exec(), check that the source // is an expression switch ( type ) { case 'expr' : case 'list_or_tuple' : case 'op' : case 'ternary' : // If the source is an expression, what we must execute is the // block inside the \"try\" clause : if we run root, since it's // wrapped in try / finally, the value produced by // eval(root.to_js()) will be None var children = try_node . children root . children . splice ( root . children . length - 2 , 2 ) for ( var i = 0 ; i < children . length - 1 ; i ++ ) { root . add ( children [ i ] ) } break default : if ( ! is_exec ) { throw _b_ . SyntaxError . $factory ( \"eval() argument must be an expression\" , '<string>' , 1 , 1 , src ) } } js = root . to_js ( ) if ( is_exec ) { var locals_obj = eval ( \"$locals_\" + locals_id ) , globals_obj = eval ( \"$locals_\" + globals_id ) if ( _globals === _b_ . None ) { var res = new Function ( \"$locals_\" + globals_id , \"$locals_\" + locals_id , js ) ( globals_obj , locals_obj ) } else { current_globals_obj = current_frame [ 3 ] current_locals_obj = current_frame [ 1 ] var res = new Function ( \"$locals_\" + globals_id , \"$locals_\" + locals_id , \"$locals_\" + current_globals_id , \"$locals_\" + current_locals_id , js ) ( globals_obj , locals_obj , current_globals_obj , current_locals_obj ) } } else { var res = eval ( js ) } gns = eval ( \"$locals_\" + globals_id ) if ( $B . frames_stack [ $B . frames_stack . length - 1 ] [ 2 ] == globals_id ) { gns = $B . frames_stack [ $B . frames_stack . length - 1 ] [ 3 ] } // Update _locals with the namespace after execution if ( _locals !== _b_ . None ) { lns = eval ( \"$locals_\" + locals_id ) for ( var attr in lns ) { var attr1 = $B . from_alias ( attr ) if ( attr1 . charAt ( 0 ) != '$' ) { if ( _locals . $jsobj ) { _locals . $jsobj [ attr ] = lns [ attr ] } else { _locals . $string_dict [ attr1 ] = lns [ attr ] } } } } else { for ( var attr in lns ) { if ( attr !== \"$src\" ) { current_frame [ 1 ] [ attr ] = lns [ attr ] } } } if ( _globals !== _b_ . None ) { // Update _globals with the namespace after execution for ( var attr in gns ) { attr1 = $B . from_alias ( attr ) if ( attr1 . charAt ( 0 ) != '$' ) { if ( _globals . $jsobj ) { _globals . $jsobj [ attr ] = gns [ attr ] } else { _globals . $string_dict [ attr1 ] = gns [ attr ] } } } } else { for ( var attr in gns ) { if ( attr !== \"$src\" ) { current_frame [ 3 ] [ attr ] = gns [ attr ] } } } // fixme: some extra variables are bleeding into locals... /*  This also causes issues for unittests */ if ( res === undefined ) { return _b_ . None } return res } catch ( err ) { err . src = src err . module = globals_id if ( err . $py_error === undefined ) { throw $B . exception ( err ) } throw err } finally { // \"leave_frame\" was removed so we must execute it here if ( $B . frames_stack . length == stack_len + 1 ) { $B . frames_stack . pop ( ) } root = null js = null gns = null lns = null $B . clear_ns ( globals_id ) $B . clear_ns ( locals_id ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "not a direct alias of prompt : input has no default value [CODESPLIT] function input ( msg ) { var stdin = ( $B . imported . sys && $B . imported . sys . stdin || $B . stdin ) ; if ( stdin . __original__ ) { return prompt ( msg || '' ) || '' } msg = msg || \"\" if ( msg ) { $B . stdout . write ( msg ) } stdin . msg = msg var val = $B . $getattr ( stdin , 'readline' ) ( ) val = val . split ( '\\n' ) [ 0 ] if ( stdin . len === stdin . pos ) { $B . $getattr ( stdin , 'close' ) ( ) } // $B.stdout.write(val+'\\n'); // uncomment if we are to mimic the behavior in the console return val }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * A class to parse color values @author Stoyan Stefanov <sstoo@gmail . com > @link http : // www . phpied . com / rgb - color - parser - in - javascript / Use it if you like it [CODESPLIT] function RGBColor ( m ) { this . ok = ! 1 ; m . charAt ( 0 ) == \"#\" && ( m = m . substr ( 1 , 6 ) ) ; var m = m . replace ( /   / g , \"\" ) , m = m . toLowerCase ( ) , a = { aliceblue : \"f0f8ff\" , antiquewhite : \"faebd7\" , aqua : \"00ffff\" , aquamarine : \"7fffd4\" , azure : \"f0ffff\" , beige : \"f5f5dc\" , bisque : \"ffe4c4\" , black : \"000000\" , blanchedalmond : \"ffebcd\" , blue : \"0000ff\" , blueviolet : \"8a2be2\" , brown : \"a52a2a\" , burlywood : \"deb887\" , cadetblue : \"5f9ea0\" , chartreuse : \"7fff00\" , chocolate : \"d2691e\" , coral : \"ff7f50\" , cornflowerblue : \"6495ed\" , cornsilk : \"fff8dc\" , crimson : \"dc143c\" , cyan : \"00ffff\" , darkblue : \"00008b\" , darkcyan : \"008b8b\" , darkgoldenrod : \"b8860b\" , darkgray : \"a9a9a9\" , darkgreen : \"006400\" , darkkhaki : \"bdb76b\" , darkmagenta : \"8b008b\" , darkolivegreen : \"556b2f\" , darkorange : \"ff8c00\" , darkorchid : \"9932cc\" , darkred : \"8b0000\" , darksalmon : \"e9967a\" , darkseagreen : \"8fbc8f\" , darkslateblue : \"483d8b\" , darkslategray : \"2f4f4f\" , darkturquoise : \"00ced1\" , darkviolet : \"9400d3\" , deeppink : \"ff1493\" , deepskyblue : \"00bfff\" , dimgray : \"696969\" , dodgerblue : \"1e90ff\" , feldspar : \"d19275\" , firebrick : \"b22222\" , floralwhite : \"fffaf0\" , forestgreen : \"228b22\" , fuchsia : \"ff00ff\" , gainsboro : \"dcdcdc\" , ghostwhite : \"f8f8ff\" , gold : \"ffd700\" , goldenrod : \"daa520\" , gray : \"808080\" , green : \"008000\" , greenyellow : \"adff2f\" , honeydew : \"f0fff0\" , hotpink : \"ff69b4\" , indianred : \"cd5c5c\" , indigo : \"4b0082\" , ivory : \"fffff0\" , khaki : \"f0e68c\" , lavender : \"e6e6fa\" , lavenderblush : \"fff0f5\" , lawngreen : \"7cfc00\" , lemonchiffon : \"fffacd\" , lightblue : \"add8e6\" , lightcoral : \"f08080\" , lightcyan : \"e0ffff\" , lightgoldenrodyellow : \"fafad2\" , lightgrey : \"d3d3d3\" , lightgreen : \"90ee90\" , lightpink : \"ffb6c1\" , lightsalmon : \"ffa07a\" , lightseagreen : \"20b2aa\" , lightskyblue : \"87cefa\" , lightslateblue : \"8470ff\" , lightslategray : \"778899\" , lightsteelblue : \"b0c4de\" , lightyellow : \"ffffe0\" , lime : \"00ff00\" , limegreen : \"32cd32\" , linen : \"faf0e6\" , magenta : \"ff00ff\" , maroon : \"800000\" , mediumaquamarine : \"66cdaa\" , mediumblue : \"0000cd\" , mediumorchid : \"ba55d3\" , mediumpurple : \"9370d8\" , mediumseagreen : \"3cb371\" , mediumslateblue : \"7b68ee\" , mediumspringgreen : \"00fa9a\" , mediumturquoise : \"48d1cc\" , mediumvioletred : \"c71585\" , midnightblue : \"191970\" , mintcream : \"f5fffa\" , mistyrose : \"ffe4e1\" , moccasin : \"ffe4b5\" , navajowhite : \"ffdead\" , navy : \"000080\" , oldlace : \"fdf5e6\" , olive : \"808000\" , olivedrab : \"6b8e23\" , orange : \"ffa500\" , orangered : \"ff4500\" , orchid : \"da70d6\" , palegoldenrod : \"eee8aa\" , palegreen : \"98fb98\" , paleturquoise : \"afeeee\" , palevioletred : \"d87093\" , papayawhip : \"ffefd5\" , peachpuff : \"ffdab9\" , peru : \"cd853f\" , pink : \"ffc0cb\" , plum : \"dda0dd\" , powderblue : \"b0e0e6\" , purple : \"800080\" , red : \"ff0000\" , rosybrown : \"bc8f8f\" , royalblue : \"4169e1\" , saddlebrown : \"8b4513\" , salmon : \"fa8072\" , sandybrown : \"f4a460\" , seagreen : \"2e8b57\" , seashell : \"fff5ee\" , sienna : \"a0522d\" , silver : \"c0c0c0\" , skyblue : \"87ceeb\" , slateblue : \"6a5acd\" , slategray : \"708090\" , snow : \"fffafa\" , springgreen : \"00ff7f\" , steelblue : \"4682b4\" , tan : \"d2b48c\" , teal : \"008080\" , thistle : \"d8bfd8\" , tomato : \"ff6347\" , turquoise : \"40e0d0\" , violet : \"ee82ee\" , violetred : \"d02090\" , wheat : \"f5deb3\" , white : \"ffffff\" , whitesmoke : \"f5f5f5\" , yellow : \"ffff00\" , yellowgreen : \"9acd32\" } , c ; for ( c in a ) m == c && ( m = a [ c ] ) ; var d = [ { re : / ^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$ / , example : [ \"rgb(123, 234, 45)\" , \"rgb(255,234,245)\" ] , process : function ( b ) { return [ parseInt ( b [ 1 ] ) , parseInt ( b [ 2 ] ) , parseInt ( b [ 3 ] ) ] } } , { re : / ^(\\w{2})(\\w{2})(\\w{2})$ / , example : [ \"#00ff00\" , \"336699\" ] , process : function ( b ) { return [ parseInt ( b [ 1 ] , 16 ) , parseInt ( b [ 2 ] , 16 ) , parseInt ( b [ 3 ] , 16 ) ] } } , { re : / ^(\\w{1})(\\w{1})(\\w{1})$ / , example : [ \"#fb0\" , \"f0f\" ] , process : function ( b ) { return [ parseInt ( b [ 1 ] + b [ 1 ] , 16 ) , parseInt ( b [ 2 ] + b [ 2 ] , 16 ) , parseInt ( b [ 3 ] + b [ 3 ] , 16 ) ] } } ] ; for ( c = 0 ; c < d . length ; c ++ ) { var b = d [ c ] . process , k = d [ c ] . re . exec ( m ) ; if ( k ) channels = b ( k ) , this . r = channels [ 0 ] , this . g = channels [ 1 ] , this . b = channels [ 2 ] , this . ok = ! 0 } this . r = this . r < 0 || isNaN ( this . r ) ? 0 : this . r > 255 ? 255 : this . r ; this . g = this . g < 0 || isNaN ( this . g ) ? 0 : this . g > 255 ? 255 : this . g ; this . b = this . b < 0 || isNaN ( this . b ) ? 0 : this . b > 255 ? 255 : this . b ; this . toRGB = function ( ) { return \"rgb(\" + this . r + \", \" + this . g + \", \" + this . b + \")\" } ; this . toHex = function ( ) { var b = this . r . toString ( 16 ) , a = this . g . toString ( 16 ) , d = this . b . toString ( 16 ) ; b . length == 1 && ( b = \"0\" + b ) ; a . length == 1 && ( a = \"0\" + a ) ; d . length == 1 && ( d = \"0\" + d ) ; return \"#\" + b + a + d } ; this . getHelpXML = function ( ) { for ( var b = [ ] , k = 0 ; k < d . length ; k ++ ) for ( var c = d [ k ] . example , j = 0 ; j < c . length ; j ++ ) b [ b . length ] = c [ j ] ; for ( var h in a ) b [ b . length ] = h ; c = document . createElement ( \"ul\" ) ; c . setAttribute ( \"id\" , \"rgbcolor-examples\" ) ; for ( k = 0 ; k < b . length ; k ++ ) try { var l = document . createElement ( \"li\" ) , o = new RGBColor ( b [ k ] ) , n = document . createElement ( \"div\" ) ; n . style . cssText = \"margin: 3px; border: 1px solid black; background:\" + o . toHex ( ) + \"; color:\" + o . toHex ( ) ; n . appendChild ( document . createTextNode ( \"test\" ) ) ; var q = document . createTextNode ( \" \" + b [ k ] + \" -> \" + o . toRGB ( ) + \" -> \" + o . toHex ( ) ) ; l . appendChild ( n ) ; l . appendChild ( q ) ; c . appendChild ( l ) } catch ( p ) { } return c } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "5 . Run rollup inside the / build folder to generate our Flat ES module and place the generated file into the / dist folder [CODESPLIT] function ( name , path ) { path = path || '' ; return gulp . src ( ` ${ buildFolder } ${ path } ` ) // transform the files here. . pipe ( rollup ( { // Bundle's entry point // See \"input\" in https://rollupjs.org/#core-functionality input : ` ${ buildFolder } ${ path } ` , // Allow mixing of hypothetical and actual files. \"Actual\" files can be files // accessed by Rollup or produced by plugins further down the chain. // This prevents errors like: 'path/file' does not exist in the hypothetical file system // when subdirectories are used in the `src` directory. allowRealFiles : true , // A list of IDs of modules that should remain external to the bundle // See \"external\" in https://rollupjs.org/#core-functionality external : [ '@angular/core' , '@angular/common' ] , output : { // Format of generated bundle // See \"format\" in https://rollupjs.org/#core-functionality format : 'es' } } ) ) . pipe ( gulp . dest ( ` ${ distFolder } ${ path } ` ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simple Promiseify function that takes a Node API and return a version that supports promises . We use promises instead of synchronized functions to make the process less I / O bound and faster . It also simplifies the code . [CODESPLIT] function promiseify ( fn ) { return function ( ) { const args = [ ] . slice . call ( arguments , 0 ) ; return new Promise ( ( resolve , reject ) => { fn . apply ( this , args . concat ( [ function ( err , value ) { if ( err ) { reject ( err ) ; } else { resolve ( value ) ; } } ] ) ) ; } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inline resources from a string content . [CODESPLIT] function inlineResourcesFromString ( content , urlResolver ) { // Curry through the inlining functions. return [ inlineTemplate , inlineStyle , removeModuleId ] . reduce ( ( content , fn ) => fn ( content , urlResolver ) , content ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inline the styles for a source file . Simply search for instances of styleUrls : [ ... ] and replace with styles : [ ... ] ( with the content of the file included ) . [CODESPLIT] function inlineStyle ( content , urlResolver ) { return content . replace ( / styleUrls\\s*:\\s*(\\[[\\s\\S]*?\\]) / gm , function ( m , styleUrls ) { const urls = eval ( styleUrls ) ; return 'styles: [' + urls . map ( styleUrl => { const styleFile = urlResolver ( styleUrl ) ; const originContent = fs . readFileSync ( styleFile , 'utf-8' ) ; const styleContent = styleFile . endsWith ( '.scss' ) ? buildSass ( originContent , styleFile ) : originContent ; const shortenedStyle = styleContent . replace ( / ([\\n\\r]\\s*)+ / gm , ' ' ) . replace ( / \" / g , '\\\\\"' ) ; return ` ${ shortenedStyle } ` ; } ) . join ( ',\\n' ) + ']' ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build sass content to css [CODESPLIT] function buildSass ( content , sourceFile ) { try { const result = sass . renderSync ( { data : content , file : sourceFile , importer : tildeImporter } ) ; return result . css . toString ( ) } catch ( e ) { console . error ( '\\x1b[41m' ) ; console . error ( 'at ' + sourceFile + ':' + e . line + \":\" + e . column ) ; console . error ( e . formatted ) ; console . error ( '\\x1b[0m' ) ; return \"\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The routes used to define a resource . [CODESPLIT] function FormioResourceRoutes ( config ) { config = config || { } ; return [ { path : '' , component : config . index || index_component_1 . FormioResourceIndexComponent } , { path : 'new' , component : config . create || create_component_1 . FormioResourceCreateComponent } , { path : ':id' , component : config . resource || resource_component_1 . FormioResourceComponent , children : [ { path : '' , redirectTo : 'view' , pathMatch : 'full' } , { path : 'view' , component : config . view || view_component_1 . FormioResourceViewComponent } , { path : 'edit' , component : config . edit || edit_component_1 . FormioResourceEditComponent } , { path : 'delete' , component : config . delete || delete_component_1 . FormioResourceDeleteComponent } ] } ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Converts : [CODESPLIT] function groupPartitionsByTopic ( topicPartitions ) { assert ( Array . isArray ( topicPartitions ) ) ; return topicPartitions . reduce ( function ( result , tp ) { if ( ! ( tp . topic in result ) ) { result [ tp . topic ] = [ tp . partition ] ; } else { result [ tp . topic ] . push ( tp . partition ) ; } return result ; } , { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Converts : { test : [ 0 1 ] bob : [ 0 ] } [CODESPLIT] function createTopicPartitionList ( topicPartitions ) { var tpList = [ ] ; for ( var topic in topicPartitions ) { if ( ! topicPartitions . hasOwnProperty ( topic ) ) { continue ; } topicPartitions [ topic ] . forEach ( function ( partition ) { tpList . push ( { topic : topic , partition : partition } ) ; } ) ; } return tpList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ported from : https : // github . com / Shopify / sarama / blob / a3e2437d6d26cda6b2dc501dbdab4d3f6befa295 / snappy . go [CODESPLIT] function decodeSnappy ( buffer , cb ) { if ( isChunked ( buffer ) ) { var pos = 16 ; var max = buffer . length ; var encoded = [ ] ; var size ; while ( pos < max ) { size = buffer . readUInt32BE ( pos ) ; pos += 4 ; encoded . push ( buffer . slice ( pos , pos + size ) ) ; pos += size ; } return async . mapSeries ( encoded , snappy . uncompress , function ( err , decodedChunks ) { if ( err ) return cb ( err ) ; return cb ( null , Buffer . concat ( decodedChunks ) ) ; } ) ; } return snappy . uncompress ( buffer , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * { 1001 : { jmx_port : - 1 timestamp : 1492521177416 endpoints : [ PLAINTEXT : // 127 . 0 . 0 . 1 : 9092 SSL : // 127 . 0 . 0 . 1 : 9093 ] host : 127 . 0 . 0 . 1 version : 2 port : 9092 id : 1001 } } [CODESPLIT] function parseHost ( hostString ) { const ip = hostString . substring ( 0 , hostString . lastIndexOf ( ':' ) ) ; const port = + hostString . substring ( hostString . lastIndexOf ( ':' ) + 1 ) ; const isIpv6 = ip . match ( / \\[(.*)\\] / ) ; const host = isIpv6 ? isIpv6 [ 1 ] : ip ; return { host , port } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides common functionality for a kafka producer [CODESPLIT] function BaseProducer ( client , options , defaultPartitionerType , customPartitioner ) { EventEmitter . call ( this ) ; options = options || { } ; this . ready = false ; this . client = client ; this . requireAcks = options . requireAcks === undefined ? DEFAULTS . requireAcks : options . requireAcks ; this . ackTimeoutMs = options . ackTimeoutMs === undefined ? DEFAULTS . ackTimeoutMs : options . ackTimeoutMs ; if ( customPartitioner !== undefined && options . partitionerType !== PARTITIONER_TYPES . custom ) { throw new Error ( 'Partitioner Type must be custom if providing a customPartitioner.' ) ; } else if ( customPartitioner === undefined && options . partitionerType === PARTITIONER_TYPES . custom ) { throw new Error ( 'No customer partitioner defined' ) ; } var partitionerType = PARTITIONER_MAP [ options . partitionerType ] || PARTITIONER_MAP [ defaultPartitionerType ] ; // eslint-disable-next-line this . partitioner = new partitionerType ( customPartitioner ) ; this . connect ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function encodeGroupProtocol ( protocol ) { this . Int16BE ( protocol . name . length ) . string ( protocol . name ) . string ( _encodeProtocolData ( protocol ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * MemberAssignment = > Version PartitionAssignment Version = > int16 PartitionAssignment = > [ Topic [ Partition ]] Topic = > string Partition = > int32 UserData = > bytes [CODESPLIT] function decodeMemberAssignment ( assignmentBytes ) { var assignment = { partitions : { } } ; Binary . parse ( assignmentBytes ) . word16bs ( 'version' ) . tap ( function ( vars ) { assignment . version = vars . version ; } ) . word32bs ( 'partitionAssignment' ) . loop ( function ( end , vars ) { if ( vars . partitionAssignment -- === 0 ) return end ( ) ; var topic ; var partitions = [ ] ; this . word16bs ( 'topic' ) . tap ( function ( vars ) { this . buffer ( 'topic' , vars . topic ) ; topic = vars . topic . toString ( ) ; } ) . word32bs ( 'partitionsNum' ) . loop ( function ( end , vars ) { if ( vars . partitionsNum -- === 0 ) return end ( ) ; this . word32bs ( 'partition' ) . tap ( function ( vars ) { partitions . push ( vars . partition ) ; } ) ; } ) ; assignment . partitions [ topic ] = partitions ; } ) . word32bs ( 'userData' ) . tap ( function ( vars ) { if ( vars . userData == null || vars . userData === - 1 ) { return ; } this . buffer ( 'userData' , vars . userData ) ; try { assignment . userData = JSON . parse ( vars . userData . toString ( ) ) ; } catch ( e ) { assignment . userData = 'JSON Parse error' ; } } ) ; return assignment ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ name : // string subscription : [ / * topics * / ] version : 0 // integer userData : {} // arbitary } / * JoinGroupRequest = > GroupId SessionTimeout MemberId ProtocolType GroupProtocols GroupId = > string SessionTimeout = > int32 MemberId = > string ProtocolType = > string GroupProtocols = > [ ProtocolName ProtocolMetadata ] ProtocolName = > string ProtocolMetadata = > bytes [CODESPLIT] function encodeJoinGroupRequest ( clientId , correlationId , groupId , memberId , sessionTimeout , groupProtocols ) { var request = encodeRequestHeader ( clientId , correlationId , REQUEST_TYPE . joinGroup ) ; request . Int16BE ( groupId . length ) . string ( groupId ) . Int32BE ( sessionTimeout ) . Int16BE ( memberId . length ) . string ( memberId ) . Int16BE ( GROUPS_PROTOCOL_TYPE . length ) . string ( GROUPS_PROTOCOL_TYPE ) . Int32BE ( groupProtocols . length ) ; groupProtocols . forEach ( encodeGroupProtocol . bind ( request ) ) ; return encodeRequestWithLength ( request . make ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function decodeJoinGroupResponse ( resp ) { var result = { members : [ ] } ; var error ; Binary . parse ( resp ) . word32bs ( 'size' ) . word32bs ( 'correlationId' ) . word16bs ( 'errorCode' ) . tap ( function ( vars ) { error = createGroupError ( vars . errorCode ) ; } ) . word32bs ( 'generationId' ) . tap ( function ( vars ) { result . generationId = vars . generationId ; } ) . word16bs ( 'groupProtocol' ) . tap ( function ( vars ) { this . buffer ( 'groupProtocol' , vars . groupProtocol ) ; result . groupProtocol = vars . groupProtocol = vars . groupProtocol . toString ( ) ; } ) . word16bs ( 'leaderId' ) . tap ( function ( vars ) { this . buffer ( 'leaderId' , vars . leaderId ) ; result . leaderId = vars . leaderId = vars . leaderId . toString ( ) ; } ) . word16bs ( 'memberId' ) . tap ( function ( vars ) { this . buffer ( 'memberId' , vars . memberId ) ; result . memberId = vars . memberId = vars . memberId . toString ( ) ; } ) . word32bs ( 'memberNum' ) . loop ( function ( end , vars ) { if ( error ) { return end ( ) ; } if ( vars . memberNum -- === 0 ) return end ( ) ; var memberMetadata ; this . word16bs ( 'groupMemberId' ) . tap ( function ( vars ) { this . buffer ( 'groupMemberId' , vars . groupMemberId ) ; vars . memberId = vars . groupMemberId . toString ( ) ; } ) . word32bs ( 'memberMetadata' ) . tap ( function ( vars ) { if ( vars . memberMetadata > - 1 ) { this . buffer ( 'memberMetadata' , vars . memberMetadata ) ; memberMetadata = decodeGroupData ( this . vars . memberMetadata ) ; memberMetadata . id = vars . memberId ; result . members . push ( memberMetadata ) ; } } ) ; } ) ; return error || result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private helper [CODESPLIT] function fetchOffsets ( offset , topics , cb , when ) { if ( ! offset . ready ) { if ( when === - 1 ) { offset . once ( 'ready' , ( ) => offset . fetchLatestOffsets ( topics , cb ) ) ; } else if ( when === - 2 ) { offset . once ( 'ready' , ( ) => offset . fetchEarliestOffsets ( topics , cb ) ) ; } return ; } async . waterfall ( [ callback => { offset . client . loadMetadataForTopics ( topics , callback ) ; } , ( topicsMetaData , callback ) => { var payloads = [ ] ; var metaDatas = topicsMetaData [ 1 ] . metadata ; Object . keys ( metaDatas ) . forEach ( function ( topicName ) { var topic = metaDatas [ topicName ] ; Object . keys ( topic ) . forEach ( function ( partition ) { payloads . push ( { topic : topicName , partition : partition , time : when } ) ; } ) ; } ) ; if ( payloads . length === 0 ) { return callback ( new Error ( 'Topic(s) does not exist' ) ) ; } offset . fetch ( payloads , callback ) ; } , function ( results , callback ) { Object . keys ( results ) . forEach ( function ( topicName ) { var topic = results [ topicName ] ; Object . keys ( topic ) . forEach ( function ( partitionName ) { topic [ partitionName ] = topic [ partitionName ] [ 0 ] ; } ) ; } ) ; callback ( null , results ) ; } ] , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Helper method topic in payloads may send to different broker so we cache data util all request came back [CODESPLIT] function wrap ( payloads , cb ) { var out = { } ; var count = Object . keys ( payloads ) . length ; return function ( err , data ) { // data: { topicName1: {}, topicName2: {} } if ( err ) return cb && cb ( err ) ; _ . merge ( out , data ) ; count -= 1 ; // Waiting for all request return if ( count !== 0 ) return ; cb && cb ( null , out ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Global context used to evaluate standard IUAM JS challenge [CODESPLIT] function Context ( options ) { if ( ! options ) options = { body : '' , hostname : '' } ; const body = options . body ; const href = 'http://' + options . hostname + '/' ; const cache = Object . create ( null ) ; const keys = [ ] ; this . atob = function ( str ) { return Buffer . from ( str , 'base64' ) . toString ( 'binary' ) ; } ; // Used for eval during onRedirectChallenge this . location = { reload : function ( ) { } } ; this . document = { createElement : function ( ) { return { firstChild : { href : href } } ; } , getElementById : function ( id ) { if ( keys . indexOf ( id ) === - 1 ) { const re = new RegExp ( ' id=[\\'\"]?' + id + '[^>]*>([^<]*)' ) ; const match = body . match ( re ) ; keys . push ( id ) ; cache [ id ] = match === null ? match : { innerHTML : match [ 1 ] } ; } return cache [ id ] ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pseudo function that returns a promise instead of calling captcha . submit () [CODESPLIT] function handler ( options , { captcha } ) { return new Promise ( ( resolve , reject ) => { // Here you do some magic with the siteKey provided by cloudscraper console . error ( 'The url is \"' + captcha . url + '\"' ) ; console . error ( 'The site key is \"' + captcha . siteKey + '\"' ) ; // captcha.form['g-recaptcha-response'] = /* Obtain from your service */ reject ( new Error ( 'This is a dummy function.' ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An example handler with destructuring arguments [CODESPLIT] function alternative ( options , { captcha : { url , siteKey } } ) { // Here you do some magic with the siteKey provided by cloudscraper console . error ( 'The url is \"' + url + '\"' ) ; console . error ( 'The site key is \"' + siteKey + '\"' ) ; return Promise . reject ( new Error ( 'This is a dummy function' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function is wrapped to ensure that we get new options on first call . The options object is reused in subsequent calls when calling it directly . [CODESPLIT] function performRequest ( options , isFirstRequest ) { // This should be the default export of either request or request-promise. const requester = options . requester ; // Note that request is always an instanceof ReadableStream, EventEmitter // If the requester is request-promise, it is also thenable. const request = requester ( options ) ; // We must define the host header ourselves to preserve case and order. if ( request . getHeader ( 'host' ) === HOST ) { request . setHeader ( 'host' , request . uri . host ) ; } // If the requester is not request-promise, ensure we get a callback. if ( typeof request . callback !== 'function' ) { throw new TypeError ( 'Expected a callback function, got ' + typeof ( request . callback ) + ' instead.' ) ; } // We only need the callback from the first request. // The other callbacks can be safely ignored. if ( isFirstRequest ) { // This should be a user supplied callback or request-promise's callback. // The callback is always wrapped/bound to the request instance. options . callback = request . callback ; } request . removeAllListeners ( 'error' ) . once ( 'error' , function ( error ) { onRequestResponse ( options , error ) ; } ) ; request . removeAllListeners ( 'complete' ) . once ( 'complete' , function ( response , body ) { onRequestResponse ( options , null , response , body ) ; } ) ; // Indicate that this is a cloudscraper request request . cloudscraper = true ; return request ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The argument convention is options first where possible options always before response and body always after response . [CODESPLIT] function onRequestResponse ( options , error , response , body ) { const callback = options . callback ; // Encoding is null so body should be a buffer object if ( error || ! body || ! body . toString ) { // Pure request error (bad connection, wrong url, etc) return callback ( new RequestError ( error , options , response ) ) ; } response . responseStartTime = Date . now ( ) ; response . isCloudflare = / ^cloudflare / i . test ( '' + response . caseless . get ( 'server' ) ) ; response . isHTML = / text\\/html / i . test ( '' + response . caseless . get ( 'content-type' ) ) ; // If body isn't a buffer, this is a custom response body. if ( ! Buffer . isBuffer ( body ) ) { return callback ( null , response , body ) ; } // Decompress brotli compressed responses if ( / \\bbr\\b / i . test ( '' + response . caseless . get ( 'content-encoding' ) ) ) { if ( ! brotli . isAvailable ) { const cause = 'Received a Brotli compressed response. Please install brotli' ; return callback ( new RequestError ( cause , options , response ) ) ; } response . body = body = brotli . decompress ( body ) ; } if ( response . isCloudflare && response . isHTML ) { onCloudflareResponse ( options , response , body ) ; } else { onRequestComplete ( options , response , body ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the reCAPTCHA form and hands control over to the user [CODESPLIT] function onCaptcha ( options , response , body ) { const callback = options . callback ; // UDF that has the responsibility of returning control back to cloudscraper const handler = options . onCaptcha ; // The form data to send back to Cloudflare const payload = { /* s, g-re-captcha-response */ } ; let cause ; let match ; match = body . match ( / <form(?: [^<>]*)? id=[\"']?challenge-form['\"]?(?: [^<>]*)?>([\\S\\s]*?)<\\/form> / ) ; if ( ! match ) { cause = 'Challenge form extraction failed' ; return callback ( new ParserError ( cause , options , response ) ) ; } // Defining response.challengeForm for debugging purposes const form = response . challengeForm = match [ 1 ] ; match = form . match ( / \\/recaptcha\\/api\\/fallback\\?k=([^\\s\"'<>]*) / ) ; if ( ! match ) { // The site key wasn't inside the form so search the entire document match = body . match ( / data-sitekey=[\"']?([^\\s\"'<>]*) / ) ; if ( ! match ) { cause = 'Unable to find the reCAPTCHA site key' ; return callback ( new ParserError ( cause , options , response ) ) ; } } // Everything that is needed to solve the reCAPTCHA response . captcha = { url : response . request . uri . href , siteKey : match [ 1 ] , form : payload } ; // Adding formData match = form . match ( / <input(?: [^<>]*)? name=[^<>]+> / g ) ; if ( ! match ) { cause = 'Challenge form is missing inputs' ; return callback ( new ParserError ( cause , options , response ) ) ; } const inputs = match ; // Only adding inputs that have both a name and value defined for ( let name , value , i = 0 ; i < inputs . length ; i ++ ) { name = inputs [ i ] . match ( / name=[\"']?([^\\s\"'<>]*) / ) ; if ( name ) { value = inputs [ i ] . match ( / value=[\"']?([^\\s\"'<>]*) / ) ; if ( value ) { payload [ name [ 1 ] ] = value [ 1 ] ; } } } // Sanity check if ( ! payload [ 's' ] ) { cause = 'Challenge form is missing secret input' ; return callback ( new ParserError ( cause , options , response ) ) ; } // The callback used to green light form submission const submit = function ( error ) { if ( error ) { // Pass an user defined error back to the original request call return callback ( new CaptchaError ( error , options , response ) ) ; } onSubmitCaptcha ( options , response , body ) ; } ; // This seems like an okay-ish API (fewer arguments to the handler) response . captcha . submit = submit ; // We're handing control over to the user now. const thenable = handler ( options , response , body ) ; // Handle the case where the user returns a promise if ( thenable && typeof thenable . then === 'function' ) { // eslint-disable-next-line promise/catch-or-return thenable . then ( submit , function ( error ) { if ( ! error ) { // The user broke their promise with a falsy error submit ( new Error ( 'Falsy error' ) ) ; } else { submit ( error ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The callback used to green light form submission [CODESPLIT] function ( error ) { if ( error ) { // Pass an user defined error back to the original request call return callback ( new CaptchaError ( error , options , response ) ) ; } onSubmitCaptcha ( options , response , body ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ts [CODESPLIT] function insertTs ( name ) { const tsIndexPath = path . resolve ( __dirname , '../src/index.ts' ) ; const tsIndexFile = fs . readFileSync ( tsIndexPath , { encoding : 'utf-8' } ) ; const moduleExports = tsIndexFile . trim ( ) . split ( '\\n' ) ; moduleExports . push ( ` ${ name } ` ) ; sortByModulePath ( moduleExports ) ; fs . writeFileSync ( tsIndexPath , ` ${ moduleExports . join ( '\\n' ) } \\n ` ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "style [CODESPLIT] function insertCss ( name ) { const cssIndexPath = path . resolve ( __dirname , '../assets/index.scss' ) ; const cssIndexFile = fs . readFileSync ( cssIndexPath , { encoding : 'utf-8' } ) ; const cssImportStr = ` ${ name } ` ; const cssIndexFileArr = cssIndexFile . trim ( ) . split ( '\\n' ) ; cssIndexFileArr . push ( cssImportStr ) ; // Make sure base comes first const base = cssIndexFileArr . splice ( 0 , 1 ) ; sortByModulePath ( cssIndexFileArr ) ; cssIndexFileArr . unshift ( base ) ; fs . writeFileSync ( cssIndexPath , ` ${ cssIndexFileArr . join ( '\\n' ) } \\n ` ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "创建组件文件夹以及js / css文件 [CODESPLIT] function addFiles ( name ) { const packagesDir = path . resolve ( __dirname , '../src' ) ; const assetsDir = path . resolve ( __dirname , '../assets' ) ; const componentDir = ` ${ packagesDir } ${ name } ` ; const upperComponentName = getComponentName ( name ) ; console . log ( ` up perComponentName}` ) ;   if ( ! fs . existsSync ( componentDir ) ) { fs . mkdirSync ( componentDir ) ; } else { console . log ( ` ${ upperComponentName } ` ) ; process . exit ( 2 ) ; } fs . writeFileSync ( ` ${ componentDir } ` , ` ${ upperComponentName } ${ upperComponentName } \\n \\n ${ upperComponentName } \\n ` ) ; fs . writeFileSync ( ` ${ componentDir } ` , ` ${ upperComponentName } ${ name } ${ upperComponentName } ${ upperComponentName } ` ) ; fs . writeFileSync ( ` ${ componentDir } ` , ` ${ upperComponentName } ${ name } ${ upperComponentName } om ponentName} 组件。  ` ) ; fs . writeFileSync ( ` ${ componentDir } ${ upperComponentName } ` , '' ) ; fs . writeFileSync ( ` ${ assetsDir } ${ name } ` , '' ) ; addFilesToIndex ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "为src目录下的所有子目录创建alias [CODESPLIT] function createMapper ( ) { var packagesDir = path . resolve ( __dirname , '../src' ) ; var packages = fs . readdirSync ( packagesDir ) ; return packages . filter ( p => fs . statSync ( path . join ( packagesDir , p ) ) . isDirectory ( ) ) . reduce ( ( alias , p ) => { alias [ ` ${ p } ` ] = ` ${ p } ` ; alias [ ` ${ p } ` ] = ` ${ p } ` ; return alias ; } , { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disable Google Maps scrolling See http : // stackoverflow . com / a / 25904582 / 1607849 Disable scroll zooming and bind back the click event [CODESPLIT] function ( event ) { var that = $ ( this ) ; that . on ( 'click' , onMapClickHandler ) ; that . off ( 'mouseleave' , onMapMouseleaveHandler ) ; that . find ( 'iframe' ) . css ( \"pointer-events\" , \"none\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Following function will make the . sidebar - opener clickable and it will open / close the sidebar on the documentations [CODESPLIT] function toggleDocumentationSidebar ( ) { const sidebarNav = document . querySelector ( 'nav.sidebar' ) ; const trigger = document . querySelector ( '.sidebar-opener' ) ; function init ( ) { const bodySize = document . body . clientWidth ; if ( bodySize <= 960 && sidebarNav ) { trigger . addEventListener ( 'click' , ( ) => { sidebarNav . classList . toggle ( 'Showed' ) ; trigger . classList . toggle ( 'Showed' ) ; } ) ; } } init ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Metalsmith plugin to include static assets . [CODESPLIT] function assets ( userOptions = { } ) { const options = { ... defaults , ... userOptions , } ; return ( files , metalsmith , cb ) => { const src = metalsmith . path ( options . source ) ; const dest = options . destination ; // copied almost line for line from https://github.com/segmentio/metalsmith/blob/master/lib/index.js readdir ( src , ( readDirError , arr ) => { if ( readDirError ) { cb ( readDirError ) ; return ; } each ( arr , read , err => cb ( err , files ) ) ; } ) ; function read ( file , done ) { const name = path . join ( dest , path . relative ( src , file ) ) ; fs . stat ( file , ( statError , stats ) => { if ( statError ) { done ( statError ) ; return ; } fs . readFile ( file , ( err , buffer ) => { if ( err ) { done ( err ) ; return ; } const newFile = { } ; newFile . contents = buffer ; newFile . stats = stats ; newFile . mode = mode ( stats ) . toOctal ( ) ; files [ name ] = newFile ; done ( ) ; } ) ; } ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines the limits where to start or stop the stickiness [CODESPLIT] function getStartStopBoundaries ( parent , sidebar , topOffset ) { const bbox = parent . getBoundingClientRect ( ) ; const sidebarBbox = sidebar . getBoundingClientRect ( ) ; const bodyBbox = document . body . getBoundingClientRect ( ) ; const containerAbsoluteTop = bbox . top - bodyBbox . top ; const sidebarAbsoluteTop = sidebarBbox . top - bodyBbox . top ; const marginTop = sidebarAbsoluteTop - containerAbsoluteTop ; const start = containerAbsoluteTop - topOffset ; const stop = bbox . height + containerAbsoluteTop - sidebarBbox . height - marginTop - topOffset ; return { start , stop , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Install an around function ; AOP . [CODESPLIT] function around ( obj , method , fn ) { var old = obj [ method ] obj [ method ] = function ( ) { var args = new Array ( arguments . length ) for ( var i = 0 ; i < args . length ; i ++ ) args [ i ] = arguments [ i ] return fn . call ( this , old , args ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Install a before function ; AOP . [CODESPLIT] function before ( obj , method , fn ) { var old = obj [ method ] obj [ method ] = function ( ) { fn . call ( this ) old . apply ( this , arguments ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prompt for confirmation on STDOUT / STDIN [CODESPLIT] function confirm ( msg , callback ) { var rl = readline . createInterface ( { input : process . stdin , output : process . stdout } ) rl . question ( msg , function ( input ) { rl . close ( ) callback ( / ^y|yes|ok|true$ / i . test ( input ) ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy file from template directory . [CODESPLIT] function copyTemplate ( from , to ) { write ( to , fs . readFileSync ( path . join ( TEMPLATE_DIR , from ) , 'utf-8' ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy multiple files from template directory . [CODESPLIT] function copyTemplateMulti ( fromDir , toDir , nameGlob ) { fs . readdirSync ( path . join ( TEMPLATE_DIR , fromDir ) ) . filter ( minimatch . filter ( nameGlob , { matchBase : true } ) ) . forEach ( function ( name ) { copyTemplate ( path . join ( fromDir , name ) , path . join ( toDir , name ) ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create application at the given directory . [CODESPLIT] function createApplication ( name , dir ) { console . log ( ) // Package var pkg = { name : name , version : '0.0.0' , private : true , scripts : { start : 'node ./bin/www' } , dependencies : { 'debug' : '~2.6.9' , 'express' : '~4.16.1' } } // JavaScript var app = loadTemplate ( 'js/app.js' ) var www = loadTemplate ( 'js/www' ) // App name www . locals . name = name // App modules app . locals . localModules = Object . create ( null ) app . locals . modules = Object . create ( null ) app . locals . mounts = [ ] app . locals . uses = [ ] // Request logger app . locals . modules . logger = 'morgan' app . locals . uses . push ( \"logger('dev')\" ) pkg . dependencies . morgan = '~1.9.1' // Body parsers app . locals . uses . push ( 'express.json()' ) app . locals . uses . push ( 'express.urlencoded({ extended: false })' ) // Cookie parser app . locals . modules . cookieParser = 'cookie-parser' app . locals . uses . push ( 'cookieParser()' ) pkg . dependencies [ 'cookie-parser' ] = '~1.4.4' if ( dir !== '.' ) { mkdir ( dir , '.' ) } mkdir ( dir , 'public' ) mkdir ( dir , 'public/javascripts' ) mkdir ( dir , 'public/images' ) mkdir ( dir , 'public/stylesheets' ) // copy css templates switch ( program . css ) { case 'less' : copyTemplateMulti ( 'css' , dir + '/public/stylesheets' , '*.less' ) break case 'stylus' : copyTemplateMulti ( 'css' , dir + '/public/stylesheets' , '*.styl' ) break case 'compass' : copyTemplateMulti ( 'css' , dir + '/public/stylesheets' , '*.scss' ) break case 'sass' : copyTemplateMulti ( 'css' , dir + '/public/stylesheets' , '*.sass' ) break default : copyTemplateMulti ( 'css' , dir + '/public/stylesheets' , '*.css' ) break } // copy route templates mkdir ( dir , 'routes' ) copyTemplateMulti ( 'js/routes' , dir + '/routes' , '*.js' ) if ( program . view ) { // Copy view templates mkdir ( dir , 'views' ) pkg . dependencies [ 'http-errors' ] = '~1.6.3' switch ( program . view ) { case 'dust' : copyTemplateMulti ( 'views' , dir + '/views' , '*.dust' ) break case 'ejs' : copyTemplateMulti ( 'views' , dir + '/views' , '*.ejs' ) break case 'hbs' : copyTemplateMulti ( 'views' , dir + '/views' , '*.hbs' ) break case 'hjs' : copyTemplateMulti ( 'views' , dir + '/views' , '*.hjs' ) break case 'jade' : copyTemplateMulti ( 'views' , dir + '/views' , '*.jade' ) break case 'pug' : copyTemplateMulti ( 'views' , dir + '/views' , '*.pug' ) break case 'twig' : copyTemplateMulti ( 'views' , dir + '/views' , '*.twig' ) break case 'vash' : copyTemplateMulti ( 'views' , dir + '/views' , '*.vash' ) break } } else { // Copy extra public files copyTemplate ( 'js/index.html' , path . join ( dir , 'public/index.html' ) ) } // CSS Engine support switch ( program . css ) { case 'compass' : app . locals . modules . compass = 'node-compass' app . locals . uses . push ( \"compass({ mode: 'expanded' })\" ) pkg . dependencies [ 'node-compass' ] = '0.2.3' break case 'less' : app . locals . modules . lessMiddleware = 'less-middleware' app . locals . uses . push ( \"lessMiddleware(path.join(__dirname, 'public'))\" ) pkg . dependencies [ 'less-middleware' ] = '~2.2.1' break case 'sass' : app . locals . modules . sassMiddleware = 'node-sass-middleware' app . locals . uses . push ( \"sassMiddleware({\\n  src: path.join(__dirname, 'public'),\\n  dest: path.join(__dirname, 'public'),\\n  indentedSyntax: true, // true = .sass and false = .scss\\n  sourceMap: true\\n})\" ) pkg . dependencies [ 'node-sass-middleware' ] = '0.11.0' break case 'stylus' : app . locals . modules . stylus = 'stylus' app . locals . uses . push ( \"stylus.middleware(path.join(__dirname, 'public'))\" ) pkg . dependencies [ 'stylus' ] = '0.54.5' break } // Index router mount app . locals . localModules . indexRouter = './routes/index' app . locals . mounts . push ( { path : '/' , code : 'indexRouter' } ) // User router mount app . locals . localModules . usersRouter = './routes/users' app . locals . mounts . push ( { path : '/users' , code : 'usersRouter' } ) // Template support switch ( program . view ) { case 'dust' : app . locals . modules . adaro = 'adaro' app . locals . view = { engine : 'dust' , render : 'adaro.dust()' } pkg . dependencies . adaro = '~1.0.4' break case 'ejs' : app . locals . view = { engine : 'ejs' } pkg . dependencies . ejs = '~2.6.1' break case 'hbs' : app . locals . view = { engine : 'hbs' } pkg . dependencies . hbs = '~4.0.4' break case 'hjs' : app . locals . view = { engine : 'hjs' } pkg . dependencies . hjs = '~0.0.6' break case 'jade' : app . locals . view = { engine : 'jade' } pkg . dependencies . jade = '~1.11.0' break case 'pug' : app . locals . view = { engine : 'pug' } pkg . dependencies . pug = '2.0.0-beta11' break case 'twig' : app . locals . view = { engine : 'twig' } pkg . dependencies . twig = '~0.10.3' break case 'vash' : app . locals . view = { engine : 'vash' } pkg . dependencies . vash = '~0.12.6' break default : app . locals . view = false break } // Static files app . locals . uses . push ( \"express.static(path.join(__dirname, 'public'))\" ) if ( program . git ) { copyTemplate ( 'js/gitignore' , path . join ( dir , '.gitignore' ) ) } // sort dependencies like npm(1) pkg . dependencies = sortedObject ( pkg . dependencies ) // write files write ( path . join ( dir , 'app.js' ) , app . render ( ) ) write ( path . join ( dir , 'package.json' ) , JSON . stringify ( pkg , null , 2 ) + '\\n' ) mkdir ( dir , 'bin' ) write ( path . join ( dir , 'bin/www' ) , www . render ( ) , MODE_0755 ) var prompt = launchedFromCmd ( ) ? '>' : '$' if ( dir !== '.' ) { console . log ( ) console . log ( '   change directory:' ) console . log ( '     %s cd %s' , prompt , dir ) } console . log ( ) console . log ( '   install dependencies:' ) console . log ( '     %s npm install' , prompt ) console . log ( ) console . log ( '   run the app:' ) if ( launchedFromCmd ( ) ) { console . log ( '     %s SET DEBUG=%s:* & npm start' , prompt , name ) } else { console . log ( '     %s DEBUG=%s:* npm start' , prompt , name ) } console . log ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an app name from a directory path fitting npm naming requirements . [CODESPLIT] function createAppName ( pathName ) { return path . basename ( pathName ) . replace ( / [^A-Za-z0-9.-]+ / g , '-' ) . replace ( / ^[-_.]+|-+$ / g , '' ) . toLowerCase ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given directory dir is empty . [CODESPLIT] function emptyDirectory ( dir , fn ) { fs . readdir ( dir , function ( err , files ) { if ( err && err . code !== 'ENOENT' ) throw err fn ( ! files || ! files . length ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Graceful exit for async STDIO [CODESPLIT] function exit ( code ) { // flush output for Node.js Windows pipe bug // https://github.com/joyent/node/issues/6247 is just one bug example // https://github.com/visionmedia/mocha/issues/333 has a good discussion function done ( ) { if ( ! ( draining -- ) ) _exit ( code ) } var draining = 0 var streams = [ process . stdout , process . stderr ] exit . exited = true streams . forEach ( function ( stream ) { // submit empty write request and wait for completion draining += 1 stream . write ( '' , done ) } ) done ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load template file . [CODESPLIT] function loadTemplate ( name ) { var contents = fs . readFileSync ( path . join ( __dirname , '..' , 'templates' , ( name + '.ejs' ) ) , 'utf-8' ) var locals = Object . create ( null ) function render ( ) { return ejs . render ( contents , locals , { escape : util . inspect } ) } return { locals : locals , render : render } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main program . [CODESPLIT] function main ( ) { // Path var destinationPath = program . args . shift ( ) || '.' // App name var appName = createAppName ( path . resolve ( destinationPath ) ) || 'hello-world' // View engine if ( program . view === true ) { if ( program . ejs ) program . view = 'ejs' if ( program . hbs ) program . view = 'hbs' if ( program . hogan ) program . view = 'hjs' if ( program . pug ) program . view = 'pug' } // Default view engine if ( program . view === true ) { warning ( 'the default view engine will not be jade in future releases\\n' + \"use `--view=jade' or `--help' for additional options\" ) program . view = 'jade' } // Generate application emptyDirectory ( destinationPath , function ( empty ) { if ( empty || program . force ) { createApplication ( appName , destinationPath ) } else { confirm ( 'destination is not empty, continue? [y/N] ' , function ( ok ) { if ( ok ) { process . stdin . destroy ( ) createApplication ( appName , destinationPath ) } else { console . error ( 'aborting' ) exit ( 1 ) } } ) } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the given dir relative to base . [CODESPLIT] function mkdir ( base , dir ) { var loc = path . join ( base , dir ) console . log ( '   \\x1b[36mcreate\\x1b[0m : ' + loc + path . sep ) mkdirp . sync ( loc , MODE_0755 ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a callback function for commander to warn about renamed option . [CODESPLIT] function renamedOption ( originalName , newName ) { return function ( val ) { warning ( util . format ( \"option `%s' has been renamed to `%s'\" , originalName , newName ) ) return val } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Display a warning similar to how errors are displayed by commander . [CODESPLIT] function warning ( message ) { console . error ( ) message . split ( '\\n' ) . forEach ( function ( line ) { console . error ( '  warning: %s' , line ) } ) console . error ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "echo str > file . [CODESPLIT] function write ( file , str , mode ) { fs . writeFileSync ( file , str , { mode : mode || MODE_0666 } ) console . log ( '   \\x1b[36mcreate\\x1b[0m : ' + file ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Algo to calculate position 1 . center position for popup content : the center of the trigger will be the center of the content content so the popup content position will be like this : top = > the y of the center for the trigger element : trigger . top + trigger . height / 2 left = > the x of the center for the trigger element : trigger . left + trigger . width / 2 [CODESPLIT] function getCoordinatesForPosition ( triggerBounding , ContentBounding , position , arrow , _ref ) { var offsetX = _ref . offsetX , offsetY = _ref . offsetY ; var margin = arrow ? 8 : 0 ; var args = position . split ( \" \" ) ; // the step N 1 : center the popup content => ok var CenterTop = triggerBounding . top + triggerBounding . height / 2 ; var CenterLeft = triggerBounding . left + triggerBounding . width / 2 ; var height = ContentBounding . height , width = ContentBounding . width ; var top = CenterTop - height / 2 ; var left = CenterLeft - width / 2 ; var transform = \"\" ; var arrowTop = \"0%\" ; var arrowLeft = \"0%\" ; // the  step N 2 : => ok switch ( args [ 0 ] ) { case \"top\" : top -= height / 2 + triggerBounding . height / 2 + margin ; transform = \"rotate(45deg)\" ; arrowTop = \"100%\" ; arrowLeft = \"50%\" ; break ; case \"bottom\" : top += height / 2 + triggerBounding . height / 2 + margin ; transform = \"rotate(225deg)\" ; arrowLeft = \"50%\" ; break ; case \"left\" : left -= width / 2 + triggerBounding . width / 2 + margin ; transform = \" rotate(-45deg)\" ; arrowLeft = \"100%\" ; arrowTop = \"50%\" ; break ; case \"right\" : left += width / 2 + triggerBounding . width / 2 + margin ; transform = \"rotate(135deg)\" ; arrowTop = \"50%\" ; break ; } switch ( args [ 1 ] ) { case \"top\" : top = triggerBounding . top ; arrowTop = triggerBounding . height / 2 + \"px\" ; break ; case \"bottom\" : top = triggerBounding . top - height + triggerBounding . height ; arrowTop = height - triggerBounding . height / 2 + \"px\" ; break ; case \"left\" : left = triggerBounding . left ; arrowLeft = triggerBounding . width / 2 + \"px\" ; break ; case \"right\" : left = triggerBounding . left - width + triggerBounding . width ; arrowLeft = width - triggerBounding . width / 2 + \"px\" ; break ; } top = args [ 0 ] === \"top\" ? top - offsetY : top + offsetY ; left = args [ 0 ] === \"left\" ? left - offsetX : left + offsetX ; return { top : top , left : left , transform : transform , arrowLeft : arrowLeft , arrowTop : arrowTop } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It can deals with these 6 cases : which are threated in the same order shape is 0 dim and it s a string interpret as color shape is 1 dim items are strings seperate color for each item shape is 2 dim items are strings sequence of the above shape is 1 dim items are floats it should be of length 3 - > rgb values shape is 2 dim items are float it should be of shape ( len ( x ) 3 ) - > rgb values shape is 3 dim items are float it should be ( sequence_length len ( x ) 3 ) - > rgb values [CODESPLIT] function string_array_to_rgb ( string_array ) { var rgbs = new Float32Array ( string_array . length * 3 ) ; for ( var i = 0 ; i < string_array . length ; i ++ ) { var color = new THREE . Color ( string_array [ i ] ) ; rgbs [ i * 3 + 0 ] = color . r ; rgbs [ i * 3 + 1 ] = color . g ; rgbs [ i * 3 + 2 ] = color . b ; } return rgbs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "similar to _ . bind except it puts this as first argument to f followed be other arguments and make context f s this [CODESPLIT] function bind_d3 ( f , context ) { return function ( ) { var args = [ this ] . concat ( [ ] . slice . call ( arguments ) ) // convert argument to array f . apply ( context , args ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The default export is an alias of render () . [CODESPLIT] function renderToString ( vnode , context , opts , inner , isSvgMode , selectValue ) { if ( vnode == null || typeof vnode === 'boolean' ) { return '' ; } let nodeName = vnode . type , props = vnode . props , isComponent = false ; context = context || { } ; opts = opts || { } ; let pretty = ENABLE_PRETTY && opts . pretty , indentChar = pretty && typeof pretty === 'string' ? pretty : '\\t' ; // #text nodes if ( typeof vnode !== 'object' && ! nodeName ) { return encodeEntities ( vnode ) ; } // components if ( typeof nodeName === 'function' ) { isComponent = true ; if ( opts . shallow && ( inner || opts . renderRootComponent === false ) ) { nodeName = getComponentName ( nodeName ) ; } else if ( nodeName === Fragment ) { let rendered = '' ; let children = [ ] ; getChildren ( children , vnode . props . children ) ; for ( let i = 0 ; i < children . length ; i ++ ) { rendered += renderToString ( children [ i ] , context , opts , opts . shallowHighOrder !== false , isSvgMode , selectValue ) ; } return rendered ; } else { let rendered ; let c = vnode . __c = { __v : vnode , context , props : vnode . props } ; if ( options . render ) options . render ( vnode ) ; if ( ! nodeName . prototype || typeof nodeName . prototype . render !== 'function' ) { // Necessary for createContext api. Setting this property will pass // the context value as `this.context` just for this component. let cxType = nodeName . contextType ; let provider = cxType && context [ cxType . __c ] ; let cctx = cxType != null ? ( provider ? provider . props . value : cxType . _defaultValue ) : context ; // stateless functional components rendered = nodeName . call ( vnode . __c , props , cctx ) ; } else { // class-based components // c = new nodeName(props, context); c = vnode . __c = new nodeName ( props , context ) ; c . __v = vnode ; // turn off stateful re-rendering: c . _dirty = c . __d = true ; c . props = props ; c . context = context ; if ( nodeName . getDerivedStateFromProps ) c . state = assign ( assign ( { } , c . state ) , nodeName . getDerivedStateFromProps ( c . props , c . state ) ) ; else if ( c . componentWillMount ) c . componentWillMount ( ) ; rendered = c . render ( c . props , c . state , c . context ) ; } if ( c . getChildContext ) { context = assign ( assign ( { } , context ) , c . getChildContext ( ) ) ; } return renderToString ( rendered , context , opts , opts . shallowHighOrder !== false , isSvgMode , selectValue ) ; } } // render JSX to HTML let s = '' , html ; if ( props ) { let attrs = Object . keys ( props ) ; // allow sorting lexicographically for more determinism (useful for tests, such as via preact-jsx-chai) if ( opts && opts . sortAttributes === true ) attrs . sort ( ) ; for ( let i = 0 ; i < attrs . length ; i ++ ) { let name = attrs [ i ] , v = props [ name ] ; if ( name === 'children' ) continue ; if ( name . match ( / [\\s\\n\\\\/='\"\\0<>] / ) ) continue ; if ( ! ( opts && opts . allAttributes ) && ( name === 'key' || name === 'ref' ) ) continue ; if ( name === 'className' ) { if ( props . class ) continue ; name = 'class' ; } else if ( isSvgMode && name . match ( / ^xlink:?. / ) ) { name = name . toLowerCase ( ) . replace ( / ^xlink:? / , 'xlink:' ) ; } if ( name === 'style' && v && typeof v === 'object' ) { v = styleObjToCss ( v ) ; } let hooked = opts . attributeHook && opts . attributeHook ( name , v , context , opts , isComponent ) ; if ( hooked || hooked === '' ) { s += hooked ; continue ; } if ( name === 'dangerouslySetInnerHTML' ) { html = v && v . __html ; } else if ( ( v || v === 0 || v === '' ) && typeof v !== 'function' ) { if ( v === true || v === '' ) { v = name ; // in non-xml mode, allow boolean attributes if ( ! opts || ! opts . xml ) { s += ' ' + name ; continue ; } } if ( name === 'value' ) { if ( nodeName === 'select' ) { selectValue = v ; continue ; } else if ( nodeName === 'option' && selectValue == v ) { s += ` ` ; } } s += ` ${ name } ${ encodeEntities ( v ) } ` ; } } } // account for >1 multiline attribute if ( pretty ) { let sub = s . replace ( / ^\\n\\s* / , ' ' ) ; if ( sub !== s && ! ~ sub . indexOf ( '\\n' ) ) s = sub ; else if ( pretty && ~ s . indexOf ( '\\n' ) ) s += '\\n' ; } s = ` ${ nodeName } ${ s } ` ; if ( String ( nodeName ) . match ( / [\\s\\n\\\\/='\"\\0<>] / ) ) throw s ; let isVoid = String ( nodeName ) . match ( VOID_ELEMENTS ) ; if ( isVoid ) s = s . replace ( / >$ / , ' />' ) ; let pieces = [ ] ; let children ; if ( html ) { // if multiline, indent. if ( pretty && isLargeString ( html ) ) { html = '\\n' + indentChar + indent ( html , indentChar ) ; } s += html ; } else if ( props && getChildren ( children = [ ] , props . children ) . length ) { let hasLarge = pretty && ~ s . indexOf ( '\\n' ) ; for ( let i = 0 ; i < children . length ; i ++ ) { let child = children [ i ] ; if ( child != null && child !== false ) { let childSvgMode = nodeName === 'svg' ? true : nodeName === 'foreignObject' ? false : isSvgMode , ret = renderToString ( child , context , opts , true , childSvgMode , selectValue ) ; if ( pretty && ! hasLarge && isLargeString ( ret ) ) hasLarge = true ; if ( ret ) pieces . push ( ret ) ; } } if ( pretty && hasLarge ) { for ( let i = pieces . length ; i -- ; ) { pieces [ i ] = '\\n' + indentChar + indent ( pieces [ i ] , indentChar ) ; } } } if ( pieces . length ) { s += pieces . join ( '' ) ; } else if ( opts && opts . xml ) { return s . substring ( 0 , s . length - 1 ) + ' />' ; } if ( ! isVoid ) { if ( pretty && ~ s . indexOf ( '\\n' ) ) s += '\\n' ; s += ` ${ nodeName } ` ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts development server [CODESPLIT] async function start ( opts : * ) { const isTaken = await isPortTaken ( opts . port ) ; if ( isTaken ) { if ( ! opts . no_interactive ) { const { userChoice } = await inquirer . prompt ( { type : 'list' , name : 'userChoice' , message : ` ${ opts . port } ` , choices : [ ` ${ opts . port } ` , 'Quit' , ] , } ) ; if ( userChoice === 'Quit' ) { process . exit ( ) ; } try { await killProcess ( opts . port ) ; } catch ( e ) { logger . error ( ` \\n ${ e . message } ` ) ; process . exit ( 1 ) ; } logger . info ( ` ` ) ; } else { logger . error ( ` ${ opts . port } ` ) ; process . exit ( 1 ) ; } } const directory = process . cwd ( ) ; const configPath = getWebpackConfigPath ( directory , opts . config ) ; let assetsDest ; if ( opts . assetsDest ) { assetsDest = path . isAbsolute ( opts . assetsDest ) ? opts . assetsDest : path . join ( directory , opts . assetsDest ) ; } else { assetsDest = fs . mkdtempSync ( path . join ( os . tmpdir ( ) , 'haul-start-' ) ) ; } const configOptions = { root : directory , assetsDest , dev : opts . dev , minify : opts . minify , port : opts . port , eager : opts . eager , disableHotReloading : ! opts . hotReloading , } ; createServer ( { configPath , configOptions , } ) . listen ( opts . port ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Check if the port is already in use [CODESPLIT] function isPortTaken ( port : number ) : Promise < boolean > { return new Promise ( resolve => { const portTester = net . createServer ( ) . once ( 'error' , ( ) => { return resolve ( true ) ; } ) . once ( 'listening' , ( ) => { portTester . close ( ) ; resolve ( false ) ; } ) . listen ( port ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bundles your application code [CODESPLIT] async function bundle ( opts : * ) { const directory = process . cwd ( ) ; const configPath = getWebpackConfigPath ( directory , opts . config ) ; const config = getConfig ( configPath , { root : directory , dev : opts . dev , minify : opts . minify , bundle : true , } , opts . platform , logger ) ; if ( opts . assetsDest ) { config . output . path = path . isAbsolute ( opts . assetsDest ) ? opts . assetsDest : path . join ( directory , opts . assetsDest ) ; } if ( opts . bundleOutput ) { config . output . filename = path . isAbsolute ( opts . bundleOutput ) ? path . relative ( config . output . path , opts . bundleOutput ) : path . relative ( config . output . path , path . join ( directory , opts . bundleOutput ) ) ; } logger . info ( ` ${ config . output . path } ` ) ; logger . info ( ` ${ config . output . filename } ` ) ; logger . info ( ` ${ path . resolve ( config . output . filename ) } ` ) ; // attach progress plugin if ( opts . progress !== 'none' ) { config . plugins = config . plugins . concat ( [ new SimpleProgressWebpackPlugin ( { format : opts . progress , } ) , ] ) ; } const compiler = webpack ( config ) ; logger . info ( messages . initialBundleInformation ( { entry : config . entry , dev : opts . dev , } ) ) ; const stats = await new Promise ( ( resolve , reject ) => compiler . run ( ( err , info ) => { if ( err || info . hasErrors ( ) ) { reject ( new MessageError ( messages . bundleFailed ( { errors : err ? [ err . message ] : info . toJson ( { errorDetails : true } ) . errors , } ) ) ) ; } else if ( info . hasWarnings ( ) ) { logger . warn ( info . toJson ( ) . warnings ) ; resolve ( info ) ; } else { resolve ( info ) ; } } ) ) ; clear ( ) ; logger . done ( messages . bundleBuilt ( { stats , platform : opts . platform , assetsPath : config . output . path , bundlePath : config . output . filename , } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow config file to override the list of availiable platforms [CODESPLIT] function adjustOptions ( options ) { const directory = process . cwd ( ) ; const configPath = getWebpackConfigPath ( directory , options . config ) ; const haulOptions = getHaulConfig ( configPath , logger ) ; if ( haulOptions . platforms ) { const platformOption = command . options && command . options . find ( _ => _ . name === 'platform' ) ; if ( platformOption ) { platformOption . choices = [ ] ; for ( const platformName in haulOptions . platforms ) { if ( Object . prototype . hasOwnProperty . call ( haulOptions . platforms , platformName ) ) { if ( platformOption . choices ) { platformOption . choices . push ( { value : platformName , description : ` ${ haulOptions . platforms [ platformName ] } ` , } ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eslint - disable - line camelcase [CODESPLIT] function exec ( args : string ) : Promise < void > { return new Promise ( ( resolve , reject ) => { child_process . exec ( args , ( err , stdout , stderr ) => { if ( err ) { reject ( new Error ( stderr ) ) ; } else { resolve ( ) ; } } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Create label based on passed platform We use labelOptions to customize know platforms If platform is not know returns default styles [CODESPLIT] function createLabel ( platform : string ) { if ( labelOptions [ platform ] ) { const { color , label } = labelOptions [ platform ] ; return ` ${ chalk . bold [ color ] ( label ) } ` . padEnd ( 30 ) ; } return ` ${ chalk . bold . magenta ( platform ) } ` . padEnd ( 30 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Create progress bar itself [CODESPLIT] function createBarFormat ( platform : string ) { const label = createLabel ( platform ) ; const leftBar = chalk . bold ( '[' ) ; const rightBar = chalk . bold ( ']' ) ; const percent = chalk . bold . blue ( ':percent' ) ; return ` ${ label } ${ leftBar } ${ rightBar } ${ percent } ` ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copyright 2017 - present Callstack . All rights reserved . [CODESPLIT] function cleanPathMiddleware ( req , res , next ) { req . cleanPath = req . path . replace ( / \\/$ / , '' ) ; next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Packager - like Server running on top of Webpack [CODESPLIT] function createServer ( config : { configPath : ? string , configOptions : Object } ) { const appHandler = express ( ) ; appHandler . disable ( 'etag' ) ; const { configPath , configOptions } = config ; const compiler = new Compiler ( { configPath , configOptions , } ) ; const loggerMiddleware = initUI ( compiler , configOptions ) ; process . on ( 'uncaughtException' , err => { compiler . terminate ( ) ; throw err ; } ) ; process . on ( 'SIGINT' , ( ) => { compiler . terminate ( ) ; process . exit ( 0 ) ; } ) ; process . on ( 'SIGTERM' , ( ) => { compiler . terminate ( ) ; process . exit ( 2 ) ; } ) ; const compilerMiddleware = createCompilerMiddleware ( compiler , { configPath , configOptions , } ) ; const httpServer = http . createServer ( appHandler ) ; const webSocketServer = new WebSocketServer ( { server : httpServer } ) ; const debuggerProxy = new WebSocketDebuggerProxy ( webSocketProxy ( webSocketServer , '/debugger-proxy' ) ) ; if ( ! configOptions . disableHotReloading ) { hotMiddleware ( compiler , { nativeProxy : webSocketProxy ( webSocketServer , '/hot' ) , haulProxy : webSocketProxy ( webSocketServer , '/haul-hmr' ) , } ) ; } // Middlewares appHandler . use ( express . static ( path . join ( __dirname , '/assets/public' ) ) ) . use ( rawBodyMiddleware ) . use ( cleanPathMiddleware ) . use ( devToolsMiddleware ( debuggerProxy ) ) . use ( liveReloadMiddleware ( compiler ) ) . use ( statusPageMiddleware ) . use ( symbolicateMiddleware ( compiler , { configPath , configOptions , } ) ) . use ( openInEditorMiddleware ( ) ) . use ( '/systrace' , systraceMiddleware ) . use ( loggerMiddleware ) . use ( compilerMiddleware ) . use ( missingBundleMiddleware ) ; if ( configOptions . eager ) { if ( ! Array . isArray ( configOptions . eager ) && typeof configOptions . eager === 'boolean' ) { // implicitly true... // TODO: Eager loading for all platforms configOptions . eager = [ 'android' , 'ios' /* , ... potentially more? */ ] ; } configOptions . eager . forEach ( platform => { compiler . emit ( Compiler . Events . REQUEST_BUNDLE , { filename : ` ${ platform } ` , // XXX: maybe the entry bundle is arbitary platform , callback ( ) { } , } ) ; } ) ; } return httpServer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Devtools middleware compatible with default React Native implementation [CODESPLIT] function devToolsMiddleware ( debuggerProxy ) { return ( req , res , next ) => { switch ( req . cleanPath ) { /**\n       * Request for the debugger frontend\n       */ case '/debugger-ui/' : case '/debugger-ui' : { const readStream = fs . createReadStream ( path . join ( __dirname , '../assets/debugger.html' ) ) ; res . writeHead ( 200 , { 'Content-Type' : 'text/html' } ) ; readStream . pipe ( res ) ; break ; } /**\n       * Request for the debugger worker\n       */ case '/debugger-ui/debuggerWorker.js' : case '/debuggerWorker.js' : { const readStream = fs . createReadStream ( path . join ( __dirname , '../assets/debuggerWorker.js' ) ) ; res . writeHead ( 200 , { 'Content-Type' : 'application/javascript' } ) ; readStream . pipe ( res ) ; break ; } /**\n       * Request for (maybe) launching devtools\n       */ case '/launch-js-devtools' : { if ( ! debuggerProxy . isDebuggerConnected ( ) ) { launchBrowser ( ` ${ req . socket . localPort } ` ) ; } res . end ( 'OK' ) ; break ; } default : next ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eslint - disable - line import / no - unresolved [CODESPLIT] function normalizeOptions ( { path , quiet , overlay , reload , name } ) { const shouldLog = ! quiet ; const options = { path , overlay : true , reload : false , name : '' , logger : { shouldLog , log ( ... args ) { if ( shouldLog ) { console . log ( ... args ) ; } } , warn ( ... args ) { if ( shouldLog ) { console . warn ( ... args ) ; } } , error ( ... args ) { if ( shouldLog ) { console . error ( ... args ) ; } } , } , } ; if ( overlay ) { options . overlay = overlay !== 'false' ; } if ( reload ) { options . reload = reload !== 'false' ; } if ( name ) { options . name = name ; } return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a SourceMapConsumer so we can query it . [CODESPLIT] async function createSourceMapConsumer ( compiler : Compiler , url : string ) { const response = await fetch ( url ) ; const sourceMap = await response . text ( ) ; // we stop here if we couldn't find that map if ( ! sourceMap ) { logger . warn ( messages . sourceMapFileNotFound ( ) ) ; return null ; } // feed the raw source map into our consumer try { return new SourceMapConsumer ( sourceMap ) ; } catch ( err ) { logger . error ( messages . sourceMapInvalidFormat ( ) ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copyright 2017 - present Callstack . All rights reserved . [CODESPLIT] function fixRequireIssue ( ) { return { visitor : { AssignmentExpression ( path ) { if ( path . node . operator === '=' ) { const { left } = path . node ; if ( left . type !== 'MemberExpression' ) { return ; } const { object } = left ; if ( // require.xxx ( object . type === 'Identifier' && object . name === 'require' ) || // (require: any).xxx ( object . type === 'TypeCastExpression' && object . expression . name === 'require' ) ) { path . remove ( ) ; } } } , } , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * eslint - disable no - bitwise no - extend - native radix no - self - compare https : // developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / Array / findIndex [CODESPLIT] function findIndex ( predicate , context ) { if ( this == null ) { throw new TypeError ( 'Array.prototype.findIndex called on null or undefined' ) ; } if ( typeof predicate !== 'function' ) { throw new TypeError ( 'predicate must be a function' ) ; } const list = Object ( this ) ; const length = list . length >>> 0 ; for ( let i = 0 ; i < length ; i ++ ) { if ( predicate . call ( context , list [ i ] , i , list ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles demo load events . [CODESPLIT] function onLoad ( event ) { // Prepare the render pass. event . demo . renderPass . camera = event . demo . camera ; document . getElementById ( \"viewport\" ) . children [ 0 ] . style . display = \"none\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prefixes substrings within the given strings . [CODESPLIT] function prefixSubstrings ( prefix , substrings , strings ) { let prefixed , regExp ; for ( const substring of substrings ) { prefixed = \"$1\" + prefix + substring . charAt ( 0 ) . toUpperCase ( ) + substring . slice ( 1 ) ; regExp = new RegExp ( \"([^\\\\.])(\\\\b\" + substring + \"\\\\b)\" , \"g\" ) ; for ( const entry of strings . entries ( ) ) { if ( entry [ 1 ] !== null ) { strings . set ( entry [ 0 ] , entry [ 1 ] . replace ( regExp , prefixed ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Integrates the given effect . [CODESPLIT] function integrateEffect ( prefix , effect , shaderParts , blendModes , defines , uniforms , attributes ) { const functionRegExp = / (?:\\w+\\s+(\\w+)\\([\\w\\s,]*\\)\\s*{[^}]+}) / g ; const varyingRegExp = / (?:varying\\s+\\w+\\s+(\\w*)) / g ; const blendMode = effect . blendMode ; const shaders = new Map ( [ [ \"fragment\" , effect . fragmentShader ] , [ \"vertex\" , effect . vertexShader ] ] ) ; const mainImageExists = ( shaders . get ( \"fragment\" ) !== undefined && shaders . get ( \"fragment\" ) . indexOf ( \"mainImage\" ) >= 0 ) ; const mainUvExists = ( shaders . get ( \"fragment\" ) !== undefined && shaders . get ( \"fragment\" ) . indexOf ( \"mainUv\" ) >= 0 ) ; let varyings = [ ] , names = [ ] ; let transformedUv = false ; let readDepth = false ; if ( shaders . get ( \"fragment\" ) === undefined ) { console . error ( \"Missing fragment shader\" , effect ) ; } else if ( mainUvExists && ( attributes & EffectAttribute . CONVOLUTION ) !== 0 ) { console . error ( \"Effects that transform UV coordinates are incompatible with convolution effects\" , effect ) ; } else if ( ! mainImageExists && ! mainUvExists ) { console . error ( \"The fragment shader contains neither a mainImage nor a mainUv function\" , effect ) ; } else { if ( mainUvExists ) { shaderParts . set ( Section . FRAGMENT_MAIN_UV , shaderParts . get ( Section . FRAGMENT_MAIN_UV ) + \"\\t\" + prefix + \"MainUv(UV);\\n\" ) ; transformedUv = true ; } if ( shaders . get ( \"vertex\" ) !== null && shaders . get ( \"vertex\" ) . indexOf ( \"mainSupport\" ) >= 0 ) { shaderParts . set ( Section . VERTEX_MAIN_SUPPORT , shaderParts . get ( Section . VERTEX_MAIN_SUPPORT ) + \"\\t\" + prefix + \"MainSupport();\\n\" ) ; varyings = varyings . concat ( findSubstrings ( varyingRegExp , shaders . get ( \"vertex\" ) ) ) ; names = names . concat ( varyings ) . concat ( findSubstrings ( functionRegExp , shaders . get ( \"vertex\" ) ) ) ; } names = names . concat ( findSubstrings ( functionRegExp , shaders . get ( \"fragment\" ) ) ) . concat ( Array . from ( effect . uniforms . keys ( ) ) ) . concat ( Array . from ( effect . defines . keys ( ) ) ) ; // Store prefixed uniforms and macros. effect . uniforms . forEach ( ( value , key ) => uniforms . set ( prefix + key . charAt ( 0 ) . toUpperCase ( ) + key . slice ( 1 ) , value ) ) ; effect . defines . forEach ( ( value , key ) => defines . set ( prefix + key . charAt ( 0 ) . toUpperCase ( ) + key . slice ( 1 ) , value ) ) ; // Prefix varyings, functions, uniforms and macros. prefixSubstrings ( prefix , names , defines ) ; prefixSubstrings ( prefix , names , shaders ) ; // Collect unique blend modes. blendModes . set ( blendMode . blendFunction , blendMode ) ; if ( mainImageExists ) { let string = prefix + \"MainImage(color0, UV, \" ; // The effect may sample depth in a different shader. if ( ( attributes & EffectAttribute . DEPTH ) !== 0 && shaders . get ( \"fragment\" ) . indexOf ( \"depth\" ) >= 0 ) { string += \"depth, \" ; readDepth = true ; } string += \"color1);\\n\\t\" ; // Include the blend opacity uniform of this effect. const blendOpacity = prefix + \"BlendOpacity\" ; uniforms . set ( blendOpacity , blendMode . opacity ) ; // Blend the result of this effect with the input color. string += \"color0 = blend\" + blendMode . blendFunction + \"(color0, color1, \" + blendOpacity + \");\\n\\n\\t\" ; shaderParts . set ( Section . FRAGMENT_MAIN_IMAGE , shaderParts . get ( Section . FRAGMENT_MAIN_IMAGE ) + string ) ; shaderParts . set ( Section . FRAGMENT_HEAD , shaderParts . get ( Section . FRAGMENT_HEAD ) + \"uniform float \" + blendOpacity + \";\\n\\n\" ) ; } // Include the modified code in the final shader. shaderParts . set ( Section . FRAGMENT_HEAD , shaderParts . get ( Section . FRAGMENT_HEAD ) + shaders . get ( \"fragment\" ) + \"\\n\" ) ; if ( shaders . get ( \"vertex\" ) !== null ) { shaderParts . set ( Section . VERTEX_HEAD , shaderParts . get ( Section . VERTEX_HEAD ) + shaders . get ( \"vertex\" ) + \"\\n\" ) ; } } return { varyings , transformedUv , readDepth } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new canvas from raw image data . [CODESPLIT] function createCanvas ( width , height , data , channels ) { const canvas = document . createElementNS ( \"http://www.w3.org/1999/xhtml\" , \"canvas\" ) ; const context = canvas . getContext ( \"2d\" ) ; const imageData = context . createImageData ( width , height ) ; const target = imageData . data ; let x , y ; let i , j ; for ( y = 0 ; y < height ; ++ y ) { for ( x = 0 ; x < width ; ++ x ) { i = ( y * width + x ) * 4 ; j = ( y * width + x ) * channels ; target [ i ] = ( channels > 0 ) ? data [ j ] : 0 ; target [ i + 1 ] = ( channels > 1 ) ? data [ j + 1 ] : 0 ; target [ i + 2 ] = ( channels > 2 ) ? data [ j + 2 ] : 0 ; target [ i + 3 ] = ( channels > 3 ) ? data [ j + 3 ] : 255 ; } } canvas . width = width ; canvas . height = height ; context . putImageData ( imageData , 0 , 0 ) ; return canvas ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A smoothing function for small U - patterns . [CODESPLIT] function smoothArea ( d , b ) { const a1 = b . min ; const a2 = b . max ; const b1X = Math . sqrt ( a1 . x * 2.0 ) * 0.5 ; const b1Y = Math . sqrt ( a1 . y * 2.0 ) * 0.5 ; const b2X = Math . sqrt ( a2 . x * 2.0 ) * 0.5 ; const b2Y = Math . sqrt ( a2 . y * 2.0 ) * 0.5 ; const p = saturate ( d / SMOOTH_MAX_DISTANCE ) ; a1 . set ( lerp ( b1X , a1 . x , p ) , lerp ( b1Y , a1 . y , p ) ) ; a2 . set ( lerp ( b2X , a2 . x , p ) , lerp ( b2Y , a2 . y , p ) ) ; return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the area under the line p1 - > p2 for the pixel p using brute force sampling . [CODESPLIT] function calculateDiagonalAreaForPixel ( p1 , p2 , pX , pY ) { let a ; let x , y ; let offsetX , offsetY ; for ( a = 0 , y = 0 ; y < DIAGONAL_SAMPLES ; ++ y ) { for ( x = 0 ; x < DIAGONAL_SAMPLES ; ++ x ) { offsetX = x / ( DIAGONAL_SAMPLES - 1.0 ) ; offsetY = y / ( DIAGONAL_SAMPLES - 1.0 ) ; if ( isInsideArea ( p1 , p2 , pX + offsetX , pY + offsetY ) ) { ++ a ; } } } return a / ( DIAGONAL_SAMPLES * DIAGONAL_SAMPLES ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the area under the line p1 - > p2 . This includes the pixel and its opposite . [CODESPLIT] function calculateDiagonalArea ( pattern , p1 , p2 , left , offset , result ) { const e = diagonalEdges [ pattern ] ; const e1 = e [ 0 ] ; const e2 = e [ 1 ] ; if ( e1 > 0 ) { p1 . x += offset [ 0 ] ; p1 . y += offset [ 1 ] ; } if ( e2 > 0 ) { p2 . x += offset [ 0 ] ; p2 . y += offset [ 1 ] ; } return result . set ( 1.0 - calculateDiagonalAreaForPixel ( p1 , p2 , 1.0 + left , 0.0 + left ) , calculateDiagonalAreaForPixel ( p1 , p2 , 1.0 + left , 1.0 + left ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the area for a given pattern and distances to the left and to the right biased by an offset . [CODESPLIT] function calculateDiagonalAreaForPattern ( pattern , left , right , offset , result ) { const p1 = b0 . min ; const p2 = b0 . max ; const a1 = b1 . min ; const a2 = b1 . max ; const d = left + right + 1 ; /* There is some Black Magic involved in the diagonal area calculations.\n\t *\n\t * Unlike orthogonal patterns, the \"null\" pattern (one without crossing edges)\n\t * must be filtered, and the ends of both the \"null\" and L patterns are not\n\t * known: L and U patterns have different endings, and the adjacent pattern is\n\t * unknown. Therefore, a blend of both possibilites is computed.\n\t */ switch ( pattern ) { case 0 : { /*         .-´\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t *   .-´\n\t\t\t *   ´\n\t\t\t */ // First possibility. calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , a1 ) ; // Second possibility. calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , a2 ) ; // Blend both possibilities together. result . addVectors ( a1 , a2 ) . divideScalar ( 2.0 ) ; break ; } case 1 : { /*         .-´\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t *   .-´\n\t\t\t *   |\n\t\t\t *   |\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 0.0 + d , 0.0 + d ) , left , offset , a1 ) ; calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , a2 ) ; result . addVectors ( a1 , a2 ) . divideScalar ( 2.0 ) ; break ; } case 2 : { /*         .----\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t *   .-´\n\t\t\t *   ´\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 0.0 , 0.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , a1 ) ; calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , a2 ) ; result . addVectors ( a1 , a2 ) . divideScalar ( 2.0 ) ; break ; } case 3 : { /*\n\t\t\t *         .----\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t *   .-´\n\t\t\t *   |\n\t\t\t *   |\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , result ) ; break ; } case 4 : { /*         .-´\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t * ----´\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 0.0 + d , 0.0 + d ) , left , offset , a1 ) ; calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , a2 ) ; result . addVectors ( a1 , a2 ) . divideScalar ( 2.0 ) ; break ; } case 5 : { /*         .-´\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t * --.-´\n\t\t\t *   |\n\t\t\t *   |\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 0.0 + d , 0.0 + d ) , left , offset , a1 ) ; calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , a2 ) ; result . addVectors ( a1 , a2 ) . divideScalar ( 2.0 ) ; break ; } case 6 : { /*         .----\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t * ----´\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , result ) ; break ; } case 7 : { /*         .----\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t * --.-´\n\t\t\t *   |\n\t\t\t *   |\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , a1 ) ; calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , a2 ) ; result . addVectors ( a1 , a2 ) . divideScalar ( 2.0 ) ; break ; } case 8 : { /*         |\n\t\t\t *         |\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t *   .-´\n\t\t\t *   ´\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 0.0 , 0.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , a1 ) ; calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , a2 ) ; result . addVectors ( a1 , a2 ) . divideScalar ( 2.0 ) ; break ; } case 9 : { /*         |\n\t\t\t *         |\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t *   .-´\n\t\t\t *   |\n\t\t\t *   |\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , result ) ; break ; } case 10 : { /*         |\n\t\t\t *         .----\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t *   .-´\n\t\t\t *   ´\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 0.0 , 0.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , a1 ) ; calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , a2 ) ; result . addVectors ( a1 , a2 ) . divideScalar ( 2.0 ) ; break ; } case 11 : { /*         |\n\t\t\t *         .----\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t *   .-´\n\t\t\t *   |\n\t\t\t *   |\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , a1 ) ; calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , a2 ) ; result . addVectors ( a1 , a2 ) . divideScalar ( 2.0 ) ; break ; } case 12 : { /*         |\n\t\t\t *         |\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t * ----´\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , result ) ; break ; } case 13 : { /*         |\n\t\t\t *         |\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t * --.-´\n\t\t\t *   |\n\t\t\t *   |\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , a1 ) ; calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , a2 ) ; result . addVectors ( a1 , a2 ) . divideScalar ( 2.0 ) ; break ; } case 14 : { /*         |\n\t\t\t *         .----\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t * ----´\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , a1 ) ; calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , a2 ) ; result . addVectors ( a1 , a2 ) . divideScalar ( 2.0 ) ; break ; } case 15 : { /*         |\n\t\t\t *         .----\n\t\t\t *       .-´\n\t\t\t *     .-´\n\t\t\t * --.-´\n\t\t\t *   |\n\t\t\t *   |\n\t\t\t */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , a1 ) ; calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , a2 ) ; result . addVectors ( a1 , a2 ) . divideScalar ( 2.0 ) ; break ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates orthogonal or diagonal patterns for a given offset . [CODESPLIT] function generatePatterns ( patterns , offset , orthogonal ) { const result = new Vector2 ( ) ; let i , l ; let x , y ; let c ; let pattern ; let data , size ; for ( i = 0 , l = patterns . length ; i < l ; ++ i ) { pattern = patterns [ i ] ; data = pattern . data ; size = pattern . width ; for ( y = 0 ; y < size ; ++ y ) { for ( x = 0 ; x < size ; ++ x ) { if ( orthogonal ) { calculateOrthogonalAreaForPattern ( i , x , y , offset , result ) ; } else { calculateDiagonalAreaForPattern ( i , x , y , offset , result ) ; } c = ( y * size + x ) * 2 ; data [ c ] = result . x * 255 ; data [ c + 1 ] = result . y * 255 ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assembles orthogonal or diagonal patterns into the final area image . [CODESPLIT] function assemble ( base , patterns , edges , size , orthogonal , target ) { const p = new Vector2 ( ) ; const dstData = target . data ; const dstWidth = target . width ; let i , l ; let x , y ; let c , d ; let edge ; let pattern ; let srcData , srcWidth ; for ( i = 0 , l = patterns . length ; i < l ; ++ i ) { edge = edges [ i ] ; pattern = patterns [ i ] ; srcData = pattern . data ; srcWidth = pattern . width ; for ( y = 0 ; y < size ; ++ y ) { for ( x = 0 ; x < size ; ++ x ) { p . fromArray ( edge ) . multiplyScalar ( size ) ; p . add ( base ) ; p . x += x ; p . y += y ; c = ( p . y * dstWidth + p . x ) * 2 ; /* The texture coordinates of orthogonal patterns are compressed\n\t\t\t\tquadratically to reach longer distances for a given texture size. */ d = orthogonal ? ( ( y * y * srcWidth + x * x ) * 2 ) : ( ( y * srcWidth + x ) * 2 ) ; dstData [ c ] = srcData [ d ] ; dstData [ c + 1 ] = srcData [ d + 1 ] ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the delta distance to add in the last step of searches to the right . [CODESPLIT] function deltaRight ( left , top ) { let d = 0 ; // If there is an edge, and no crossing edges, continue. if ( top [ 3 ] === 1 && left [ 1 ] !== 1 && left [ 3 ] !== 1 ) { d += 1 ; } /* If an edge was previously found, there is another edge and there are no\n\tcrossing edges, continue. */ if ( d === 1 && top [ 2 ] === 1 && left [ 0 ] !== 1 && left [ 2 ] !== 1 ) { d += 1 ; } return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the bilinear fetch for a certain edge combination . [CODESPLIT] function bilinear ( e ) { const a = lerp ( e [ 0 ] , e [ 1 ] , 1.0 - 0.25 ) ; const b = lerp ( e [ 2 ] , e [ 3 ] , 1.0 - 0.25 ) ; return lerp ( a , b , 1.0 - 0.125 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private functions [CODESPLIT] function getKeys ( ) { keys = { pageup : 33 , pagedown : 34 , end : 35 , home : 36 , left : 37 , up : 38 , right : 39 , down : 40 , } return keys }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TIME VALIDATION FOR DATA ENTRY [CODESPLIT] function checkForm ( that ) { var newValue = $ ( that ) . val ( ) var matches = newValue != '' ? newValue . match ( timeRegEx ) : '' var error = $ ( that ) . closest ( '.time-spinner' ) . find ( '.error_container' ) var $closerTimeSpinner = $ ( that ) . closest ( '.time-spinner' ) . find ( '.spinner-control' ) if ( matches ) { $ ( error ) . html ( '' ) //$closerTimeSpinner.find('.spinner-hour input').val(timeRegEx.split(':')[0]); //$closerTimeSpinner.find('.spinner-min input').val(timeRegEx.split(':')[1]); return true } else { var errMsg = 'Formato data non valido' $ ( error ) . html ( errMsg ) //$(that).val('Formato data non valido') return false } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helper functions : [CODESPLIT] function mc_symbol_clone ( ) { var clone = this . _cloneProps ( new this . constructor ( this . mode , this . startPosition , this . loop ) ) ; clone . gotoAndStop ( this . currentFrame ) ; clone . paused = this . paused ; clone . framerate = this . framerate ; return clone ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ripristino stato iniziale [CODESPLIT] function resetToMove ( contextControl ) { var left = contextControl . find ( '.source .transfer-group' ) var right = contextControl . find ( '.target .transfer-group' ) var textLeft = contextControl . find ( '.source .transfer-header span.num' ) var textRight = contextControl . find ( '.target .transfer-header span.num' ) var header = contextControl . find ( '.transfer-header input' ) $ ( left ) . html ( elemLeft ) $ ( right ) . html ( elemRight ) $ ( textLeft ) . text ( elemLeftNum ) $ ( textRight ) . text ( elemRightNum ) $ ( header ) . prop ( 'disabled' , false ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "control active check & header check [CODESPLIT] function checkIfActive ( targetControl , targetHeaderControl , containerTypeControl , addButtonControl ) { $ ( targetControl ) . each ( function ( el ) { if ( $ ( this ) . prop ( 'checked' ) ) { if ( ! $ ( targetHeaderControl ) . hasClass ( 'semi-checked' ) ) { $ ( targetHeaderControl ) . addClass ( 'semi-checked' ) $ ( targetHeaderControl ) . prop ( 'checked' , false ) if ( containerTypeControl . hasClass ( 'source' ) ) { $ ( addButtonControl ) . addClass ( 'active' ) } if ( containerTypeControl . hasClass ( 'target' ) ) { $ ( inverseButton ) . addClass ( 'active' ) } } return false } else { $ ( targetHeaderControl ) . removeClass ( 'semi-checked' ) if ( containerTypeControl . hasClass ( 'source' ) ) { $ ( addButtonControl ) . removeClass ( 'active' ) } if ( containerTypeControl . hasClass ( 'target' ) ) { $ ( inverseButton ) . removeClass ( 'active' ) } } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "controllo elementi source [CODESPLIT] function sourceControl ( contextControl ) { var tocheck = contextControl . find ( '.transfer-scroll' ) . find ( 'input' ) var checknum = tocheck . length var targetText = contextControl . find ( '.transfer-header' ) . find ( 'label span.num' ) var header = contextControl . find ( '.transfer-header input' ) $ ( header ) . prop ( 'checked' , false ) . removeClass ( 'semi-checked' ) if ( checknum < 1 ) { $ ( header ) . prop ( 'disabled' , true ) } else { $ ( header ) . prop ( 'disabled' , false ) } $ ( targetText ) . text ( checknum ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "controllo elementi target [CODESPLIT] function targetControl ( targetControl ) { var tocheck = targetControl . find ( 'input' ) var checknum = tocheck . length var targetText = tocheck . closest ( '.it-transfer-wrapper' ) . find ( '.transfer-header' ) . find ( 'label span.num' ) var header = $ ( targetControl ) . find ( '.transfer-header input' ) if ( checknum < 1 ) { $ ( header ) . prop ( 'disabled' , true ) } else { $ ( header ) . prop ( 'disabled' , false ) } $ ( targetText ) . text ( checknum ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "elementi da aggiungere [CODESPLIT] function checkToMove ( contextControl , targetControl ) { var elements = contextControl . find ( '.transfer-group' ) . find ( 'input:checked' ) var sourceTag = $ ( elements ) . closest ( '.form-check' ) $ ( elements ) . each ( function ( ) { $ ( this ) . prop ( 'checked' , false ) $ ( sourceTag ) . detach ( ) . appendTo ( targetControl ) . addClass ( 'added' ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "resize function [CODESPLIT] function inputNumberResize ( $target ) { var $inputNumber = $target . closest ( '.input-number' ) if ( $inputNumber . hasClass ( 'input-number-adaptive' ) ) { // width = padding (12px + 32px) + number of characters if ( ! $inputNumber . hasClass ( 'input-number-percentage' ) ) { $target . css ( 'width' , 'calc(44px + ' + $target . val ( ) . length + 'ch)' ) if ( isIe ( ) ) $target . css ( 'width' , 'calc(44px + (1.5 * ' + $target . val ( ) . length + 'ch))' ) } if ( $inputNumber . hasClass ( 'input-number-currency' ) ) { $target . css ( 'width' , 'calc(40px + 44px + ' + $target . val ( ) . length + 'ch)' ) if ( isIe ( ) ) $target . css ( 'width' , 'calc(40px + 44px + (1.5 * ' + $target . val ( ) . length + 'ch))' ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Debounced scroll handling [CODESPLIT] function updateScrollPos ( ) { if ( ! stickies . length ) { return } lastKnownScrollTop = document . documentElement . scrollTop || document . body . scrollTop // Only trigger a layout change if we’re not already waiting for one if ( ! isAnimationRequested ) { isAnimationRequested = true // Don’t update until next animation frame if we can, otherwise use a // timeout - either will help avoid too many repaints if ( requestAnimationFrame ) { requestAnimationFrame ( setPositions ) } else { if ( timeout ) { clearTimeout ( timeout ) } timeout = setTimeout ( setPositions , 15 ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns strings based on the score given . [CODESPLIT] function scoreText ( score ) { if ( score === - 1 ) { return options . shortPass } score = score < 0 ? 0 : score if ( score < 26 ) { return options . shortPass } if ( score < 51 ) { return options . badPass } if ( score < 76 ) { return options . goodPass } return options . strongPass }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a value between - 1 and 100 to score the user s password . [CODESPLIT] function calculateScore ( password ) { var score = 0 // password < options.minimumLength if ( password . length < options . minimumLength ) { return - 1 } // password length score += password . length * 4 score += checkRepetition ( 1 , password ) . length - password . length score += checkRepetition ( 2 , password ) . length - password . length score += checkRepetition ( 3 , password ) . length - password . length score += checkRepetition ( 4 , password ) . length - password . length // password has 3 numbers if ( password . match ( / (.*[0-9].*[0-9].*[0-9]) / ) ) { score += 5 } // password has at least 2 sybols var symbols = '.*[!,@,#,$,%,^,&,*,?,_,~]' symbols = new RegExp ( '(' + symbols + symbols + ')' ) if ( password . match ( symbols ) ) { score += 5 } // password has Upper and Lower chars if ( password . match ( / ([a-z].*[A-Z])|([A-Z].*[a-z]) / ) ) { score += 10 } // password has number and chars if ( password . match ( / ([a-zA-Z]) / ) && password . match ( / ([0-9]) / ) ) { score += 15 } // password has number and symbol if ( password . match ( / ([!,@,#,$,%,^,&,*,?,_,~]) / ) && password . match ( / ([0-9]) / ) ) { score += 15 } // password has char and symbol if ( password . match ( / ([!,@,#,$,%,^,&,*,?,_,~]) / ) && password . match ( / ([a-zA-Z]) / ) ) { score += 15 } // password is just numbers or chars if ( password . match ( / ^\\w+$ / ) || password . match ( / ^\\d+$ / ) ) { score -= 10 } if ( score > 100 ) { score = 100 } if ( score < 0 ) { score = 0 } return score }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks for repetition of characters in a string [CODESPLIT] function checkRepetition ( rLen , str ) { var res = '' , repeated = false for ( var i = 0 ; i < str . length ; i ++ ) { repeated = true for ( var j = 0 ; j < rLen && j + i + rLen < str . length ; j ++ ) { repeated = repeated && str . charAt ( j + i ) === str . charAt ( j + i + rLen ) } if ( j < rLen ) { repeated = false } if ( repeated ) { i += rLen - 1 repeated = false } else { res += str . charAt ( i ) } } return res }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the plugin creating and binding the required layers and events . [CODESPLIT] function init ( ) { var shown = true var $text = options . showText var $graybar = $ ( '<div>' ) . addClass ( 'password-meter progress rounded-0 position-absolute' ) $graybar . append ( ` ` ) var $colorbar = $ ( '<div>' ) . attr ( { class : 'progress-bar' , role : 'progressbar' , 'aria-valuenow' : '0' , 'aria-valuemin' : '0' , 'aria-valuemax' : '100' , } ) var $insert = $ ( '<div>' ) . append ( $graybar . append ( $colorbar ) ) if ( options . showText ) { $text = $ ( '<small>' ) . addClass ( 'form-text text-muted' ) . html ( options . enterPass ) $insert . prepend ( $text ) } $object . after ( $insert ) $object . keyup ( function ( ) { var score = calculateScore ( $object . val ( ) ) $object . trigger ( 'password.score' , [ score ] ) var perc = score < 0 ? 0 : score $colorbar . removeClass ( function ( index , className ) { return ( className . match ( / (^|\\s)bg-\\S+ / g ) || [ ] ) . join ( ' ' ) } ) $colorbar . addClass ( 'bg-' + scoreColor ( score ) ) $colorbar . css ( { width : perc + '%' , } ) $colorbar . attr ( 'aria-valuenow' , perc ) if ( options . showText ) { var text = scoreText ( score ) if ( ! $object . val ( ) . length && score <= 0 ) { text = options . enterPass } if ( $text . html ( ) !== $ ( '<div>' ) . html ( text ) . html ( ) ) { $text . html ( text ) $text . removeClass ( function ( index , className ) { return ( className . match ( / (^|\\s)text-\\S+ / g ) || [ ] ) . join ( ' ' ) } ) $text . addClass ( 'text-' + scoreColor ( score ) ) $object . trigger ( 'password.text' , [ text , score ] ) } } } ) return this }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expects : logIndex : ... transactionIndex : ... transactionHash : ... block : ... address : ... data : ... topics : ... type : ... [CODESPLIT] function Log ( data ) { var self = this ; Object . keys ( data ) . forEach ( function ( key ) { self [ key ] = data [ key ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mimics crypto . random bytes but takes in a random number generator as its second parameter . rng is expected to be a function that takes no parameters and returns a result like Math . random () . This is important because it allows for a seeded random number generator . Since this is a mock RPC library the rng doesn t need to be cryptographically secure . [CODESPLIT] function ( length , rng ) { var buf = [ ] ; for ( var i = 0 ; i < length ; i ++ ) { buf . push ( rng ( ) * 255 ) ; } return Buffer . from ( buf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Level up adapter that looks like an array . Doesn t support inserts . [CODESPLIT] function LevelUpArrayAdapter ( name , db , serializer ) { this . db = Sublevel ( db ) ; this . db = this . db . sublevel ( name ) ; this . name = name ; this . serializer = serializer || { encode : function ( val , callback ) { callback ( null , val ) ; } , decode : function ( val , callback ) { callback ( null , val ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "etheruemjs - tx s Transactions don t behave quite like we need them to so we re monkey - patching them to do what we want here . [CODESPLIT] function fixProps ( tx , data ) { // ethereumjs-tx doesn't allow for a `0` value in fields, but we want it to // in order to differentiate between a value that isn't set and a value // that is set to 0 in a fake transaction. // Once https://github.com/ethereumjs/ethereumjs-tx/issues/112 is figured // out we can probably remove this fix/hack. // We keep track of the original value and return that value when // referenced by its property name. This lets us properly encode a `0` as // an empty buffer while still being able to differentiate between a `0` // and `null`/`undefined`. tx . _originals = [ ] ; const fieldNames = [ \"nonce\" , \"gasPrice\" , \"gasLimit\" , \"value\" ] ; fieldNames . forEach ( ( fieldName ) => configZeroableField ( tx , fieldName , 32 ) ) ; // Ethereumjs-tx doesn't set the _chainId value whenever the v value is set, // which causes transaction signing to fail on transactions that include a // chain id in the v value (like ethers.js does). // Whenever the v value changes we need to make sure the chainId is also set. const vDescriptors = Object . getOwnPropertyDescriptor ( tx , \"v\" ) ; // eslint-disable-next-line accessor-pairs Object . defineProperty ( tx , \"v\" , { set : ( v ) => { vDescriptors . set . call ( tx , v ) ; // calculate chainId from signature const sigV = ethUtil . bufferToInt ( tx . v ) ; let chainId = Math . floor ( ( sigV - 35 ) / 2 ) ; if ( chainId < 0 ) { chainId = 0 ; } tx . _chainId = chainId || 0 ; } } ) ; if ( tx . isFake ( ) ) { /**\n     * @prop {Buffer} from (read/write) Set from address to bypass transaction\n     * signing on fake transactions.\n     */ Object . defineProperty ( tx , \"from\" , { enumerable : true , configurable : true , get : tx . getSenderAddress . bind ( tx ) , set : ( val ) => { if ( val ) { tx . _from = ethUtil . toBuffer ( val ) ; } else { tx . _from = null ; } } } ) ; if ( data && data . from ) { tx . from = data . from ; } tx . hash = fakeHash ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the given data object and adds its properties to the given tx . [CODESPLIT] function initData ( tx , data ) { if ( data ) { if ( typeof data === \"string\" ) { data = to . buffer ( data ) ; } if ( Buffer . isBuffer ( data ) ) { data = rlp . decode ( data ) ; } const self = tx ; if ( Array . isArray ( data ) ) { if ( data . length > tx . _fields . length ) { throw new Error ( \"wrong number of fields in data\" ) ; } // make sure all the items are buffers data . forEach ( ( d , i ) => { self [ self . _fields [ i ] ] = ethUtil . toBuffer ( d ) ; } ) ; } else if ( ( typeof data === \"undefined\" ? \"undefined\" : typeof data ) === \"object\" ) { const keys = Object . keys ( data ) ; tx . _fields . forEach ( function ( field ) { if ( keys . indexOf ( field ) !== - 1 ) { self [ field ] = data [ field ] ; } if ( field === \"gasLimit\" ) { if ( keys . indexOf ( \"gas\" ) !== - 1 ) { self [ \"gas\" ] = data [ \"gas\" ] ; } } else if ( field === \"data\" ) { if ( keys . indexOf ( \"input\" ) !== - 1 ) { self [ \"input\" ] = data [ \"input\" ] ; } } } ) ; // Set chainId value from the data, if it's there and the data didn't // contain a `v` value with chainId in it already. If we do have a // data.chainId value let's set the interval v value to it. if ( ! tx . _chainId && data && data . chainId != null ) { tx . raw [ self . _fields . indexOf ( \"v\" ) ] = tx . _chainId = data . chainId || 0 ; } } else { throw new Error ( \"invalid data\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "raised when the transaction is rejected prior to running it in the EVM . [CODESPLIT] function TXRejectedError ( message ) { // Why not just Error.apply(this, [message])? See // https://gist.github.com/justmoon/15511f92e5216fa2624b#anti-patterns Error . captureStackTrace ( this , this . constructor ) ; this . name = this . constructor . name ; this . message = message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Note : ethereumjs - vm will return an object that has a results and receipts keys . You should pass in the whole object . [CODESPLIT] function RuntimeError ( transactions , vmOutput ) { // Why not just Error.apply(this, [message])? See // https://gist.github.com/justmoon/15511f92e5216fa2624b#anti-patterns Error . captureStackTrace ( this , this . constructor ) ; this . name = this . constructor . name ; this . results = { } ; this . hashes = [ ] ; // handles creating this.message this . combine ( transactions , vmOutput ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Note : Do not use to . hex () when you really mean utils . addHexPrefix () . [CODESPLIT] function ( val ) { if ( typeof val === \"string\" ) { if ( val . indexOf ( \"0x\" ) === 0 ) { return val . trim ( ) ; } else { val = new utils . BN ( val ) ; } } if ( typeof val === \"boolean\" ) { val = val ? 1 : 0 ; } if ( typeof val === \"number\" ) { val = utils . intToHex ( val ) ; } else if ( val == null ) { return \"0x\" ; } else if ( typeof val === \"object\" ) { // Support Buffer, BigInteger and BN library // Hint: BN is used in ethereumjs val = val . toString ( \"hex\" ) ; } return utils . addHexPrefix ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "EthereumJS VM needs a blockchain object in order to get block information . When calling getBlock () it will pass a number that s of a Buffer type . Unfortunately it uses a 64 - character buffer ( when converted to hex ) to represent block numbers as well as block hashes . Since it s very unlikely any block number will get higher than the maximum safe Javascript integer we can convert this buffer to a number ahead of time before calling our own getBlock () . If the conversion succeeds we have a block number . If it doesn t we have a block hash . ( Note : Our implementation accepts both . ) [CODESPLIT] function ( number , done ) { try { number = to . number ( number ) ; } catch ( e ) { // Do nothing; must be a block hash. } self . getBlock ( number , done ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if any payloads for the specified methods are marked as external . If they are external and match the method list process them one at a time . [CODESPLIT] function RequestFunnel ( ) { // We use an object here for O(1) lookups (speed). this . methods = { eth_call : true , eth_getStorageAt : true , eth_sendTransaction : true , eth_sendRawTransaction : true , // Ensure block filter and filter changes are process one at a time // as well so filter requests that come in after a transaction get // processed once that transaction has finished processing. eth_newBlockFilter : true , eth_getFilterChanges : true , eth_getFilterLogs : true } ; this . queue = [ ] ; this . isWorking = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile SASS to CSS . [CODESPLIT] function compileSass ( _path , ext , data , callback ) { const compiledCss = sass . renderSync ( { data : data , outputStyle : 'expanded' , importer : function ( url , prev , done ) { if ( url . startsWith ( '~' ) ) { const newUrl = path . join ( __dirname , 'node_modules' , url . substr ( 1 ) ) ; return { file : newUrl } ; } else { return { file : url } ; } } } ) ; callback ( null , compiledCss . css ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Require a brocfile via either ESM or TypeScript [CODESPLIT] function requireBrocfile ( brocfilePath ) { let brocfile ; if ( brocfilePath . match ( / \\.ts$ / ) ) { try { require . resolve ( 'ts-node' ) ; } catch ( e ) { throw new Error ( ` ` ) ; } try { require . resolve ( 'typescript' ) ; } catch ( e ) { throw new Error ( ` ` ) ; } // Register ts-node typescript compiler require ( 'ts-node' ) . register ( ) ; // eslint-disable-line node/no-unpublished-require // Load brocfile via ts-node brocfile = require ( brocfilePath ) ; } else { // Load brocfile via esm shim brocfile = esmRequire ( brocfilePath ) ; } // ESM `export default X` is represented as module.exports = { default: X } if ( brocfile !== null && typeof brocfile === 'object' && brocfile . hasOwnProperty ( 'default' ) ) { brocfile = brocfile . default ; } return brocfile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a State is a rule at a position from a given starting point in the input stream ( reference ) [CODESPLIT] function State ( rule , dot , reference , wantedBy ) { this . rule = rule ; this . dot = dot ; this . reference = reference ; this . data = [ ] ; this . wantedBy = wantedBy ; this . isComplete = this . dot === rule . symbols . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is where the action is . [CODESPLIT] function runmath ( s ) { var ans ; try { // We want to catch parse errors and die appropriately // Make a parser and feed the input ans = new nearley . Parser ( grammar . ParserRules , grammar . ParserStart ) . feed ( s ) ; // Check if there are any results if ( ans . results . length ) { return ans . results [ 0 ] . toString ( ) ; } else { // This means the input is incomplete. var out = \"Error: incomplete input, parse failed. :(\" ; return out ; } } catch ( e ) { // Panic in style, by graphically pointing out the error location. var out = new Array ( PROMPT . length + e . offset + 1 ) . join ( \"-\" ) + \"^  Error.\" ; //                                  -------- //                                         ^ This comes from nearley! return out ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "=== READING ================================================================= [CODESPLIT] function ( readField , result , end ) { end = end || this . length ; while ( this . pos < end ) { var val = this . readVarint ( ) , tag = val >> 3 , startPos = this . pos ; this . type = val & 0x7 ; readField ( tag , result , this ) ; if ( this . pos === startPos ) this . skip ( val ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "64 - bit int handling is based on github . com / dpw / node - buffer - more - ints ( MIT - licensed ) [CODESPLIT] function ( ) { var val = readUInt32 ( this . buf , this . pos ) + readUInt32 ( this . buf , this . pos + 4 ) * SHIFT_LEFT_32 ; this . pos += 8 ; return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "verbose for performance reasons ; doesn t affect gzipped size [CODESPLIT] function ( arr , isSigned ) { if ( this . type !== Pbf . Bytes ) return arr . push ( this . readVarint ( isSigned ) ) ; var end = readPackedEnd ( this ) ; arr = arr || [ ] ; while ( this . pos < end ) arr . push ( this . readVarint ( isSigned ) ) ; return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Buffer code below from https : // github . com / feross / buffer MIT - licensed [CODESPLIT] function readUInt32 ( buf , pos ) { return ( ( buf [ pos ] ) | ( buf [ pos + 1 ] << 8 ) | ( buf [ pos + 2 ] << 16 ) ) + ( buf [ pos + 3 ] * 0x1000000 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we need one ORDER BY clause on at the very end to make sure everything comes back in the correct order ordering inner ( sub ) queries DOES NOT guarantee the order of those results in the outer query [CODESPLIT] function stringifyOuterOrder ( orders , q ) { const conditions = [ ] for ( let condition of orders ) { for ( let column in condition . columns ) { const direction = condition . columns [ column ] conditions . push ( ` ${ q ( condition . table ) } ${ q ( column ) } ${ direction } ` ) } } return conditions . join ( ', ' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we need to collect all fields from all the fragments requested in the union type and ask for them in SQL [CODESPLIT] function handleUnionSelections ( sqlASTNode , children , selections , gqlType , namespace , depth , options , context , internalOptions = { } ) { for ( let selection of selections ) { // we need to figure out what kind of selection this is switch ( selection . kind ) { case 'Field' : // has this field been requested once already? GraphQL does not protect against duplicates so we have to check for it const existingNode = children . find ( child => child . fieldName === selection . name . value && child . type === 'table' ) let newNode = new SQLASTNode ( sqlASTNode ) if ( existingNode ) { newNode = existingNode } else { children . push ( newNode ) } if ( internalOptions . defferedFrom ) { newNode . defferedFrom = internalOptions . defferedFrom } populateASTNode . call ( this , selection , gqlType , newNode , namespace , depth + 1 , options , context ) break // if its an inline fragment, it has some fields and we gotta recurse thru all them case 'InlineFragment' : { const selectionNameOfType = selection . typeCondition . name . value // normally, we would scan for the extra join-monster data on the current gqlType. // but the gqlType is the Union. The data isn't there, its on each of the types that make up the union // lets find that type and handle the selections based on THAT type instead const deferredType = this . schema . _typeMap [ selectionNameOfType ] const deferToObjectType = deferredType . constructor . name === 'GraphQLObjectType' const handler = deferToObjectType ? handleSelections : handleUnionSelections if ( deferToObjectType ) { const typedChildren = sqlASTNode . typedChildren children = typedChildren [ deferredType . name ] = typedChildren [ deferredType . name ] || [ ] internalOptions . defferedFrom = gqlType } handler . call ( this , sqlASTNode , children , selection . selectionSet . selections , deferredType , namespace , depth , options , context , internalOptions ) } break // if its a named fragment, we need to grab the fragment definition by its name and recurse over those fields case 'FragmentSpread' : { const fragmentName = selection . name . value const fragment = this . fragments [ fragmentName ] const fragmentNameOfType = fragment . typeCondition . name . value const deferredType = this . schema . _typeMap [ fragmentNameOfType ] const deferToObjectType = deferredType . constructor . name === 'GraphQLObjectType' const handler = deferToObjectType ? handleSelections : handleUnionSelections if ( deferToObjectType ) { const typedChildren = sqlASTNode . typedChildren children = typedChildren [ deferredType . name ] = typedChildren [ deferredType . name ] || [ ] internalOptions . defferedFrom = gqlType } handler . call ( this , sqlASTNode , children , fragment . selectionSet . selections , deferredType , namespace , depth , options , context , internalOptions ) } break /* istanbul ignore next */ default : throw new Error ( 'Unknown selection kind: ' + selection . kind ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the selections could be several types recursively handle each type here [CODESPLIT] function handleSelections ( sqlASTNode , children , selections , gqlType , namespace , depth , options , context , internalOptions = { } , ) { for ( let selection of selections ) { // we need to figure out what kind of selection this is switch ( selection . kind ) { // if its another field, recurse through that case 'Field' : // has this field been requested once already? GraphQL does not protect against duplicates so we have to check for it const existingNode = children . find ( child => child . fieldName === selection . name . value && child . type === 'table' ) let newNode = new SQLASTNode ( sqlASTNode ) if ( existingNode ) { newNode = existingNode } else { children . push ( newNode ) } if ( internalOptions . defferedFrom ) { newNode . defferedFrom = internalOptions . defferedFrom } populateASTNode . call ( this , selection , gqlType , newNode , namespace , depth + 1 , options , context ) break // if its an inline fragment, it has some fields and we gotta recurse thru all them case 'InlineFragment' : { // check to make sure the type of this fragment (or one of the interfaces it implements) matches the type being queried const selectionNameOfType = selection . typeCondition . name . value const sameType = selectionNameOfType === gqlType . name const interfaceType = ( gqlType . _interfaces || [ ] ) . map ( iface => iface . name ) . includes ( selectionNameOfType ) if ( sameType || interfaceType ) { handleSelections . call ( this , sqlASTNode , children , selection . selectionSet . selections , gqlType , namespace , depth , options , context , internalOptions ) } } break // if its a named fragment, we need to grab the fragment definition by its name and recurse over those fields case 'FragmentSpread' : { const fragmentName = selection . name . value const fragment = this . fragments [ fragmentName ] // make sure fragment type (or one of the interfaces it implements) matches the type being queried const fragmentNameOfType = fragment . typeCondition . name . value const sameType = fragmentNameOfType === gqlType . name const interfaceType = gqlType . _interfaces . map ( iface => iface . name ) . indexOf ( fragmentNameOfType ) >= 0 if ( sameType || interfaceType ) { handleSelections . call ( this , sqlASTNode , children , fragment . selectionSet . selections , gqlType , namespace , depth , options , context , internalOptions ) } } break /* istanbul ignore next */ default : throw new Error ( 'Unknown selection kind: ' + selection . kind ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tell the AST we need a column that perhaps the user didnt ask for but may be necessary for join monster to ID objects or associate ones across batches [CODESPLIT] function columnToASTChild ( columnName , namespace ) { return { type : 'column' , name : columnName , fieldName : columnName , as : namespace . generate ( 'column' , columnName ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "keys are necessary for deduplication during the hydration process this will handle singular or composite keys [CODESPLIT] function keyToASTChild ( key , namespace ) { if ( typeof key === 'string' ) { return columnToASTChild ( key , namespace ) } if ( Array . isArray ( key ) ) { const clumsyName = toClumsyName ( key ) return { type : 'composite' , name : key , fieldName : clumsyName , as : namespace . generate ( 'column' , clumsyName ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if its a connection type we need to look up the Node type inside their to find the relevant SQL info [CODESPLIT] function stripRelayConnection ( gqlType , queryASTNode , fragments ) { // get the GraphQL Type inside the list of edges inside the Node from the schema definition const edgeType = stripNonNullType ( gqlType . _fields . edges . type ) const strippedType = stripNonNullType ( stripNonNullType ( edgeType . ofType ) . _fields . node . type ) // let's remember those arguments on the connection const args = queryASTNode . arguments // and then find the fields being selected on the underlying type, also buried within edges and Node const edges = spreadFragments ( queryASTNode . selectionSet . selections , fragments , gqlType . name ) . find ( selection => selection . name . value === 'edges' ) if ( edges ) { queryASTNode = spreadFragments ( edges . selectionSet . selections , fragments , gqlType . name ) . find ( selection => selection . name . value === 'node' ) || { } } else { queryASTNode = { } } // place the arguments on this inner field, so our SQL AST picks it up later queryASTNode . arguments = args return { gqlType : strippedType , queryASTNode } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "instead of fields selections can be fragments which is another group of selections fragments can be arbitrarily nested this function recurses through and gets the relevant fields [CODESPLIT] function spreadFragments ( selections , fragments , typeName ) { return flatMap ( selections , selection => { switch ( selection . kind ) { case 'FragmentSpread' : const fragmentName = selection . name . value const fragment = fragments [ fragmentName ] return spreadFragments ( fragment . selectionSet . selections , fragments , typeName ) case 'InlineFragment' : if ( selection . typeCondition . name . value === typeName ) { return spreadFragments ( selection . selectionSet . selections , fragments , typeName ) } return [ ] default : return selection } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * _ _ | |__ ___ __ _ ( _ ) _ __ ___ ___ _ _ _ __ ___ ___ | _ \\ / _ \\ / _ | | _ \\ / __| / _ \\ | | | | __ / __ / _ \\ | |_ ) | __ / ( _| | | | | | \\ __ \\ ( _ ) | |_| | | | ( _| __ / |_ . __ / \\ ___| \\ __ |_|_| |_| |___ / \\ ___ / \\ __ _|_| \\ ___ \\ ___| |___ / Takes the GraphQL resolveInfo and returns a hydrated Object with the data . [CODESPLIT] async function joinMonster ( resolveInfo , context , dbCall , options = { } ) { // we need to read the query AST and build a new \"SQL AST\" from which the SQL and const sqlAST = queryAST . queryASTToSqlAST ( resolveInfo , options , context ) const { sql , shapeDefinition } = await compileSqlAST ( sqlAST , context , options ) if ( ! sql ) return { } // call their function for querying the DB, handle the different cases, do some validation, return a promise of the object let data = await handleUserDbCall ( dbCall , sql , sqlAST , shapeDefinition ) // if they are paginating, we'll get back an array which is essentially a \"slice\" of the whole data. // this function goes through the data tree and converts the arrays to Connection Objects data = arrToConnection ( data , sqlAST ) // so far we handled the first \"batch\". up until now, additional batches were ignored // this function recursively scanss the sqlAST and runs remaining batches await nextBatch ( sqlAST , data , dbCall , context , options ) // check for batch data if ( Array . isArray ( data ) ) { const childrenToCheck = sqlAST . children . filter ( child => child . sqlBatch ) return data . filter ( d => { for ( const child of childrenToCheck ) { if ( d [ child . fieldName ] == null ) { return false } } return true } ) } return data }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A helper for resolving the Node type in Relay . [CODESPLIT] async function getNode ( typeName , resolveInfo , context , condition , dbCall , options = { } ) { // get the GraphQL type from the schema using the name const type = resolveInfo . schema . _typeMap [ typeName ] assert ( type , ` ${ typeName } ` ) assert ( type . _typeConfig . sqlTable , ` ${ typeName } ` ) // we need to determine what the WHERE function should be let where = buildWhereFunction ( type , condition , options ) // our getGraphQLType expects every requested field to be in the schema definition. \"node\" isn't a parent of whatever type we're getting, so we'll just wrap that type in an object that LOOKS that same as a hypothetical Node type const fakeParentNode = { _fields : { node : { type , name : type . name . toLowerCase ( ) , where } } } const namespace = new AliasNamespace ( options . minify ) const sqlAST = { } const fieldNodes = resolveInfo . fieldNodes || resolveInfo . fieldASTs // uses the same underlying function as the main `joinMonster` queryAST . populateASTNode . call ( resolveInfo , fieldNodes [ 0 ] , fakeParentNode , sqlAST , namespace , 0 , options , context ) queryAST . pruneDuplicateSqlDeps ( sqlAST , namespace ) const { sql , shapeDefinition } = await compileSqlAST ( sqlAST , context , options ) const data = arrToConnection ( await handleUserDbCall ( dbCall , sql , sqlAST , shapeDefinition ) , sqlAST ) await nextBatch ( sqlAST , data , dbCall , context , options ) if ( ! data ) return data data . __type__ = type return data }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "processes a single child of the batch [CODESPLIT] async function nextBatchChild ( childAST , data , dbCall , context , options ) { if ( childAST . type !== 'table' && childAST . type !== 'union' ) return const fieldName = childAST . fieldName // see if any begin a new batch if ( childAST . sqlBatch || idx ( childAST , _ => _ . junction . sqlBatch ) ) { let thisKey let parentKey if ( childAST . sqlBatch ) { // if so, we know we'll need to get the key for matching with the parent key childAST . children . push ( childAST . sqlBatch . thisKey ) thisKey = childAST . sqlBatch . thisKey . fieldName parentKey = childAST . sqlBatch . parentKey . fieldName } else if ( idx ( childAST , _ => _ . junction . sqlBatch ) ) { childAST . children . push ( childAST . junction . sqlBatch . thisKey ) thisKey = childAST . junction . sqlBatch . thisKey . fieldName parentKey = childAST . junction . sqlBatch . parentKey . fieldName } if ( Array . isArray ( data ) ) { // the \"batch scope\" is teh set of values to match this key against from the previous batch const batchScope = uniq ( data . map ( obj => maybeQuote ( obj [ parentKey ] ) ) ) // generate the SQL, with the batch scope values incorporated in a WHERE IN clause const { sql , shapeDefinition } = await compileSqlAST ( childAST , context , { ... options , batchScope } ) // grab the data let newData = await handleUserDbCall ( dbCall , sql , childAST , wrap ( shapeDefinition ) ) // group the rows by the key so we can match them with the previous batch newData = groupBy ( newData , thisKey ) // but if we paginate, we must convert to connection type first if ( childAST . paginate ) { forIn ( newData , ( group , key , obj ) => { obj [ key ] = arrToConnection ( group , childAST ) } ) } // if we they want many rows, give them an array if ( childAST . grabMany ) { for ( let obj of data ) { obj [ fieldName ] = newData [ obj [ parentKey ] ] || ( childAST . paginate ? { total : 0 , edges : [ ] } : [ ] ) } } else { let matchedData = [ ] for ( let obj of data ) { const ob = newData [ obj [ parentKey ] ] if ( ob ) { obj [ fieldName ] = arrToConnection ( newData [ obj [ parentKey ] ] [ 0 ] , childAST ) matchedData . push ( obj ) } else { obj [ fieldName ] = null } } data = matchedData } // move down a level and recurse const nextLevelData = chain ( data ) . filter ( obj => obj != null ) . flatMap ( obj => obj [ fieldName ] ) . filter ( obj => obj != null ) . value ( ) return nextBatch ( childAST , nextLevelData , dbCall , context , options ) } const batchScope = [ maybeQuote ( data [ parentKey ] ) ] const { sql , shapeDefinition } = await compileSqlAST ( childAST , context , { ... options , batchScope } ) let newData = await handleUserDbCall ( dbCall , sql , childAST , wrap ( shapeDefinition ) ) newData = groupBy ( newData , thisKey ) if ( childAST . paginate ) { const targets = newData [ data [ parentKey ] ] data [ fieldName ] = arrToConnection ( targets , childAST ) } else if ( childAST . grabMany ) { data [ fieldName ] = newData [ data [ parentKey ] ] || [ ] } else { const targets = newData [ data [ parentKey ] ] || [ ] data [ fieldName ] = targets [ 0 ] } if ( data ) { return nextBatch ( childAST , data [ fieldName ] , dbCall , context , options ) } // otherwise, just bypass this and recurse down to the next level } else if ( Array . isArray ( data ) ) { const nextLevelData = chain ( data ) . filter ( obj => obj != null ) . flatMap ( obj => obj [ fieldName ] ) . filter ( obj => obj != null ) . value ( ) return nextBatch ( childAST , nextLevelData , dbCall , context , options ) } else if ( data ) { return nextBatch ( childAST , data [ fieldName ] , dbCall , context , options ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a function for data manipulation AFTER its nested . this is only necessary when using the SQL pagination we have to interpret the slice that comes back and generate the Connection Object type [CODESPLIT] function arrToConnection ( data , sqlAST ) { // use \"post-order\" tree traversal for ( let astChild of sqlAST . children || [ ] ) { if ( Array . isArray ( data ) ) { for ( let dataItem of data ) { recurseOnObjInData ( dataItem , astChild ) } } else if ( data ) { recurseOnObjInData ( data , astChild ) } } const pageInfo = { hasNextPage : false , hasPreviousPage : false } if ( ! data ) { if ( sqlAST . paginate ) { return { pageInfo , edges : [ ] } } return null } // is cases where pagination was done, take the data and convert to the connection object // if any two fields happen to become a reference to the same object (when their `uniqueKey`s are the same), // we must prevent the recursive processing from visting the same object twice, because mutating the object the first // time changes it everywhere. we'll set the `_paginated` property to true to prevent this if ( sqlAST . paginate && ! data . _paginated ) { if ( sqlAST . sortKey || idx ( sqlAST , _ => _ . junction . sortKey ) ) { if ( idx ( sqlAST , _ => _ . args . first ) ) { // we fetched an extra one in order to determine if there is a next page, if there is one, pop off that extra if ( data . length > sqlAST . args . first ) { pageInfo . hasNextPage = true data . pop ( ) } } else if ( sqlAST . args && sqlAST . args . last ) { // if backward paging, do the same, but also reverse it if ( data . length > sqlAST . args . last ) { pageInfo . hasPreviousPage = true data . pop ( ) } data . reverse ( ) } // convert nodes to edges and compute the cursor for each // TODO: only compute all the cursor if asked for them const sortKey = sqlAST . sortKey || sqlAST . junction . sortKey const edges = data . map ( obj => { const cursor = { } const key = sortKey . key for ( let column of wrap ( key ) ) { cursor [ column ] = obj [ column ] } return { cursor : objToCursor ( cursor ) , node : obj } } ) if ( data . length ) { pageInfo . startCursor = edges [ 0 ] . cursor pageInfo . endCursor = last ( edges ) . cursor } return { edges , pageInfo , _paginated : true } } if ( sqlAST . orderBy || ( sqlAST . junction && sqlAST . junction . orderBy ) ) { let offset = 0 if ( idx ( sqlAST , _ => _ . args . after ) ) { offset = cursorToOffset ( sqlAST . args . after ) + 1 } // $total was a special column for determining the total number of items const arrayLength = data [ 0 ] && parseInt ( data [ 0 ] . $total , 10 ) const connection = connectionFromArraySlice ( data , sqlAST . args || { } , { sliceStart : offset , arrayLength } ) connection . total = arrayLength || 0 connection . _paginated = true return connection } } return data }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "validate the data they gave us [CODESPLIT] function validate ( rows ) { // its supposed to be an array of objects if ( Array . isArray ( rows ) ) return rows // a check for the most common error. a lot of ORMs return an object with the desired data on the `rows` property if ( rows && rows . rows ) return rows . rows throw new Error ( ` ${ util . inspect ( rows , { depth : 3 } ) } ` ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "take the sort key and translate that for the where clause [CODESPLIT] function sortKeyToWhereCondition ( keyObj , descending , sortTable , dialect ) { const { name , quote : q } = dialect const sortColumns = [ ] const sortValues = [ ] for ( let key in keyObj ) { sortColumns . push ( ` ${ q ( sortTable ) } ${ q ( key ) } ` ) sortValues . push ( maybeQuote ( keyObj [ key ] , name ) ) } const operator = descending ? '<' : '>' return name === 'oracle' ? recursiveWhereJoin ( sortColumns , sortValues , operator ) : ` ${ sortColumns . join ( ', ' ) } ${ operator } ${ sortValues . join ( ', ' ) } ` }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--------- BEGIN Reflux . Store ------------ Reflux . Store : Also implements optional Reflux . Store class that is idiomatic with the React ES6 style . You extend Reflux . Store and then the rest works the same as createStore except the constructor instead of init and it holds state in a state property and a . setState method is available which automatically updates state and does a trigger . Then when using with this . store or this . stores in an ES6 component just plass the class it will deal with a singleton instantiation of the class automatically . [CODESPLIT] function ( ) { // extending doesn't really work well here, so instead we create an internal instance // and just loop through its properties/methods and make a getter/setter for each // that will actually be getting and setting on that internal instance. this . __store__ = Reflux . createStore ( ) ; this . state = { } ; var self = this ; for ( var key in this . __store__ ) { /*jshint loopfunc: true */ ( function ( prop ) { Object . defineProperty ( self , prop , { get : function ( ) { return self . __store__ [ prop ] ; } , set : function ( v ) { self . __store__ [ prop ] = v ; } } ) ; } ) ( key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "filters a state object by storeKeys array ( if it exists ) if filtering and obj contains no properties to use returns false to let the component know not to update [CODESPLIT] function filterByStoreKeys ( storeKeys , obj ) { // if there are not storeKeys defined then simply return the whole original object if ( ! storeKeys ) { return obj ; } // otherwise go through and only update properties that are in the storeKeys array, and return straight false if there are none var doUpdate = false ; var updateObj = { } ; for ( var i = 0 , ii = storeKeys . length ; i < ii ; i ++ ) { var prop = storeKeys [ i ] ; if ( obj . hasOwnProperty ( prop ) ) { doUpdate = true ; updateObj [ prop ] = obj [ prop ] ; } } return doUpdate ? updateObj : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this is utilized by some of the global state functionality in order to get a clone that will not continue to be modified as the GlobalState mutates [CODESPLIT] function clone ( frm , to ) { if ( frm === null || typeof frm !== \"object\" ) { return frm ; } if ( frm . constructor !== Object && frm . constructor !== Array ) { return frm ; } if ( frm . constructor === Date || frm . constructor === RegExp || frm . constructor === Function || frm . constructor === String || frm . constructor === Number || frm . constructor === Boolean ) { return new frm . constructor ( frm ) ; } to = to || new frm . constructor ( ) ; for ( var name in frm ) { to [ name ] = typeof to [ name ] === \"undefined\" ? clone ( frm [ name ] , null ) : to [ name ] ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set up the mixin before the initial rendering occurs . Import methods from ListenerMethods and then make the call to listenTo with the arguments provided to the factory function [CODESPLIT] function ( ) { for ( var m in ListenerMethods ) { if ( this [ m ] !== ListenerMethods [ m ] ) { if ( this [ m ] ) { throw \"Can't have other property '\" + m + \"' when using Reflux.listenTo!\" ; } this [ m ] = ListenerMethods [ m ] ; } } this . listenTo ( listenable , callback , initial ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set up the mixin before the initial rendering occurs . Import methods from ListenerMethods and then make the call to listenTo with the arguments provided to the factory function [CODESPLIT] function ( ) { for ( var m in ListenerMethods ) { if ( this [ m ] !== ListenerMethods [ m ] ) { if ( this [ m ] ) { throw \"Can't have other property '\" + m + \"' when using Reflux.listenToMany!\" ; } this [ m ] = ListenerMethods [ m ] ; } } this . listenToMany ( listenables ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "constructor [CODESPLIT] function ( data ) { var entries var self = this var input = Object . assign ( { } , data ) // prep the main container self . requests = [ ] // is it har? if ( input . log && input . log . entries ) { entries = input . log . entries } else { entries = [ { request : input } ] } entries . forEach ( function ( entry ) { // add optional properties to make validation successful entry . request . httpVersion = entry . request . httpVersion || 'HTTP/1.1' entry . request . queryString = entry . request . queryString || [ ] entry . request . headers = entry . request . headers || [ ] entry . request . cookies = entry . request . cookies || [ ] entry . request . postData = entry . request . postData || { } entry . request . postData . mimeType = entry . request . postData . mimeType || 'application/octet-stream' entry . request . bodySize = 0 entry . request . headersSize = 0 entry . request . postData . size = 0 validate . request ( entry . request , function ( err , valid ) { if ( ! valid ) { throw err } self . requests . push ( self . prepare ( entry . request ) ) } ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use strong quoting using single quotes so that we only need to deal with nested single quote characters . http : // wiki . bash - hackers . org / syntax / quoting#strong_quoting [CODESPLIT] function ( value ) { var safe = / ^[a-z0-9-_/.@%^=:]+$ / i // Unless `value` is a simple shell-safe string, quote it. if ( ! safe . test ( value ) ) { return util . format ( '\\'%s\\'' , value . replace ( / ' / g , \"'\\\\''\" ) ) } return value }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an string of given length filled with blank spaces [CODESPLIT] function buildString ( length , str ) { return Array . apply ( null , new Array ( length ) ) . map ( String . prototype . valueOf , str ) . join ( '' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a string corresponding to a Dictionary or Array literal representation with pretty option and indentation . [CODESPLIT] function concatArray ( arr , pretty , indentation , indentLevel ) { var currentIndent = buildString ( indentLevel , indentation ) var closingBraceIndent = buildString ( indentLevel - 1 , indentation ) var join = pretty ? ',\\n' + currentIndent : ', ' if ( pretty ) { return '[\\n' + currentIndent + arr . join ( join ) + '\\n' + closingBraceIndent + ']' } else { return '[' + arr . join ( join ) + ']' } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a valid Swift string of a literal value according to its type . [CODESPLIT] function ( value , opts , indentLevel ) { indentLevel = indentLevel === undefined ? 1 : indentLevel + 1 switch ( Object . prototype . toString . call ( value ) ) { case '[object Number]' : return value case '[object Array]' : // Don't prettify arrays nto not take too much space var pretty = false var valuesRepresentation = value . map ( function ( v ) { // Switch to prettify if the value is a dictionary with multiple keys if ( Object . prototype . toString . call ( v ) === '[object Object]' ) { pretty = Object . keys ( v ) . length > 1 } return this . literalRepresentation ( v , opts , indentLevel ) } . bind ( this ) ) return concatArray ( valuesRepresentation , pretty , opts . indent , indentLevel ) case '[object Object]' : var keyValuePairs = [ ] for ( var k in value ) { keyValuePairs . push ( util . format ( '\"%s\": %s' , k , this . literalRepresentation ( value [ k ] , opts , indentLevel ) ) ) } return concatArray ( keyValuePairs , opts . pretty && keyValuePairs . length > 1 , opts . indent , indentLevel ) case '[object Boolean]' : return value . toString ( ) default : if ( value === null || value === undefined ) { return '' } return '\"' + value . toString ( ) . replace ( / \" / g , '\\\\\"' ) + '\"' } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "handler definition is in multipart - readstream handler ( field file filename encoding mimetype ) opts is a per - request override for the options object [CODESPLIT] function multipart ( handler , done , opts ) { if ( typeof handler !== 'function' ) { throw new Error ( 'handler must be a function' ) } if ( typeof done !== 'function' ) { throw new Error ( 'the callback must be a function' ) } if ( ! this . isMultipart ( ) ) { done ( new Error ( 'the request is not multipart' ) ) return } const log = this . log log . debug ( 'starting multipart parsing' ) const req = this . req const busboyOptions = deepmerge . all ( [ { headers : req . headers } , options || { } , opts || { } ] ) const stream = new Busboy ( busboyOptions ) var completed = false var files = 0 var count = 0 var callDoneOnNextEos = false req . on ( 'error' , function ( err ) { stream . destroy ( ) if ( ! completed ) { completed = true done ( err ) } } ) stream . on ( 'finish' , function ( ) { log . debug ( 'finished multipart parsing' ) if ( ! completed && count === files ) { completed = true setImmediate ( done ) } else { callDoneOnNextEos = true } } ) stream . on ( 'file' , wrap ) req . pipe ( stream ) function wrap ( field , file , filename , encoding , mimetype ) { log . debug ( { field , filename , encoding , mimetype } , 'parsing part' ) files ++ eos ( file , waitForFiles ) handler ( field , file , filename , encoding , mimetype ) } function waitForFiles ( err ) { if ( err ) { completed = true done ( err ) return } if ( completed ) { return } ++ count if ( callDoneOnNextEos && count === files ) { completed = true done ( ) } } return stream }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For quiptext introduced in 0 . 1 . 044 [CODESPLIT] function ( text , placeholders ) { if ( text [ text . length - 1 ] == \"]\" && text . lastIndexOf ( \" [\" ) != - 1 ) { // Remove translation comments text = text . substr ( 0 , text . lastIndexOf ( \" [\" ) ) ; } var replaceAll = function ( str , substr , replacement ) { return str . replace ( new RegExp ( substr . replace ( / ([.*+?^=!:${}()|\\[\\]\\/\\\\]) / g , \"\\\\$1\" ) , \"g\" ) , replacement ) ; } var localeReplace = function ( text , placeholders ) { for ( var key in placeholders ) { text = replaceAll ( text , \"%(\" + key + \")s\" , placeholders [ key ] ) ; } return text ; } ; var reactLocaleReplace = function ( text , placeholders ) { var start ; var expanded = [ text ] ; for ( var key in placeholders ) { start = expanded ; expanded = [ ] ; for ( var i = 0 ; i < start . length ; i ++ ) { if ( typeof start [ i ] == \"string\" ) { var keyStr = \"%(\" + key + \")s\" ; var parts = start [ i ] . split ( keyStr ) ; var replaced = [ ] ; for ( var j = 0 ; j < parts . length - 1 ; j ++ ) { replaced . push ( parts [ j ] ) ; replaced . push ( placeholders [ key ] ) ; } replaced . push ( parts [ parts . length - 1 ] ) ; replaced = replaced . filter ( function ( str ) { return str != \"\" ; } ) ; expanded . push . apply ( expanded , replaced ) } else { expanded . push ( start [ i ] ) ; } } } return expanded ; } if ( placeholders ) { var hasReactElements = false ; for ( var key in placeholders ) { var val = placeholders [ key ] ; if ( typeof val !== \"string\" && React . isValidElement ( val ) ) { hasReactElements = true ; break ; } } return ( hasReactElements ? reactLocaleReplace ( text , placeholders ) : localeReplace ( text , placeholders ) ) ; } return text ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This class provides access to the device media interfaces to both sound and video [CODESPLIT] function ( src , successCallback , errorCallback , statusCallback ) { argscheck . checkArgs ( 'SFFF' , 'Media' , arguments ) ; this . id = utils . createUUID ( ) ; mediaObjects [ this . id ] = this ; this . src = src ; this . successCallback = successCallback ; this . errorCallback = errorCallback ; this . statusCallback = statusCallback ; this . _duration = - 1 ; this . _position = - 1 ; try { this . node = createNode ( this ) ; } catch ( err ) { Media . onStatus ( this . id , Media . MEDIA_ERROR , { code : MediaError . MEDIA_ERR_ABORTED } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new Audio node and with necessary event listeners attached [CODESPLIT] function createNode ( media ) { var node = new Audio ( ) ; node . onplay = function ( ) { Media . onStatus ( media . id , Media . MEDIA_STATE , Media . MEDIA_STARTING ) ; } ; node . onplaying = function ( ) { Media . onStatus ( media . id , Media . MEDIA_STATE , Media . MEDIA_RUNNING ) ; } ; node . ondurationchange = function ( e ) { Media . onStatus ( media . id , Media . MEDIA_DURATION , e . target . duration || - 1 ) ; } ; node . onerror = function ( e ) { // Due to media.spec.15 It should return MediaError for bad filename var err = e . target . error . code === MediaError . MEDIA_ERR_SRC_NOT_SUPPORTED ? { code : MediaError . MEDIA_ERR_ABORTED } : e . target . error ; Media . onStatus ( media . id , Media . MEDIA_ERROR , err ) ; } ; node . onended = function ( ) { Media . onStatus ( media . id , Media . MEDIA_STATE , Media . MEDIA_STOPPED ) ; } ; if ( media . src ) { node . src = media . src ; } return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initiates the audio file [CODESPLIT] function ( win , lose , args ) { var id = args [ 0 ] ; var srcUri = processUri ( args [ 1 ] ) ; var createAudioNode = ! ! args [ 2 ] ; var thisM = Media . get ( id ) ; Media . prototype . node = null ; var prefix = args [ 1 ] . split ( ':' ) . shift ( ) ; var extension = srcUri . extension ; if ( thisM . node === null ) { if ( SUPPORTED_EXTENSIONS . indexOf ( extension ) === - 1 && SUPPORTED_PREFIXES . indexOf ( prefix ) === - 1 ) { if ( lose ) { lose ( { code : MediaError . MEDIA_ERR_ABORTED } ) ; } return false ; // unable to create } // Don't create Audio object in case of record mode if ( createAudioNode === true ) { thisM . node = new Audio ( ) ; thisM . node . msAudioCategory = \"BackgroundCapableMedia\" ; thisM . node . src = srcUri . absoluteCanonicalUri ; thisM . node . onloadstart = function ( ) { Media . onStatus ( id , Media . MEDIA_STATE , Media . MEDIA_STARTING ) ; } ; thisM . node . ontimeupdate = function ( e ) { Media . onStatus ( id , Media . MEDIA_POSITION , e . target . currentTime ) ; } ; thisM . node . onplaying = function ( ) { Media . onStatus ( id , Media . MEDIA_STATE , Media . MEDIA_RUNNING ) ; } ; thisM . node . ondurationchange = function ( e ) { Media . onStatus ( id , Media . MEDIA_DURATION , e . target . duration || - 1 ) ; } ; thisM . node . onerror = function ( e ) { // Due to media.spec.15 It should return MediaError for bad filename var err = e . target . error . code === MediaError . MEDIA_ERR_SRC_NOT_SUPPORTED ? { code : MediaError . MEDIA_ERR_ABORTED } : e . target . error ; Media . onStatus ( id , Media . MEDIA_ERROR , err ) ; } ; thisM . node . onended = function ( ) { Media . onStatus ( id , Media . MEDIA_STATE , Media . MEDIA_STOPPED ) ; } ; } } return true ; // successfully created }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start playing the audio [CODESPLIT] function ( win , lose , args ) { var id = args [ 0 ] ; //var src = args[1]; //var options = args[2]; var thisM = Media . get ( id ) ; // if Media was released, then node will be null and we need to create it again if ( ! thisM . node ) { args [ 2 ] = true ; // Setting createAudioNode to true if ( ! module . exports . create ( win , lose , args ) ) { // there is no reason to continue if we can't create media // corresponding callback has been invoked in create so we don't need to call it here return ; } } try { thisM . node . play ( ) ; } catch ( err ) { if ( lose ) { lose ( { code : MediaError . MEDIA_ERR_ABORTED } ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Seeks to the position in the audio [CODESPLIT] function ( win , lose , args ) { var id = args [ 0 ] ; var milliseconds = args [ 1 ] ; var thisM = Media . get ( id ) ; try { thisM . node . currentTime = milliseconds / 1000 ; win ( thisM . node . currentTime ) ; } catch ( err ) { lose ( \"Failed to seek: \" + err ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pauses the playing audio [CODESPLIT] function ( win , lose , args ) { var id = args [ 0 ] ; var thisM = Media . get ( id ) ; try { thisM . node . pause ( ) ; Media . onStatus ( id , Media . MEDIA_STATE , Media . MEDIA_PAUSED ) ; } catch ( err ) { lose ( \"Failed to pause: \" + err ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets current position in the audio [CODESPLIT] function ( win , lose , args ) { var id = args [ 0 ] ; try { var p = ( Media . get ( id ) ) . node . currentTime ; win ( p ) ; } catch ( err ) { lose ( err ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start recording audio [CODESPLIT] function ( win , lose , args ) { var id = args [ 0 ] ; var srcUri = processUri ( args [ 1 ] ) ; var dest = parseUriToPathAndFilename ( srcUri ) ; var destFileName = dest . fileName ; var success = function ( ) { Media . onStatus ( id , Media . MEDIA_STATE , Media . MEDIA_RUNNING ) ; } ; var error = function ( reason ) { Media . onStatus ( id , Media . MEDIA_ERROR , reason ) ; } ; // Initialize device Media . prototype . mediaCaptureMgr = null ; var thisM = ( Media . get ( id ) ) ; var captureInitSettings = new Windows . Media . Capture . MediaCaptureInitializationSettings ( ) ; captureInitSettings . streamingCaptureMode = Windows . Media . Capture . StreamingCaptureMode . audio ; thisM . mediaCaptureMgr = new Windows . Media . Capture . MediaCapture ( ) ; thisM . mediaCaptureMgr . addEventListener ( \"failed\" , error ) ; thisM . mediaCaptureMgr . initializeAsync ( captureInitSettings ) . done ( function ( result ) { thisM . mediaCaptureMgr . addEventListener ( \"recordlimitationexceeded\" , error ) ; thisM . mediaCaptureMgr . addEventListener ( \"failed\" , error ) ; // Start recording Windows . Storage . ApplicationData . current . temporaryFolder . createFileAsync ( destFileName , Windows . Storage . CreationCollisionOption . replaceExisting ) . done ( function ( newFile ) { recordedFile = newFile ; var encodingProfile = null ; switch ( newFile . fileType ) { case '.m4a' : encodingProfile = Windows . Media . MediaProperties . MediaEncodingProfile . createM4a ( Windows . Media . MediaProperties . AudioEncodingQuality . auto ) ; break ; case '.mp3' : encodingProfile = Windows . Media . MediaProperties . MediaEncodingProfile . createMp3 ( Windows . Media . MediaProperties . AudioEncodingQuality . auto ) ; break ; case '.wma' : encodingProfile = Windows . Media . MediaProperties . MediaEncodingProfile . createWma ( Windows . Media . MediaProperties . AudioEncodingQuality . auto ) ; break ; default : error ( \"Invalid file type for record\" ) ; break ; } thisM . mediaCaptureMgr . startRecordToStorageFileAsync ( encodingProfile , newFile ) . done ( success , error ) ; } , error ) ; } , error ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop recording audio [CODESPLIT] function ( win , lose , args ) { var id = args [ 0 ] ; var thisM = Media . get ( id ) ; var srcUri = processUri ( thisM . src ) ; var dest = parseUriToPathAndFilename ( srcUri ) ; var destPath = dest . path ; var destFileName = dest . fileName ; var fsType = dest . fsType ; var success = function ( ) { Media . onStatus ( id , Media . MEDIA_STATE , Media . MEDIA_STOPPED ) ; } ; var error = function ( reason ) { Media . onStatus ( id , Media . MEDIA_ERROR , reason ) ; } ; thisM . mediaCaptureMgr . stopRecordAsync ( ) . done ( function ( ) { if ( fsType === fsTypes . TEMPORARY ) { if ( ! destPath ) { // if path is not defined, we leave recorded file in temporary folder (similar to iOS) success ( ) ; } else { Windows . Storage . ApplicationData . current . temporaryFolder . getFolderAsync ( destPath ) . done ( function ( destFolder ) { recordedFile . copyAsync ( destFolder , destFileName , Windows . Storage . CreationCollisionOption . replaceExisting ) . done ( success , error ) ; } , error ) ; } } else { // Copying file to persistent storage if ( ! destPath ) { recordedFile . copyAsync ( Windows . Storage . ApplicationData . current . localFolder , destFileName , Windows . Storage . CreationCollisionOption . replaceExisting ) . done ( success , error ) ; } else { Windows . Storage . ApplicationData . current . localFolder . getFolderAsync ( destPath ) . done ( function ( destFolder ) { recordedFile . copyAsync ( destFolder , destFileName , Windows . Storage . CreationCollisionOption . replaceExisting ) . done ( success , error ) ; } , error ) ; } } } , error ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Release the media object [CODESPLIT] function ( win , lose , args ) { var id = args [ 0 ] ; var thisM = Media . get ( id ) ; try { if ( thisM . node ) { thisM . node . onloadedmetadata = null ; // Unsubscribing as the media object is being released thisM . node . onerror = null ; // Needed to avoid \"0x80070005 - JavaScript runtime error: Access is denied.\" on copyAsync thisM . node . src = null ; delete thisM . node ; } } catch ( err ) { lose ( \"Failed to release: \" + err ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a path to Windows . Foundation . Uri basing on App data temporary folder if scheme is not defined e . g . : path / to / file . m4a - > ms - appdata : /// temp / path / to / file . m4a [CODESPLIT] function setTemporaryFsByDefault ( src ) { var uri ; try { uri = new Windows . Foundation . Uri ( src ) ; } catch ( e ) { if ( e . number === PARAMETER_IS_INCORRECT ) { // Use TEMPORARY fs there is no 'scheme:' uri = new Windows . Foundation . Uri ( tempFolderAppDataBasePath , src ) ; } else { throw e ; } } finally { return uri ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert native full path to ms - appdata path [CODESPLIT] function fullPathToAppData ( uri ) { if ( uri . schemeName === 'file' ) { if ( uri . rawUri . indexOf ( Windows . Storage . ApplicationData . current . localFolder . path ) !== - 1 ) { // Also remove path' beginning slash to avoid losing folder name part uri = new Windows . Foundation . Uri ( localFolderAppDataBasePath , uri . rawUri . replace ( localFolderFullPath , '' ) . replace ( / ^[\\\\\\/]{1,2} / , '' ) ) ; } else if ( uri . rawUri . indexOf ( Windows . Storage . ApplicationData . current . temporaryFolder . path ) !== - 1 ) { uri = new Windows . Foundation . Uri ( tempFolderAppDataBasePath , uri . rawUri . replace ( tempFolderFullPath , '' ) . replace ( / ^[\\\\\\/]{1,2} / , '' ) ) ; } else { throw new Error ( 'Not supported file uri: ' + uri . rawUri ) ; } } return uri ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts cdvfile paths to ms - appdata path [CODESPLIT] function cdvfileToAppData ( uri ) { var cdvFsRoot ; if ( uri . schemeName === 'cdvfile' ) { cdvFsRoot = uri . path . split ( '/' ) [ 1 ] ; if ( cdvFsRoot === 'temporary' ) { return new Windows . Foundation . Uri ( tempFolderAppDataBasePath , uri . path . split ( '/' ) . slice ( 2 ) . join ( '/' ) ) ; } else if ( cdvFsRoot === 'persistent' ) { return new Windows . Foundation . Uri ( localFolderAppDataBasePath , uri . path . split ( '/' ) . slice ( 2 ) . join ( '/' ) ) ; } else { throw new Error ( cdvFsRoot + ' cdvfile root is not supported on Windows' ) ; } } return uri ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares media src for internal usage [CODESPLIT] function processUri ( src ) { // Collapse double slashes (File plugin issue): ms-appdata:///temp//recs/memos/media.m4a => ms-appdata:///temp/recs/memos/media.m4a src = src . replace ( / ([^\\/:])(\\/\\/)([^\\/]) / g , '$1/$3' ) ; // Remove beginning slashes src = src . replace ( / ^[\\\\\\/]{1,2} / , '' ) ; var uri = setTemporaryFsByDefault ( src ) ; uri = fullPathToAppData ( uri ) ; uri = cdvfileToAppData ( uri ) ; return uri ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts path filename and filesystem type from Uri [CODESPLIT] function parseUriToPathAndFilename ( uri ) { // Removing scheme and location, using backslashes: ms-appdata:///local/path/to/file.m4a -> path\\\\to\\\\file.m4a var normalizedSrc = uri . path . split ( '/' ) . slice ( 2 ) . join ( '\\\\' ) ; var path = normalizedSrc . substr ( 0 , normalizedSrc . lastIndexOf ( '\\\\' ) ) ; var fileName = normalizedSrc . replace ( path + '\\\\' , '' ) ; var fsType ; if ( uri . path . split ( '/' ) [ 1 ] === 'local' ) { fsType = fsTypes . PERSISTENT ; } else if ( uri . path . split ( '/' ) [ 1 ] === 'temp' ) { fsType = fsTypes . TEMPORARY ; } return { path : path , fileName : fileName , fsType : fsType } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This class provides access to the device media interfaces to both sound and video [CODESPLIT] function ( src , successCallback , errorCallback , statusCallback ) { argscheck . checkArgs ( 'sFFF' , 'Media' , arguments ) ; this . id = utils . createUUID ( ) ; mediaObjects [ this . id ] = this ; this . src = src ; this . successCallback = successCallback ; this . errorCallback = errorCallback ; this . statusCallback = statusCallback ; this . _duration = - 1 ; this . _position = - 1 ; exec ( null , this . errorCallback , \"Media\" , \"create\" , [ this . id , this . src ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * proj [CODESPLIT] function proj ( location ) { // Class to handle simple project xml operations if ( ! location ) { throw new Error ( 'Project file location can\\'t be null or empty' ) ; } this . location = location ; this . xml = xml_helpers . parseElementtreeSync ( location ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates hook script context [CODESPLIT] function Context ( hook , opts ) { this . hook = hook ; // create new object, to avoid affecting input opts in other places // For example context.opts.plugin = Object is done, then it affects by reference this . opts = Object . assign ( { } , opts ) ; this . cmdLine = process . argv . join ( ' ' ) ; // Lazy-load cordova to avoid cyclical dependency Object . defineProperty ( this , 'cordova' , { get ( ) { return this . requireCordovaModule ( 'cordova-lib' ) . cordova ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove capabilities with same names [CODESPLIT] function getUniqueCapabilities ( capabilities ) { return capabilities . reduce ( function ( uniqueCaps , currCap ) { var isRepeated = uniqueCaps . some ( function ( cap ) { return getCapabilityName ( cap ) === getCapabilityName ( currCap ) ; } ) ; return isRepeated ? uniqueCaps : uniqueCaps . concat ( [ currCap ] ) ; } , [ ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Comparator function to pass to Array . sort [CODESPLIT] function compareCapabilities ( firstCap , secondCap ) { var firstCapName = getCapabilityName ( firstCap ) ; var secondCapName = getCapabilityName ( secondCap ) ; if ( firstCapName < secondCapName ) { return - 1 ; } if ( firstCapName > secondCapName ) { return 1 ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a new munge that contains <uap : Capability > elements created based on corresponding <Capability > elements from base munge . If there are no such elements found in base munge the empty munge is returned ( selectors might be present under the parents key but they will contain no changes ) . [CODESPLIT] function generateUapCapabilities ( capabilities ) { function hasCapabilityChange ( change ) { return / ^\\s*<(\\w+:)?(Device)?Capability\\s / . test ( change . xml ) ; } function createPrefixedCapabilityChange ( change ) { if ( CapsNeedUapPrefix . indexOf ( getCapabilityName ( change ) ) < 0 ) { return change ; } //  If capability is already prefixed, avoid adding another prefix var replaceXML = change . xml . indexOf ( 'uap:' ) > 0 ? change . xml : change . xml . replace ( / Capability / , 'uap:Capability' ) ; return { xml : replaceXML , count : change . count , before : change . before } ; } return capabilities // For every xml change check if it adds a <Capability> element ... . filter ( hasCapabilityChange ) // ... and create a duplicate with 'uap:' prefix . map ( createPrefixedCapabilityChange ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove <platform > . json file from plugins directory . [CODESPLIT] function removePlatformPluginsJson ( projectRoot , target ) { var plugins_json = path . join ( projectRoot , 'plugins' , target + '.json' ) ; fs . removeSync ( plugins_json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs up the directory chain looking for a . cordova directory . IF it is found we are in a Cordova project . Omit argument to use CWD . [CODESPLIT] function isCordova ( dir ) { if ( ! dir ) { // Prefer PWD over cwd so that symlinked dirs within your PWD work correctly (CB-5687). var pwd = process . env . PWD ; var cwd = process . cwd ( ) ; if ( pwd && pwd !== cwd && pwd !== 'undefined' ) { return this . isCordova ( pwd ) || this . isCordova ( cwd ) ; } return this . isCordova ( cwd ) ; } var bestReturnValueSoFar = false ; for ( var i = 0 ; i < 1000 ; ++ i ) { var result = isRootDir ( dir ) ; if ( result === 2 ) { return dir ; } if ( result === 1 ) { bestReturnValueSoFar = dir ; } var parentDir = path . normalize ( path . join ( dir , '..' ) ) ; // Detect fs root. if ( parentDir === dir ) { return bestReturnValueSoFar ; } dir = parentDir ; } console . error ( 'Hit an unhandled case in util.isCordova' ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cd to project root dir and return its path . Throw CordovaError if not in a Corodva project . [CODESPLIT] function cdProjectRoot ( ) { const projectRoot = this . getProjectRoot ( ) ; if ( ! origCwd ) { origCwd = process . env . PWD || process . cwd ( ) ; } process . env . PWD = projectRoot ; process . chdir ( projectRoot ) ; return projectRoot ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fixes up relative paths that are no longer valid due to chdir () within cdProjectRoot () . [CODESPLIT] function fixRelativePath ( value , /* optional */ cwd ) { // Don't touch absolute paths. if ( value [ 1 ] === ':' || value [ 0 ] === path . sep ) { return value ; } var newDir = cwd || process . env . PWD || process . cwd ( ) ; var origDir = getOrigWorkingDirectory ( ) ; var pathDiff = path . relative ( newDir , origDir ) ; var ret = path . normalize ( path . join ( pathDiff , value ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve any symlinks in order to avoid relative path issues . See https : // issues . apache . org / jira / browse / CB - 8757 [CODESPLIT] function convertToRealPathSafe ( path ) { if ( path && fs . existsSync ( path ) ) { return fs . realpathSync ( path ) ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively deletes . svn folders from a target path [CODESPLIT] function deleteSvnFolders ( dir ) { var contents = fs . readdirSync ( dir ) ; contents . forEach ( function ( entry ) { var fullpath = path . join ( dir , entry ) ; if ( isDirectory ( fullpath ) ) { if ( entry === '.svn' ) { fs . removeSync ( fullpath ) ; } else module . exports . deleteSvnFolders ( fullpath ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "list the directories in the path ignoring any files [CODESPLIT] function findPlugins ( pluginDir ) { var plugins = [ ] ; if ( fs . existsSync ( pluginDir ) ) { plugins = fs . readdirSync ( pluginDir ) . filter ( function ( fileName ) { var pluginPath = path . join ( pluginDir , fileName ) ; var isPlugin = isDirectory ( pluginPath ) || isSymbolicLink ( pluginPath ) ; return fileName !== '.svn' && fileName !== 'CVS' && isPlugin ; } ) ; } return plugins ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the API of the platform contained in dir . Potential errors : module isn t found can t load or doesn t implement the expected interface . [CODESPLIT] function getPlatformApiFunction ( dir ) { let PlatformApi ; try { PlatformApi = exports . requireNoCache ( dir ) ; } catch ( err ) { // Module not found or threw error during loading err . message = ` ${ dir } \\n ${ err . message } ` ; throw err ; } // Module doesn't implement the expected interface if ( ! PlatformApi || ! PlatformApi . createPlatform ) { throw new Error ( ` ${ dir } ` ) ; } events . emit ( 'verbose' , 'Platform API successfully found in: ' + dir ) ; return PlatformApi ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downloads via npm or via git clone ( tries both ) Returns a Promise [CODESPLIT] function downloadPlatform ( projectRoot , platform , version , opts ) { var target = version ? ( platform + '@' + version ) : platform ; return Promise . resolve ( ) . then ( function ( ) { // append cordova to platform if ( platform in platforms ) { target = 'cordova-' + target ; } // gitURLs don't supply a platform, it equals null if ( ! platform ) { target = version ; } events . emit ( 'log' , 'Using cordova-fetch for ' + target ) ; return fetch ( target , projectRoot , opts ) ; } ) . catch ( function ( error ) { var message = 'Failed to fetch platform ' + target + '\\nProbably this is either a connection problem, or platform spec is incorrect.' + '\\nCheck your connection and platform name/version/URL.' + '\\n' + error ; return Promise . reject ( new CordovaError ( message ) ) ; } ) . then ( function ( libDir ) { return require ( './index' ) . getPlatformDetailsFromDir ( libDir , platform ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to create a HooksRunner for passed project root . [CODESPLIT] function HooksRunner ( projectRoot ) { var root = cordovaUtil . isCordova ( projectRoot ) ; if ( ! root ) throw new CordovaError ( 'Not a Cordova project (\"' + projectRoot + '\"), can\\'t use hooks.' ) ; else this . projectRoot = root ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a promise . [CODESPLIT] function executeEventHandlersSerially ( hook , opts ) { var handlers = events . listeners ( hook ) ; if ( handlers . length ) { // Chain the handlers in series. return handlers . reduce ( function ( soFar , f ) { return soFar . then ( function ( ) { return f ( opts ) ; } ) ; } , Promise . resolve ( ) ) ; } else { return Promise . resolve ( ) ; // Nothing to do. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serially fires scripts either via Promise . resolve ( require ( pathToScript ) ( context )) or via child_process . spawn . Returns promise . [CODESPLIT] function runScriptsSerially ( scripts , context ) { if ( scripts . length === 0 ) { events . emit ( 'verbose' , 'No scripts found for hook \"' + context . hook + '\".' ) ; } return scripts . reduce ( function ( prevScriptPromise , nextScript ) { return prevScriptPromise . then ( function ( ) { return runScript ( nextScript , context ) ; } ) ; } , Promise . resolve ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts shebang interpreter from script source . [CODESPLIT] function extractSheBangInterpreter ( fullpath ) { // this is a modern cluster size. no need to read less const chunkSize = 4096 ; const fileData = readChunk . sync ( fullpath , 0 , chunkSize ) ; const fileChunk = fileData . toString ( ) ; const hookCmd = shebangCommand ( fileChunk ) ; if ( hookCmd && fileData . length === chunkSize && ! fileChunk . match ( / [\\r\\n] / ) ) { events . emit ( 'warn' , 'shebang is too long for \"' + fullpath + '\"' ) ; } return hookCmd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the given hook type is disabled at the command line option . [CODESPLIT] function isHookDisabled ( opts , hook ) { if ( opts === undefined || opts . nohooks === undefined ) { return false ; } var disabledHooks = opts . nohooks ; var length = disabledHooks . length ; for ( var i = 0 ; i < length ; i ++ ) { if ( hook . match ( disabledHooks [ i ] ) !== null ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Install platforms looking at config . xml and package . json ( if there is one ) . [CODESPLIT] function installPlatformsFromConfigXML ( platforms , opts ) { events . emit ( 'verbose' , 'Checking config.xml and package.json for saved platforms that haven\\'t been added to the project' ) ; var projectHome = cordova_util . cdProjectRoot ( ) ; var configPath = cordova_util . projectConfig ( projectHome ) ; var cfg = new ConfigParser ( configPath ) ; var engines = cfg . getEngines ( ) ; var pkgJsonPath = path . join ( projectHome , 'package.json' ) ; var pkgJson ; var pkgJsonPlatforms ; var comboArray = [ ] ; var configPlatforms = [ ] ; var modifiedPkgJson = false ; var mergedPlatformSpecs = { } ; var key ; var installAllPlatforms = ! platforms || platforms . length === 0 ; var file ; var indent ; // Check if path exists and require pkgJsonPath. if ( fs . existsSync ( pkgJsonPath ) ) { pkgJson = require ( pkgJsonPath ) ; file = fs . readFileSync ( pkgJsonPath , 'utf8' ) ; indent = detectIndent ( file ) . indent || '  ' ; } if ( pkgJson !== undefined && pkgJson . cordova !== undefined && pkgJson . cordova . platforms !== undefined ) { pkgJsonPlatforms = pkgJson . cordova . platforms ; } if ( cfg !== undefined ) { if ( pkgJsonPlatforms !== undefined ) { // Combining arrays and checking duplicates. comboArray = pkgJsonPlatforms . slice ( ) ; } engines = cfg . getEngines ( projectHome ) ; // TODO: CB-12592: Eventually refactor out to pacakge manager module. // If package.json doesn't exist, auto-create one. if ( engines . length > 0 && pkgJson === undefined ) { pkgJson = { } ; if ( cfg . packageName ( ) ) { pkgJson . name = cfg . packageName ( ) . toLowerCase ( ) ; } if ( cfg . version ( ) ) { pkgJson . version = cfg . version ( ) ; } if ( cfg . name ( ) ) { pkgJson . displayName = cfg . name ( ) ; } fs . writeFileSync ( pkgJsonPath , JSON . stringify ( pkgJson , null , indent ) , 'utf8' ) ; } configPlatforms = engines . map ( function ( Engine ) { var configPlatName = Engine . name ; // Add specs from config into mergedPlatformSpecs. if ( mergedPlatformSpecs [ configPlatName ] === undefined && Engine . spec ) { mergedPlatformSpecs [ configPlatName ] = Engine . spec ; } return configPlatName ; } ) ; configPlatforms . forEach ( function ( item ) { if ( comboArray . indexOf ( item ) < 0 ) { comboArray . push ( item ) ; } } ) ; // ComboArray should have all platforms from config.xml & package.json. // Remove duplicates in comboArray & sort. var uniq = comboArray . reduce ( function ( a , b ) { if ( a . indexOf ( b ) < 0 ) a . push ( b ) ; return a ; } , [ ] ) ; comboArray = uniq ; // No platforms to restore from either config.xml or package.json. if ( comboArray . length <= 0 ) { return Promise . resolve ( 'No platforms found in config.xml or package.json. Nothing to restore' ) ; } // If no package.json, don't continue. if ( pkgJson !== undefined ) { // If config.xml & pkgJson exist and the cordova key is undefined, create a cordova key. if ( pkgJson . cordova === undefined ) { pkgJson . cordova = { } ; } // If there is no platforms array, create an empty one. if ( pkgJson . cordova . platforms === undefined ) { pkgJson . cordova . platforms = [ ] ; } // If comboArray has the same platforms as pkg.json, no modification to pkg.json. if ( comboArray . toString ( ) === pkgJson . cordova . platforms . toString ( ) ) { events . emit ( 'verbose' , 'Config.xml and package.json platforms are the same. No pkg.json modification.' ) ; } else { // Modify pkg.json to include the elements. // From the comboArray array so that the arrays are identical. events . emit ( 'verbose' , 'Config.xml and package.json platforms are different. Updating package.json with most current list of platforms.' ) ; modifiedPkgJson = true ; } events . emit ( 'verbose' , 'Package.json and config.xml platforms are different. Updating config.xml with most current list of platforms.' ) ; comboArray . forEach ( function ( item ) { var prefixItem = ( 'cordova-' + item ) ; // Modify package.json if any of these cases are true: if ( ( pkgJson . dependencies === undefined && Object . keys ( mergedPlatformSpecs ) . length ) || ( pkgJson . dependencies && mergedPlatformSpecs && pkgJson . dependencies [ item ] === undefined && mergedPlatformSpecs [ item ] ) || ( pkgJson . dependencies && mergedPlatformSpecs && pkgJson . dependencies [ prefixItem ] === undefined && mergedPlatformSpecs [ prefixItem ] ) ) { modifiedPkgJson = true ; } // Get the cordova- prefixed spec from package.json and add it to mergedPluginSpecs. if ( pkgJson . dependencies && pkgJson . dependencies [ prefixItem ] ) { if ( mergedPlatformSpecs [ prefixItem ] !== pkgJson . dependencies [ prefixItem ] ) { modifiedPkgJson = true ; } mergedPlatformSpecs [ item ] = pkgJson . dependencies [ prefixItem ] ; } // Get the spec from package.json and add it to mergedPluginSpecs. if ( pkgJson . dependencies && pkgJson . dependencies [ item ] && pkgJson . dependencies [ prefixItem ] === undefined ) { if ( mergedPlatformSpecs [ item ] !== pkgJson . dependencies [ item ] ) { modifiedPkgJson = true ; } mergedPlatformSpecs [ item ] = pkgJson . dependencies [ item ] ; } } ) ; } // Write and update pkg.json if it has been modified. if ( modifiedPkgJson === true ) { pkgJson . cordova . platforms = comboArray ; if ( pkgJson . dependencies === undefined ) { pkgJson . dependencies = { } ; } // Check if key is part of cordova alias list. // Add prefix if it is. for ( key in mergedPlatformSpecs ) { var prefixKey = key ; if ( key in platformsList ) { prefixKey = 'cordova-' + key ; } pkgJson . dependencies [ prefixKey ] = mergedPlatformSpecs [ key ] ; } fs . writeFileSync ( pkgJsonPath , JSON . stringify ( pkgJson , null , indent ) , 'utf8' ) ; } if ( ! comboArray || ! comboArray . length ) { return Promise . resolve ( 'No platforms found in config.xml and/or package.json that haven\\'t been added to the project' ) ; } } // Run `platform add` for all the platforms separately // so that failure on one does not affect the other. // CB-9278 : Run `platform add` serially, one platform after another // Otherwise, we get a bug where the following line: https://github.com/apache/cordova-lib/blob/0b0dee5e403c2c6d4e7262b963babb9f532e7d27/cordova-lib/src/util/npm-helper.js#L39 // gets executed simultaneously by each platform and leads to an exception being thrown return promiseutil . Q_chainmap_graceful ( comboArray , function ( target ) { var cwd = process . cwd ( ) ; var platformsFolderPath = path . join ( cwd , 'platforms' ) ; var platformsInstalled = path . join ( platformsFolderPath , target ) ; if ( target ) { var platformName = target ; // Add the spec to the target if ( mergedPlatformSpecs [ target ] ) { target = target + '@' + mergedPlatformSpecs [ target ] ; } // If the platform is already installed, no need to re-install it. if ( ! fs . existsSync ( platformsInstalled ) && ( installAllPlatforms || platforms . indexOf ( platformName ) > - 1 ) ) { events . emit ( 'log' , 'Discovered platform \"' + target + '\" in config.xml or package.json. Adding it to the project' ) ; return cordovaPlatform ( 'add' , target , opts ) ; } } return Promise . resolve ( ) ; } , function ( err ) { events . emit ( 'warn' , err ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a promise . [CODESPLIT] function installPluginsFromConfigXML ( args ) { events . emit ( 'verbose' , 'Checking for saved plugins that haven\\'t been added to the project' ) ; const projectRoot = cordova_util . getProjectRoot ( ) ; const pluginsRoot = path . join ( projectRoot , 'plugins' ) ; const pkgJsonPath = path . join ( projectRoot , 'package.json' ) ; const confXmlPath = cordova_util . projectConfig ( projectRoot ) ; let pkgJson = { } ; let indent = '  ' ; if ( fs . existsSync ( pkgJsonPath ) ) { const fileData = fs . readFileSync ( pkgJsonPath , 'utf8' ) ; indent = detectIndent ( fileData ) . indent ; pkgJson = JSON . parse ( fileData ) ; } pkgJson . devDependencies = pkgJson . devDependencies || { } ; pkgJson . cordova = pkgJson . cordova || { } ; pkgJson . cordova . plugins = pkgJson . cordova . plugins || { } ; const pkgPluginIDs = Object . keys ( pkgJson . cordova . plugins ) ; const pkgSpecs = Object . assign ( { } , pkgJson . dependencies , pkgJson . devDependencies ) ; // Check for plugins listed in config.xml const cfg = new ConfigParser ( confXmlPath ) ; const cfgPluginIDs = cfg . getPluginIdList ( ) ; cfgPluginIDs . forEach ( plID => { // If package.json includes the plugin, we use that config // Otherwise, we need to add the plugin to package.json if ( ! pkgPluginIDs . includes ( plID ) ) { events . emit ( 'info' , ` ${ plID } ` ) ; const cfgPlugin = cfg . getPlugin ( plID ) ; // If config.xml has a spec for the plugin and package.json has not, // add the spec to devDependencies of package.json if ( cfgPlugin . spec && ! ( plID in pkgSpecs ) ) { pkgJson . devDependencies [ plID ] = cfgPlugin . spec ; } pkgJson . cordova . plugins [ plID ] = Object . assign ( { } , cfgPlugin . variables ) ; } } ) ; // Now that plugins have been updated, re-fetch them from package.json const pluginIDs = Object . keys ( pkgJson . cordova . plugins ) ; if ( pluginIDs . length !== pkgPluginIDs . length ) { // We've modified package.json and need to save it fs . outputJsonSync ( pkgJsonPath , pkgJson , { indent : indent , encoding : 'utf8' } ) ; } const specs = Object . assign ( { } , pkgJson . dependencies , pkgJson . devDependencies ) ; const plugins = pluginIDs . map ( plID => ( { name : plID , spec : specs [ plID ] , variables : pkgJson . cordova . plugins [ plID ] || { } } ) ) ; let pluginName = '' ; // CB-9560 : Run `plugin add` serially, one plugin after another // We need to wait for the plugin and its dependencies to be installed // before installing the next root plugin otherwise we can have common // plugin dependencies installed twice which throws a nasty error. return promiseutil . Q_chainmap_graceful ( plugins , function ( pluginConfig ) { pluginName = pluginConfig . name ; const pluginPath = path . join ( pluginsRoot , pluginName ) ; if ( fs . existsSync ( pluginPath ) ) { // Plugin already exists return Promise . resolve ( ) ; } events . emit ( 'log' , ` ${ pluginName } ` ) ; // Install from given URL if defined or using a plugin id. If spec isn't a valid version or version range, // assume it is the location to install from. // CB-10761 If plugin spec is not specified, use plugin name var installFrom = pluginConfig . spec || pluginName ; if ( pluginConfig . spec && semver . validRange ( pluginConfig . spec , true ) ) { installFrom = pluginName + '@' + pluginConfig . spec ; } // Add feature preferences as CLI variables if have any var options = { cli_variables : pluginConfig . variables , searchpath : args . searchpath , save : args . save || false } ; const plugin = require ( './plugin' ) ; return plugin ( 'add' , installFrom , options ) ; } , function ( error ) { // CB-10921 emit a warning in case of error var msg = 'Failed to restore plugin \"' + pluginName + '\" from config.xml. ' + 'You might need to try adding it again. Error: ' + error ; process . exitCode = 1 ; events . emit ( 'warn' , msg ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cordova - js [CODESPLIT] function ( ) { var modulemapper = require ( 'cordova/modulemapper' ) ; var channel = require ( 'cordova/channel' ) ; modulemapper . clobbers ( 'cordova/exec/proxy' , 'cordova.commandProxy' ) ; channel . onNativeReady . fire ( ) ; document . addEventListener ( \"visibilitychange\" , function ( ) { if ( document . hidden ) { channel . onPause . fire ( ) ; } else { channel . onResume . fire ( ) ; } } ) ; // End of bootstrap }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // issues . apache . org / jira / browse / CB - 11274 Use referer url to redirect absolute urls to the requested platform resources so that an URL is resolved against that platform www directory . [CODESPLIT] function absolutePathHandler ( request , response , next ) { if ( ! request . headers . referer ) return next ( ) ; // @todo Use 'url.URL' constructor instead since 'url.parse' was deprecated since v11.0.0 const { pathname } = url . parse ( request . headers . referer ) ; // eslint-disable-line const platform = pathname . split ( '/' ) [ 1 ] ; if ( installedPlatforms . includes ( platform ) && ! request . originalUrl . includes ( platform ) ) { response . redirect ( ` ${ platform } ` + request . originalUrl ) ; } else { next ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all script files for the hook type specified . [CODESPLIT] function ( hook , opts ) { // args check if ( ! hook ) { throw new Error ( 'hook type is not specified' ) ; } return getApplicationHookScripts ( hook , opts ) . concat ( getPluginsHookScripts ( hook , opts ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns script files defined on application level . They are stored in . cordova / hooks folders and in config . xml . [CODESPLIT] function getApplicationHookScripts ( hook , opts ) { // args check if ( ! hook ) { throw new Error ( 'hook type is not specified' ) ; } return getApplicationHookScriptsFromDir ( path . join ( opts . projectRoot , '.cordova' , 'hooks' , hook ) ) . concat ( getApplicationHookScriptsFromDir ( path . join ( opts . projectRoot , 'hooks' , hook ) ) ) . concat ( getScriptsFromConfigXml ( hook , opts ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns script files defined by plugin developers as part of plugin . xml . [CODESPLIT] function getPluginsHookScripts ( hook , opts ) { // args check if ( ! hook ) { throw new Error ( 'hook type is not specified' ) ; } // In case before_plugin_install, after_plugin_install, before_plugin_uninstall hooks we receive opts.plugin and // retrieve scripts exclusive for this plugin. if ( opts . plugin ) { events . emit ( 'verbose' , 'Finding scripts for \"' + hook + '\" hook from plugin ' + opts . plugin . id + ' on ' + opts . plugin . platform + ' platform only.' ) ; // if plugin hook is not run for specific platform then use all available platforms return getPluginScriptFiles ( opts . plugin , hook , opts . plugin . platform ? [ opts . plugin . platform ] : opts . cordova . platforms ) ; } return getAllPluginsHookScriptFiles ( hook , opts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets application level hooks from the directrory specified . [CODESPLIT] function getApplicationHookScriptsFromDir ( dir ) { if ( ! ( fs . existsSync ( dir ) ) ) { return [ ] ; } var compareNumbers = function ( a , b ) { // TODO SG looks very complex, do we really need this? return isNaN ( parseInt ( a , 10 ) ) ? a . toLowerCase ( ) . localeCompare ( b . toLowerCase ? b . toLowerCase ( ) : b ) : parseInt ( a , 10 ) > parseInt ( b , 10 ) ? 1 : parseInt ( a , 10 ) < parseInt ( b , 10 ) ? - 1 : 0 ; } ; var scripts = fs . readdirSync ( dir ) . sort ( compareNumbers ) . filter ( function ( s ) { return s [ 0 ] !== '.' ; } ) ; return scripts . map ( function ( scriptPath ) { // for old style hook files we don't use module loader for backward compatibility return { path : scriptPath , fullPath : path . join ( dir , scriptPath ) , useModuleLoader : false } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets all scripts defined in config . xml with the specified type and platforms . [CODESPLIT] function getScriptsFromConfigXml ( hook , opts ) { var configPath = cordovaUtil . projectConfig ( opts . projectRoot ) ; var configXml = new ConfigParser ( configPath ) ; return configXml . getHookScripts ( hook , opts . cordova . platforms ) . map ( function ( scriptElement ) { return { path : scriptElement . attrib . src , fullPath : path . join ( opts . projectRoot , scriptElement . attrib . src ) } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets hook scripts defined by the plugin . [CODESPLIT] function getPluginScriptFiles ( plugin , hook , platforms ) { var scriptElements = plugin . pluginInfo . getHookScripts ( hook , platforms ) ; return scriptElements . map ( function ( scriptElement ) { return { path : scriptElement . attrib . src , fullPath : path . join ( plugin . dir , scriptElement . attrib . src ) , plugin : plugin } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets hook scripts defined by all plugins . [CODESPLIT] function getAllPluginsHookScriptFiles ( hook , opts ) { var scripts = [ ] ; var currentPluginOptions ; var plugins = ( new PluginInfoProvider ( ) ) . getAllWithinSearchPath ( path . join ( opts . projectRoot , 'plugins' ) ) ; plugins . forEach ( function ( pluginInfo ) { currentPluginOptions = { id : pluginInfo . id , pluginInfo : pluginInfo , dir : pluginInfo . dir } ; scripts = scripts . concat ( getPluginScriptFiles ( currentPluginOptions , hook , opts . cordova . platforms ) ) ; } ) ; return scripts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@constructor @constructs AppxManifest [CODESPLIT] function AppxManifest ( path , prefix ) { this . path = path ; // Append ':' to prefix if needed prefix = prefix || '' ; this . prefix = ( prefix . indexOf ( ':' ) === prefix . length - 1 ) ? prefix : prefix + ':' ; this . doc = xml . parseElementtreeSync ( path ) ; if ( this . doc . getroot ( ) . tag !== 'Package' ) { // Some basic validation throw new Error ( path + ' has incorrect root node name (expected \"Package\")' ) ; } // Indicates that this manifest is for phone application (either WinPhone 8.1 or Universal Windows 10) this . hasPhoneIdentity = this . prefix === 'uap:' || this . prefix === 'm3:' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks for capabilities which require the uap : prefix in Windows 10 . [CODESPLIT] function ensureUapPrefixedCapabilities ( capabilities ) { capabilities . getchildren ( ) . forEach ( function ( el ) { if ( CAPS_NEEDING_UAPNS . indexOf ( el . attrib . Name ) > - 1 && el . tag . indexOf ( 'uap:' ) !== 0 ) { el . tag = 'uap:' + el . tag ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleans up duplicate capability declarations that were generated during the prepare process [CODESPLIT] function ensureUniqueCapabilities ( capabilities ) { var uniqueCapabilities = [ ] ; capabilities . getchildren ( ) . forEach ( function ( el ) { var name = el . attrib . Name ; if ( uniqueCapabilities . indexOf ( name ) !== - 1 ) { capabilities . remove ( el ) ; } else { uniqueCapabilities . push ( name ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Merges cli and config . xml variables . [CODESPLIT] function mergeVariables ( pluginInfo , cfg , opts ) { // Validate top-level required variables var pluginVariables = pluginInfo . getPreferences ( ) ; opts . cli_variables = opts . cli_variables || { } ; var pluginEntry = cfg . getPlugin ( pluginInfo . id ) ; // Get variables from config.xml var configVariables = pluginEntry ? pluginEntry . variables : { } ; // Add config variable if it's missing in cli_variables Object . keys ( configVariables ) . forEach ( function ( variable ) { opts . cli_variables [ variable ] = opts . cli_variables [ variable ] || configVariables [ variable ] ; } ) ; var missingVariables = Object . keys ( pluginVariables ) . filter ( function ( variableName ) { // discard variables with default value return ! ( pluginVariables [ variableName ] || opts . cli_variables [ variableName ] ) ; } ) ; if ( missingVariables . length ) { events . emit ( 'verbose' , 'Removing ' + pluginInfo . dir + ' because mandatory plugin variables were missing.' ) ; fs . removeSync ( pluginInfo . dir ) ; var msg = 'Variable(s) missing (use: --variable ' + missingVariables . join ( '=value --variable ' ) + '=value).' ; throw new CordovaError ( msg ) ; } return opts . cli_variables ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as copy file but throws error if target exists [CODESPLIT] function copyNewFile ( plugin_dir , src , project_dir , dest , link ) { var target_path = path . resolve ( project_dir , dest ) ; if ( fs . existsSync ( target_path ) ) throw new CordovaError ( '\"' + target_path + '\" already exists!' ) ; copyFile ( plugin_dir , src , project_dir , dest , ! ! link ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents a parsed specification for a plugin [CODESPLIT] function PluginSpec ( raw , scope , id , version ) { /** @member {String|null} The npm scope of the plugin spec or null if it does not have one */ this . scope = scope || null ; /** @member {String|null} The id of the plugin or the raw plugin spec if it is not an npm package */ this . id = id || raw ; /** @member {String|null} The specified version of the plugin or null if no version was specified */ this . version = version || null ; /** @member {String|null} The npm package of the plugin (with scope) or null if this is not a spec for an npm package */ this . package = ( scope ? scope + id : id ) || null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to parse the given string as an npm - style package specification of the form ( @scope / ) ?package ( @version ) ? and return the various parts . [CODESPLIT] function parse ( raw ) { var split = NPM_SPEC_REGEX . exec ( raw ) ; if ( split ) { return new PluginSpec ( raw , split [ 1 ] , split [ 2 ] , split [ 3 ] ) ; } return new PluginSpec ( raw ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns relative file path for a file in the plugin s folder that can be referenced from a project file . [CODESPLIT] function getPluginFilePath ( plugin , pluginFile , targetDir ) { var src = path . resolve ( plugin . dir , pluginFile ) ; return '$(ProjectDir)' + path . relative ( targetDir , src ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a function and an array of values creates a chain of promises that will sequentially execute func ( args [ i ] ) . Returns a promise . [CODESPLIT] function Q_chainmap ( args , func ) { return Promise . resolve ( ) . then ( function ( inValue ) { return args . reduce ( function ( soFar , arg ) { return soFar . then ( function ( val ) { return func ( arg , val ) ; } ) ; } , Promise . resolve ( inValue ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles all cordova platform commands . [CODESPLIT] function platform ( command , targets , opts ) { // CB-10519 wrap function code into promise so throwing error // would result in promise rejection instead of uncaught exception return Promise . resolve ( ) . then ( function ( ) { var msg ; var projectRoot = cordova_util . cdProjectRoot ( ) ; var hooksRunner = new HooksRunner ( projectRoot ) ; if ( arguments . length === 0 ) command = 'ls' ; if ( targets && ! ( targets instanceof Array ) ) targets = [ targets ] ; // TODO: wouldn't update need a platform, too? what about save? if ( ( command === 'add' || command === 'rm' || command === 'remove' ) && ( ! targets || ( targets instanceof Array && targets . length === 0 ) ) ) { msg = 'You need to qualify `' + command + '` with one or more platforms!' ; return Promise . reject ( new CordovaError ( msg ) ) ; } opts = opts || { } ; opts . platforms = targets ; switch ( command ) { case 'add' : return module . exports . add ( hooksRunner , projectRoot , targets , opts ) ; case 'rm' : case 'remove' : return module . exports . remove ( hooksRunner , projectRoot , targets , opts ) ; case 'update' : case 'up' : return module . exports . update ( hooksRunner , projectRoot , targets , opts ) ; case 'check' : return module . exports . check ( hooksRunner , projectRoot ) ; default : return module . exports . list ( hooksRunner , projectRoot , opts ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "callbackOptions param represents additional optional parameters command could pass back like keepCallback or custom callbackId for example { callbackId : id keepCallback : true status : cordova . callbackStatus . JSON_EXCEPTION } [CODESPLIT] function ( result , callbackOptions ) { callbackOptions = callbackOptions || { } ; var callbackStatus ; // covering both undefined and null. // strict null comparison was causing callbackStatus to be undefined // and then no callback was called because of the check in cordova.callbackFromNative // see CB-8996 Mobilespec app hang on windows if ( callbackOptions . status !== undefined && callbackOptions . status !== null ) { callbackStatus = callbackOptions . status ; } else { callbackStatus = cordova . callbackStatus . OK ; } cordova . callbackSuccess ( callbackOptions . callbackId || callbackId , { status : callbackStatus , message : result , keepCallback : callbackOptions . keepCallback || false } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all the platforms that are currently saved into config . xml [CODESPLIT] function getPlatforms ( projectRoot ) { var xml = cordova_util . projectConfig ( projectRoot ) ; var cfg = new ConfigParser ( xml ) ; // If an engine's 'version' property is really its source, map that to the appropriate field. var engines = cfg . getEngines ( ) . map ( function ( engine ) { var result = { name : engine . name } ; if ( semver . validRange ( engine . spec , true ) ) { result . version = engine . spec ; } else { result . src = engine . spec ; } return result ; } ) ; return Promise . resolve ( engines ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all the plugins that are currently saved into config . xml [CODESPLIT] function getPlugins ( projectRoot ) { var xml = cordova_util . projectConfig ( projectRoot ) ; var cfg = new ConfigParser ( xml ) ; // Map variables object to an array var plugins = cfg . getPlugins ( ) . map ( function ( plugin ) { var result = { name : plugin . name } ; if ( semver . validRange ( plugin . spec , true ) ) { result . version = plugin . spec ; } else { result . src = plugin . spec ; } var variablesObject = plugin . variables ; var variablesArray = [ ] ; if ( variablesObject ) { for ( var variable in variablesObject ) { variablesArray . push ( { name : variable , value : variablesObject [ variable ] } ) ; } } result . variables = variablesArray ; return result ; } ) ; return Promise . resolve ( plugins ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getPlatformApi () should be the only method of instantiating the PlatformProject classes for now . [CODESPLIT] function getPlatformApi ( platform , platformRootDir ) { // if platformRootDir is not specified, try to detect it first if ( ! platformRootDir ) { var projectRootDir = util . isCordova ( ) ; platformRootDir = projectRootDir && path . join ( projectRootDir , 'platforms' , platform ) ; } if ( ! platformRootDir ) { // If platformRootDir is still undefined, then we're probably is not inside of cordova project throw new Error ( 'Current location is not a Cordova project' ) ; } // CB-11174 Resolve symlinks first before working with root directory platformRootDir = util . convertToRealPathSafe ( platformRootDir ) ; // Make sure the platforms/platform folder exists if ( ! fs . existsSync ( platformRootDir ) ) { throw new Error ( 'The platform \"' + platform + '\" does not appear to have been added to this project.' ) ; } var platformApi ; var cached = cachedApis [ platformRootDir ] ; var libDir = path . join ( platformRootDir , 'cordova' , 'Api.js' ) ; if ( cached && cached . platform === platform ) { platformApi = cached ; } else { var PlatformApi = util . getPlatformApiFunction ( libDir , platform ) ; platformApi = new PlatformApi ( platform , platformRootDir , events ) ; cachedApis [ platformRootDir ] = platformApi ; } return platformApi ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of top - level plugins which are ( transitively ) dependent on the given plugin . [CODESPLIT] function ( plugin_id , plugins_dir , platformJson , pluginInfoProvider ) { var depsInfo ; if ( typeof plugins_dir === 'object' ) { depsInfo = plugins_dir ; } else { depsInfo = pkg . generateDependencyInfo ( platformJson , plugins_dir , pluginInfoProvider ) ; } var graph = depsInfo . graph ; var tlps = depsInfo . top_level_plugins ; var dependents = tlps . filter ( function ( tlp ) { return tlp !== plugin_id && graph . getChain ( tlp ) . indexOf ( plugin_id ) >= 0 ; } ) ; return dependents ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of plugins which the given plugin depends on for which it is the only dependent . In other words if the given plugin were deleted these dangling dependencies should be deleted too . [CODESPLIT] function ( plugin_id , plugins_dir , platformJson , pluginInfoProvider ) { var depsInfo ; if ( typeof plugins_dir === 'object' ) { depsInfo = plugins_dir ; } else { depsInfo = pkg . generateDependencyInfo ( platformJson , plugins_dir , pluginInfoProvider ) ; } var graph = depsInfo . graph ; var dependencies = graph . getChain ( plugin_id ) ; var tlps = depsInfo . top_level_plugins ; var diff_arr = [ ] ; tlps . forEach ( function ( tlp ) { if ( tlp !== plugin_id ) { diff_arr . push ( graph . getChain ( tlp ) ) ; } } ) ; // if this plugin has dependencies, do a set difference to determine which dependencies are not required by other existing plugins diff_arr . unshift ( dependencies ) ; var danglers = underscore . difference . apply ( null , diff_arr ) ; // Ensure no top-level plugins are tagged as danglers. danglers = danglers && danglers . filter ( function ( x ) { return tlps . indexOf ( x ) < 0 ; } ) ; return danglers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a local function that creates the new replacement representing the mutation . Used to save code further down . [CODESPLIT] function createReplacement ( manifestFile , originalChange ) { var replacement = { target : manifestFile , parent : originalChange . parent , after : originalChange . after , xmls : originalChange . xmls , versions : originalChange . versions , deviceTarget : originalChange . deviceTarget } ; return replacement ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * A class for holidng the information currently stored in plugin . xml It s inherited from cordova - common s PluginInfo class In addition it overrides getConfigFiles getEditConfigs getFrameworks methods to use windows - specific logic [CODESPLIT] function PluginInfo ( dirname ) { //  We're not using `util.inherit' because original PluginInfo defines //  its' methods inside of constructor CommonPluginInfo . apply ( this , arguments ) ; var parentGetConfigFiles = this . getConfigFiles ; var parentGetEditConfigs = this . getEditConfigs ; this . getEditConfigs = function ( platform ) { var editConfigs = parentGetEditConfigs ( platform ) ; return processChanges ( editConfigs ) ; } ; this . getConfigFiles = function ( platform ) { var configFiles = parentGetConfigFiles ( platform ) ; return processChanges ( configFiles ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper function for checking expected plugin IDs against reality . [CODESPLIT] function checkID ( expectedIdAndVersion , pinfo ) { if ( ! expectedIdAndVersion ) return ; var parsedSpec = pluginSpec . parse ( expectedIdAndVersion ) ; if ( parsedSpec . id !== pinfo . id ) { throw new Error ( 'Expected plugin to have ID \"' + parsedSpec . id + '\" but got \"' + pinfo . id + '\".' ) ; } if ( parsedSpec . version && ! semver . satisfies ( pinfo . version , parsedSpec . version ) ) { throw new Error ( 'Expected plugin ' + pinfo . id + ' to satisfy version \"' + parsedSpec . version + '\" but got \"' + pinfo . version + '\".' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a plugin is fund in local search path return a PluginInfo for it . Ignore plugins that don t satisfy the required version spec . If several versions are present in search path return the latest . Examples of accepted plugin_src strings : org . apache . cordova . file org . apache . cordova . file [CODESPLIT] function findLocalPlugin ( plugin_src , searchpath , pluginInfoProvider ) { loadLocalPlugins ( searchpath , pluginInfoProvider ) ; var parsedSpec = pluginSpec . parse ( plugin_src ) ; var versionspec = parsedSpec . version || '*' ; var latest = null ; var versions = localPlugins . plugins [ parsedSpec . id ] ; if ( ! versions ) return null ; versions . forEach ( function ( pinfo ) { // Ignore versions that don't satisfy the the requested version range. // Ignore -dev suffix because latest semver versions doesn't handle it properly (CB-9421) if ( ! semver . satisfies ( pinfo . version . replace ( / -dev$ / , '' ) , versionspec ) ) { return ; } if ( ! latest ) { latest = pinfo ; return ; } if ( semver . gt ( pinfo . version , latest . version ) ) { latest = pinfo ; } } ) ; return latest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy or link a plugin from plugin_dir to plugins_dir / plugin_id . if alternative ID of plugin exists in plugins_dir / plugin_id skip copying [CODESPLIT] function copyPlugin ( pinfo , plugins_dir , link ) { var plugin_dir = pinfo . dir ; var dest = path . join ( plugins_dir , pinfo . id ) ; fs . removeSync ( dest ) ; if ( ! link && dest . indexOf ( path . resolve ( plugin_dir ) + path . sep ) === 0 ) { events . emit ( 'verbose' , 'Copy plugin destination is child of src. Forcing --link mode.' ) ; link = true ; } if ( link ) { var isRelativePath = plugin_dir . charAt ( 1 ) !== ':' && plugin_dir . charAt ( 0 ) !== path . sep ; var fixedPath = isRelativePath ? path . join ( path . relative ( plugins_dir , process . env . PWD || process . cwd ( ) ) , plugin_dir ) : plugin_dir ; events . emit ( 'verbose' , 'Linking \"' + dest + '\" => \"' + fixedPath + '\"' ) ; fs . symlinkSync ( fixedPath , dest , 'junction' ) ; } else { events . emit ( 'verbose' , 'Copying plugin \"' + plugin_dir + '\" => \"' + dest + '\"' ) ; fs . copySync ( plugin_dir , dest , { dereference : true } ) ; } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Deletes plugin from plugins directory and node_modules directory . [CODESPLIT] function ( id ) { var plugin_dir = path . join ( plugins_dir , id ) ; if ( ! fs . existsSync ( plugin_dir ) ) { events . emit ( 'verbose' , 'Plugin \"' + id + '\" already removed (' + plugin_dir + ')' ) ; return Promise . resolve ( ) ; } fs . removeSync ( plugin_dir ) ; events . emit ( 'verbose' , 'Deleted plugin \"' + id + '\"' ) ; // remove plugin from node_modules directory return npmUninstall ( id , options . projectRoot , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "possible options : cli_variables www_dir is_top_level Returns a promise [CODESPLIT] function runUninstallPlatform ( actions , platform , project_dir , plugin_dir , plugins_dir , options ) { var pluginInfoProvider = options . pluginInfoProvider ; // If this plugin is not really installed, return (CB-7004). if ( ! fs . existsSync ( plugin_dir ) ) { return Promise . resolve ( true ) ; } var pluginInfo = pluginInfoProvider . get ( plugin_dir ) ; var plugin_id = pluginInfo . id ; // Merge cli_variables and plugin.xml variables var variables = variableMerge . mergeVariables ( plugin_dir , platform , options ) ; // Deps info can be passed recusively var platformJson = PlatformJson . load ( plugins_dir , platform ) ; var depsInfo = options . depsInfo || dependencies . generateDependencyInfo ( platformJson , plugins_dir , pluginInfoProvider ) ; // Check that this plugin has no dependents. var dependents = dependencies . dependents ( plugin_id , depsInfo , platformJson , pluginInfoProvider ) ; if ( options . is_top_level && dependents && dependents . length > 0 ) { var msg = 'The plugin \\'' + plugin_id + '\\' is required by (' + dependents . join ( ', ' ) + ')' ; if ( options . force ) { events . emit ( 'warn' , msg + ' but forcing removal' ) ; } else { return Promise . reject ( new CordovaError ( msg + ', skipping uninstallation. (try --force if trying to update)' ) ) ; } } // Check how many dangling dependencies this plugin has. var deps = depsInfo . graph . getChain ( plugin_id ) ; var danglers = dependencies . danglers ( plugin_id , depsInfo , platformJson , pluginInfoProvider ) ; var promise ; if ( deps && deps . length && danglers && danglers . length ) { // @tests - important this event is checked spec/uninstall.spec.js events . emit ( 'log' , 'Uninstalling ' + danglers . length + ' dependent plugins.' ) ; promise = promiseutil . Q_chainmap ( danglers , function ( dangler ) { var dependent_path = path . join ( plugins_dir , dangler ) ; var opts = underscore . extend ( { } , options , { is_top_level : depsInfo . top_level_plugins . indexOf ( dangler ) > - 1 , depsInfo : depsInfo } ) ; return runUninstallPlatform ( actions , platform , project_dir , dependent_path , plugins_dir , opts ) ; } ) ; } else { promise = Promise . resolve ( ) ; } var projectRoot = cordovaUtil . isCordova ( ) ; if ( projectRoot ) { // CB-10708 This is the case when we're trying to uninstall plugin using plugman from specific // platform inside of the existing CLI project. This option is usually set by cordova-lib for CLI projects // but since we're running this code through plugman, we need to set it here implicitly options . usePlatformWww = true ; options . cli_variables = variables ; } return promise . then ( function ( ) { if ( ! projectRoot ) return ; var hooksRunner = new HooksRunner ( projectRoot ) ; var hooksRunnerOptions = { cordova : { platforms : [ platform ] } , plugin : { id : pluginInfo . id , pluginInfo : pluginInfo , platform : platform , dir : plugin_dir } } ; return hooksRunner . fire ( 'before_plugin_uninstall' , hooksRunnerOptions ) ; } ) . then ( function ( ) { return handleUninstall ( actions , platform , pluginInfo , project_dir , options . www_dir , plugins_dir , options . is_top_level , options ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a promise . [CODESPLIT] function handleUninstall ( actions , platform , pluginInfo , project_dir , www_dir , plugins_dir , is_top_level , options ) { events . emit ( 'log' , 'Uninstalling ' + pluginInfo . id + ' from ' + platform ) ; // Set up platform to uninstall asset files/js modules // from <platform>/platform_www dir instead of <platform>/www. options . usePlatformWww = true ; return platform_modules . getPlatformApi ( platform , project_dir ) . removePlugin ( pluginInfo , options ) . then ( function ( result ) { // Remove plugin from installed list. This already done in platform, // but need to be duplicated here to remove plugin entry from project's // plugin list to manage dependencies properly. PlatformJson . load ( plugins_dir , platform ) . removePlugin ( pluginInfo . id , is_top_level ) . save ( ) ; // CB-11022 propagate `removePlugin` result to the caller return Promise . resolve ( result ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets platform details from a directory [CODESPLIT] function getPlatformDetailsFromDir ( dir , platformIfKnown ) { var libDir = path . resolve ( dir ) ; var platform ; var version ; // console.log(\"getPlatformDetailsFromDir : \", dir, platformIfKnown, libDir); try { var pkgPath = path . join ( libDir , 'package.json' ) ; var pkg = cordova_util . requireNoCache ( pkgPath ) ; platform = module . exports . platformFromName ( pkg . name ) ; version = pkg . version ; } catch ( e ) { return Promise . reject ( new CordovaError ( 'The provided path does not seem to contain a valid package.json or a valid Cordova platform: ' + libDir ) ) ; } // platform does NOT have to exist in 'platforms', but it should have a name, and a version if ( ! version || ! platform ) { return Promise . reject ( new CordovaError ( 'The provided path does not seem to contain a ' + 'Cordova platform: ' + libDir ) ) ; } return Promise . resolve ( { libDir : libDir , platform : platform , version : version } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the cordova - prefix from the platform s name for known platforms . [CODESPLIT] function platformFromName ( name ) { var platName = name ; var platMatch = / ^cordova-([a-z0-9-]+)$ / . exec ( name ) ; if ( platMatch && ( platMatch [ 1 ] in platforms ) ) { platName = platMatch [ 1 ] ; events . emit ( 'verbose' , 'Removing \"cordova-\" prefix from ' + name ) ; } return platName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes a single message as encoded by NativeToJsMessageQueue . java . [CODESPLIT] function processMessage ( message ) { var firstChar = message . charAt ( 0 ) ; if ( firstChar == 'J' ) { // This is deprecated on the .java side. It doesn't work with CSP enabled. eval ( message . slice ( 1 ) ) ; } else if ( firstChar == 'S' || firstChar == 'F' ) { var success = firstChar == 'S' ; var keepCallback = message . charAt ( 1 ) == '1' ; var spaceIdx = message . indexOf ( ' ' , 2 ) ; var status = + message . slice ( 2 , spaceIdx ) ; var nextSpaceIdx = message . indexOf ( ' ' , spaceIdx + 1 ) ; var callbackId = message . slice ( spaceIdx + 1 , nextSpaceIdx ) ; var payloadMessage = message . slice ( nextSpaceIdx + 1 ) ; var payload = [ ] ; buildPayload ( payload , payloadMessage ) ; cordova . callbackFromNative ( callbackId , success , status , payload , keepCallback ) ; } else { console . log ( \"processMessage failed: invalid message: \" + JSON . stringify ( message ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "possible options : subdir cli_variables www_dir git_ref is_top_level Returns a promise . [CODESPLIT] function possiblyFetch ( id , plugins_dir , options ) { var parsedSpec = pluginSpec . parse ( id ) ; // if plugin is a relative path, check if it already exists var plugin_src_dir = isAbsolutePath ( id ) ? id : path . join ( plugins_dir , parsedSpec . id ) ; // Check that the plugin has already been fetched. if ( fs . existsSync ( plugin_src_dir ) ) { return Promise . resolve ( plugin_src_dir ) ; } var opts = underscore . extend ( { } , options , { client : 'plugman' } ) ; // TODO: without runtime require below, we have a circular dependency. return require ( './plugman' ) . fetch ( id , plugins_dir , opts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "exec engine scripts in order to get the current engine version Returns a promise for the array of engines . [CODESPLIT] function callEngineScripts ( engines , project_dir ) { return Promise . all ( engines . map ( function ( engine ) { // CB-5192; on Windows scriptSrc doesn't have file extension so we shouldn't check whether the script exists var scriptPath = engine . scriptSrc || null ; if ( scriptPath && ( isWindows || fs . existsSync ( engine . scriptSrc ) ) ) { if ( ! isWindows ) { // not required on Windows fs . chmodSync ( engine . scriptSrc , '755' ) ; } return superspawn . spawn ( scriptPath ) . then ( stdout => { engine . currentVersion = cleanVersionOutput ( stdout , engine . name ) ; if ( engine . currentVersion === '' ) { events . emit ( 'warn' , engine . name + ' version check returned nothing (' + scriptPath + '), continuing anyways.' ) ; engine . currentVersion = null ; } } , ( ) => { events . emit ( 'warn' , engine . name + ' version check failed (' + scriptPath + '), continuing anyways.' ) ; engine . currentVersion = null ; } ) . then ( _ => engine ) ; } else { if ( engine . currentVersion ) { engine . currentVersion = cleanVersionOutput ( engine . currentVersion , engine . name ) ; } else { events . emit ( 'warn' , engine . name + ' version not detected (lacks script ' + scriptPath + ' ), continuing.' ) ; } return Promise . resolve ( engine ) ; } } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy or link a plugin from plugin_dir to plugins_dir / plugin_id . [CODESPLIT] function copyPlugin ( plugin_src_dir , plugins_dir , link , pluginInfoProvider ) { var pluginInfo = new PluginInfo ( plugin_src_dir ) ; var dest = path . join ( plugins_dir , pluginInfo . id ) ; if ( link ) { events . emit ( 'verbose' , 'Symlinking from location \"' + plugin_src_dir + '\" to location \"' + dest + '\"' ) ; fs . removeSync ( dest ) ; fs . ensureSymlinkSync ( plugin_src_dir , dest , 'junction' ) ; } else { events . emit ( 'verbose' , 'Copying from location \"' + plugin_src_dir + '\" to location \"' + dest + '\"' ) ; fs . copySync ( plugin_src_dir , dest ) ; } pluginInfo . dir = dest ; pluginInfoProvider . put ( pluginInfo ) ; return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Class that acts as abstraction over particular platform . Encapsulates the platform s properties and methods . [CODESPLIT] function Api ( platform , platformRootDir , events ) { this . platform = PLATFORM ; this . root = path . resolve ( __dirname , '..' ) ; setupEvents ( events ) ; var self = this ; this . locations = { root : self . root , www : path . join ( self . root , 'assets/www' ) , res : path . join ( self . root , 'res' ) , platformWww : path . join ( self . root , 'platform_www' ) , configXml : path . join ( self . root , 'res/xml/config.xml' ) , defaultConfigXml : path . join ( self . root , 'cordova/defaults.xml' ) , strings : path . join ( self . root , 'res/values/strings.xml' ) , manifest : path . join ( self . root , 'AndroidManifest.xml' ) , build : path . join ( self . root , 'build' ) , // NOTE: Due to platformApi spec we need to return relative paths here cordovaJs : 'bin/templates/project/assets/www/cordova.js' , cordovaJsSrc : 'cordova-js-src' } ; // XXX Override some locations for Android Studio projects if ( AndroidStudio . isAndroidStudioProject ( self . root ) === true ) { selfEvents . emit ( 'log' , 'Android Studio project detected' ) ; this . android_studio = true ; this . locations . configXml = path . join ( self . root , 'app/src/main/res/xml/config.xml' ) ; this . locations . strings = path . join ( self . root , 'app/src/main/res/xml/strings.xml' ) ; this . locations . manifest = path . join ( self . root , 'app/src/main/AndroidManifest.xml' ) ; this . locations . www = path . join ( self . root , 'app/src/main/assets/www' ) ; this . locations . res = path . join ( self . root , 'app/src/main/res' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns a promise [CODESPLIT] function createPackageJson ( plugin_path ) { var pluginInfo = new PluginInfo ( plugin_path ) ; var defaults = { id : pluginInfo . id , version : pluginInfo . version , description : pluginInfo . description , license : pluginInfo . license , keywords : pluginInfo . getKeywordsAndPlatforms ( ) , repository : pluginInfo . repo , engines : pluginInfo . getEngines ( ) , platforms : pluginInfo . getPlatformsArray ( ) } ; var initFile = require . resolve ( './init-defaults' ) ; return initPkgJson ( plugin_path , initFile , defaults ) . then ( _ => { events . emit ( 'verbose' , 'Package.json successfully created' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls platformApi . prepare for each platform in project [CODESPLIT] function preparePlatforms ( platformList , projectRoot , options ) { return Promise . all ( platformList . map ( function ( platform ) { // TODO: this need to be replaced by real projectInfo // instance for current project. var project = { root : projectRoot , projectConfig : new ConfigParser ( cordova_util . projectConfig ( projectRoot ) ) , locations : { plugins : path . join ( projectRoot , 'plugins' ) , www : cordova_util . projectWww ( projectRoot ) , rootConfigXml : cordova_util . projectConfig ( projectRoot ) } } ; // CB-9987 We need to reinstall the plugins for the platform it they were added by cordova@<5.4.0 return module . exports . restoreMissingPluginsForPlatform ( platform , projectRoot , options ) . then ( function ( ) { // platformApi prepare takes care of all functionality // which previously had been executed by cordova.prepare: //   - reset config.xml and then merge changes from project's one, //   - update www directory from project's one and merge assets from platform_www, //   - reapply config changes, made by plugins, //   - update platform's project // Please note that plugins' changes, such as installed js files, assets and // config changes is not being reinstalled on each prepare. var platformApi = platforms . getPlatformApi ( platform ) ; return platformApi . prepare ( project , _ . clone ( options ) ) . then ( function ( ) { // Handle edit-config in config.xml var platformRoot = path . join ( projectRoot , 'platforms' , platform ) ; var platformJson = PlatformJson . load ( platformRoot , platform ) ; var munger = new PlatformMunger ( platform , platformRoot , platformJson ) ; // the boolean argument below is \"should_increment\" munger . add_config_changes ( project . projectConfig , true ) . save_all ( ) ; } ) ; } ) ; } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Class that acts as abstraction over particular platform . Encapsulates the platform s properties and methods . [CODESPLIT] function Api ( platform , platformRootDir , eventEmitter ) { this . platform = PLATFORM ; this . root = path . resolve ( __dirname , '..' ) ; setupEvents ( eventEmitter ) ; var self = this ; this . locations = { root : self . root , www : path . join ( self . root , 'www' ) , platformWww : path . join ( self . root , 'platform_www' ) , configXml : path . join ( self . root , 'config.xml' ) , defaultConfigXml : path . join ( self . root , 'cordova/defaults.xml' ) , // NOTE: Due to platformApi spec we need to return relative paths here cordovaJs : 'template/www/cordova.js' , cordovaJsSrc : 'cordova-js-src' } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * At this point cli and config vars have already merged . Merges those vars ( cli and config ) with plugin . xml variables . [CODESPLIT] function mergeVariables ( plugin_dir , platform , options ) { options . pluginInfoProvider = options . pluginInfoProvider || new PluginInfoProvider ( ) ; var pluginInfoProvider = options . pluginInfoProvider ; var pluginInfo = pluginInfoProvider . get ( plugin_dir ) ; var filtered_variables = { } ; var prefs = pluginInfo . getPreferences ( platform ) ; var keys = underscore . keys ( prefs ) ; options . cli_variables = options . cli_variables || { } ; var missing_vars = underscore . difference ( keys , Object . keys ( options . cli_variables ) ) ; underscore . each ( missing_vars , function ( _key ) { var def = prefs [ _key ] ; if ( def ) { options . cli_variables [ _key ] = def ; } } ) ; // test missing vars once again after having default missing_vars = underscore . difference ( keys , Object . keys ( options . cli_variables ) ) ; if ( missing_vars . length > 0 ) { throw new Error ( 'Variable(s) missing: ' + missing_vars . join ( ', ' ) ) ; } filtered_variables = underscore . pick ( options . cli_variables , keys ) ; return filtered_variables ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consturct the default value for versionCode as PATCH + MINOR * 100 + MAJOR * 10000 see http : // developer . android . com / tools / publishing / versioning . html [CODESPLIT] function default_versionCode ( version ) { var nums = version . split ( '-' ) [ 0 ] . split ( '.' ) ; var versionCode = 0 ; if ( + nums [ 0 ] ) { versionCode += + nums [ 0 ] * 10000 ; } if ( + nums [ 1 ] ) { versionCode += + nums [ 1 ] * 100 ; } if ( + nums [ 2 ] ) { versionCode += + nums [ 2 ] ; } events . emit ( 'verbose' , 'android-versionCode not found in config.xml. Generating a code based on version in config.xml (' + version + '): ' + versionCode ) ; return versionCode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find the best matching icon for a given density or size [CODESPLIT] function ( icon , icon_size ) { // do I have a platform icon for that density already var density = icon . density || sizeToDensityMap [ icon_size ] ; if ( ! density ) { // invalid icon defition ( or unsupported size) return ; } var previous = android_icons [ density ] ; if ( previous && previous . platform ) { return ; } android_icons [ density ] = icon ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a map containing resources of a specified name from all drawable folders in a directory . [CODESPLIT] function mapImageResources ( rootDir , subDir , type , resourceName ) { var pathMap = { } ; shell . ls ( path . join ( rootDir , subDir , type + '-*' ) ) . forEach ( function ( drawableFolder ) { var imagePath = path . join ( subDir , path . basename ( drawableFolder ) , resourceName ) ; pathMap [ imagePath ] = null ; } ) ; return pathMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets and validates AndroidLaunchMode prepference from config . xml . Returns preference value and warns if it doesn t seems to be valid [CODESPLIT] function findAndroidLaunchModePreference ( platformConfig ) { var launchMode = platformConfig . getPreference ( 'AndroidLaunchMode' ) ; if ( ! launchMode ) { // Return a default value return 'singleTop' ; } var expectedValues = [ 'standard' , 'singleTop' , 'singleTask' , 'singleInstance' ] ; var valid = expectedValues . indexOf ( launchMode ) >= 0 ; if ( ! valid ) { // Note: warn, but leave the launch mode as developer wanted, in case the list of options changes in the future events . emit ( 'warn' , 'Unrecognized value for AndroidLaunchMode preference: ' + launchMode + '. Expected values are: ' + expectedValues . join ( ', ' ) ) ; } return launchMode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps an AndroidManifest file [CODESPLIT] function AndroidManifest ( path ) { this . path = path ; this . doc = xml . parseElementtreeSync ( path ) ; if ( this . doc . getroot ( ) . tag !== 'manifest' ) { throw new Error ( 'AndroidManifest at ' + path + ' has incorrect root node name (expected \"manifest\")' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the warnings that were printed by the CLI to ensure that the code is listing the correct reasons for failure . Checks against the global warnings object which is reset before each test [CODESPLIT] function expectUnmetRequirements ( expected ) { const actual = unmetRequirementsCollector . store ; expect ( actual ) . toEqual ( jasmine . arrayWithExactContents ( expected ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the version of a plugin that should be fetched for a given project based on the plugin s engine information from NPM and the platforms / plugins installed in the project . The cordovaDependencies object in the package . json s engines entry takes the form of an object that maps plugin versions to a series of constraints and semver ranges . For example : [CODESPLIT] function getFetchVersion ( projectRoot , pluginInfo , cordovaVersion ) { // Figure out the project requirements if ( pluginInfo . engines && pluginInfo . engines . cordovaDependencies ) { // grab array of already installed plugins var pluginList = plugin_util . getInstalledPlugins ( projectRoot ) ; var pluginMap = { } ; pluginList . forEach ( function ( plugin ) { pluginMap [ plugin . id ] = plugin . version ; } ) ; return cordova_util . getInstalledPlatformsWithVersions ( projectRoot ) . then ( function ( platformVersions ) { return module . exports . determinePluginVersionToFetch ( pluginInfo , pluginMap , platformVersions , cordovaVersion ) ; } ) ; } else { // If we have no engine, we want to fall back to the default behavior events . emit ( 'verbose' , 'npm info for ' + pluginInfo . name + ' did not contain any engine info. Fetching latest release' ) ; return Promise . resolve ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * The engine entry maps plugin versions to constraints like so : { 1 . 0 . 0 : { cordova : <5 . 0 . 0 } <2 . 0 . 0 : { cordova : > = 5 . 0 . 0 cordova - ios : ~5 . 0 . 0 cordova - plugin - camera : ~5 . 0 . 0 } 3 . 0 . 0 : { cordova - ios : > 5 . 0 . 0 } } [CODESPLIT] function determinePluginVersionToFetch ( pluginInfo , pluginMap , platformMap , cordovaVersion ) { var allVersions = pluginInfo . versions ; var engine = pluginInfo . engines . cordovaDependencies ; var name = pluginInfo . name ; // Filters out pre-release versions var latest = semver . maxSatisfying ( allVersions , '>=0.0.0' ) ; var versions = [ ] ; var upperBound = null ; var upperBoundRange = null ; var upperBoundExists = false ; // TODO: lots of 'versions' being thrown around in this function: cordova version, // platform version, plugin version. The below for loop: what version is it // iterating over? plugin version? please clarify the variable name. for ( var version in engine ) { // if a single version && less than latest if ( semver . valid ( semver . clean ( version ) ) && semver . lte ( version , latest ) ) { versions . push ( version ) ; } else { // Check if this is an upperbound; validRange() handles whitespace var cleanedRange = semver . validRange ( version ) ; if ( cleanedRange && UPPER_BOUND_REGEX . exec ( cleanedRange ) ) { upperBoundExists = true ; // We only care about the highest upper bound that our project does not support if ( module . exports . getFailedRequirements ( engine [ version ] , pluginMap , platformMap , cordovaVersion ) . length !== 0 ) { var maxMatchingUpperBound = cleanedRange . substring ( 1 ) ; if ( maxMatchingUpperBound && ( ! upperBound || semver . gt ( maxMatchingUpperBound , upperBound ) ) ) { upperBound = maxMatchingUpperBound ; upperBoundRange = version ; } } } else { events . emit ( 'verbose' , 'Ignoring invalid version in ' + name + ' cordovaDependencies: ' + version + ' (must be a single version <= latest or an upper bound)' ) ; } } } // If there were no valid requirements, we fall back to old behavior if ( ! upperBoundExists && versions . length === 0 ) { events . emit ( 'verbose' , 'Ignoring ' + name + ' cordovaDependencies entry because it did not contain any valid plugin version entries' ) ; return null ; } // Handle the lower end of versions by giving them a satisfied engine if ( ! module . exports . findVersion ( versions , '0.0.0' ) ) { versions . push ( '0.0.0' ) ; engine [ '0.0.0' ] = { } ; } // Add an entry after the upper bound to handle the versions above the // upper bound but below the next entry. For example: 0.0.0, <1.0.0, 2.0.0 // needs a 1.0.0 entry that has the same engine as 0.0.0 if ( upperBound && ! module . exports . findVersion ( versions , upperBound ) && ! semver . gt ( upperBound , latest ) ) { versions . push ( upperBound ) ; var below = semver . maxSatisfying ( versions , upperBoundRange ) ; // Get the original entry without trimmed whitespace below = below ? module . exports . findVersion ( versions , below ) : null ; engine [ upperBound ] = below ? engine [ below ] : { } ; } // Sort in descending order; we want to start at latest and work back versions . sort ( semver . rcompare ) ; for ( var i = 0 ; i < versions . length ; i ++ ) { if ( upperBound && semver . lt ( versions [ i ] , upperBound ) ) { // Because we sorted in desc. order, if the upper bound we found // applies to this version (and thus the ones below) we can just // quit break ; } var range = i ? ( '>=' + versions [ i ] + ' <' + versions [ i - 1 ] ) : ( '>=' + versions [ i ] ) ; var maxMatchingVersion = semver . maxSatisfying ( allVersions , range ) ; if ( maxMatchingVersion && module . exports . getFailedRequirements ( engine [ versions [ i ] ] , pluginMap , platformMap , cordovaVersion ) . length === 0 ) { // Because we sorted in descending order, we can stop searching once // we hit a satisfied constraint if ( maxMatchingVersion !== latest ) { var failedReqs = module . exports . getFailedRequirements ( engine [ versions [ 0 ] ] , pluginMap , platformMap , cordovaVersion ) ; // Warn the user that we are not fetching latest module . exports . listUnmetRequirements ( name , failedReqs ) ; events . emit ( 'warn' , 'Fetching highest version of ' + name + ' that this project supports: ' + maxMatchingVersion + ' (latest is ' + latest + ')' ) ; } return maxMatchingVersion ; } } // No version of the plugin is satisfied. In this case, we fall back to // fetching the latest version, but also output a warning var latestFailedReqs = versions . length > 0 ? module . exports . getFailedRequirements ( engine [ versions [ 0 ] ] , pluginMap , platformMap , cordovaVersion ) : [ ] ; // If the upper bound is greater than latest, we need to combine its engine // requirements with latest to print out in the warning if ( upperBound && semver . satisfies ( latest , upperBoundRange ) ) { var upperFailedReqs = module . exports . getFailedRequirements ( engine [ upperBoundRange ] , pluginMap , platformMap , cordovaVersion ) ; upperFailedReqs . forEach ( function ( failedReq ) { for ( var i = 0 ; i < latestFailedReqs . length ; i ++ ) { if ( latestFailedReqs [ i ] . dependency === failedReq . dependency ) { // Not going to overcomplicate things and actually merge the ranges latestFailedReqs [ i ] . required += ' AND ' + failedReq . required ; return ; } } // There is no req to merge it with latestFailedReqs . push ( failedReq ) ; } ) ; } module . exports . listUnmetRequirements ( name , latestFailedReqs ) ; events . emit ( 'warn' , 'Current project does not satisfy the engine requirements specified by any version of ' + name + '. Fetching latest version of plugin anyway (may be incompatible)' ) ; // No constraints were satisfied return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns an array full of objects of dependency requirements that are not met . reqs - CordovaDependency object from plugin s package . json pluginMap - previously installed plugins in the project platformMap - previously installed platforms in the project cordovaVersion - version of cordova being used [CODESPLIT] function getFailedRequirements ( reqs , pluginMap , platformMap , cordovaVersion ) { var failed = [ ] ; var version = cordovaVersion ; if ( semver . prerelease ( version ) ) { //  semver.inc with 'patch' type removes prereleased tag from version version = semver . inc ( version , 'patch' ) ; } for ( var req in reqs ) { if ( reqs . hasOwnProperty ( req ) && typeof req === 'string' && semver . validRange ( reqs [ req ] ) ) { var badInstalledVersion = null ; // remove potential whitespace var trimmedReq = req . trim ( ) ; if ( pluginMap [ trimmedReq ] && ! semver . satisfies ( pluginMap [ trimmedReq ] , reqs [ req ] ) ) { badInstalledVersion = pluginMap [ req ] ; } else if ( trimmedReq === 'cordova' && ! semver . satisfies ( version , reqs [ req ] ) ) { badInstalledVersion = cordovaVersion ; } else if ( trimmedReq . indexOf ( 'cordova-' ) === 0 ) { // Might be a platform constraint var platform = trimmedReq . substring ( 8 ) ; if ( platformMap [ platform ] && ! semver . satisfies ( platformMap [ platform ] , reqs [ req ] ) ) { badInstalledVersion = platformMap [ platform ] ; } } if ( badInstalledVersion ) { failed . push ( { dependency : trimmedReq , installed : badInstalledVersion . trim ( ) , required : reqs [ req ] . trim ( ) } ) ; } } else { events . emit ( 'verbose' , 'Ignoring invalid plugin dependency constraint ' + req + ':' + reqs [ req ] ) ; } } return failed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return the version if it is in the versions array return null if the version doesn t exist in the array [CODESPLIT] function findVersion ( versions , version ) { var cleanedVersion = semver . clean ( version ) ; for ( var i = 0 ; i < versions . length ; i ++ ) { if ( semver . clean ( versions [ i ] ) === cleanedVersion ) { return versions [ i ] ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "emits warnings to users of failed dependnecy requirements in their projects [CODESPLIT] function listUnmetRequirements ( name , failedRequirements ) { events . emit ( 'warn' , 'Unmet project requirements for latest version of ' + name + ':' ) ; failedRequirements . forEach ( function ( req ) { events . emit ( 'warn' , '    ' + req . dependency + ' (' + req . installed + ' in project, ' + req . required + ' required)' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ret is { output : string code : number } [CODESPLIT] function utilExec ( cmdLine ) { var defer = Q . defer ( ) ; shell . exec ( cmdLine , function ( code , output ) { defer . resolve ( { code : code , output : output } ) ; } ) ; return defer . promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the structure of a task . json file . [CODESPLIT] function ( folderName , task ) { var defer = Q . defer ( ) ; var vn = ( task . name || folderName ) ; if ( ! task . id || ! check . isUUID ( task . id ) ) { defer . reject ( createError ( vn + ': id is a required guid' ) ) ; } ; if ( ! task . name || ! check . isAlphanumeric ( task . name ) ) { defer . reject ( createError ( vn + ': name is a required alphanumeric string' ) ) ; } if ( ! task . friendlyName || ! check . isLength ( task . friendlyName , 1 , 40 ) ) { defer . reject ( createError ( vn + ': friendlyName is a required string <= 40 chars' ) ) ; } if ( ! task . instanceNameFormat ) { defer . reject ( createError ( vn + ': instanceNameFormat is required' ) ) ; } // resolve if not already rejected\r defer . resolve ( ) ; return defer . promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------- Results and Exiting ----------------------------------------------------- [CODESPLIT] function setResult ( result , message ) { debug ( 'task result: ' + TaskResult [ result ] ) ; command ( 'task.complete' , { 'result' : TaskResult [ result ] } , message ) ; if ( result == TaskResult . Failed ) { _writeError ( message ) ; } if ( result == TaskResult . Failed ) { process . exit ( 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------- Input Helpers ----------------------------------------------------- [CODESPLIT] function getVariable ( name ) { var varval = process . env [ name . replace ( / \\. / g , '_' ) . toUpperCase ( ) ] ; debug ( name + '=' + varval ) ; var mocked = mock . getResponse ( 'getVariable' , name ) ; return mocked || varval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split - do not use for splitting args! Instead use arg () - it will split and handle this is for splitting a simple list of items like targets [CODESPLIT] function getDelimitedInput ( name , delim , required ) { var inval = getInput ( name , required ) ; if ( ! inval ) { return [ ] ; } return inval . split ( delim ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------- Endpoint Helpers ----------------------------------------------------- [CODESPLIT] function getEndpointUrl ( id , optional ) { var urlval = getVariable ( 'ENDPOINT_URL_' + id ) ; debug ( id + '=' + urlval ) ; if ( ! optional && ! urlval ) { _writeError ( 'Endpoint not present: ' + id ) ; exit ( 1 ) ; } return urlval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------- Cmd Helpers ----------------------------------------------------- [CODESPLIT] function command ( command , properties , message ) { var taskCmd = new tcm . TaskCommand ( command , properties , message ) ; _writeLine ( taskCmd . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ Validation Helpers ------------------------------------------------ [CODESPLIT] function checkPath ( p , name ) { debug ( 'check path : ' + p ) ; if ( ! p || ! mock . getResponse ( 'checkPath' , p ) ) { setResult ( TaskResult . Failed , 'not found ' + name + ': ' + p ) ; // exit } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------- Exec convenience wrapper ----------------------------------------------------- [CODESPLIT] function exec ( tool , args , options ) { var toolPath = which ( tool , true ) ; var tr = createToolRunner ( toolPath ) ; if ( args ) { tr . arg ( args ) ; } return tr . exec ( options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adapted from https : // github . com / polvo - labs / card - type / blob / aaab11f80fa1939bccc8f24905a06ae3cd864356 / src / cardType . js#L37 - L42 [CODESPLIT] function matchesRange ( cardNumber , min , max ) { var maxLengthToCheck = String ( min ) . length ; var substr = cardNumber . substr ( 0 , maxLengthToCheck ) ; var integerRepresentationOfCardNumber = parseInt ( substr , 10 ) ; min = parseInt ( String ( min ) . substr ( 0 , substr . length ) , 10 ) ; max = parseInt ( String ( max ) . substr ( 0 , substr . length ) , 10 ) ; return integerRepresentationOfCardNumber >= min && integerRepresentationOfCardNumber <= max ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "legacy repoDocs have only true / false set at repository . files [ yarn . lock ] ect newer repoDocs have an array ( empty or with the paths ) packageFilename : path of pckage . json [CODESPLIT] function ( files , packageFilename ) { const convertedFiles = _ . flatten ( Object . keys ( files ) . map ( key => { if ( files [ key ] === true ) return key else return files [ key ] } ) ) const hasPackageLock = _ . includes ( convertedFiles , packageFilename . replace ( 'package.json' , 'package-lock.json' ) ) if ( hasPackageLock ) return packageFilename . replace ( 'package.json' , 'package-lock.json' ) const hasYarnLock = _ . includes ( convertedFiles , packageFilename . replace ( 'package.json' , 'yarn.lock' ) ) if ( hasYarnLock ) return packageFilename . replace ( 'package.json' , 'yarn.lock' ) return null }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "version is a string : v8 . 10 - 10 Dubnium - lts / * etc returns a boolean versionOnly : true will _not_ match placeholder strings for current versions such as stable [CODESPLIT] function ( version , newVersion , newCodeName , versionOnly = false ) { let matches = [ ` ${ newCodeName } ` , newCodeName , newVersion ] // eslint-disable-line const tags = [ 'node' , 'stable' , 'lts/\\\\*' ] if ( ! versionOnly ) { matches = matches . concat ( tags ) } const overallResult = ! ! matches . find ( ( match ) => { // first regex matches in array form ('- 10'), second regex matches the inline form ('10') return ! ! ( version . match ( RegExp ( ` ${ match } ` , 'i' ) ) || version . match ( RegExp ( ` ${ match } ` , 'i' ) ) ) } ) return overallResult }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "existingVersionStrings is just an array of strings : [ - 7 - 8 ] or [ 9 ] or [ v8 . 10 ] returns an index [CODESPLIT] function ( existingVersionStrings , newVersion , newCodeName , versionOnly = false ) { if ( ! existingVersionStrings || existingVersionStrings . length === 0 ) return - 1 return existingVersionStrings . findIndex ( ( version ) => { return hasNodeVersion ( version , newVersion , newCodeName , versionOnly ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop! YAMLtime! existingVersions is the output of getNodeVersionsFromTravisYML [CODESPLIT] function ( travisYML , newVersion , newCodeName , existingVersions ) { // Should only add the new version if it is not present in any form if ( existingVersions . versions . length === 0 ) return travisYML const nodeVersionIndex = getNodeVersionIndex ( existingVersions . versions , newVersion , newCodeName ) const travisYMLLines = travisYML . split ( '\\n' ) // We only need to do something if the new version isn’t present if ( nodeVersionIndex === - 1 ) { let delimiter = '' let leadingSpaces = '' if ( existingVersions . versions && existingVersions . versions . length > 0 ) { if ( existingVersions . versions [ 0 ] . match ( / \" / ) ) { delimiter = '\"' } if ( existingVersions . versions [ 0 ] . match ( / ' / ) ) { delimiter = \"'\" } leadingSpaces = existingVersions . versions [ 0 ] . match ( / ^([ ]*) / ) [ 1 ] } // splice the new version back onto the end of the node version list in the original travisYMLLines array, // unless it wasn’t an array but an inline definition of a single version, eg: `node_js: 9` if ( existingVersions . versions . length === 1 && existingVersions . startIndex === existingVersions . endIndex ) { // A single node version was defined in inline format, now we want to define two versions in array format travisYMLLines . splice ( existingVersions . startIndex , 1 , 'node_js:' ) travisYMLLines . splice ( existingVersions . startIndex + 1 , 0 , ` ${ leadingSpaces } ${ existingVersions . versions [ 0 ] } ` ) travisYMLLines . splice ( existingVersions . startIndex + 2 , 0 , ` ${ leadingSpaces } ${ delimiter } ${ newVersion } ${ delimiter } ` ) } else { // Multiple node versions were defined in array format travisYMLLines . splice ( existingVersions . endIndex + 1 , 0 , ` ${ leadingSpaces } ${ delimiter } ${ newVersion } ${ delimiter } ` ) } } return travisYMLLines . join ( '\\n' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "existingVersions is the output of getNodeVersionsFromTravisYML [CODESPLIT] function ( travisYML , newVersion , newCodeName , existingVersions ) { // Should only remove the old version if it is actually present in any form if ( existingVersions . versions . length === 0 ) return travisYML const nodeVersionIndex = getNodeVersionIndex ( existingVersions . versions , newVersion , newCodeName , true ) let travisYMLLines = travisYML . split ( '\\n' ) // We only need to do something if the old version is present if ( nodeVersionIndex !== - 1 ) { // If it’s the only version we don’t want to remove it if ( existingVersions . versions . length !== 1 ) { // Multiple node versions were defined in array format // set lines we want to remove to undefined in existingVersion.versions and filter them out afterwards const updatedVersionsArray = _ . filter ( existingVersions . versions . map ( ( version ) => { return hasNodeVersion ( version , newVersion , newCodeName , true ) ? undefined : version } ) , Boolean ) // splice the updated existingversions into travisymllines travisYMLLines . splice ( existingVersions . startIndex + 1 , existingVersions . endIndex - existingVersions . startIndex , updatedVersionsArray ) // has an array in an array, needs to be flattened travisYMLLines = _ . flatten ( travisYMLLines ) } } return travisYMLLines . join ( '\\n' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Not closing the issue so decision whether to explicitly upgrade or just close is with the user await github . issues . update ( { owner repo number state : closed } ) [CODESPLIT] function hasVersionComment ( issue , version ) { if ( ! issue . version && ! issue . comments ) { log . error ( 'no version information on issue document' , { issue } ) return false } return issue . version === version || ( issue . comments && issue . comments . includes ( version ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "trigger ( several ) initial - subgroup - pr ( s ) : - if a package . json is added / renamed / moved in the greenkeeper . json - if a greenkeeper . json is added [CODESPLIT] async function updateRepoDoc ( { installationId , doc , filePaths , log } ) { const fullName = doc . fullName const oldGreenkeeperConfig = doc . greenkeeper // set a default empty config so the job can continue if the file get fails for some reason let greenkeeperConfigFile = { } try { greenkeeperConfigFile = await getGreenkeeperConfigFile ( installationId , fullName , log ) } catch ( e ) { throw e } finally { if ( ! _ . isEmpty ( greenkeeperConfigFile ) ) { log . info ( 'UpdateRepoDoc: Fetched greenkeeper.json from GitHub' , greenkeeperConfigFile ) } _ . set ( doc , [ 'greenkeeper' ] , greenkeeperConfigFile ) const defaultFiles = { 'package.json' : [ ] , 'package-lock.json' : [ ] , 'yarn.lock' : [ ] , 'npm-shrinkwrap.json' : [ ] } let filePathsFromConfig = [ ] if ( ! _ . isEmpty ( greenkeeperConfigFile ) ) { if ( validate ( greenkeeperConfigFile ) . error ) { log . info ( 'UpdateRepoDoc: setting file paths to the ones from the old greenkeeper.json' ) filePathsFromConfig = getPackagePathsFromConfigFile ( oldGreenkeeperConfig ) } else { log . info ( 'UpdateRepoDoc: setting file paths to the ones found via greenkeeper.json' ) filePathsFromConfig = getPackagePathsFromConfigFile ( greenkeeperConfigFile ) } } // try to get file paths from either the autodiscovered filePaths // or from the greenkeeper.json if ( ! _ . isEmpty ( filePaths ) ) { log . info ( 'UpdateRepoDoc: setting file paths to the ones found per autodiscovery' ) filePathsFromConfig = getPackagePathsFromConfigFile ( { groups : { default : { packages : filePaths } } } ) } log . info ( 'UpdateRepoDoc: requesting files from GitHub' , { files : filePathsFromConfig } ) const filesFromConfig = _ . isEmpty ( filePathsFromConfig ) ? await getFiles ( { installationId , fullName , sha : doc . headSha , log } ) : await getFiles ( { installationId , fullName , files : filePathsFromConfig , sha : doc . headSha , log } ) const files = _ . merge ( filesFromConfig , defaultFiles ) // handles multiple paths for files like this: // files: { //   package.json: ['package.json', 'backend/package.json', 'frontend/package.json'] //   package-lock.json: ['package-lock.json', 'backend/package-lock.json'] //   npm-shrinkwrap.json: [], //   yarn.lock: [] // } doc . files = _ . mapValues ( files , fileType => fileType . filter ( file => ! ! file . content ) . map ( file => file . path ) ) // formats *all* the package.json files const pkg = formatPackageJson ( files [ 'package.json' ] ) if ( ! pkg ) { _ . unset ( doc , [ 'packages' ] ) } else { _ . set ( doc , [ 'packages' ] , pkg ) } log . info ( 'UpdateRepoDoc: doc updated' , { doc } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of objects where each object describes a package . json : [ { content : eyJuYW1lIjoidGVzdCJ9 name : package . json path : frontend / package . json type : file } ] [CODESPLIT] async function discoverPackageFiles ( { installationId , fullName , defaultBranch , log } ) { const ghqueue = githubQueue ( installationId ) const relevantPackageFilePaths = await discoverPackageFilePaths ( { installationId , fullName , defaultBranch , log } ) const [ owner , repo ] = fullName . split ( '/' ) // Fetch the content for each relevant package.json file const packageFiles = await Promise . all ( relevantPackageFilePaths . map ( ( path ) => getGithubFile ( ghqueue , { path , owner , repo } ) ) ) log . info ( ` ${ packageFiles . length } ` ) return packageFiles }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of paths of package . json files : [ package . json frontend / package . json backend / package . json ] [CODESPLIT] async function discoverPackageFilePaths ( { installationId , fullName , defaultBranch , log } ) { // https://api.github.com/repos/neighbourhoodie/gk-test-lerna-yarn-workspaces/git/trees/master?recursive=1 const [ owner , repo ] = fullName . split ( '/' ) const ghqueue = githubQueue ( installationId ) try { const result = ( await ghqueue . read ( github => github . gitdata . getTree ( { owner , repo , tree_sha : defaultBranch , recursive : 1 } ) ) ) const filesInRepo = result . tree && result . tree . length ? result . tree : [ ] // Construct an array of all relevant package.json paths const relevantPackageFilePaths = filesInRepo . map ( ( item ) => { // Just pick out the paths, eg. `packages/retext-dutch/package.json` return item . path } ) . filter ( ( item ) => { // We don’t want any package.json files from `node_modules` return ! ( item . includes ( 'node_modules' ) || item . includes ( 'test/' ) || item . includes ( 'tests/' ) || item . includes ( 'elm-package.json' ) ) && item . match ( / (.+\\/package.json$|^package.json$) / ) } ) log . info ( 'relevant package file paths' , { relevantPackageFilePaths } ) return relevantPackageFilePaths } catch ( error ) { log . warn ( ` ${ defaultBranch } ` , { error : error . message } ) return [ ] } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "needs to handle files as an array of arrays! [CODESPLIT] function hasLockFileText ( files ) { if ( ! files ) return const lockFiles = [ 'package-lock.json' , 'npm-shrinkwrap.json' , 'yarn.lock' ] . filter ( ( key ) => { if ( _ . isArray ( files [ key ] ) && files [ key ] . length ) { return true } if ( files [ key ] === true ) { return true } return false } ) if ( lockFiles . length === 0 ) return if ( lockFiles . includes ( 'npm-shrinkwrap.json' ) ) { return md ` .c od e ('np m -shrinkwrap.json')} f i l  } const lockFile = lockFiles [ 0 ] return md ` d. co d e(lo c kFile)}  f i  }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "1 . fetch . travis . yml [CODESPLIT] function travisTransform ( travisYML ) { try { var travisJSON = yaml . safeLoad ( travisYML , { schema : yaml . FAILSAFE_SCHEMA } ) } catch ( e ) { // ignore .travis.yml if it can not be parsed return } // No node versions specified in root level of travis YML // There may be node versions defined in the matrix or jobs keys, but those can become // far too complex for us to handle, so we don’t if ( ! _ . get ( travisJSON , 'node_js' ) ) return const nodeVersionFromYaml = getNodeVersionsFromTravisYML ( travisYML ) const hasNodeVersion = getNodeVersionIndex ( nodeVersionFromYaml . versions , nodeVersion , codeName ) !== - 1 if ( hasNodeVersion ) return const updatedTravisYaml = addNodeVersionToTravisYML ( travisYML , nodeVersion , codeName , nodeVersionFromYaml ) return updatedTravisYaml }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a groups array and a package path returns the package file’s group or undefined [CODESPLIT] function getGroupForPackageFile ( groups , packageFilePath ) { return Object . keys ( groups ) . find ( ( group ) => { return groups [ group ] . packages && groups [ group ] . packages . includes ( packageFilePath ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a groups array a package path and a dependency name returns whether that dep is ignored for that package in any group [CODESPLIT] function isDependencyIgnoredInGroups ( groups , packageFilePath , dependencyName ) { const groupName = getGroupForPackageFile ( groups , packageFilePath ) return groupName && _ . includes ( groups [ groupName ] . ignore , dependencyName ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns a url object if you pass in a GitHub repositoryURL returns a string with an npm URL if you just pass in a dependency name [CODESPLIT] function getDependencyURL ( { repositoryURL , dependency } ) { // githubURL is an object! const githubURL = url . parse ( githubFromGit ( repositoryURL ) || '' ) if ( dependency && ! githubURL . href ) { return ` ${ dependency } ` } return githubURL }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "expects an array of package . json paths returns an array of unique dependencies from those package . jsons : / * Returns : [ { name : [CODESPLIT] function getDependenciesFromPackageFiles ( packagePaths , packageJsonContents ) { return _ . compact ( _ . uniqWith ( _ . flatten ( packagePaths . map ( path => { return _ . flatten ( [ 'dependencies' , 'devDependencies' , 'optionalDependencies' ] . map ( type => { if ( packageJsonContents [ path ] ) { return _ . map ( packageJsonContents [ path ] [ type ] , ( version , name ) => ( { name , version , type } ) ) } } ) ) } ) ) , _ . isEqual ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add npm package data to dependency info from previous function / * Returns : [ { name : [CODESPLIT] async function addNPMPackageData ( dependencyInfo , registryGet , log ) { return Promise . mapSeries ( dependencyInfo , async dep => { try { dep . data = await registryGet ( registryUrl + dep . name . replace ( '/' , '%2F' ) , { } ) return dep } catch ( err ) { log . error ( 'npm: Could not get package data' , { dependency : dep , error : err } ) } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get new version for all dependencies in files / * Arguments : packagePaths : array of strings eg . [ package . json frontend / package . json ] packageJsonContents : array of objects eg . [ { devDependencies : { @finnpauls / dep : 1 . 0 . 0 } } ] registryGet : instance of promisified npm - registry - client ignore : array of strings eg . [ eslint standard ] from config ( package . json greenkeeper . json etc . ) log : an instance of the logger [CODESPLIT] async function getUpdatedDependenciesForFiles ( { packagePaths , packageJsonContents , registryGet , ignore , log } ) { const dependencyInfo = module . exports . getDependenciesFromPackageFiles ( packagePaths , packageJsonContents , log ) // Filter out ignored dependencies const unignoredDependencyInfo = dependencyInfo . filter ( ( dep ) => ! ignore . includes ( dep . name ) ) log . info ( 'dependencies found' , { parsedDependencies : unignoredDependencyInfo , ignoredDependencies : ignore , packageJsonContents : packageJsonContents } ) let dependencies = await module . exports . addNPMPackageData ( unignoredDependencyInfo , registryGet , log ) let dependencyActionsLog = { } // add `newVersion` to each dependency object in the array const outputDependencies = _ ( dependencies ) . filter ( Boolean ) // remove falsy values from input array . map ( dependency => { // neither version nor range, so it's something weird (git url) // better not touch it if ( ! semver . validRange ( dependency . version ) ) { dependencyActionsLog [ dependency . name ] = 'invalid range' return } // new version is prerelease const oldIsPrerelease = _ . get ( semver . parse ( dependency . version ) , 'prerelease.length' ) > 0 let latest = _ . get ( dependency , 'data.dist-tags.latest' ) const prereleaseDiff = oldIsPrerelease && semver . diff ( dependency . version , latest ) === 'prerelease' if ( ! prereleaseDiff && _ . get ( semver . parse ( latest ) , 'prerelease.length' , 0 ) > 0 ) { const versions = _ . keys ( _ . get ( dependency , 'data.versions' ) ) latest = _ . reduce ( versions , function ( current , next ) { const parsed = semver . parse ( next ) if ( ! parsed ) return current if ( _ . get ( parsed , 'prerelease.length' , 0 ) > 0 ) return current if ( semver . gtr ( next , current ) ) return next return current } ) } // no to need change anything :) if ( semver . satisfies ( latest , dependency . version ) ) { dependencyActionsLog [ dependency . name ] = 'satisfies semver' return } // no downgrades if ( semver . ltr ( latest , dependency . version ) ) { dependencyActionsLog [ dependency . name ] = 'would be a downgrade' return } dependency . newVersion = getRangedVersion ( latest , dependency . version ) dependencyActionsLog [ dependency . name ] = ` ${ dependency . newVersion } ` return dependency } ) . filter ( Boolean ) // remove falsy values from output array . value ( ) // run lodash chain log . info ( 'parsed dependency actions' , { dependencyActionsLog } ) return outputDependencies }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a hack suggested here : https : // github . com / amir20 / phantomjs - node / issues / 292 [CODESPLIT] function checkForData ( ) { ph . windowProperty ( \"DATA\" ) . then ( function ( data ) { if ( data !== undefined ) { writeToFile ( data ) ; ph . exit ( ) ; } else { setTimeout ( checkForData , 100 ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "extracts lists of methods from each service object . [CODESPLIT] function extractApis ( services ) { var filterTypes = arguments . length <= 1 || arguments [ 1 ] === undefined ? [ ] : arguments [ 1 ] ; services = Array . isArray ( services ) ? services : [ services ] ; var apis = services . reduce ( function ( total , service ) { var obj = service . constructor === Object ? service : Object . getPrototypeOf ( service ) ; var keys = aggregateApisByType ( obj , total , filterTypes ) ; total . push . apply ( total , keys ) ; return total ; } , [ ] ) ; return apis ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * eslint - disable Constructor for SearchResults [CODESPLIT] function SearchResults ( state , results ) { var mainSubResponse = results [ 0 ] ; this . _rawResults = results ; /**\n   * query used to generate the results\n   * @member {string}\n   */ this . query = mainSubResponse . query ; /**\n   * The query as parsed by the engine given all the rules.\n   * @member {string}\n   */ this . parsedQuery = mainSubResponse . parsedQuery ; /**\n   * all the records that match the search parameters. Each record is\n   * augmented with a new attribute `_highlightResult`\n   * which is an object keyed by attribute and with the following properties:\n   *  - `value` : the value of the facet highlighted (html)\n   *  - `matchLevel`: full, partial or none depending on how the query terms match\n   * @member {object[]}\n   */ this . hits = mainSubResponse . hits ; /**\n   * index where the results come from\n   * @member {string}\n   */ this . index = mainSubResponse . index ; /**\n   * number of hits per page requested\n   * @member {number}\n   */ this . hitsPerPage = mainSubResponse . hitsPerPage ; /**\n   * total number of hits of this query on the index\n   * @member {number}\n   */ this . nbHits = mainSubResponse . nbHits ; /**\n   * total number of pages with respect to the number of hits per page and the total number of hits\n   * @member {number}\n   */ this . nbPages = mainSubResponse . nbPages ; /**\n   * current page\n   * @member {number}\n   */ this . page = mainSubResponse . page ; /**\n   * sum of the processing time of all the queries\n   * @member {number}\n   */ this . processingTimeMS = sumBy ( results , 'processingTimeMS' ) ; /**\n   * The position if the position was guessed by IP.\n   * @member {string}\n   * @example \"48.8637,2.3615\",\n   */ this . aroundLatLng = mainSubResponse . aroundLatLng ; /**\n   * The radius computed by Algolia.\n   * @member {string}\n   * @example \"126792922\",\n   */ this . automaticRadius = mainSubResponse . automaticRadius ; /**\n   * String identifying the server used to serve this request.\n   * @member {string}\n   * @example \"c7-use-2.algolia.net\",\n   */ this . serverUsed = mainSubResponse . serverUsed ; /**\n   * Boolean that indicates if the computation of the counts did time out.\n   * @deprecated\n   * @member {boolean}\n   */ this . timeoutCounts = mainSubResponse . timeoutCounts ; /**\n   * Boolean that indicates if the computation of the hits did time out.\n   * @deprecated\n   * @member {boolean}\n   */ this . timeoutHits = mainSubResponse . timeoutHits ; /**\n   * True if the counts of the facets is exhaustive\n   * @member {boolean}\n   */ this . exhaustiveFacetsCount = mainSubResponse . exhaustiveFacetsCount ; /**\n   * True if the number of hits is exhaustive\n   * @member {boolean}\n   */ this . exhaustiveNbHits = mainSubResponse . exhaustiveNbHits ; /**\n   * Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/).\n   * @member {object[]}\n   */ this . userData = mainSubResponse . userData ; /**\n   * queryID is the unique identifier of the query used to generate the current search results.\n   * This value is only available if the `clickAnalytics` search parameter is set to `true`.\n   * @member {string}\n   */ this . queryID = mainSubResponse . queryID ; /**\n   * disjunctive facets results\n   * @member {SearchResults.Facet[]}\n   */ this . disjunctiveFacets = [ ] ; /**\n   * disjunctive facets results\n   * @member {SearchResults.HierarchicalFacet[]}\n   */ this . hierarchicalFacets = map ( state . hierarchicalFacets , function initFutureTree ( ) { return [ ] ; } ) ; /**\n   * other facets results\n   * @member {SearchResults.Facet[]}\n   */ this . facets = [ ] ; var disjunctiveFacets = state . getRefinedDisjunctiveFacets ( ) ; var facetsIndices = getIndices ( state . facets ) ; var disjunctiveFacetsIndices = getIndices ( state . disjunctiveFacets ) ; var nextDisjunctiveResult = 1 ; var self = this ; // Since we send request only for disjunctive facets that have been refined, // we get the facets informations from the first, general, response. forEach ( mainSubResponse . facets , function ( facetValueObject , facetKey ) { var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName ( state . hierarchicalFacets , facetKey ) ; if ( hierarchicalFacet ) { // Place the hierarchicalFacet data at the correct index depending on // the attributes order that was defined at the helper initialization var facetIndex = hierarchicalFacet . attributes . indexOf ( facetKey ) ; var idxAttributeName = findIndex ( state . hierarchicalFacets , { name : hierarchicalFacet . name } ) ; self . hierarchicalFacets [ idxAttributeName ] [ facetIndex ] = { attribute : facetKey , data : facetValueObject , exhaustive : mainSubResponse . exhaustiveFacetsCount } ; } else { var isFacetDisjunctive = indexOf ( state . disjunctiveFacets , facetKey ) !== - 1 ; var isFacetConjunctive = indexOf ( state . facets , facetKey ) !== - 1 ; var position ; if ( isFacetDisjunctive ) { position = disjunctiveFacetsIndices [ facetKey ] ; self . disjunctiveFacets [ position ] = { name : facetKey , data : facetValueObject , exhaustive : mainSubResponse . exhaustiveFacetsCount } ; assignFacetStats ( self . disjunctiveFacets [ position ] , mainSubResponse . facets_stats , facetKey ) ; } if ( isFacetConjunctive ) { position = facetsIndices [ facetKey ] ; self . facets [ position ] = { name : facetKey , data : facetValueObject , exhaustive : mainSubResponse . exhaustiveFacetsCount } ; assignFacetStats ( self . facets [ position ] , mainSubResponse . facets_stats , facetKey ) ; } } } ) ; // Make sure we do not keep holes within the hierarchical facets this . hierarchicalFacets = compact ( this . hierarchicalFacets ) ; // aggregate the refined disjunctive facets forEach ( disjunctiveFacets , function ( disjunctiveFacet ) { var result = results [ nextDisjunctiveResult ] ; var hierarchicalFacet = state . getHierarchicalFacetByName ( disjunctiveFacet ) ; // There should be only item in facets. forEach ( result . facets , function ( facetResults , dfacet ) { var position ; if ( hierarchicalFacet ) { position = findIndex ( state . hierarchicalFacets , { name : hierarchicalFacet . name } ) ; var attributeIndex = findIndex ( self . hierarchicalFacets [ position ] , { attribute : dfacet } ) ; // previous refinements and no results so not able to find it if ( attributeIndex === - 1 ) { return ; } self . hierarchicalFacets [ position ] [ attributeIndex ] . data = merge ( { } , self . hierarchicalFacets [ position ] [ attributeIndex ] . data , facetResults ) ; } else { position = disjunctiveFacetsIndices [ dfacet ] ; var dataFromMainRequest = mainSubResponse . facets && mainSubResponse . facets [ dfacet ] || { } ; self . disjunctiveFacets [ position ] = { name : dfacet , data : defaults ( { } , facetResults , dataFromMainRequest ) , exhaustive : result . exhaustiveFacetsCount } ; assignFacetStats ( self . disjunctiveFacets [ position ] , result . facets_stats , dfacet ) ; if ( state . disjunctiveFacetsRefinements [ dfacet ] ) { forEach ( state . disjunctiveFacetsRefinements [ dfacet ] , function ( refinementValue ) { // add the disjunctive refinements if it is no more retrieved if ( ! self . disjunctiveFacets [ position ] . data [ refinementValue ] && indexOf ( state . disjunctiveFacetsRefinements [ dfacet ] , refinementValue ) > - 1 ) { self . disjunctiveFacets [ position ] . data [ refinementValue ] = 0 ; } } ) ; } } } ) ; nextDisjunctiveResult ++ ; } ) ; // if we have some root level values for hierarchical facets, merge them forEach ( state . getRefinedHierarchicalFacets ( ) , function ( refinedFacet ) { var hierarchicalFacet = state . getHierarchicalFacetByName ( refinedFacet ) ; var separator = state . _getHierarchicalFacetSeparator ( hierarchicalFacet ) ; var currentRefinement = state . getHierarchicalRefinement ( refinedFacet ) ; // if we are already at a root refinement (or no refinement at all), there is no // root level values request if ( currentRefinement . length === 0 || currentRefinement [ 0 ] . split ( separator ) . length < 2 ) { return ; } var result = results [ nextDisjunctiveResult ] ; forEach ( result . facets , function ( facetResults , dfacet ) { var position = findIndex ( state . hierarchicalFacets , { name : hierarchicalFacet . name } ) ; var attributeIndex = findIndex ( self . hierarchicalFacets [ position ] , { attribute : dfacet } ) ; // previous refinements and no results so not able to find it if ( attributeIndex === - 1 ) { return ; } // when we always get root levels, if the hits refinement is `beers > IPA` (count: 5), // then the disjunctive values will be `beers` (count: 100), // but we do not want to display //   | beers (100) //     > IPA (5) // We want //   | beers (5) //     > IPA (5) var defaultData = { } ; if ( currentRefinement . length > 0 ) { var root = currentRefinement [ 0 ] . split ( separator ) [ 0 ] ; defaultData [ root ] = self . hierarchicalFacets [ position ] [ attributeIndex ] . data [ root ] ; } self . hierarchicalFacets [ position ] [ attributeIndex ] . data = defaults ( defaultData , facetResults , self . hierarchicalFacets [ position ] [ attributeIndex ] . data ) ; } ) ; nextDisjunctiveResult ++ ; } ) ; // add the excludes forEach ( state . facetsExcludes , function ( excludes , facetName ) { var position = facetsIndices [ facetName ] ; self . facets [ position ] = { name : facetName , data : mainSubResponse . facets [ facetName ] , exhaustive : mainSubResponse . exhaustiveFacetsCount } ; forEach ( excludes , function ( facetValue ) { self . facets [ position ] = self . facets [ position ] || { name : facetName } ; self . facets [ position ] . data = self . facets [ position ] . data || { } ; self . facets [ position ] . data [ facetValue ] = 0 ; } ) ; } ) ; this . hierarchicalFacets = map ( this . hierarchicalFacets , generateHierarchicalTree ( state ) ) ; this . facets = compact ( this . facets ) ; this . disjunctiveFacets = compact ( this . disjunctiveFacets ) ; this . _state = state ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the facet values of a specified attribute from a SearchResults object . [CODESPLIT] function extractNormalizedFacetValues ( results , attribute ) { var predicate = { name : attribute } ; if ( results . _state . isConjunctiveFacet ( attribute ) ) { var facet = find ( results . facets , predicate ) ; if ( ! facet ) return [ ] ; return map ( facet . data , function ( v , k ) { return { name : k , count : v , isRefined : results . _state . isFacetRefined ( attribute , k ) , isExcluded : results . _state . isExcludeRefined ( attribute , k ) } ; } ) ; } else if ( results . _state . isDisjunctiveFacet ( attribute ) ) { var disjunctiveFacet = find ( results . disjunctiveFacets , predicate ) ; if ( ! disjunctiveFacet ) return [ ] ; return map ( disjunctiveFacet . data , function ( v , k ) { return { name : k , count : v , isRefined : results . _state . isDisjunctiveFacetRefined ( attribute , k ) } ; } ) ; } else if ( results . _state . isHierarchicalFacet ( attribute ) ) { return find ( results . hierarchicalFacets , predicate ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort nodes of a hierarchical facet results [CODESPLIT] function recSort ( sortFn , node ) { if ( ! node . data || node . data . length === 0 ) { return node ; } var children = map ( node . data , partial ( recSort , sortFn ) ) ; var sortedChildren = sortFn ( children ) ; var newNode = merge ( { } , node , { data : sortedChildren } ) ; return newNode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Structure to store numeric filters with the operator as the key . The supported operators are = > < > = < = and ! = . [CODESPLIT] function SearchParameters ( newParameters ) { var params = newParameters ? SearchParameters . _parseNumbers ( newParameters ) : { } ; /**\n   * Targeted index. This parameter is mandatory.\n   * @member {string}\n   */ this . index = params . index || '' ; // Query /**\n   * Query string of the instant search. The empty string is a valid query.\n   * @member {string}\n   * @see https://www.algolia.com/doc/rest#param-query\n   */ this . query = params . query || '' ; // Facets /**\n   * This attribute contains the list of all the conjunctive facets\n   * used. This list will be added to requested facets in the\n   * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.\n   * @member {string[]}\n   */ this . facets = params . facets || [ ] ; /**\n   * This attribute contains the list of all the disjunctive facets\n   * used. This list will be added to requested facets in the\n   * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.\n   * @member {string[]}\n   */ this . disjunctiveFacets = params . disjunctiveFacets || [ ] ; /**\n   * This attribute contains the list of all the hierarchical facets\n   * used. This list will be added to requested facets in the\n   * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.\n   * Hierarchical facets are a sub type of disjunctive facets that\n   * let you filter faceted attributes hierarchically.\n   * @member {string[]|object[]}\n   */ this . hierarchicalFacets = params . hierarchicalFacets || [ ] ; // Refinements /**\n   * This attribute contains all the filters that need to be\n   * applied on the conjunctive facets. Each facet must be properly\n   * defined in the `facets` attribute.\n   *\n   * The key is the name of the facet, and the `FacetList` contains all\n   * filters selected for the associated facet name.\n   *\n   * When querying algolia, the values stored in this attribute will\n   * be translated into the `facetFilters` attribute.\n   * @member {Object.<string, SearchParameters.FacetList>}\n   */ this . facetsRefinements = params . facetsRefinements || { } ; /**\n   * This attribute contains all the filters that need to be\n   * excluded from the conjunctive facets. Each facet must be properly\n   * defined in the `facets` attribute.\n   *\n   * The key is the name of the facet, and the `FacetList` contains all\n   * filters excluded for the associated facet name.\n   *\n   * When querying algolia, the values stored in this attribute will\n   * be translated into the `facetFilters` attribute.\n   * @member {Object.<string, SearchParameters.FacetList>}\n   */ this . facetsExcludes = params . facetsExcludes || { } ; /**\n   * This attribute contains all the filters that need to be\n   * applied on the disjunctive facets. Each facet must be properly\n   * defined in the `disjunctiveFacets` attribute.\n   *\n   * The key is the name of the facet, and the `FacetList` contains all\n   * filters selected for the associated facet name.\n   *\n   * When querying algolia, the values stored in this attribute will\n   * be translated into the `facetFilters` attribute.\n   * @member {Object.<string, SearchParameters.FacetList>}\n   */ this . disjunctiveFacetsRefinements = params . disjunctiveFacetsRefinements || { } ; /**\n   * This attribute contains all the filters that need to be\n   * applied on the numeric attributes.\n   *\n   * The key is the name of the attribute, and the value is the\n   * filters to apply to this attribute.\n   *\n   * When querying algolia, the values stored in this attribute will\n   * be translated into the `numericFilters` attribute.\n   * @member {Object.<string, SearchParameters.OperatorList>}\n   */ this . numericRefinements = params . numericRefinements || { } ; /**\n   * This attribute contains all the tags used to refine the query.\n   *\n   * When querying algolia, the values stored in this attribute will\n   * be translated into the `tagFilters` attribute.\n   * @member {string[]}\n   */ this . tagRefinements = params . tagRefinements || [ ] ; /**\n   * This attribute contains all the filters that need to be\n   * applied on the hierarchical facets. Each facet must be properly\n   * defined in the `hierarchicalFacets` attribute.\n   *\n   * The key is the name of the facet, and the `FacetList` contains all\n   * filters selected for the associated facet name. The FacetList values\n   * are structured as a string that contain the values for each level\n   * separated by the configured separator.\n   *\n   * When querying algolia, the values stored in this attribute will\n   * be translated into the `facetFilters` attribute.\n   * @member {Object.<string, SearchParameters.FacetList>}\n   */ this . hierarchicalFacetsRefinements = params . hierarchicalFacetsRefinements || { } ; /**\n   * Contains the numeric filters in the raw format of the Algolia API. Setting\n   * this parameter is not compatible with the usage of numeric filters methods.\n   * @see https://www.algolia.com/doc/javascript#numericFilters\n   * @member {string}\n   */ this . numericFilters = params . numericFilters ; /**\n   * Contains the tag filters in the raw format of the Algolia API. Setting this\n   * parameter is not compatible with the of the add/remove/toggle methods of the\n   * tag api.\n   * @see https://www.algolia.com/doc/rest#param-tagFilters\n   * @member {string}\n   */ this . tagFilters = params . tagFilters ; /**\n   * Contains the optional tag filters in the raw format of the Algolia API.\n   * @see https://www.algolia.com/doc/rest#param-tagFilters\n   * @member {string}\n   */ this . optionalTagFilters = params . optionalTagFilters ; /**\n   * Contains the optional facet filters in the raw format of the Algolia API.\n   * @see https://www.algolia.com/doc/rest#param-tagFilters\n   * @member {string}\n   */ this . optionalFacetFilters = params . optionalFacetFilters ; // Misc. parameters /**\n   * Number of hits to be returned by the search API\n   * @member {number}\n   * @see https://www.algolia.com/doc/rest#param-hitsPerPage\n   */ this . hitsPerPage = params . hitsPerPage ; /**\n   * Number of values for each faceted attribute\n   * @member {number}\n   * @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet\n   */ this . maxValuesPerFacet = params . maxValuesPerFacet ; /**\n   * The current page number\n   * @member {number}\n   * @see https://www.algolia.com/doc/rest#param-page\n   */ this . page = params . page || 0 ; /**\n   * How the query should be treated by the search engine.\n   * Possible values: prefixAll, prefixLast, prefixNone\n   * @see https://www.algolia.com/doc/rest#param-queryType\n   * @member {string}\n   */ this . queryType = params . queryType ; /**\n   * How the typo tolerance behave in the search engine.\n   * Possible values: true, false, min, strict\n   * @see https://www.algolia.com/doc/rest#param-typoTolerance\n   * @member {string}\n   */ this . typoTolerance = params . typoTolerance ; /**\n   * Number of characters to wait before doing one character replacement.\n   * @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo\n   * @member {number}\n   */ this . minWordSizefor1Typo = params . minWordSizefor1Typo ; /**\n   * Number of characters to wait before doing a second character replacement.\n   * @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos\n   * @member {number}\n   */ this . minWordSizefor2Typos = params . minWordSizefor2Typos ; /**\n   * Configure the precision of the proximity ranking criterion\n   * @see https://www.algolia.com/doc/rest#param-minProximity\n   */ this . minProximity = params . minProximity ; /**\n   * Should the engine allow typos on numerics.\n   * @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens\n   * @member {boolean}\n   */ this . allowTyposOnNumericTokens = params . allowTyposOnNumericTokens ; /**\n   * Should the plurals be ignored\n   * @see https://www.algolia.com/doc/rest#param-ignorePlurals\n   * @member {boolean}\n   */ this . ignorePlurals = params . ignorePlurals ; /**\n   * Restrict which attribute is searched.\n   * @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes\n   * @member {string}\n   */ this . restrictSearchableAttributes = params . restrictSearchableAttributes ; /**\n   * Enable the advanced syntax.\n   * @see https://www.algolia.com/doc/rest#param-advancedSyntax\n   * @member {boolean}\n   */ this . advancedSyntax = params . advancedSyntax ; /**\n   * Enable the analytics\n   * @see https://www.algolia.com/doc/rest#param-analytics\n   * @member {boolean}\n   */ this . analytics = params . analytics ; /**\n   * Tag of the query in the analytics.\n   * @see https://www.algolia.com/doc/rest#param-analyticsTags\n   * @member {string}\n   */ this . analyticsTags = params . analyticsTags ; /**\n   * Enable the synonyms\n   * @see https://www.algolia.com/doc/rest#param-synonyms\n   * @member {boolean}\n   */ this . synonyms = params . synonyms ; /**\n   * Should the engine replace the synonyms in the highlighted results.\n   * @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight\n   * @member {boolean}\n   */ this . replaceSynonymsInHighlight = params . replaceSynonymsInHighlight ; /**\n   * Add some optional words to those defined in the dashboard\n   * @see https://www.algolia.com/doc/rest#param-optionalWords\n   * @member {string}\n   */ this . optionalWords = params . optionalWords ; /**\n   * Possible values are \"lastWords\" \"firstWords\" \"allOptional\" \"none\" (default)\n   * @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults\n   * @member {string}\n   */ this . removeWordsIfNoResults = params . removeWordsIfNoResults ; /**\n   * List of attributes to retrieve\n   * @see https://www.algolia.com/doc/rest#param-attributesToRetrieve\n   * @member {string}\n   */ this . attributesToRetrieve = params . attributesToRetrieve ; /**\n   * List of attributes to highlight\n   * @see https://www.algolia.com/doc/rest#param-attributesToHighlight\n   * @member {string}\n   */ this . attributesToHighlight = params . attributesToHighlight ; /**\n   * Code to be embedded on the left part of the highlighted results\n   * @see https://www.algolia.com/doc/rest#param-highlightPreTag\n   * @member {string}\n   */ this . highlightPreTag = params . highlightPreTag ; /**\n   * Code to be embedded on the right part of the highlighted results\n   * @see https://www.algolia.com/doc/rest#param-highlightPostTag\n   * @member {string}\n   */ this . highlightPostTag = params . highlightPostTag ; /**\n   * List of attributes to snippet\n   * @see https://www.algolia.com/doc/rest#param-attributesToSnippet\n   * @member {string}\n   */ this . attributesToSnippet = params . attributesToSnippet ; /**\n   * Enable the ranking informations in the response, set to 1 to activate\n   * @see https://www.algolia.com/doc/rest#param-getRankingInfo\n   * @member {number}\n   */ this . getRankingInfo = params . getRankingInfo ; /**\n   * Remove duplicates based on the index setting attributeForDistinct\n   * @see https://www.algolia.com/doc/rest#param-distinct\n   * @member {boolean|number}\n   */ this . distinct = params . distinct ; /**\n   * Center of the geo search.\n   * @see https://www.algolia.com/doc/rest#param-aroundLatLng\n   * @member {string}\n   */ this . aroundLatLng = params . aroundLatLng ; /**\n   * Center of the search, retrieve from the user IP.\n   * @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP\n   * @member {boolean}\n   */ this . aroundLatLngViaIP = params . aroundLatLngViaIP ; /**\n   * Radius of the geo search.\n   * @see https://www.algolia.com/doc/rest#param-aroundRadius\n   * @member {number}\n   */ this . aroundRadius = params . aroundRadius ; /**\n   * Precision of the geo search.\n   * @see https://www.algolia.com/doc/rest#param-aroundPrecision\n   * @member {number}\n   */ this . minimumAroundRadius = params . minimumAroundRadius ; /**\n   * Precision of the geo search.\n   * @see https://www.algolia.com/doc/rest#param-minimumAroundRadius\n   * @member {number}\n   */ this . aroundPrecision = params . aroundPrecision ; /**\n   * Geo search inside a box.\n   * @see https://www.algolia.com/doc/rest#param-insideBoundingBox\n   * @member {string}\n   */ this . insideBoundingBox = params . insideBoundingBox ; /**\n   * Geo search inside a polygon.\n   * @see https://www.algolia.com/doc/rest#param-insidePolygon\n   * @member {string}\n   */ this . insidePolygon = params . insidePolygon ; /**\n   * Allows to specify an ellipsis character for the snippet when we truncate the text\n   * (added before and after if truncated).\n   * The default value is an empty string and we recommend to set it to \"…\"\n   * @see https://www.algolia.com/doc/rest#param-insidePolygon\n   * @member {string}\n   */ this . snippetEllipsisText = params . snippetEllipsisText ; /**\n   * Allows to specify some attributes name on which exact won't be applied.\n   * Attributes are separated with a comma (for example \"name,address\" ), you can also use a\n   * JSON string array encoding (for example encodeURIComponent('[\"name\",\"address\"]') ).\n   * By default the list is empty.\n   * @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes\n   * @member {string|string[]}\n   */ this . disableExactOnAttributes = params . disableExactOnAttributes ; /**\n   * Applies 'exact' on single word queries if the word contains at least 3 characters\n   * and is not a stop word.\n   * Can take two values: true or false.\n   * By default, its set to false.\n   * @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery\n   * @member {boolean}\n   */ this . enableExactOnSingleWordQuery = params . enableExactOnSingleWordQuery ; // Undocumented parameters, still needed otherwise we fail this . offset = params . offset ; this . length = params . length ; var self = this ; forOwn ( params , function checkForUnknownParameter ( paramValue , paramName ) { if ( SearchParameters . PARAMETERS . indexOf ( paramName ) === - 1 ) { self [ paramName ] = paramValue ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all refinements ( disjunctive + conjunctive + excludes + numeric filters ) [CODESPLIT] function clearRefinements ( attribute ) { var clear = RefinementList . clearRefinement ; var patch = { numericRefinements : this . _clearNumericRefinements ( attribute ) , facetsRefinements : clear ( this . facetsRefinements , attribute , 'conjunctiveFacet' ) , facetsExcludes : clear ( this . facetsExcludes , attribute , 'exclude' ) , disjunctiveFacetsRefinements : clear ( this . disjunctiveFacetsRefinements , attribute , 'disjunctiveFacet' ) , hierarchicalFacetsRefinements : clear ( this . hierarchicalFacetsRefinements , attribute , 'hierarchicalFacet' ) } ; if ( patch . numericRefinements === this . numericRefinements && patch . facetsRefinements === this . facetsRefinements && patch . facetsExcludes === this . facetsExcludes && patch . disjunctiveFacetsRefinements === this . disjunctiveFacetsRefinements && patch . hierarchicalFacetsRefinements === this . hierarchicalFacetsRefinements ) { return this ; } return this . setQueryParameters ( patch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a numeric filter for a given attribute When value is an array they are combined with OR When value is a single value it will combined with AND [CODESPLIT] function ( attribute , operator , v ) { var value = valToNumber ( v ) ; if ( this . isNumericRefined ( attribute , operator , value ) ) return this ; var mod = merge ( { } , this . numericRefinements ) ; mod [ attribute ] = merge ( { } , mod [ attribute ] ) ; if ( mod [ attribute ] [ operator ] ) { // Array copy mod [ attribute ] [ operator ] = mod [ attribute ] [ operator ] . slice ( ) ; // Add the element. Concat can't be used here because value can be an array. mod [ attribute ] [ operator ] . push ( value ) ; } else { mod [ attribute ] [ operator ] = [ value ] ; } return this . setQueryParameters ( { numericRefinements : mod } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all the numeric filter for a given ( attribute operator ) [CODESPLIT] function ( attribute , operator , paramValue ) { if ( paramValue !== undefined ) { var paramValueAsNumber = valToNumber ( paramValue ) ; if ( ! this . isNumericRefined ( attribute , operator , paramValueAsNumber ) ) return this ; return this . setQueryParameters ( { numericRefinements : this . _clearNumericRefinements ( function ( value , key ) { return key === attribute && value . op === operator && isEqual ( value . val , paramValueAsNumber ) ; } ) } ) ; } else if ( operator !== undefined ) { if ( ! this . isNumericRefined ( attribute , operator ) ) return this ; return this . setQueryParameters ( { numericRefinements : this . _clearNumericRefinements ( function ( value , key ) { return key === attribute && value . op === operator ; } ) } ) ; } if ( ! this . isNumericRefined ( attribute ) ) return this ; return this . setQueryParameters ( { numericRefinements : this . _clearNumericRefinements ( function ( value , key ) { return key === attribute ; } ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear numeric filters . [CODESPLIT] function _clearNumericRefinements ( attribute ) { if ( isUndefined ( attribute ) ) { if ( isEmpty ( this . numericRefinements ) ) return this . numericRefinements ; return { } ; } else if ( isString ( attribute ) ) { if ( isEmpty ( this . numericRefinements [ attribute ] ) ) return this . numericRefinements ; return omit ( this . numericRefinements , attribute ) ; } else if ( isFunction ( attribute ) ) { var hasChanged = false ; var newNumericRefinements = reduce ( this . numericRefinements , function ( memo , operators , key ) { var operatorList = { } ; forEach ( operators , function ( values , operator ) { var outValues = [ ] ; forEach ( values , function ( value ) { var predicateResult = attribute ( { val : value , op : operator } , key , 'numeric' ) ; if ( ! predicateResult ) outValues . push ( value ) ; } ) ; if ( ! isEmpty ( outValues ) ) { if ( outValues . length !== values . length ) hasChanged = true ; operatorList [ operator ] = outValues ; } else hasChanged = true ; } ) ; if ( ! isEmpty ( operatorList ) ) memo [ key ] = operatorList ; return memo ; } , { } ) ; if ( hasChanged ) return newNumericRefinements ; return this . numericRefinements ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a hierarchical facet to the hierarchicalFacets attribute of the helper configuration . [CODESPLIT] function addHierarchicalFacet ( hierarchicalFacet ) { if ( this . isHierarchicalFacet ( hierarchicalFacet . name ) ) { throw new Error ( 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet . name + '`' ) ; } return this . setQueryParameters ( { hierarchicalFacets : this . hierarchicalFacets . concat ( [ hierarchicalFacet ] ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a refinement on a normal facet [CODESPLIT] function addFacetRefinement ( facet , value ) { if ( ! this . isConjunctiveFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the facets attribute of the helper configuration' ) ; } if ( RefinementList . isRefined ( this . facetsRefinements , facet , value ) ) return this ; return this . setQueryParameters ( { facetsRefinements : RefinementList . addRefinement ( this . facetsRefinements , facet , value ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exclude a value from a normal facet [CODESPLIT] function addExcludeRefinement ( facet , value ) { if ( ! this . isConjunctiveFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the facets attribute of the helper configuration' ) ; } if ( RefinementList . isRefined ( this . facetsExcludes , facet , value ) ) return this ; return this . setQueryParameters ( { facetsExcludes : RefinementList . addRefinement ( this . facetsExcludes , facet , value ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a refinement on a disjunctive facet . [CODESPLIT] function addDisjunctiveFacetRefinement ( facet , value ) { if ( ! this . isDisjunctiveFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ) ; } if ( RefinementList . isRefined ( this . disjunctiveFacetsRefinements , facet , value ) ) return this ; return this . setQueryParameters ( { disjunctiveFacetsRefinements : RefinementList . addRefinement ( this . disjunctiveFacetsRefinements , facet , value ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "addTagRefinement adds a tag to the list used to filter the results [CODESPLIT] function addTagRefinement ( tag ) { if ( this . isTagRefined ( tag ) ) return this ; var modification = { tagRefinements : this . tagRefinements . concat ( tag ) } ; return this . setQueryParameters ( modification ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a facet from the facets attribute of the helper configuration if it is present . [CODESPLIT] function removeFacet ( facet ) { if ( ! this . isConjunctiveFacet ( facet ) ) { return this ; } return this . clearRefinements ( facet ) . setQueryParameters ( { facets : filter ( this . facets , function ( f ) { return f !== facet ; } ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a disjunctive facet from the disjunctiveFacets attribute of the helper configuration if it is present . [CODESPLIT] function removeDisjunctiveFacet ( facet ) { if ( ! this . isDisjunctiveFacet ( facet ) ) { return this ; } return this . clearRefinements ( facet ) . setQueryParameters ( { disjunctiveFacets : filter ( this . disjunctiveFacets , function ( f ) { return f !== facet ; } ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a hierarchical facet from the hierarchicalFacets attribute of the helper configuration if it is present . [CODESPLIT] function removeHierarchicalFacet ( facet ) { if ( ! this . isHierarchicalFacet ( facet ) ) { return this ; } return this . clearRefinements ( facet ) . setQueryParameters ( { hierarchicalFacets : filter ( this . hierarchicalFacets , function ( f ) { return f . name !== facet ; } ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a refinement set on facet . If a value is provided it will clear the refinement for the given value otherwise it will clear all the refinement values for the faceted attribute . [CODESPLIT] function removeFacetRefinement ( facet , value ) { if ( ! this . isConjunctiveFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the facets attribute of the helper configuration' ) ; } if ( ! RefinementList . isRefined ( this . facetsRefinements , facet , value ) ) return this ; return this . setQueryParameters ( { facetsRefinements : RefinementList . removeRefinement ( this . facetsRefinements , facet , value ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a negative refinement on a facet [CODESPLIT] function removeExcludeRefinement ( facet , value ) { if ( ! this . isConjunctiveFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the facets attribute of the helper configuration' ) ; } if ( ! RefinementList . isRefined ( this . facetsExcludes , facet , value ) ) return this ; return this . setQueryParameters ( { facetsExcludes : RefinementList . removeRefinement ( this . facetsExcludes , facet , value ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a refinement on a disjunctive facet [CODESPLIT] function removeDisjunctiveFacetRefinement ( facet , value ) { if ( ! this . isDisjunctiveFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ) ; } if ( ! RefinementList . isRefined ( this . disjunctiveFacetsRefinements , facet , value ) ) return this ; return this . setQueryParameters ( { disjunctiveFacetsRefinements : RefinementList . removeRefinement ( this . disjunctiveFacetsRefinements , facet , value ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a tag from the list of tag refinements [CODESPLIT] function removeTagRefinement ( tag ) { if ( ! this . isTagRefined ( tag ) ) return this ; var modification = { tagRefinements : filter ( this . tagRefinements , function ( t ) { return t !== tag ; } ) } ; return this . setQueryParameters ( modification ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generic toggle refinement method to use with facet disjunctive facets and hierarchical facets [CODESPLIT] function toggleFacetRefinement ( facet , value ) { if ( this . isHierarchicalFacet ( facet ) ) { return this . toggleHierarchicalFacetRefinement ( facet , value ) ; } else if ( this . isConjunctiveFacet ( facet ) ) { return this . toggleConjunctiveFacetRefinement ( facet , value ) ; } else if ( this . isDisjunctiveFacet ( facet ) ) { return this . toggleDisjunctiveFacetRefinement ( facet , value ) ; } throw new Error ( 'Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Switch the refinement applied over a facet / value [CODESPLIT] function toggleConjunctiveFacetRefinement ( facet , value ) { if ( ! this . isConjunctiveFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the facets attribute of the helper configuration' ) ; } return this . setQueryParameters ( { facetsRefinements : RefinementList . toggleRefinement ( this . facetsRefinements , facet , value ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Switch the refinement applied over a facet / value [CODESPLIT] function toggleExcludeFacetRefinement ( facet , value ) { if ( ! this . isConjunctiveFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the facets attribute of the helper configuration' ) ; } return this . setQueryParameters ( { facetsExcludes : RefinementList . toggleRefinement ( this . facetsExcludes , facet , value ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Switch the refinement applied over a facet / value [CODESPLIT] function toggleDisjunctiveFacetRefinement ( facet , value ) { if ( ! this . isDisjunctiveFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ) ; } return this . setQueryParameters ( { disjunctiveFacetsRefinements : RefinementList . toggleRefinement ( this . disjunctiveFacetsRefinements , facet , value ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Switch the refinement applied over a facet / value [CODESPLIT] function toggleHierarchicalFacetRefinement ( facet , value ) { if ( ! this . isHierarchicalFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration' ) ; } var separator = this . _getHierarchicalFacetSeparator ( this . getHierarchicalFacetByName ( facet ) ) ; var mod = { } ; var upOneOrMultipleLevel = this . hierarchicalFacetsRefinements [ facet ] !== undefined && this . hierarchicalFacetsRefinements [ facet ] . length > 0 && ( // remove current refinement: // refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer` this . hierarchicalFacetsRefinements [ facet ] [ 0 ] === value || // remove a parent refinement of the current refinement: //  - refinement was 'beer > IPA > Flying dog' //  - call is toggleRefine('beer > IPA') //  - refinement should be `beer` this . hierarchicalFacetsRefinements [ facet ] [ 0 ] . indexOf ( value + separator ) === 0 ) ; if ( upOneOrMultipleLevel ) { if ( value . indexOf ( separator ) === - 1 ) { // go back to root level mod [ facet ] = [ ] ; } else { mod [ facet ] = [ value . slice ( 0 , value . lastIndexOf ( separator ) ) ] ; } } else { mod [ facet ] = [ value ] ; } return this . setQueryParameters ( { hierarchicalFacetsRefinements : defaults ( { } , mod , this . hierarchicalFacetsRefinements ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a refinement on a hierarchical facet . [CODESPLIT] function ( facet , path ) { if ( this . isHierarchicalFacetRefined ( facet ) ) { throw new Error ( facet + ' is already refined.' ) ; } var mod = { } ; mod [ facet ] = [ path ] ; return this . setQueryParameters ( { hierarchicalFacetsRefinements : defaults ( { } , mod , this . hierarchicalFacetsRefinements ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the facet is refined either for a specific value or in general . [CODESPLIT] function isFacetRefined ( facet , value ) { if ( ! this . isConjunctiveFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the facets attribute of the helper configuration' ) ; } return RefinementList . isRefined ( this . facetsRefinements , facet , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the facet contains exclusions or if a specific value is excluded . [CODESPLIT] function isExcludeRefined ( facet , value ) { if ( ! this . isConjunctiveFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the facets attribute of the helper configuration' ) ; } return RefinementList . isRefined ( this . facetsExcludes , facet , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the facet contains a refinement or if a value passed is a refinement for the facet . [CODESPLIT] function isDisjunctiveFacetRefined ( facet , value ) { if ( ! this . isDisjunctiveFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ) ; } return RefinementList . isRefined ( this . disjunctiveFacetsRefinements , facet , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the facet contains a refinement or if a value passed is a refinement for the facet . [CODESPLIT] function isHierarchicalFacetRefined ( facet , value ) { if ( ! this . isHierarchicalFacet ( facet ) ) { throw new Error ( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration' ) ; } var refinements = this . getHierarchicalRefinement ( facet ) ; if ( ! value ) { return refinements . length > 0 ; } return indexOf ( refinements , value ) !== - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if the triple ( attribute operator value ) is already refined . If only the attribute and the operator are provided it tests if the contains any refinement value . [CODESPLIT] function isNumericRefined ( attribute , operator , value ) { if ( isUndefined ( value ) && isUndefined ( operator ) ) { return ! ! this . numericRefinements [ attribute ] ; } var isOperatorDefined = this . numericRefinements [ attribute ] && ! isUndefined ( this . numericRefinements [ attribute ] [ operator ] ) ; if ( isUndefined ( value ) || ! isOperatorDefined ) { return isOperatorDefined ; } var parsedValue = valToNumber ( value ) ; var isAttributeValueDefined = ! isUndefined ( findArray ( this . numericRefinements [ attribute ] [ operator ] , parsedValue ) ) ; return isOperatorDefined && isAttributeValueDefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the list of all disjunctive facets refined [CODESPLIT] function getRefinedDisjunctiveFacets ( ) { // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection ( keys ( this . numericRefinements ) , this . disjunctiveFacets ) ; return keys ( this . disjunctiveFacetsRefinements ) . concat ( disjunctiveNumericRefinedFacets ) . concat ( this . getRefinedHierarchicalFacets ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Let the user set a specific value for a given parameter . Will return the same instance if the parameter is invalid or if the value is the same as the previous one . [CODESPLIT] function setParameter ( parameter , value ) { if ( this [ parameter ] === value ) return this ; var modification = { } ; modification [ parameter ] = value ; return this . setQueryParameters ( modification ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Let the user set any of the parameters with a plain object . [CODESPLIT] function setQueryParameters ( params ) { if ( ! params ) return this ; var error = SearchParameters . validate ( this , params ) ; if ( error ) { throw error ; } var parsedParams = SearchParameters . _parseNumbers ( params ) ; return this . mutateMe ( function mergeWith ( newInstance ) { var ks = keys ( params ) ; forEach ( ks , function ( k ) { newInstance [ k ] = parsedParams [ k ] ; } ) ; return newInstance ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current breadcrumb for a hierarchical facet as an array [CODESPLIT] function ( facetName ) { if ( ! this . isHierarchicalFacet ( facetName ) ) { throw new Error ( 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`' ) ; } var refinement = this . getHierarchicalRefinement ( facetName ) [ 0 ] ; if ( ! refinement ) return [ ] ; var separator = this . _getHierarchicalFacetSeparator ( this . getHierarchicalFacetByName ( facetName ) ) ; var path = refinement . split ( separator ) ; return map ( path , trim ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event triggered when the queue of queries have been depleted ( with any result or outdated queries ) @event AlgoliaSearchHelper#event : searchQueueEmpty @example helper . on ( searchQueueEmpty function () { console . log ( No more search pending ) ; // This is received before the result event if we re not expecting new results } ) ; [CODESPLIT] function AlgoliaSearchHelper ( client , index , options ) { if ( client . addAlgoliaAgent && ! doesClientAgentContainsHelper ( client ) ) { client . addAlgoliaAgent ( 'JS Helper (' + version + ')' ) ; } this . setClient ( client ) ; var opts = options || { } ; opts . index = index ; this . state = SearchParameters . make ( opts ) ; this . lastResults = null ; this . _queryId = 0 ; this . _lastQueryIdReceived = - 1 ; this . derivedHelpers = [ ] ; this . _currentNbQueries = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs a command using the specified arguments . [CODESPLIT] function runCommand ( cmd , args ) { var prev = null ; console . log ( chalk . cyanBright ( cmd ) + \" \" + args . map ( arg => { if ( arg . startsWith ( \"-\" ) ) return chalk . gray ( \"\\\\\" ) + \"\\n \" + chalk . bold ( arg ) ; return arg ; } ) . join ( \" \" ) + \"\\n\" ) ; var proc = child_process . spawnSync ( cmd , args , { stdio : \"inherit\" } ) ; if ( proc . error ) throw proc . error ; if ( proc . status !== 0 ) throw Error ( \"exited with \" + proc . status ) ; return proc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles embedded intrinsics used by the targets below . [CODESPLIT] function compileIntrinsics ( ) { var target = path . join ( sourceDirectory , \"passes\" , \"WasmIntrinsics.cpp\" ) ; runCommand ( \"python\" , [ path . join ( binaryenDirectory , \"scripts\" , \"embedwast.py\" ) , path . join ( sourceDirectory , \"passes\" , \"wasm-intrinsics.wast\" ) , target ] ) ; sourceFiles . push ( target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles shared bitcode used to build the targets below . [CODESPLIT] function compileShared ( ) { runCommand ( \"python\" , [ path . join ( emscriptenDirectory , \"em++\" ) ] . concat ( sourceFiles ) . concat ( commonOptions ) . concat ( [ \"-o\" , \"shared.bc\" ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles the JavaScript target . [CODESPLIT] function compileJs ( options ) { runCommand ( \"python\" , [ path . join ( emscriptenDirectory , \"em++\" ) , \"shared.bc\" ] . concat ( commonOptions ) . concat ( [ \"--post-js\" , options . post , \"--closure\" , \"1\" , \"-s\" , \"WASM=0\" , \"-s\" , \"EXPORTED_FUNCTIONS=[\" + exportedFunctionsArg + \"]\" , \"-s\" , \"ALLOW_MEMORY_GROWTH=1\" , \"-s\" , \"ELIMINATE_DUPLICATE_FUNCTIONS=1\" , \"-s\" , \"MODULARIZE_INSTANCE=1\" , \"-s\" , \"EXPORT_NAME=\\\"Binaryen\\\"\" , \"-o\" , options . out , \"-Oz\" ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles the WebAssembly target . [CODESPLIT] function compileWasm ( options ) { run ( \"python\" , [ path . join ( emscriptenDirectory , \"em++\" ) , \"shared.bc\" ] . concat ( commonOptions ) . concat ( [ \"--post-js\" , options . post , \"--closure\" , \"1\" , \"-s\" , \"EXPORTED_FUNCTIONS=[\" + exportedFunctionsArg + \"]\" , \"-s\" , \"ALLOW_MEMORY_GROWTH=1\" , \"-s\" , \"BINARYEN=1\" , \"-s\" , \"BINARYEN_METHOD=\\\"native-wasm\\\"\" , \"-s\" , \"MODULARIZE_INSTANCE=1\" , \"-s\" , \"EXPORT_NAME=\\\"Binaryen\\\"\" , \"-o\" , options . out , \"-Oz\" ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a function returning the state object [CODESPLIT] function pluginState ( ) { return { _sync : { signedIn : false , userId : null , unsubscribe : { } , pathVariables : { } , patching : false , syncStack : { inserts : [ ] , updates : { } , propDeletions : { } , deletions : [ ] , debounceTimer : null , } , fetched : { } , stopPatchingTimeout : null } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge if exists [CODESPLIT] function helpers ( originVal , newVal ) { if ( isArray ( originVal ) && isArrayHelper ( newVal ) ) { newVal = newVal . executeOn ( originVal ) ; } if ( isNumber ( originVal ) && isIncrementHelper ( newVal ) ) { newVal = newVal . executeOn ( originVal ) ; } return newVal ; // always return newVal as fallback!! }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Debounce helper [CODESPLIT] function startDebounce ( ms ) { var startTime = Date . now ( ) ; var done = new Promise ( function ( resolve , reject ) { var interval = setInterval ( function ( _ ) { var now = Date . now ( ) ; var deltaT = now - startTime ; if ( deltaT >= ms ) { clearInterval ( interval ) ; resolve ( true ) ; } } , 10 ) ; } ) ; var refresh = function ( ) { return ( startTime = Date . now ( ) ) ; } ; return { done : done , refresh : refresh } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grab until the api limit ( 500 ) put the rest back in the syncStack . [CODESPLIT] function grabUntilApiLimit ( syncStackProp , count , maxCount , state ) { var targets = state . _sync . syncStack [ syncStackProp ] ; // Check if there are more than maxCount batch items already if ( count >= maxCount ) { // already at maxCount or more, leave items in syncstack, and don't add anything to batch targets = [ ] ; } else { // Convert to array if targets is an object (eg. updates) var targetIsObject = isPlainObject ( targets ) ; if ( targetIsObject ) { targets = Object . values ( targets ) ; } // Batch supports only until maxCount items var grabCount = maxCount - count ; var targetsOK = targets . slice ( 0 , grabCount ) ; var targetsLeft = targets . slice ( grabCount ) ; // Put back the remaining items over maxCount if ( targetIsObject ) { targetsLeft = Object . values ( targetsLeft ) . reduce ( function ( carry , update ) { var id = update . id ; carry [ id ] = update ; return carry ; } , { } ) ; } state . _sync . syncStack [ syncStackProp ] = targetsLeft ; // Define the items we'll add below targets = targetsOK ; } return targets ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Firebase batch from a syncStack to be passed inside the state param . [CODESPLIT] function makeBatchFromSyncstack ( state , getters , Firebase , batchMaxCount ) { if ( batchMaxCount === void 0 ) { batchMaxCount = 500 ; } // get state & getter variables var firestorePath = state . _conf . firestorePath ; var firestorePathComplete = getters . firestorePathComplete ; var dbRef = getters . dbRef ; var collectionMode = getters . collectionMode ; // make batch var batch = Firebase . firestore ( ) . batch ( ) ; var log = { } ; var count = 0 ; // Add 'updates' to batch var updates = grabUntilApiLimit ( 'updates' , count , batchMaxCount , state ) ; log [ 'updates: ' ] = updates ; count = count + updates . length ; // Add to batch updates . forEach ( function ( item ) { var id = item . id ; var docRef = ( collectionMode ) ? dbRef . doc ( id ) : dbRef ; if ( state . _conf . sync . guard . includes ( 'id' ) ) delete item . id ; // @ts-ignore batch . update ( docRef , item ) ; } ) ; // Add 'propDeletions' to batch var propDeletions = grabUntilApiLimit ( 'propDeletions' , count , batchMaxCount , state ) ; log [ 'prop deletions: ' ] = propDeletions ; count = count + propDeletions . length ; // Add to batch propDeletions . forEach ( function ( item ) { var id = item . id ; var docRef = ( collectionMode ) ? dbRef . doc ( id ) : dbRef ; if ( state . _conf . sync . guard . includes ( 'id' ) ) delete item . id ; // @ts-ignore batch . update ( docRef , item ) ; } ) ; // Add 'deletions' to batch var deletions = grabUntilApiLimit ( 'deletions' , count , batchMaxCount , state ) ; log [ 'deletions: ' ] = deletions ; count = count + deletions . length ; // Add to batch deletions . forEach ( function ( id ) { var docRef = dbRef . doc ( id ) ; batch . delete ( docRef ) ; } ) ; // Add 'inserts' to batch var inserts = grabUntilApiLimit ( 'inserts' , count , batchMaxCount , state ) ; log [ 'inserts: ' ] = inserts ; count = count + inserts . length ; // Add to batch inserts . forEach ( function ( item ) { var newRef = dbRef . doc ( item . id ) ; batch . set ( newRef , item ) ; } ) ; // log the batch contents if ( state . _conf . logging ) { console . group ( '[vuex-easy-firestore] api call batch:' ) ; console . log ( \"%cFirestore PATH: \" + firestorePathComplete + \" [\" + firestorePath + \"]\" , 'color: grey' ) ; Object . keys ( log ) . forEach ( function ( key ) { console . log ( key , log [ key ] ) ; } ) ; console . groupEnd ( ) ; } return batch ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the matches of path variables : eg . return [ groupId ] if pathPiece is { groupId } [CODESPLIT] function getPathVarMatches ( pathPiece ) { var matches = pathPiece . match ( / \\{([a-z]+)\\} / gi ) ; if ( ! matches ) return [ ] ; return matches . map ( function ( key ) { return trimAccolades ( key ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets an object with { where orderBy } filters and returns a unique identifier for that [CODESPLIT] function createFetchIdentifier ( whereOrderBy ) { if ( whereOrderBy === void 0 ) { whereOrderBy = { } ; } var identifier = '' ; if ( 'where' in whereOrderBy ) { identifier += '[where]' + whereOrderBy . where . map ( function ( where ) { return stringifyParams ( where ) ; } ) . join ( ) ; } if ( 'orderBy' in whereOrderBy ) { identifier += '[orderBy]' + stringifyParams ( whereOrderBy . orderBy ) ; } if ( 'pathVariables' in whereOrderBy ) { delete whereOrderBy . pathVariables . where ; delete whereOrderBy . pathVariables . orderBy ; identifier += '[pathVariables]' + JSON . stringify ( whereOrderBy . pathVariables ) ; } return identifier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a value of a payload piece . Eg . { [ id ] : val } will return val [CODESPLIT] function getValueFromPayloadPiece ( payloadPiece ) { if ( isPlainObject ( payloadPiece ) && ! payloadPiece . id && Object . keys ( payloadPiece ) . length === 1 && isPlainObject ( payloadPiece [ Object . keys ( payloadPiece ) [ 0 ] ] ) ) { return Object . values ( payloadPiece ) [ 0 ] ; } return payloadPiece ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "define storeUpdateFn () [CODESPLIT] function storeUpdateFn ( _doc ) { switch ( change ) { case 'added' : commit ( 'INSERT_DOC' , _doc ) ; break ; case 'removed' : commit ( 'DELETE_DOC' , id ) ; break ; default : dispatch ( 'deleteMissingProps' , _doc ) ; commit ( 'PATCH_DOC' , _doc ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "define the store update [CODESPLIT] function storeUpdateFn ( _val ) { commit ( 'PATCH_DOC' , _val ) ; return dispatch ( 'patchDoc' , { id : id , doc : copy ( _val ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "define the store update [CODESPLIT] function storeUpdateFn ( _doc , _ids ) { _ids . forEach ( function ( _id ) { commit ( 'PATCH_DOC' , __assign ( { id : _id } , _doc ) ) ; } ) ; return dispatch ( 'patchDoc' , { ids : _ids , doc : _doc } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "define the store update [CODESPLIT] function storeUpdateFn ( _ids ) { _ids . forEach ( function ( _id ) { // id is a path var pathDelete = ( _id . includes ( '.' ) || ! getters . collectionMode ) ; if ( pathDelete ) { var path = _id ; if ( ! path ) return error ( 'delete-missing-path' ) ; commit ( 'DELETE_PROP' , path ) ; return dispatch ( 'deleteProp' , path ) ; } if ( ! _id ) return error ( 'delete-missing-id' ) ; commit ( 'DELETE_DOC' , _id ) ; return dispatch ( 'deleteDoc' , _id ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the config for type errors for non - TypeScript users [CODESPLIT] function errorCheck ( config ) { var errors = [ ] ; var reqProps = [ 'firestorePath' , 'moduleName' ] ; reqProps . forEach ( function ( prop ) { if ( ! config [ prop ] ) { errors . push ( \"Missing `\" + prop + \"` in your module!\" ) ; } } ) ; if ( / (\\.|\\/) / . test ( config . statePropName ) ) { errors . push ( \"statePropName must only include letters from [a-z]\" ) ; } if ( / \\. / . test ( config . moduleName ) ) { errors . push ( \"moduleName must only include letters from [a-z] and forward slashes '/'\" ) ; } var syncProps = [ 'where' , 'orderBy' , 'fillables' , 'guard' , 'defaultValues' , 'insertHook' , 'patchHook' , 'deleteHook' , 'insertBatchHook' , 'patchBatchHook' , 'deleteBatchHook' ] ; syncProps . forEach ( function ( prop ) { if ( config [ prop ] ) { errors . push ( \"We found `\" + prop + \"` on your module, are you sure this shouldn't be inside a prop called `sync`?\" ) ; } } ) ; var serverChangeProps = [ 'modifiedHook' , 'defaultValues' , 'addedHook' , 'removedHook' ] ; serverChangeProps . forEach ( function ( prop ) { if ( config [ prop ] ) { errors . push ( \"We found `\" + prop + \"` on your module, are you sure this shouldn't be inside a prop called `serverChange`?\" ) ; } } ) ; var fetchProps = [ 'docLimit' ] ; fetchProps . forEach ( function ( prop ) { if ( config [ prop ] ) { errors . push ( \"We found `\" + prop + \"` on your module, are you sure this shouldn't be inside a prop called `fetch`?\" ) ; } } ) ; var numberProps = [ 'docLimit' ] ; numberProps . forEach ( function ( prop ) { var _prop = config . fetch [ prop ] ; if ( ! isNumber ( _prop ) ) errors . push ( \"`\" + prop + \"` should be a Number, but is not.\" ) ; } ) ; var functionProps = [ 'insertHook' , 'patchHook' , 'deleteHook' , 'insertBatchHook' , 'patchBatchHook' , 'deleteBatchHook' , 'addedHook' , 'modifiedHook' , 'removedHook' ] ; functionProps . forEach ( function ( prop ) { var _prop = ( syncProps . includes ( prop ) ) ? config . sync [ prop ] : config . serverChange [ prop ] ; if ( ! isFunction ( _prop ) ) errors . push ( \"`\" + prop + \"` should be a Function, but is not.\" ) ; } ) ; var objectProps = [ 'sync' , 'serverChange' , 'defaultValues' , 'fetch' ] ; objectProps . forEach ( function ( prop ) { var _prop = ( prop === 'defaultValues' ) ? config . sync [ prop ] : config [ prop ] ; if ( ! isPlainObject ( _prop ) ) errors . push ( \"`\" + prop + \"` should be an Object, but is not.\" ) ; } ) ; var stringProps = [ 'firestorePath' , 'firestoreRefType' , 'moduleName' , 'statePropName' ] ; stringProps . forEach ( function ( prop ) { var _prop = config [ prop ] ; if ( ! isString ( _prop ) ) errors . push ( \"`\" + prop + \"` should be a String, but is not.\" ) ; } ) ; var arrayProps = [ 'where' , 'orderBy' , 'fillables' , 'guard' ] ; arrayProps . forEach ( function ( prop ) { var _prop = config . sync [ prop ] ; if ( ! isArray ( _prop ) ) errors . push ( \"`\" + prop + \"` should be an Array, but is not.\" ) ; } ) ; if ( errors . length ) { console . group ( '[vuex-easy-firestore] ERRORS:' ) ; console . error ( \"Module: \" + config . moduleName ) ; errors . forEach ( function ( e ) { return console . error ( ' - ' , e ) ; } ) ; console . groupEnd ( ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A function that returns a vuex module object with seamless 2 - way sync for firestore . [CODESPLIT] function iniModule ( userConfig , FirebaseDependency ) { // prepare state._conf var conf = copy ( merge ( { state : { } , mutations : { } , actions : { } , getters : { } } , defaultConfig , userConfig ) ) ; if ( ! errorCheck ( conf ) ) return ; var userState = conf . state ; var userMutations = conf . mutations ; var userActions = conf . actions ; var userGetters = conf . getters ; delete conf . state ; delete conf . mutations ; delete conf . actions ; delete conf . getters ; // prepare rest of state var docContainer = { } ; if ( conf . statePropName ) docContainer [ conf . statePropName ] = { } ; var restOfState = merge ( userState , docContainer ) ; // if 'doc' mode, set merge initial state onto default values if ( conf . firestoreRefType === 'doc' ) { var defaultValsInState = ( conf . statePropName ) ? restOfState [ conf . statePropName ] : restOfState ; conf . sync . defaultValues = copy ( merge ( defaultValsInState , conf . sync . defaultValues ) ) ; } return { namespaced : true , state : merge ( pluginState ( ) , restOfState , { _conf : conf } ) , mutations : merge ( userMutations , pluginMutations ( merge ( userState , { _conf : conf } ) ) ) , actions : merge ( userActions , pluginActions ( FirebaseDependency ) ) , getters : merge ( userGetters , pluginGetters ( FirebaseDependency ) ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------------------------------ Builds ------------------------------------------------------------------------------------------ [CODESPLIT] function defaults ( config ) { // defaults const defaults = { plugins , external } // defaults.output config . output = config . output . map ( output => { return Object . assign ( { sourcemap : false , name : className , } , output ) } ) return Object . assign ( defaults , config ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a function returning the mutations object [CODESPLIT] function pluginMutations ( userState ) { return { SET_PATHVARS : function ( state , pathVars ) { var self = this ; Object . keys ( pathVars ) . forEach ( function ( key ) { var pathPiece = pathVars [ key ] ; self . _vm . $set ( state . _sync . pathVariables , key , pathPiece ) ; } ) ; } , SET_SYNCFILTERS : function ( state , _a ) { var where = _a . where , orderBy = _a . orderBy ; if ( where && isWhat . isArray ( where ) ) state . _conf . sync . where = where ; if ( orderBy && isWhat . isArray ( orderBy ) ) state . _conf . sync . orderBy = orderBy ; } , SET_USER_ID : function ( state , userId ) { if ( ! userId ) { state . _sync . signedIn = false ; state . _sync . userId = null ; } else { state . _sync . signedIn = true ; state . _sync . userId = userId ; } } , CLEAR_USER : function ( state ) { state . _sync . signedIn = false ; state . _sync . userId = null ; } , RESET_VUEX_EASY_FIRESTORE_STATE : function ( state ) { // unsubscribe all DBChannel listeners: Object . keys ( state . _sync . unsubscribe ) . forEach ( function ( unsubscribe ) { if ( isWhat . isFunction ( unsubscribe ) ) unsubscribe ( ) ; } ) ; var self = this ; var _sync = merge ( state . _sync , { // make null once to be able to overwrite with empty object unsubscribe : null , pathVariables : null , syncStack : { updates : null , propDeletions : null } , fetched : null , } , { unsubscribe : { } , pathVariables : { } , patching : false , syncStack : { inserts : [ ] , updates : { } , propDeletions : { } , deletions : [ ] , debounceTimer : null , } , fetched : { } , stopPatchingTimeout : null } ) ; var newState = merge ( userState , { _sync : _sync } ) ; var docContainer = ( state . _conf . statePropName ) ? state [ state . _conf . statePropName ] : state ; Object . keys ( newState ) . forEach ( function ( key ) { self . _vm . $set ( state , key , newState [ key ] ) ; } ) ; Object . keys ( docContainer ) . forEach ( function ( key ) { if ( Object . keys ( newState ) . includes ( key ) ) return ; self . _vm . $delete ( docContainer , key ) ; } ) ; } , resetSyncStack : function ( state ) { state . _sync . syncStack = { updates : { } , deletions : [ ] , inserts : [ ] , debounceTimer : null } ; } , INSERT_DOC : function ( state , doc ) { if ( state . _conf . firestoreRefType . toLowerCase ( ) !== 'collection' ) return ; if ( state . _conf . statePropName ) { this . _vm . $set ( state [ state . _conf . statePropName ] , doc . id , doc ) ; } else { this . _vm . $set ( state , doc . id , doc ) ; } } , PATCH_DOC : function ( state , patches ) { var _this = this ; // Get the state prop ref var ref = ( state . _conf . statePropName ) ? state [ state . _conf . statePropName ] : state ; if ( state . _conf . firestoreRefType . toLowerCase ( ) === 'collection' ) { ref = ref [ patches . id ] ; } if ( ! ref ) return error ( 'patch-no-ref' ) ; return Object . keys ( patches ) . forEach ( function ( key ) { var newVal = patches [ key ] ; // Merge if exists function helpers ( originVal , newVal ) { if ( isWhat . isArray ( originVal ) && isArrayHelper ( newVal ) ) { newVal = newVal . executeOn ( originVal ) ; } if ( isWhat . isNumber ( originVal ) && isIncrementHelper ( newVal ) ) { newVal = newVal . executeOn ( originVal ) ; } return newVal ; // always return newVal as fallback!! } newVal = merge ( { extensions : [ helpers ] } , ref [ key ] , patches [ key ] ) ; _this . _vm . $set ( ref , key , newVal ) ; } ) ; } , DELETE_DOC : function ( state , id ) { if ( state . _conf . firestoreRefType . toLowerCase ( ) !== 'collection' ) return ; if ( state . _conf . statePropName ) { this . _vm . $delete ( state [ state . _conf . statePropName ] , id ) ; } else { this . _vm . $delete ( state , id ) ; } } , DELETE_PROP : function ( state , path ) { var searchTarget = ( state . _conf . statePropName ) ? state [ state . _conf . statePropName ] : state ; var propArr = path . split ( '.' ) ; var target = propArr . pop ( ) ; if ( ! propArr . length ) { return this . _vm . $delete ( searchTarget , target ) ; } var ref = vuexEasyAccess . getDeepRef ( searchTarget , propArr . join ( '.' ) ) ; return this . _vm . $delete ( ref , target ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert to new Date () if defaultValue == %convertTimestamp% [CODESPLIT] function convertTimestamps ( originVal , targetVal ) { if ( originVal === '%convertTimestamp%' ) { // firestore timestamps // @ts-ignore if ( isWhat . isAnyObject ( targetVal ) && ! isWhat . isPlainObject ( targetVal ) && isWhat . isFunction ( targetVal . toDate ) ) { // @ts-ignore return targetVal . toDate ( ) ; } // strings if ( isWhat . isString ( targetVal ) && isWhat . isDate ( new Date ( targetVal ) ) ) { return new Date ( targetVal ) ; } } return targetVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge an object onto defaultValues [CODESPLIT] function setDefaultValues ( obj , defaultValues ) { if ( ! isWhat . isPlainObject ( defaultValues ) ) console . error ( '[vuex-easy-firestore] Trying to merge target:' , obj , 'onto a non-object (defaultValues):' , defaultValues ) ; if ( ! isWhat . isPlainObject ( obj ) ) console . error ( '[vuex-easy-firestore] Trying to merge a non-object:' , obj , 'onto the defaultValues:' , defaultValues ) ; var result = merge ( { extensions : [ convertTimestamps ] } , defaultValues , obj ) ; return findAndReplaceAnything . findAndReplace ( result , '%convertTimestamp%' , null , { onlyPlainObjects : true } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets an ID from a single piece of payload . [CODESPLIT] function getId ( payloadPiece , conf , path , fullPayload ) { if ( isWhat . isString ( payloadPiece ) ) return payloadPiece ; if ( isWhat . isPlainObject ( payloadPiece ) ) { if ( 'id' in payloadPiece ) return payloadPiece . id ; var keys = Object . keys ( payloadPiece ) ; if ( keys . length === 1 ) return keys [ 0 ] ; } return '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A function returning the actions object [CODESPLIT] function pluginActions ( Firebase ) { var _this = this ; return { setUserId : function ( _a , userId ) { var commit = _a . commit , getters = _a . getters ; if ( userId === undefined ) userId = null ; // undefined cannot be synced to firestore if ( ! userId && Firebase . auth ( ) . currentUser ) { userId = Firebase . auth ( ) . currentUser . uid ; } commit ( 'SET_USER_ID' , userId ) ; if ( getters . firestorePathComplete . includes ( '{userId}' ) ) return error ( 'user-auth' ) ; } , clearUser : function ( _a ) { var commit = _a . commit ; commit ( 'CLEAR_USER' ) ; } , setPathVars : function ( _a , pathVars ) { var commit = _a . commit ; commit ( 'SET_PATHVARS' , pathVars ) ; } , duplicate : function ( _a , id ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; return __awaiter ( _this , void 0 , void 0 , function ( ) { var _b , doc , dId , idMap ; return __generator ( this , function ( _c ) { switch ( _c . label ) { case 0 : if ( ! getters . collectionMode ) return [ 2 /*return*/ , error ( 'only-in-collection-mode' ) ] ; if ( ! id ) return [ 2 /*return*/ , { } ] ; doc = merge ( getters . storeRef [ id ] , { id : null } ) ; return [ 4 /*yield*/ , dispatch ( 'insert' , doc ) ] ; case 1 : dId = _c . sent ( ) ; idMap = ( _b = { } , _b [ id ] = dId , _b ) ; return [ 2 /*return*/ , idMap ] ; } } ) ; } ) ; } , duplicateBatch : function ( _a , ids ) { var _this = this ; var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; if ( ids === void 0 ) { ids = [ ] ; } if ( ! getters . collectionMode ) return error ( 'only-in-collection-mode' ) ; if ( ! isWhat . isArray ( ids ) || ! ids . length ) return { } ; var idsMap = ids . reduce ( function ( carry , id ) { return __awaiter ( _this , void 0 , void 0 , function ( ) { var idMap ; return __generator ( this , function ( _a ) { switch ( _a . label ) { case 0 : return [ 4 /*yield*/ , dispatch ( 'duplicate' , id ) ] ; case 1 : idMap = _a . sent ( ) ; return [ 4 /*yield*/ , carry ] ; case 2 : carry = _a . sent ( ) ; return [ 2 /*return*/ , Object . assign ( carry , idMap ) ] ; } } ) ; } ) ; } , { } ) ; return idsMap ; } , patchDoc : function ( _a , _b ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; var _c = _b === void 0 ? { ids : [ ] , doc : { } } : _b , _d = _c . id , id = _d === void 0 ? '' : _d , _e = _c . ids , ids = _e === void 0 ? [ ] : _e , doc = _c . doc ; // 0. payload correction (only arrays) if ( ! isWhat . isArray ( ids ) ) return error ( \"`ids` prop passed to 'patch' needs to be an array\" ) ; if ( id ) ids . push ( id ) ; // EXTRA: check if doc is being inserted if so state . _sync . syncStack . inserts . forEach ( function ( newDoc , newDocIndex ) { // get the index of the id that is also in the insert stack var indexIdInInsert = ids . indexOf ( newDoc . id ) ; if ( indexIdInInsert === - 1 ) return ; // the doc trying to be synced is also in insert // prepare the doc as new doc: var patchDoc = getters . prepareForInsert ( [ doc ] ) [ 0 ] ; // replace insert sync stack with merged item: state . _sync . syncStack . inserts [ newDocIndex ] = merge ( newDoc , patchDoc ) ; // empty out the id that was to be patched: ids . splice ( indexIdInInsert , 1 ) ; } ) ; // 1. Prepare for patching var syncStackItems = getters . prepareForPatch ( ids , doc ) ; // 2. Push to syncStack Object . keys ( syncStackItems ) . forEach ( function ( id ) { var newVal ; if ( ! state . _sync . syncStack . updates [ id ] ) { // replace arrayUnion and arrayRemove newVal = findAndReplaceAnything . findAndReplaceIf ( syncStackItems [ id ] , function ( foundVal ) { if ( isArrayHelper ( foundVal ) ) { return foundVal . getFirestoreFieldValue ( ) ; } if ( isIncrementHelper ( foundVal ) ) { return foundVal . getFirestoreFieldValue ( ) ; } return foundVal ; } ) ; } else { newVal = merge ( { extensions : [ function ( originVal , newVal ) { if ( originVal instanceof Firebase . firestore . FieldValue && isArrayHelper ( newVal ) ) { originVal . _elements = originVal . _elements . concat ( newVal . payload ) ; newVal = originVal ; } if ( originVal instanceof Firebase . firestore . FieldValue && isIncrementHelper ( newVal ) ) { originVal . _operand = originVal . _operand + newVal . payload ; newVal = originVal ; } return newVal ; // always return newVal as fallback!! } ] } , state . _sync . syncStack . updates [ id ] , syncStackItems [ id ] ) ; } state . _sync . syncStack . updates [ id ] = newVal ; } ) ; // 3. Create or refresh debounce return dispatch ( 'handleSyncStackDebounce' ) ; } , deleteDoc : function ( _a , ids ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; if ( ids === void 0 ) { ids = [ ] ; } // 0. payload correction (only arrays) if ( ! isWhat . isArray ( ids ) ) ids = [ ids ] ; // 1. Prepare for patching // 2. Push to syncStack var deletions = state . _sync . syncStack . deletions . concat ( ids ) ; state . _sync . syncStack . deletions = deletions ; if ( ! state . _sync . syncStack . deletions . length ) return ; // 3. Create or refresh debounce return dispatch ( 'handleSyncStackDebounce' ) ; } , deleteProp : function ( _a , path ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; // 1. Prepare for patching var syncStackItem = getters . prepareForPropDeletion ( path ) ; // 2. Push to syncStack Object . keys ( syncStackItem ) . forEach ( function ( id ) { var newVal = ( ! state . _sync . syncStack . propDeletions [ id ] ) ? syncStackItem [ id ] : merge ( state . _sync . syncStack . propDeletions [ id ] , syncStackItem [ id ] ) ; state . _sync . syncStack . propDeletions [ id ] = newVal ; } ) ; // 3. Create or refresh debounce return dispatch ( 'handleSyncStackDebounce' ) ; } , insertDoc : function ( _a , docs ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; if ( docs === void 0 ) { docs = [ ] ; } // 0. payload correction (only arrays) if ( ! isWhat . isArray ( docs ) ) docs = [ docs ] ; // 1. Prepare for patching var syncStack = getters . prepareForInsert ( docs ) ; // 2. Push to syncStack var inserts = state . _sync . syncStack . inserts . concat ( syncStack ) ; state . _sync . syncStack . inserts = inserts ; // 3. Create or refresh debounce dispatch ( 'handleSyncStackDebounce' ) ; return docs . map ( function ( d ) { return d . id ; } ) ; } , insertInitialDoc : function ( _a ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; // 0. only docMode if ( getters . collectionMode ) return ; // 1. Prepare for insert var initialDoc = ( getters . storeRef ) ? getters . storeRef : { } ; var initialDocPrepared = getters . prepareInitialDocForInsert ( initialDoc ) ; // 2. Create a reference to the SF doc. var initialDocRef = getters . dbRef ; return Firebase . firestore ( ) . runTransaction ( function ( transaction ) { // This code may get re-run multiple times if there are conflicts. return transaction . get ( initialDocRef ) . then ( function ( foundInitialDoc ) { if ( ! foundInitialDoc . exists ) { transaction . set ( initialDocRef , initialDocPrepared ) ; } } ) ; } ) . then ( function ( _ ) { if ( state . _conf . logging ) { console . log ( '[vuex-easy-firestore] Initial doc succesfully inserted.' ) ; } } ) . catch ( function ( error$1 ) { return error ( 'initial-doc-failed' , error$1 ) ; } ) ; } , handleSyncStackDebounce : function ( _a ) { var state = _a . state , commit = _a . commit , dispatch = _a . dispatch , getters = _a . getters ; if ( ! getters . signedIn ) return false ; if ( ! state . _sync . syncStack . debounceTimer ) { var ms = state . _conf . sync . debounceTimerMs ; var debounceTimer = startDebounce ( ms ) ; debounceTimer . done . then ( function ( _ ) { return dispatch ( 'batchSync' ) ; } ) ; state . _sync . syncStack . debounceTimer = debounceTimer ; } state . _sync . syncStack . debounceTimer . refresh ( ) ; } , batchSync : function ( _a ) { var getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch , state = _a . state ; var batch = makeBatchFromSyncstack ( state , getters , Firebase ) ; dispatch ( '_startPatching' ) ; state . _sync . syncStack . debounceTimer = null ; return new Promise ( function ( resolve , reject ) { batch . commit ( ) . then ( function ( _ ) { var remainingSyncStack = Object . keys ( state . _sync . syncStack . updates ) . length + state . _sync . syncStack . deletions . length + state . _sync . syncStack . inserts . length + state . _sync . syncStack . propDeletions . length ; if ( remainingSyncStack ) { dispatch ( 'batchSync' ) ; } dispatch ( '_stopPatching' ) ; return resolve ( ) ; } ) . catch ( function ( error$1 ) { state . _sync . patching = 'error' ; state . _sync . syncStack . debounceTimer = null ; return reject ( error$1 ) ; } ) ; } ) ; } , fetch : function ( _a , pathVariables // where: [['archived', '==', true]] // orderBy: ['done_date', 'desc'] ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; if ( pathVariables === void 0 ) { pathVariables = { where : [ ] , whereFilters : [ ] , orderBy : [ ] } ; } dispatch ( 'setUserId' ) ; var where = pathVariables . where , whereFilters = pathVariables . whereFilters , orderBy = pathVariables . orderBy ; if ( ! isWhat . isArray ( where ) ) where = [ ] ; if ( ! isWhat . isArray ( orderBy ) ) orderBy = [ ] ; if ( isWhat . isArray ( whereFilters ) && whereFilters . length ) where = whereFilters ; // depreciated if ( pathVariables && isWhat . isPlainObject ( pathVariables ) ) { commit ( 'SET_PATHVARS' , pathVariables ) ; } return new Promise ( function ( resolve , reject ) { // log if ( state . _conf . logging ) { console . log ( \"%c fetch for Firestore PATH: \" + getters . firestorePathComplete + \" [\" + state . _conf . firestorePath + \"]\" , 'color: lightcoral' ) ; } if ( ! getters . signedIn ) return resolve ( ) ; var identifier = createFetchIdentifier ( { where : where , orderBy : orderBy } ) ; var fetched = state . _sync . fetched [ identifier ] ; // We've never fetched this before: if ( ! fetched ) { var ref_1 = getters . dbRef ; // apply where filters and orderBy getters . getWhereArrays ( where ) . forEach ( function ( paramsArr ) { ref_1 = ref_1 . where . apply ( ref_1 , paramsArr ) ; } ) ; if ( orderBy . length ) ref_1 = ref_1 . orderBy . apply ( ref_1 , orderBy ) ; state . _sync . fetched [ identifier ] = { ref : ref_1 , done : false , retrievedFetchRefs : [ ] , nextFetchRef : null } ; } var fRequest = state . _sync . fetched [ identifier ] ; // We're already done fetching everything: if ( fRequest . done ) { if ( state . _conf . logging ) console . log ( '[vuex-easy-firestore] done fetching' ) ; return resolve ( { done : true } ) ; } // attach fetch filters var fRef = state . _sync . fetched [ identifier ] . ref ; if ( fRequest . nextFetchRef ) { // get next ref if saved in state fRef = state . _sync . fetched [ identifier ] . nextFetchRef ; } // add doc limit var limit = ( isWhat . isNumber ( pathVariables . limit ) ) ? pathVariables . limit : state . _conf . fetch . docLimit ; if ( limit > 0 ) fRef = fRef . limit ( limit ) ; // Stop if all records already fetched if ( fRequest . retrievedFetchRefs . includes ( fRef ) ) { console . log ( '[vuex-easy-firestore] Already retrieved this part.' ) ; return resolve ( ) ; } // make fetch request fRef . get ( ) . then ( function ( querySnapshot ) { var docs = querySnapshot . docs ; if ( docs . length === 0 ) { state . _sync . fetched [ identifier ] . done = true ; querySnapshot . done = true ; return resolve ( querySnapshot ) ; } if ( docs . length < limit ) { state . _sync . fetched [ identifier ] . done = true ; } state . _sync . fetched [ identifier ] . retrievedFetchRefs . push ( fRef ) ; // Get the last visible document resolve ( querySnapshot ) ; var lastVisible = docs [ docs . length - 1 ] ; // set the reference for the next records. var next = fRef . startAfter ( lastVisible ) ; state . _sync . fetched [ identifier ] . nextFetchRef = next ; } ) . catch ( function ( error$1 ) { return reject ( error ( error$1 ) ) ; } ) ; } ) ; } , fetchAndAdd : function ( _a , pathVariables // where: [['archived', '==', true]] // orderBy: ['done_date', 'desc'] ) { var _this = this ; var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; if ( pathVariables === void 0 ) { pathVariables = { where : [ ] , whereFilters : [ ] , orderBy : [ ] } ; } if ( pathVariables && isWhat . isPlainObject ( pathVariables ) ) { commit ( 'SET_PATHVARS' , pathVariables ) ; } // 'doc' mode: if ( ! getters . collectionMode ) { dispatch ( 'setUserId' ) ; if ( state . _conf . logging ) { console . log ( \"%c fetch for Firestore PATH: \" + getters . firestorePathComplete + \" [\" + state . _conf . firestorePath + \"]\" , 'color: lightcoral' ) ; } return getters . dbRef . get ( ) . then ( function ( _doc ) { return __awaiter ( _this , void 0 , void 0 , function ( ) { var id , doc ; return __generator ( this , function ( _a ) { switch ( _a . label ) { case 0 : if ( ! ! _doc . exists ) return [ 3 /*break*/ , 2 ] ; // No initial doc found in docMode if ( state . _conf . sync . preventInitialDocInsertion ) throw 'preventInitialDocInsertion' ; if ( state . _conf . logging ) console . log ( '[vuex-easy-firestore] inserting initial doc' ) ; return [ 4 /*yield*/ , dispatch ( 'insertInitialDoc' ) ] ; case 1 : _a . sent ( ) ; return [ 2 /*return*/ , _doc ] ; case 2 : id = getters . docModeId ; doc = getters . cleanUpRetrievedDoc ( _doc . data ( ) , id ) ; dispatch ( 'applyHooksAndUpdateState' , { change : 'modified' , id : id , doc : doc } ) ; return [ 2 /*return*/ , doc ] ; } } ) ; } ) ; } ) . catch ( function ( error$1 ) { return error ( error$1 ) ; } ) ; } // 'collection' mode: return dispatch ( 'fetch' , pathVariables ) . then ( function ( querySnapshot ) { if ( querySnapshot . done === true ) return querySnapshot ; if ( isWhat . isFunction ( querySnapshot . forEach ) ) { querySnapshot . forEach ( function ( _doc ) { var id = _doc . id ; var doc = getters . cleanUpRetrievedDoc ( _doc . data ( ) , id ) ; dispatch ( 'applyHooksAndUpdateState' , { change : 'added' , id : id , doc : doc } ) ; } ) ; } return querySnapshot ; } ) ; } , fetchById : function ( _a , id ) { var dispatch = _a . dispatch , getters = _a . getters , state = _a . state ; return __awaiter ( this , void 0 , void 0 , function ( ) { var ref , _doc , doc , e_1 ; return __generator ( this , function ( _b ) { switch ( _b . label ) { case 0 : _b . trys . push ( [ 0 , 2 , , 3 ] ) ; if ( ! id ) throw 'missing-id' ; if ( ! getters . collectionMode ) throw 'only-in-collection-mode' ; ref = getters . dbRef ; return [ 4 /*yield*/ , ref . doc ( id ) . get ( ) ] ; case 1 : _doc = _b . sent ( ) ; if ( ! _doc . exists ) { if ( state . _conf . logging ) { throw \"Doc with id \\\"\" + id + \"\\\" not found!\" ; } } doc = getters . cleanUpRetrievedDoc ( _doc . data ( ) , id ) ; dispatch ( 'applyHooksAndUpdateState' , { change : 'added' , id : id , doc : doc } ) ; return [ 2 /*return*/ , doc ] ; case 2 : e_1 = _b . sent ( ) ; return [ 2 /*return*/ , error ( e_1 ) ] ; case 3 : return [ 2 /*return*/ ] ; } } ) ; } ) ; } , applyHooksAndUpdateState : function ( // this is only on server retrievals _a , _b ) { var getters = _a . getters , state = _a . state , commit = _a . commit , dispatch = _a . dispatch ; var change = _b . change , id = _b . id , _c = _b . doc , doc = _c === void 0 ? { } : _c ; var store = this ; // define storeUpdateFn() function storeUpdateFn ( _doc ) { switch ( change ) { case 'added' : commit ( 'INSERT_DOC' , _doc ) ; break ; case 'removed' : commit ( 'DELETE_DOC' , id ) ; break ; default : dispatch ( 'deleteMissingProps' , _doc ) ; commit ( 'PATCH_DOC' , _doc ) ; break ; } } // get user set sync hook function var syncHookFn = state . _conf . serverChange [ change + 'Hook' ] ; if ( isWhat . isFunction ( syncHookFn ) ) { syncHookFn ( storeUpdateFn , doc , id , store , 'server' , change ) ; } else { storeUpdateFn ( doc ) ; } } , deleteMissingProps : function ( _a , doc ) { var getters = _a . getters , commit = _a . commit ; var defaultValues = getters . defaultValues ; var searchTarget = ( getters . collectionMode ) ? getters . storeRef [ doc . id ] : getters . storeRef ; var compareInfo = compareAnything . compareObjectProps ( flatten ( doc ) , // presentIn 0 flatten ( defaultValues ) , // presentIn 1 flatten ( searchTarget ) // presentIn 2 ) ; Object . keys ( compareInfo . presentIn ) . forEach ( function ( prop ) { // don't worry about props not in fillables if ( getters . fillables . length && ! getters . fillables . includes ( prop ) ) { return ; } // don't worry about props in guard if ( getters . guard . includes ( prop ) ) return ; // don't worry about props starting with _sync or _conf if ( prop . split ( '.' ) [ 0 ] === '_sync' || prop . split ( '.' ) [ 0 ] === '_conf' ) return ; // where is the prop present? var presence = compareInfo . presentIn [ prop ] ; var propNotInDoc = ( ! presence . includes ( 0 ) ) ; var propNotInDefaultValues = ( ! presence . includes ( 1 ) ) ; // delete props that are not present in the doc and default values if ( propNotInDoc && propNotInDefaultValues ) { var path = ( getters . collectionMode ) ? doc . id + \".\" + prop : prop ; return commit ( 'DELETE_PROP' , path ) ; } } ) ; } , openDBChannel : function ( _a , pathVariables ) { var _this = this ; var getters = _a . getters , state = _a . state , commit = _a . commit , dispatch = _a . dispatch ; dispatch ( 'setUserId' ) ; // `first` makes sure that local changes made during offline are reflected as server changes which the app is refreshed during offline mode var first = true ; // set state for pathVariables if ( pathVariables && isWhat . isPlainObject ( pathVariables ) ) { commit ( 'SET_SYNCFILTERS' , pathVariables ) ; delete pathVariables . where ; delete pathVariables . orderBy ; commit ( 'SET_PATHVARS' , pathVariables ) ; } var identifier = createFetchIdentifier ( { where : state . _conf . sync . where , orderBy : state . _conf . sync . orderBy , pathVariables : state . _sync . pathVariables } ) ; if ( isWhat . isFunction ( state . _sync . unsubscribe [ identifier ] ) ) { var channelAlreadyOpenError_1 = \"openDBChannel was already called for these filters and pathvariables. Identifier: \" + identifier ; if ( state . _conf . logging ) { console . log ( channelAlreadyOpenError_1 ) ; } return new Promise ( function ( resolve , reject ) { reject ( channelAlreadyOpenError_1 ) ; } ) ; } // getters.dbRef should already have pathVariables swapped out var dbRef = getters . dbRef ; // apply where filters and orderBy if ( getters . collectionMode ) { getters . getWhereArrays ( ) . forEach ( function ( whereParams ) { dbRef = dbRef . where . apply ( dbRef , whereParams ) ; } ) ; if ( state . _conf . sync . orderBy . length ) { dbRef = dbRef . orderBy . apply ( dbRef , state . _conf . sync . orderBy ) ; } } // make a promise return new Promise ( function ( resolve , reject ) { // log if ( state . _conf . logging ) { console . log ( \"%c openDBChannel for Firestore PATH: \" + getters . firestorePathComplete + \" [\" + state . _conf . firestorePath + \"]\" , 'color: lightcoral' ) ; } var unsubscribe = dbRef . onSnapshot ( function ( querySnapshot ) { return __awaiter ( _this , void 0 , void 0 , function ( ) { var source , id , doc ; return __generator ( this , function ( _a ) { switch ( _a . label ) { case 0 : source = querySnapshot . metadata . hasPendingWrites ? 'local' : 'server' ; if ( ! ! getters . collectionMode ) return [ 3 /*break*/ , 3 ] ; if ( ! ! querySnapshot . data ( ) ) return [ 3 /*break*/ , 2 ] ; // No initial doc found in docMode if ( state . _conf . sync . preventInitialDocInsertion ) return [ 2 /*return*/ , reject ( 'preventInitialDocInsertion' ) ] ; if ( state . _conf . logging ) console . log ( '[vuex-easy-firestore] inserting initial doc' ) ; return [ 4 /*yield*/ , dispatch ( 'insertInitialDoc' ) ] ; case 1 : _a . sent ( ) ; return [ 2 /*return*/ , resolve ( ) ] ; case 2 : if ( source === 'local' && ! first ) return [ 2 /*return*/ , resolve ( ) ] ; id = getters . docModeId ; doc = getters . cleanUpRetrievedDoc ( querySnapshot . data ( ) , id ) ; dispatch ( 'applyHooksAndUpdateState' , { change : 'modified' , id : id , doc : doc } ) ; first = false ; return [ 2 /*return*/ , resolve ( ) ] ; case 3 : // 'collection' mode: querySnapshot . docChanges ( ) . forEach ( function ( change ) { var changeType = change . type ; // Don't do anything for local modifications & removals if ( source === 'local' && ! first ) return resolve ( ) ; var id = change . doc . id ; var doc = getters . cleanUpRetrievedDoc ( change . doc . data ( ) , id ) ; dispatch ( 'applyHooksAndUpdateState' , { change : changeType , id : id , doc : doc } ) ; } ) ; first = false ; return [ 2 /*return*/ , resolve ( ) ] ; } } ) ; } ) ; } , function ( error$1 ) { state . _sync . patching = 'error' ; return reject ( error ( error$1 ) ) ; } ) ; state . _sync . unsubscribe [ identifier ] = unsubscribe ; } ) ; } , closeDBChannel : function ( _a , _b ) { var getters = _a . getters , state = _a . state , commit = _a . commit , dispatch = _a . dispatch ; var _c = ( _b === void 0 ? { clearModule : false } : _b ) . clearModule , clearModule = _c === void 0 ? false : _c ; var identifier = createFetchIdentifier ( { where : state . _conf . sync . where , orderBy : state . _conf . sync . orderBy , pathVariables : state . _sync . pathVariables } ) ; var unsubscribeDBChannel = state . _sync . unsubscribe [ identifier ] ; if ( isWhat . isFunction ( unsubscribeDBChannel ) ) { unsubscribeDBChannel ( ) ; state . _sync . unsubscribe [ identifier ] = null ; } if ( clearModule ) { commit ( 'RESET_VUEX_EASY_FIRESTORE_STATE' ) ; } } , set : function ( _a , doc ) { var commit = _a . commit , dispatch = _a . dispatch , getters = _a . getters , state = _a . state ; if ( ! doc ) return ; if ( ! getters . collectionMode ) { return dispatch ( 'patch' , doc ) ; } var id = getId ( doc ) ; if ( ! id || ( ! state . _conf . statePropName && ! state [ id ] ) || ( state . _conf . statePropName && ! state [ state . _conf . statePropName ] [ id ] ) ) { return dispatch ( 'insert' , doc ) ; } return dispatch ( 'patch' , doc ) ; } , insert : function ( _a , doc ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; var store = this ; // check payload if ( ! doc ) return ; // check userId dispatch ( 'setUserId' ) ; var newDoc = doc ; if ( ! newDoc . id ) newDoc . id = getters . dbRef . doc ( ) . id ; // apply default values var newDocWithDefaults = setDefaultValues ( newDoc , state . _conf . sync . defaultValues ) ; // define the store update function storeUpdateFn ( _doc ) { commit ( 'INSERT_DOC' , _doc ) ; return dispatch ( 'insertDoc' , _doc ) ; } // check for hooks if ( state . _conf . sync . insertHook ) { state . _conf . sync . insertHook ( storeUpdateFn , newDocWithDefaults , store ) ; return newDocWithDefaults . id ; } storeUpdateFn ( newDocWithDefaults ) ; return newDocWithDefaults . id ; } , insertBatch : function ( _a , docs ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; var store = this ; // check payload if ( ! isWhat . isArray ( docs ) || ! docs . length ) return [ ] ; // check userId dispatch ( 'setUserId' ) ; var newDocs = docs . reduce ( function ( carry , _doc ) { var newDoc = getValueFromPayloadPiece ( _doc ) ; if ( ! newDoc . id ) newDoc . id = getters . dbRef . doc ( ) . id ; carry . push ( newDoc ) ; return carry ; } , [ ] ) ; // define the store update function storeUpdateFn ( _docs ) { _docs . forEach ( function ( _doc ) { commit ( 'INSERT_DOC' , _doc ) ; } ) ; return dispatch ( 'insertDoc' , _docs ) ; } // check for hooks if ( state . _conf . sync . insertBatchHook ) { state . _conf . sync . insertBatchHook ( storeUpdateFn , newDocs , store ) ; return newDocs . map ( function ( _doc ) { return _doc . id ; } ) ; } storeUpdateFn ( newDocs ) ; return newDocs . map ( function ( _doc ) { return _doc . id ; } ) ; } , patch : function ( _a , doc ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; var store = this ; // check payload if ( ! doc ) return ; var id = ( getters . collectionMode ) ? getId ( doc ) : getters . docModeId ; var value = ( getters . collectionMode ) ? getValueFromPayloadPiece ( doc ) : doc ; if ( ! id && getters . collectionMode ) return error ( 'patch-missing-id' ) ; // check userId dispatch ( 'setUserId' ) ; // add id to value if ( ! value . id ) value . id = id ; // define the store update function storeUpdateFn ( _val ) { commit ( 'PATCH_DOC' , _val ) ; return dispatch ( 'patchDoc' , { id : id , doc : copy ( _val ) } ) ; } // check for hooks if ( state . _conf . sync . patchHook ) { state . _conf . sync . patchHook ( storeUpdateFn , value , store ) ; return id ; } storeUpdateFn ( value ) ; return id ; } , patchBatch : function ( _a , _b ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; var doc = _b . doc , _c = _b . ids , ids = _c === void 0 ? [ ] : _c ; var store = this ; // check payload if ( ! doc ) return [ ] ; if ( ! isWhat . isArray ( ids ) || ! ids . length ) return [ ] ; // check userId dispatch ( 'setUserId' ) ; // define the store update function storeUpdateFn ( _doc , _ids ) { _ids . forEach ( function ( _id ) { commit ( 'PATCH_DOC' , __assign ( { id : _id } , _doc ) ) ; } ) ; return dispatch ( 'patchDoc' , { ids : _ids , doc : _doc } ) ; } // check for hooks if ( state . _conf . sync . patchBatchHook ) { state . _conf . sync . patchBatchHook ( storeUpdateFn , doc , ids , store ) ; return ids ; } storeUpdateFn ( doc , ids ) ; return ids ; } , delete : function ( _a , id ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; var store = this ; // check payload if ( ! id ) return ; // check userId dispatch ( 'setUserId' ) ; function storeUpdateFn ( _id ) { // id is a path var pathDelete = ( _id . includes ( '.' ) || ! getters . collectionMode ) ; if ( pathDelete ) { var path = _id ; if ( ! path ) return error ( 'delete-missing-path' ) ; commit ( 'DELETE_PROP' , path ) ; return dispatch ( 'deleteProp' , path ) ; } if ( ! _id ) return error ( 'delete-missing-id' ) ; commit ( 'DELETE_DOC' , _id ) ; return dispatch ( 'deleteDoc' , _id ) ; } // check for hooks if ( state . _conf . sync . deleteHook ) { state . _conf . sync . deleteHook ( storeUpdateFn , id , store ) ; return id ; } storeUpdateFn ( id ) ; return id ; } , deleteBatch : function ( _a , ids ) { var state = _a . state , getters = _a . getters , commit = _a . commit , dispatch = _a . dispatch ; var store = this ; // check payload if ( ! isWhat . isArray ( ids ) || ! ids . length ) return [ ] ; // check userId dispatch ( 'setUserId' ) ; // define the store update function storeUpdateFn ( _ids ) { _ids . forEach ( function ( _id ) { // id is a path var pathDelete = ( _id . includes ( '.' ) || ! getters . collectionMode ) ; if ( pathDelete ) { var path = _id ; if ( ! path ) return error ( 'delete-missing-path' ) ; commit ( 'DELETE_PROP' , path ) ; return dispatch ( 'deleteProp' , path ) ; } if ( ! _id ) return error ( 'delete-missing-id' ) ; commit ( 'DELETE_DOC' , _id ) ; return dispatch ( 'deleteDoc' , _id ) ; } ) ; } // check for hooks if ( state . _conf . sync . deleteBatchHook ) { state . _conf . sync . deleteBatchHook ( storeUpdateFn , ids , store ) ; return ids ; } storeUpdateFn ( ids ) ; return ids ; } , _stopPatching : function ( _a ) { var state = _a . state , commit = _a . commit ; if ( state . _sync . stopPatchingTimeout ) { clearTimeout ( state . _sync . stopPatchingTimeout ) ; } state . _sync . stopPatchingTimeout = setTimeout ( function ( _ ) { state . _sync . patching = false ; } , 300 ) ; } , _startPatching : function ( _a ) { var state = _a . state , commit = _a . commit ; if ( state . _sync . stopPatchingTimeout ) { clearTimeout ( state . _sync . stopPatchingTimeout ) ; } state . _sync . patching = true ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A function returning the getters object [CODESPLIT] function pluginGetters ( Firebase ) { return { firestorePathComplete : function ( state , getters ) { var path = state . _conf . firestorePath ; Object . keys ( state . _sync . pathVariables ) . forEach ( function ( key ) { var pathPiece = state . _sync . pathVariables [ key ] ; path = path . replace ( \"{\" + key + \"}\" , \"\" + pathPiece ) ; } ) ; var requireUser = path . includes ( '{userId}' ) ; if ( requireUser ) { var userId = state . _sync . userId ; if ( getters . signedIn && isWhat . isString ( userId ) && userId !== '' && userId !== '{userId}' ) { path = path . replace ( '{userId}' , userId ) ; } } return path ; } , signedIn : function ( state , getters , rootState , rootGetters ) { var requireUser = state . _conf . firestorePath . includes ( '{userId}' ) ; if ( ! requireUser ) return true ; return state . _sync . signedIn ; } , dbRef : function ( state , getters , rootState , rootGetters ) { var path = getters . firestorePathComplete ; return ( getters . collectionMode ) ? Firebase . firestore ( ) . collection ( path ) : Firebase . firestore ( ) . doc ( path ) ; } , storeRef : function ( state , getters , rootState ) { var path = ( state . _conf . statePropName ) ? state . _conf . moduleName + \"/\" + state . _conf . statePropName : state . _conf . moduleName ; return vuexEasyAccess . getDeepRef ( rootState , path ) ; } , collectionMode : function ( state , getters , rootState ) { return ( state . _conf . firestoreRefType . toLowerCase ( ) === 'collection' ) ; } , docModeId : function ( state , getters ) { return getters . firestorePathComplete . split ( '/' ) . pop ( ) ; } , fillables : function ( state ) { var fillables = state . _conf . sync . fillables ; if ( ! fillables . length ) return fillables ; return fillables . concat ( [ 'updated_at' , 'updated_by' , 'id' , 'created_at' , 'created_by' ] ) ; } , guard : function ( state ) { return state . _conf . sync . guard . concat ( [ '_conf' , '_sync' ] ) ; } , defaultValues : function ( state , getters ) { return merge ( state . _conf . sync . defaultValues , state . _conf . serverChange . defaultValues // depreciated ) ; } , cleanUpRetrievedDoc : function ( state , getters , rootState , rootGetters ) { return function ( doc , id ) { var defaultValues = merge ( getters . defaultValues , state . _conf . serverChange . convertTimestamps ) ; var cleanDoc = setDefaultValues ( doc , defaultValues ) ; cleanDoc . id = id ; return cleanDoc ; } ; } , prepareForPatch : function ( state , getters , rootState , rootGetters ) { return function ( ids , doc ) { if ( ids === void 0 ) { ids = [ ] ; } if ( doc === void 0 ) { doc = { } ; } // get relevant data from the storeRef var collectionMode = getters . collectionMode ; if ( ! collectionMode ) ids . push ( getters . docModeId ) ; // returns {object} -> {id: data} return ids . reduce ( function ( carry , id ) { var patchData = { } ; // retrieve full object in case there's an empty doc passed if ( ! Object . keys ( doc ) . length ) { patchData = ( collectionMode ) ? getters . storeRef [ id ] : getters . storeRef ; } else { patchData = doc ; } // set default fields patchData . updated_at = new Date ( ) ; patchData . updated_by = state . _sync . userId ; // clean up item var cleanedPatchData = filter ( patchData , getters . fillables , getters . guard ) ; var itemToUpdate = flatten ( cleanedPatchData ) ; // add id (required to get ref later at apiHelpers.ts) itemToUpdate . id = id ; carry [ id ] = itemToUpdate ; return carry ; } , { } ) ; } ; } , prepareForPropDeletion : function ( state , getters , rootState , rootGetters ) { return function ( path ) { if ( path === void 0 ) { path = '' ; } var _a ; var collectionMode = getters . collectionMode ; var patchData = { } ; // set default fields patchData . updated_at = new Date ( ) ; patchData . updated_by = state . _sync . userId ; // add fillable and guard defaults // clean up item var cleanedPatchData = filter ( patchData , getters . fillables , getters . guard ) ; // add id (required to get ref later at apiHelpers.ts) var id , cleanedPath ; if ( collectionMode ) { id = path . substring ( 0 , path . indexOf ( '.' ) ) ; cleanedPath = path . substring ( path . indexOf ( '.' ) + 1 ) ; } else { id = getters . docModeId ; cleanedPath = path ; } cleanedPatchData [ cleanedPath ] = Firebase . firestore . FieldValue . delete ( ) ; cleanedPatchData . id = id ; return _a = { } , _a [ id ] = cleanedPatchData , _a ; } ; } , prepareForInsert : function ( state , getters , rootState , rootGetters ) { return function ( items ) { if ( items === void 0 ) { items = [ ] ; } // add fillable and guard defaults return items . reduce ( function ( carry , item ) { // set default fields item . created_at = new Date ( ) ; item . created_by = state . _sync . userId ; // clean up item item = filter ( item , getters . fillables , getters . guard ) ; carry . push ( item ) ; return carry ; } , [ ] ) ; } ; } , prepareInitialDocForInsert : function ( state , getters , rootState , rootGetters ) { return function ( doc ) { // add fillable and guard defaults // set default fields doc . created_at = new Date ( ) ; doc . created_by = state . _sync . userId ; doc . id = getters . docModeId ; // clean up item doc = filter ( doc , getters . fillables , getters . guard ) ; return doc ; } ; } , getWhereArrays : function ( state , getters ) { return function ( whereArrays ) { if ( ! isWhat . isArray ( whereArrays ) ) whereArrays = state . _conf . sync . where ; if ( Firebase . auth ( ) . currentUser ) { state . _sync . signedIn = true ; state . _sync . userId = Firebase . auth ( ) . currentUser . uid ; } return whereArrays . map ( function ( whereClause ) { return whereClause . map ( function ( param ) { if ( ! isWhat . isString ( param ) ) return param ; var cleanedParam = param ; getPathVarMatches ( param ) . forEach ( function ( key ) { var keyRegEx = new RegExp ( \"{\" + key + \"}\" , 'g' ) ; if ( key === 'userId' ) { cleanedParam = cleanedParam . replace ( keyRegEx , state . _sync . userId ) ; return ; } if ( ! Object . keys ( state . _sync . pathVariables ) . includes ( key ) ) { return error ( 'missing-path-variables' ) ; } var varVal = state . _sync . pathVariables [ key ] ; // if path is only a param we need to just assign to avoid stringification if ( param === \"{\" + key + \"}\" ) { cleanedParam = varVal ; return ; } cleanedParam = cleanedParam . replace ( keyRegEx , varVal ) ; } ) ; return cleanedParam ; } ) ; } ) ; } ; } , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Firebase Create vuex - easy - firestore modules . Add as single plugin to Vuex Store . [CODESPLIT] function vuexEasyFirestore ( easyFirestoreModule , _a ) { var _b = _a === void 0 ? { logging : false , preventInitialDocInsertion : false , FirebaseDependency : Firebase$2 } : _a , _c = _b . logging , logging = _c === void 0 ? false : _c , _d = _b . preventInitialDocInsertion , preventInitialDocInsertion = _d === void 0 ? false : _d , _e = _b . FirebaseDependency , FirebaseDependency = _e === void 0 ? Firebase$2 : _e ; if ( FirebaseDependency ) { setFirebaseDependency ( FirebaseDependency ) ; setFirebaseDependency$1 ( FirebaseDependency ) ; } return function ( store ) { // Get an array of config files if ( ! isWhat . isArray ( easyFirestoreModule ) ) easyFirestoreModule = [ easyFirestoreModule ] ; // Create a module for each config file easyFirestoreModule . forEach ( function ( config ) { config . logging = logging ; if ( config . sync && config . sync . preventInitialDocInsertion === undefined ) { config . sync . preventInitialDocInsertion = preventInitialDocInsertion ; } var moduleName = vuexEasyAccess . getKeysFromPath ( config . moduleName ) ; store . registerModule ( moduleName , iniModule ( config , FirebaseDependency ) ) ; } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * eslint - disable [CODESPLIT] function addAttrs ( element , attrs ) { Object . keys ( attrs ) . forEach ( function ( key ) { element . setAttribute ( key , attrs [ key ] ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_transformToHierarchy - Transforms a flat array of parent - child links into a hierarchy . @private @param { array<object > } links Set of parent - child link objects @param { array<string > |undefined } attributeFields Set of link fields to be used as attributes [CODESPLIT] function _transformToHierarchy ( links , attributeFields ) { const nodesByName = { } ; const assignNode = name => { if ( ! nodesByName [ name ] ) { nodesByName [ name ] = { name } ; } return nodesByName [ name ] ; } ; const assignNodeWithAttributes = ( name , attributes ) => { if ( ! nodesByName [ name ] ) { nodesByName [ name ] = { name , attributes , } ; } return nodesByName [ name ] ; } ; // Create nodes for each unique source and target. links . forEach ( link => { // if `attributeFields` is defined, create/overwrite current `link.attributes` if ( attributeFields ) { const customAttributes = { } ; attributeFields . forEach ( field => { customAttributes [ field ] = link [ field ] ; } ) ; link . attributes = customAttributes ; } link . source = assignNode ( link . parent ) ; link . target = assignNodeWithAttributes ( link . child , link . attributes ) ; const parent = link . source ; const child = link . target ; parent . id = uuid . v4 ( ) ; child . id = uuid . v4 ( ) ; child . parent = parent . name || null ; parent . _collapsed = child . _collapsed = false ; // eslint-disable-line // NOTE We assign to a custom `_children` field instead of D3's reserved // `children` to avoid update anomalies when collapsing/re-expanding nodes. parent . _children ? parent . _children . push ( child ) : ( parent . _children = [ child ] ) ; } ) ; // Extract & return the root node const rootLinks = links . filter ( link => ! link . source . parent ) ; return [ rootLinks [ 0 ] . source ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parseCSV - Parses a CSV file into a hierarchy structure . [CODESPLIT] function parseCSV ( csvFilePath , attributeFields ) { return new Promise ( ( resolve , reject ) => { try { csv ( csvFilePath , data => resolve ( _transformToHierarchy ( data , attributeFields ) ) ) ; // lol hello Lisp } catch ( err ) { reject ( err ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parseJSON - Parses a hierarchical JSON file that requires no further transformation . [CODESPLIT] function parseJSON ( jsonFilePath ) { return new Promise ( ( resolve , reject ) => { try { json ( jsonFilePath , data => resolve ( [ data ] ) ) ; } catch ( err ) { reject ( err ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parseFlatJSON - Parses a flat JSON file into a hierarchy structure . [CODESPLIT] function parseFlatJSON ( jsonFilePath , attributeFields ) { return new Promise ( ( resolve , reject ) => { try { json ( jsonFilePath , data => resolve ( _transformToHierarchy ( data , attributeFields ) ) ) ; } catch ( err ) { reject ( err ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assert that the values match with the type specs . Error messages are memorized and will only be shown once . [CODESPLIT] function checkPropTypes ( typeSpecs , values , location , componentName , getStack ) { if ( true ) { for ( var typeSpecName in typeSpecs ) { if ( typeSpecs . hasOwnProperty ( typeSpecName ) ) { var error ; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if ( typeof typeSpecs [ typeSpecName ] !== 'function' ) { var err = Error ( ( componentName || 'React class' ) + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs [ typeSpecName ] + '`.' ) ; err . name = 'Invariant Violation' ; throw err ; } error = typeSpecs [ typeSpecName ] ( values , typeSpecName , componentName , location , null , ReactPropTypesSecret ) ; } catch ( ex ) { error = ex ; } if ( error && ! ( error instanceof Error ) ) { printWarning ( ( componentName || 'React class' ) + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).' ) } if ( error instanceof Error && ! ( error . message in loggedTypeFailures ) ) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures [ error . message ] = true ; var stack = getStack ? getStack ( ) : '' ; printWarning ( 'Failed ' + location + ' type: ' + error . message + ( stack != null ? stack : '' ) ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call a function while guarding against errors that happens within it . Returns an error if it throws otherwise null . [CODESPLIT] function invokeGuardedCallback ( name , func , context , a , b , c , d , e , f ) { hasError = false ; caughtError = null ; invokeGuardedCallbackImpl$1 . apply ( reporter , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as invokeGuardedCallback but instead of returning an error it stores it in a global so it can be rethrown by rethrowCaughtError later . TODO : See if caughtError and rethrowError can be unified . [CODESPLIT] function invokeGuardedCallbackAndCatchFirstError ( name , func , context , a , b , c , d , e , f ) { invokeGuardedCallback . apply ( this , arguments ) ; if ( hasError ) { var error = clearCaughtError ( ) ; if ( ! hasRethrowError ) { hasRethrowError = true ; rethrowError = error ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a DOM node return the closest ReactDOMComponent or ReactDOMTextComponent instance ancestor . [CODESPLIT] function getClosestInstanceFromNode ( node ) { if ( node [ internalInstanceKey ] ) { return node [ internalInstanceKey ] ; } while ( ! node [ internalInstanceKey ] ) { if ( node . parentNode ) { node = node . parentNode ; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null ; } } var inst = node [ internalInstanceKey ] ; if ( inst . tag === HostComponent || inst . tag === HostText ) { // In Fiber, this will always be the deepest root. return inst ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a DOM node return the ReactDOMComponent or ReactDOMTextComponent instance or null if the node was not rendered by this React . [CODESPLIT] function getInstanceFromNode$1 ( node ) { var inst = node [ internalInstanceKey ] ; if ( inst ) { if ( inst . tag === HostComponent || inst . tag === HostText ) { return inst ; } else { return null ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a ReactDOMComponent or ReactDOMTextComponent return the corresponding DOM node . [CODESPLIT] function getNodeFromInstance$1 ( inst ) { if ( inst . tag === HostComponent || inst . tag === HostText ) { // In Fiber this, is just the state node right now. We assume it will be // a host component or host text. return inst . stateNode ; } // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. invariant ( false , 'getNodeFromInstance: Invalid argument.' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Traverses the ID hierarchy and invokes the supplied cb on any IDs that should would receive a mouseEnter or mouseLeave event . [CODESPLIT] function traverseEnterLeave ( from , to , fn , argFrom , argTo ) { var common = from && to ? getLowestCommonAncestor ( from , to ) : null ; var pathFrom = [ ] ; while ( true ) { if ( ! from ) { break ; } if ( from === common ) { break ; } var alternate = from . alternate ; if ( alternate !== null && alternate === common ) { break ; } pathFrom . push ( from ) ; from = getParent ( from ) ; } var pathTo = [ ] ; while ( true ) { if ( ! to ) { break ; } if ( to === common ) { break ; } var _alternate = to . alternate ; if ( _alternate !== null && _alternate === common ) { break ; } pathTo . push ( to ) ; to = getParent ( to ) ; } for ( var i = 0 ; i < pathFrom . length ; i ++ ) { fn ( pathFrom [ i ] , 'bubbled' , argFrom ) ; } for ( var _i = pathTo . length ; _i -- > 0 ; ) { fn ( pathTo [ _i ] , 'captured' , argTo ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A small set of propagation patterns each of which will accept a small amount of information and generate a set of dispatch ready event objects - which are sets of events that have already been annotated with a set of dispatched listener functions / ids . The API is designed this way to discourage these propagation strategies from actually executing the dispatches since we always want to collect the entire set of dispatches before executing even a single one . Tags a SyntheticEvent with dispatched listeners . Creating this function here allows us to not have to bind or create functions for each event . Mutating the event s members allows us to not have to create a wrapping dispatch object that pairs the event with the listener . [CODESPLIT] function accumulateDirectionalDispatches ( inst , phase , event ) { { ! inst ? warningWithoutStack$1 ( false , 'Dispatching inst must not be null' ) : void 0 ; } var listener = listenerAtPhase ( inst , event , phase ) ; if ( listener ) { event . _dispatchListeners = accumulateInto ( event . _dispatchListeners , listener ) ; event . _dispatchInstances = accumulateInto ( event . _dispatchInstances , inst ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a mapping of standard vendor prefixes using the defined style property and event name . [CODESPLIT] function makePrefixMap ( styleProp , eventName ) { var prefixes = { } ; prefixes [ styleProp . toLowerCase ( ) ] = eventName . toLowerCase ( ) ; prefixes [ 'Webkit' + styleProp ] = 'webkit' + eventName ; prefixes [ 'Moz' + styleProp ] = 'moz' + eventName ; return prefixes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PooledClass looks for destructor on each instance it releases . [CODESPLIT] function ( ) { var Interface = this . constructor . Interface ; for ( var propName in Interface ) { { Object . defineProperty ( this , propName , getPooledWarningPropertyDefinition ( propName , Interface [ propName ] ) ) ; } } this . dispatchConfig = null ; this . _targetInst = null ; this . nativeEvent = null ; this . isDefaultPrevented = functionThatReturnsFalse ; this . isPropagationStopped = functionThatReturnsFalse ; this . _dispatchListeners = null ; this . _dispatchInstances = null ; { Object . defineProperty ( this , 'nativeEvent' , getPooledWarningPropertyDefinition ( 'nativeEvent' , null ) ) ; Object . defineProperty ( this , 'isDefaultPrevented' , getPooledWarningPropertyDefinition ( 'isDefaultPrevented' , functionThatReturnsFalse ) ) ; Object . defineProperty ( this , 'isPropagationStopped' , getPooledWarningPropertyDefinition ( 'isPropagationStopped' , functionThatReturnsFalse ) ) ; Object . defineProperty ( this , 'preventDefault' , getPooledWarningPropertyDefinition ( 'preventDefault' , function ( ) { } ) ) ; Object . defineProperty ( this , 'stopPropagation' , getPooledWarningPropertyDefinition ( 'stopPropagation' , function ( ) { } ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translate native top level events into event types . [CODESPLIT] function getCompositionEventType ( topLevelType ) { switch ( topLevelType ) { case TOP_COMPOSITION_START : return eventTypes . compositionStart ; case TOP_COMPOSITION_END : return eventTypes . compositionEnd ; case TOP_COMPOSITION_UPDATE : return eventTypes . compositionUpdate ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does our fallback mode think that this event is the end of composition? [CODESPLIT] function isFallbackCompositionEnd ( topLevelType , nativeEvent ) { switch ( topLevelType ) { case TOP_KEY_UP : // Command keys insert or clear IME input. return END_KEYCODES . indexOf ( nativeEvent . keyCode ) !== - 1 ; case TOP_KEY_DOWN : // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent . keyCode !== START_KEYCODE ; case TOP_KEY_PRESS : case TOP_MOUSE_DOWN : case TOP_BLUR : // Events are not possible without cancelling IME. return true ; default : return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value for a property on a node . Only used in DEV for SSR validation . The expected argument is used as a hint of what the expected value is . Some properties have multiple equivalent values . [CODESPLIT] function getValueForProperty ( node , name , expected , propertyInfo ) { { if ( propertyInfo . mustUseProperty ) { var propertyName = propertyInfo . propertyName ; return node [ propertyName ] ; } else { var attributeName = propertyInfo . attributeName ; var stringValue = null ; if ( propertyInfo . type === OVERLOADED_BOOLEAN ) { if ( node . hasAttribute ( attributeName ) ) { var value = node . getAttribute ( attributeName ) ; if ( value === '' ) { return true ; } if ( shouldRemoveAttribute ( name , expected , propertyInfo , false ) ) { return value ; } if ( value === '' + expected ) { return expected ; } return value ; } } else if ( node . hasAttribute ( attributeName ) ) { if ( shouldRemoveAttribute ( name , expected , propertyInfo , false ) ) { // We had an attribute but shouldn't have had one, so read it // for the error message. return node . getAttribute ( attributeName ) ; } if ( propertyInfo . type === BOOLEAN ) { // If this was a boolean, it doesn't matter what the value is // the fact that we have it is the same as the expected. return expected ; } // Even if this property uses a namespace we use getAttribute // because we assume its namespaced name is the same as our config. // To use getAttributeNS we need the local name which we don't have // in our config atm. stringValue = node . getAttribute ( attributeName ) ; } if ( shouldRemoveAttribute ( name , expected , propertyInfo , false ) ) { return stringValue === null ? expected : stringValue ; } else if ( stringValue === '' + expected ) { return expected ; } else { return stringValue ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value for a property on a node . [CODESPLIT] function setValueForProperty ( node , name , value , isCustomComponentTag ) { var propertyInfo = getPropertyInfo ( name ) ; if ( shouldIgnoreAttribute ( name , propertyInfo , isCustomComponentTag ) ) { return ; } if ( shouldRemoveAttribute ( name , value , propertyInfo , isCustomComponentTag ) ) { value = null ; } // If the prop isn't in the special list, treat it as a simple attribute. if ( isCustomComponentTag || propertyInfo === null ) { if ( isAttributeNameSafe ( name ) ) { var _attributeName = name ; if ( value === null ) { node . removeAttribute ( _attributeName ) ; } else { node . setAttribute ( _attributeName , '' + value ) ; } } return ; } var mustUseProperty = propertyInfo . mustUseProperty ; if ( mustUseProperty ) { var propertyName = propertyInfo . propertyName ; if ( value === null ) { var type = propertyInfo . type ; node [ propertyName ] = type === BOOLEAN ? false : '' ; } else { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node [ propertyName ] = value ; } return ; } // The rest are treated as attributes with special cases. var attributeName = propertyInfo . attributeName , attributeNamespace = propertyInfo . attributeNamespace ; if ( value === null ) { node . removeAttribute ( attributeName ) ; } else { var _type = propertyInfo . type ; var attributeValue = void 0 ; if ( _type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true ) { attributeValue = '' ; } else { // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. attributeValue = '' + value ; } if ( attributeNamespace ) { node . setAttributeNS ( attributeNamespace , attributeName , attributeValue ) ; } else { node . setAttribute ( attributeName , attributeValue ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements an <input > host component that allows setting these optional props : checked value defaultChecked and defaultValue . [CODESPLIT] function getHostProps ( element , props ) { var node = element ; var checked = props . checked ; var hostProps = _assign ( { } , props , { defaultChecked : undefined , defaultValue : undefined , value : undefined , checked : checked != null ? checked : node . _wrapperState . initialChecked } ) ; return hostProps ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For IE8 and IE9 . [CODESPLIT] function getTargetInstForInputEventPolyfill ( topLevelType , targetInst ) { if ( topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN ) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. return getInstIfValueChanged ( activeElementInst ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For almost every interaction we care about there will be both a top - level mouseover and mouseout event that occurs . Only use mouseout so that we do not extract duplicate events . However moving the mouse into the browser from outside will not fire a mouseout event . In this case we use the mouseover top - level event . [CODESPLIT] function ( topLevelType , targetInst , nativeEvent , nativeEventTarget ) { var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER ; var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT ; if ( isOverEvent && ( nativeEvent . relatedTarget || nativeEvent . fromElement ) ) { return null ; } if ( ! isOutEvent && ! isOverEvent ) { // Must not be a mouse or pointer in or out - ignoring. return null ; } var win = void 0 ; if ( nativeEventTarget . window === nativeEventTarget ) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget ; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget . ownerDocument ; if ( doc ) { win = doc . defaultView || doc . parentWindow ; } else { win = window ; } } var from = void 0 ; var to = void 0 ; if ( isOutEvent ) { from = targetInst ; var related = nativeEvent . relatedTarget || nativeEvent . toElement ; to = related ? getClosestInstanceFromNode ( related ) : null ; } else { // Moving to a node from outside the window. from = null ; to = targetInst ; } if ( from === to ) { // Nothing pertains to our managed components. return null ; } var eventInterface = void 0 , leaveEventType = void 0 , enterEventType = void 0 , eventTypePrefix = void 0 ; if ( topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER ) { eventInterface = SyntheticMouseEvent ; leaveEventType = eventTypes$2 . mouseLeave ; enterEventType = eventTypes$2 . mouseEnter ; eventTypePrefix = 'mouse' ; } else if ( topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER ) { eventInterface = SyntheticPointerEvent ; leaveEventType = eventTypes$2 . pointerLeave ; enterEventType = eventTypes$2 . pointerEnter ; eventTypePrefix = 'pointer' ; } var fromNode = from == null ? win : getNodeFromInstance$1 ( from ) ; var toNode = to == null ? win : getNodeFromInstance$1 ( to ) ; var leave = eventInterface . getPooled ( leaveEventType , from , nativeEvent , nativeEventTarget ) ; leave . type = eventTypePrefix + 'leave' ; leave . target = fromNode ; leave . relatedTarget = toNode ; var enter = eventInterface . getPooled ( enterEventType , to , nativeEvent , nativeEventTarget ) ; enter . type = eventTypePrefix + 'enter' ; enter . target = toNode ; enter . relatedTarget = fromNode ; accumulateEnterLeaveDispatches ( leave , enter , from , to ) ; return [ leave , enter ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the deepest React component completely containing the root of the passed - in instance ( for use when entire React trees are nested within each other ) . If React trees are not nested returns null . [CODESPLIT] function findRootContainerNode ( inst ) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. while ( inst . return ) { inst = inst . return ; } if ( inst . tag !== HostRoot ) { // This can happen if we're in a detached tree. return null ; } return inst . stateNode . containerInfo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We listen for bubbled touch events on the document object . [CODESPLIT] function listenTo ( registrationName , mountAt ) { var isListening = getListeningForDocument ( mountAt ) ; var dependencies = registrationNameDependencies [ registrationName ] ; for ( var i = 0 ; i < dependencies . length ; i ++ ) { var dependency = dependencies [ i ] ; if ( ! ( isListening . hasOwnProperty ( dependency ) && isListening [ dependency ] ) ) { switch ( dependency ) { case TOP_SCROLL : trapCapturedEvent ( TOP_SCROLL , mountAt ) ; break ; case TOP_FOCUS : case TOP_BLUR : trapCapturedEvent ( TOP_FOCUS , mountAt ) ; trapCapturedEvent ( TOP_BLUR , mountAt ) ; // We set the flag for a single dependency later in this function, // but this ensures we mark both as attached rather than just one. isListening [ TOP_BLUR ] = true ; isListening [ TOP_FOCUS ] = true ; break ; case TOP_CANCEL : case TOP_CLOSE : if ( isEventSupported ( getRawEventName ( dependency ) ) ) { trapCapturedEvent ( dependency , mountAt ) ; } break ; case TOP_INVALID : case TOP_SUBMIT : case TOP_RESET : // We listen to them on the target DOM elements. // Some of them bubble so we don't want them to fire twice. break ; default : // By default, listen on the top level to all non-media events. // Media events don't bubble so adding the listener wouldn't do anything. var isMediaEvent = mediaEventTypes . indexOf ( dependency ) !== - 1 ; if ( ! isMediaEvent ) { trapBubbledEvent ( dependency , mountAt ) ; } break ; } isListening [ dependency ] = true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get document associated with the event target . [CODESPLIT] function getEventTargetDocument ( eventTarget ) { return eventTarget . window === eventTarget ? eventTarget . document : eventTarget . nodeType === DOCUMENT_NODE ? eventTarget : eventTarget . ownerDocument ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll selection to see whether it s changed . [CODESPLIT] function constructSelectEvent ( nativeEvent , nativeEventTarget ) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. var doc = getEventTargetDocument ( nativeEventTarget ) ; if ( mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement ( doc ) ) { return null ; } // Only fire when selection has actually changed. var currentSelection = getSelection ( activeElement$1 ) ; if ( ! lastSelection || ! shallowEqual ( lastSelection , currentSelection ) ) { lastSelection = currentSelection ; var syntheticEvent = SyntheticEvent . getPooled ( eventTypes$3 . select , activeElementInst$1 , nativeEvent , nativeEventTarget ) ; syntheticEvent . type = 'select' ; syntheticEvent . target = activeElement$1 ; accumulateTwoPhaseDispatches ( syntheticEvent ) ; return syntheticEvent ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements an <option > host component that warns when selected is set . [CODESPLIT] function validateProps ( element , props ) { { // This mirrors the codepath above, but runs for hydration too. // Warn about invalid children here so that client and hydration are consistent. // TODO: this seems like it could cause a DEV-only throw for hydration // if children contains a non-element object. We should try to avoid that. if ( typeof props . children === 'object' && props . children !== null ) { React . Children . forEach ( props . children , function ( child ) { if ( child == null ) { return ; } if ( typeof child === 'string' || typeof child === 'number' ) { return ; } if ( typeof child . type !== 'string' ) { return ; } if ( ! didWarnInvalidChild ) { didWarnInvalidChild = true ; warning$1 ( false , 'Only strings and numbers are supported as <option> children.' ) ; } } ) ; } // TODO: Remove support for `selected` in <option>. if ( props . selected != null && ! didWarnSelectedSetOnOption ) { warning$1 ( false , 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.' ) ; didWarnSelectedSetOnOption = true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the textContent property of a node . For text updates it s faster to set the nodeValue of the Text node directly instead of using . textContent which will remove the existing node and create a new one . [CODESPLIT] function ( node , text ) { if ( text ) { var firstChild = node . firstChild ; if ( firstChild && firstChild === node . lastChild && firstChild . nodeType === TEXT_NODE ) { firstChild . nodeValue = text ; return ; } } node . textContent = text ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a value into the proper css writable value . The style name name should be logical ( no hyphens ) as specified in CSSProperty . isUnitlessNumber . [CODESPLIT] function dangerousStyleValue ( name , value , isCustomProperty ) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === '' ; if ( isEmpty ) { return '' ; } if ( ! isCustomProperty && typeof value === 'number' && value !== 0 && ! ( isUnitlessNumber . hasOwnProperty ( name ) && isUnitlessNumber [ name ] ) ) { return value + 'px' ; // Presumes implicit 'px' suffix for unitless numbers } return ( '' + value ) . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Operations for dealing with CSS properties . This creates a string that is expected to be equivalent to the style attribute generated by server - side rendering . It by - passes warnings and security checks so it s not safe to use this value for anything other than comparison . It is only used in DEV for SSR validation . [CODESPLIT] function createDangerousStringForStyles ( styles ) { { var serialized = '' ; var delimiter = '' ; for ( var styleName in styles ) { if ( ! styles . hasOwnProperty ( styleName ) ) { continue ; } var styleValue = styles [ styleName ] ; if ( styleValue != null ) { var isCustomProperty = styleName . indexOf ( '--' ) === 0 ; serialized += delimiter + hyphenateStyleName ( styleName ) + ':' ; serialized += dangerousStyleValue ( styleName , styleValue , isCustomProperty ) ; delimiter = ';' ; } } return serialized || null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value for multiple styles on a node . If a value is specified as ( empty string ) the corresponding style property will be unset . [CODESPLIT] function setValueForStyles ( node , styles ) { var style = node . style ; for ( var styleName in styles ) { if ( ! styles . hasOwnProperty ( styleName ) ) { continue ; } var isCustomProperty = styleName . indexOf ( '--' ) === 0 ; { if ( ! isCustomProperty ) { warnValidStyle$1 ( styleName , styles [ styleName ] ) ; } } var styleValue = dangerousStyleValue ( styleName , styles [ styleName ] , isCustomProperty ) ; if ( styleName === 'float' ) { styleName = 'cssFloat' ; } if ( isCustomProperty ) { style . setProperty ( styleName , styleValue ) ; } else { style [ styleName ] = styleValue ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exported FiberRoot type includes all properties To avoid requiring potentially error - prone : any casts throughout the project . Profiling properties are only safe to access in profiling builds ( when enableSchedulerTracing is true ) . The types are defined separately within this file to ensure they stay in sync . ( We don t have to use an inline : any cast when enableSchedulerTracing is disabled . ) / * eslint - enable no - use - before - define [CODESPLIT] function createFiberRoot ( containerInfo , isAsync , hydrate ) { // Cyclic construction. This cheats the type system right now because // stateNode is any. var uninitializedFiber = createHostRootFiber ( isAsync ) ; var root = void 0 ; if ( enableSchedulerTracing ) { root = { current : uninitializedFiber , containerInfo : containerInfo , pendingChildren : null , earliestPendingTime : NoWork , latestPendingTime : NoWork , earliestSuspendedTime : NoWork , latestSuspendedTime : NoWork , latestPingedTime : NoWork , didError : false , pendingCommitExpirationTime : NoWork , finishedWork : null , timeoutHandle : noTimeout , context : null , pendingContext : null , hydrate : hydrate , nextExpirationTimeToWorkOn : NoWork , expirationTime : NoWork , firstBatch : null , nextScheduledRoot : null , interactionThreadID : tracing . unstable_getThreadID ( ) , memoizedInteractions : new Set ( ) , pendingInteractionMap : new Map ( ) } ; } else { root = { current : uninitializedFiber , containerInfo : containerInfo , pendingChildren : null , earliestPendingTime : NoWork , latestPendingTime : NoWork , earliestSuspendedTime : NoWork , latestSuspendedTime : NoWork , latestPingedTime : NoWork , didError : false , pendingCommitExpirationTime : NoWork , finishedWork : null , timeoutHandle : noTimeout , context : null , pendingContext : null , hydrate : hydrate , nextExpirationTimeToWorkOn : NoWork , expirationTime : NoWork , firstBatch : null , nextScheduledRoot : null } ; } uninitializedFiber . stateNode = root ; // The reason for the way the Flow types are structured in this file, // Is to avoid needing :any casts everywhere interaction tracing fields are used. // Unfortunately that requires an :any cast for non-interaction tracing capable builds. // $FlowFixMe Remove this :any cast and replace it with something better. return root ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Offscreen updates should never suspend . However a promise that suspended inside an offscreen subtree should be able to ping at the priority of the outer render . [CODESPLIT] function markPendingPriorityLevel ( root , expirationTime ) { // If there's a gap between completing a failed root and retrying it, // additional updates may be scheduled. Clear `didError`, in case the update // is sufficient to fix the error. root . didError = false ; // Update the latest and earliest pending times var earliestPendingTime = root . earliestPendingTime ; if ( earliestPendingTime === NoWork ) { // No other pending updates. root . earliestPendingTime = root . latestPendingTime = expirationTime ; } else { if ( earliestPendingTime > expirationTime ) { // This is the earliest pending update. root . earliestPendingTime = expirationTime ; } else { var latestPendingTime = root . latestPendingTime ; if ( latestPendingTime < expirationTime ) { // This is the latest pending update root . latestPendingTime = expirationTime ; } } } findNextExpirationTimeToWorkOn ( expirationTime , root ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Warns if there is a duplicate or missing key [CODESPLIT] function warnOnInvalidKey ( child , knownKeys ) { { if ( typeof child !== 'object' || child === null ) { return knownKeys ; } switch ( child . $$typeof ) { case REACT_ELEMENT_TYPE : case REACT_PORTAL_TYPE : warnForMissingKey ( child ) ; var key = child . key ; if ( typeof key !== 'string' ) { break ; } if ( knownKeys === null ) { knownKeys = new Set ( ) ; knownKeys . add ( key ) ; break ; } if ( ! knownKeys . has ( key ) ) { knownKeys . add ( key ) ; break ; } warning$1 ( false , 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + ' ould change in a future version.',  k y);   break ; default : break ; } } return knownKeys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * function reuseChildrenEffects ( returnFiber : Fiber firstChild : Fiber ) { let child = firstChild ; do { Ensure that the first and last effect of the parent corresponds to the children s first and last effect . if ( !returnFiber . firstEffect ) { returnFiber . firstEffect = child . firstEffect ; } if ( child . lastEffect ) { if ( returnFiber . lastEffect ) { returnFiber . lastEffect . nextEffect = child . firstEffect ; } returnFiber . lastEffect = child . lastEffect ; } } while ( child = child . sibling ) ; } [CODESPLIT] function bailoutOnAlreadyFinishedWork ( current$$1 , workInProgress , renderExpirationTime ) { cancelWorkTimer ( workInProgress ) ; if ( current$$1 !== null ) { // Reuse previous context list workInProgress . firstContextDependency = current$$1 . firstContextDependency ; } if ( enableProfilerTimer ) { // Don't update \"base\" render times for bailouts. stopProfilerTimerIfRunning ( workInProgress ) ; } // Check if the children have any pending work. var childExpirationTime = workInProgress . childExpirationTime ; if ( childExpirationTime === NoWork || childExpirationTime > renderExpirationTime ) { // The children don't have any work either. We can skip them. // TODO: Once we add back resuming, we should check if the children are // a work-in-progress set. If so, we need to transfer their effects. return null ; } else { // This fiber doesn't have work, but its subtree does. Clone the child // fibers and continue. cloneChildFibers ( current$$1 , workInProgress ) ; return workInProgress . child ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Persistent host tree mode An unfortunate fork of appendAllChildren because we have two different parent types . [CODESPLIT] function ( containerChildSet , workInProgress ) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress . child ; while ( node !== null ) { if ( node . tag === HostComponent || node . tag === HostText ) { appendChildToContainerChildSet ( containerChildSet , node . stateNode ) ; } else if ( node . tag === HostPortal ) { // If we have a portal child, then we don't want to traverse // down its children. Instead, we'll get insertions from each child in // the portal directly. } else if ( node . child !== null ) { node . child . return = node ; node = node . child ; continue ; } if ( node === workInProgress ) { return ; } while ( node . sibling === null ) { if ( node . return === null || node . return === workInProgress ) { return ; } node = node . return ; } node . sibling . return = node . return ; node = node . sibling ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Capture errors so they don t interrupt unmounting . [CODESPLIT] function safelyCallComponentWillUnmount ( current$$1 , instance ) { { invokeGuardedCallback ( null , callComponentWillUnmountWithTimer , null , current$$1 , instance ) ; if ( hasCaughtError ( ) ) { var unmountError = clearCaughtError ( ) ; captureCommitPhaseError ( current$$1 , unmountError ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "User - originating errors ( lifecycles and refs ) should not interrupt deletion so don t let them throw . Host - originating errors should interrupt deletion so it s okay [CODESPLIT] function commitUnmount ( current$$1 ) { onCommitUnmount ( current$$1 ) ; switch ( current$$1 . tag ) { case ClassComponent : case ClassComponentLazy : { safelyDetachRef ( current$$1 ) ; var instance = current$$1 . stateNode ; if ( typeof instance . componentWillUnmount === 'function' ) { safelyCallComponentWillUnmount ( current$$1 , instance ) ; } return ; } case HostComponent : { safelyDetachRef ( current$$1 ) ; return ; } case HostPortal : { // TODO: this is recursive. // We are also not using this parent because // the portal will get pushed immediately. if ( supportsMutation ) { unmountHostComponents ( current$$1 ) ; } else if ( supportsPersistence ) { emptyPortalContainer ( current$$1 ) ; } return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a unique async expiration time . [CODESPLIT] function computeUniqueAsyncExpiration ( ) { var currentTime = requestCurrentTime ( ) ; var result = computeAsyncExpiration ( currentTime ) ; if ( result <= lastUniqueAsyncExpiration ) { // Since we assume the current time monotonically increases, we only hit // this branch when computeUniqueAsyncExpiration is fired multiple times // within a 200ms window (or whatever the async bucket size is). result = lastUniqueAsyncExpiration + 1 ; } lastUniqueAsyncExpiration = result ; return lastUniqueAsyncExpiration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Batching should be implemented at the renderer level not inside the reconciler . [CODESPLIT] function batchedUpdates$1 ( fn , a ) { var previousIsBatchingUpdates = isBatchingUpdates ; isBatchingUpdates = true ; try { return fn ( a ) ; } finally { isBatchingUpdates = previousIsBatchingUpdates ; if ( ! isBatchingUpdates && ! isRendering ) { performSyncWork ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Batching should be implemented at the renderer level not within the reconciler . [CODESPLIT] function flushSync ( fn , a ) { ! ! isRendering ? invariant ( false , 'flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.' ) : void 0 ; var previousIsBatchingUpdates = isBatchingUpdates ; isBatchingUpdates = true ; try { return syncUpdates ( fn , a ) ; } finally { isBatchingUpdates = previousIsBatchingUpdates ; performSyncWork ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This file intentionally does * not * have the Flow annotation . Don t add it . See . / inline - typed . js for an explanation . [CODESPLIT] function createPortal$1 ( children , containerInfo , // TODO: figure out the API for cross-renderer implementation. implementation ) { var key = arguments . length > 3 && arguments [ 3 ] !== undefined ? arguments [ 3 ] : null ; return { // This tag allow us to uniquely identify this as a React Portal $$typeof : REACT_PORTAL_TYPE , key : key == null ? null : '' + key , children : children , containerInfo : containerInfo , implementation : implementation } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * eslint - disable no - use - before - define / * eslint - enable no - use - before - define [CODESPLIT] function ReactBatch ( root ) { var expirationTime = computeUniqueAsyncExpiration ( ) ; this . _expirationTime = expirationTime ; this . _root = root ; this . _next = null ; this . _callbacks = null ; this . _didComplete = false ; this . _hasChildren = false ; this . _children = null ; this . _defer = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Base class helpers for the updating state of a component . [CODESPLIT] function Component ( props , context , updater ) { this . props = props ; this . context = context ; // If a component has string refs, we will assign a different object later. this . refs = emptyObject ; // We initialize the default updater but the real one gets injected by the // renderer. this . updater = updater || ReactNoopUpdateQueue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flatten a children object ( typically specified as props . children ) and return an array with appropriately re - keyed children . [CODESPLIT] function toArray ( children ) { var result = [ ] ; mapIntoWithKeyPrefixInternal ( children , result , null , function ( child ) { return child ; } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given an element validate that its props follow the propTypes definition provided by the type . [CODESPLIT] function validatePropTypes ( element ) { var type = element . type ; var name = void 0 , propTypes = void 0 ; if ( typeof type === 'function' ) { // Class or functional component name = type . displayName || type . name ; propTypes = type . propTypes ; } else if ( typeof type === 'object' && type !== null && type . $$typeof === REACT_FORWARD_REF_TYPE ) { // ForwardRef var functionName = type . render . displayName || type . render . name || '' ; name = type . displayName || ( functionName !== '' ? 'ForwardRef(' + functionName + ')' : 'ForwardRef' ) ; propTypes = type . propTypes ; } else { return ; } if ( propTypes ) { setCurrentlyValidatingElement ( element ) ; checkPropTypes ( propTypes , element . props , 'prop' , name , ReactDebugCurrentFrame . getStackAddendum ) ; setCurrentlyValidatingElement ( null ) ; } else if ( type . PropTypes !== undefined && ! propTypesMisspellWarningShown ) { propTypesMisspellWarningShown = true ; warningWithoutStack$1 ( false , 'Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?' , name || 'Unknown' ) ; } if ( typeof type . getDefaultProps === 'function' ) { ! type . getDefaultProps . isReactClassApproved ? warningWithoutStack$1 ( false , 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.' ) : void 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a fragment validate that it can only be provided with fragment props [CODESPLIT] function validateFragmentProps ( fragment ) { setCurrentlyValidatingElement ( fragment ) ; var keys = Object . keys ( fragment . props ) ; for ( var i = 0 ; i < keys . length ; i ++ ) { var key = keys [ i ] ; if ( key !== 'children' && key !== 'key' ) { warning$1 ( false , 'Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.' , key ) ; break ; } } if ( fragment . ref !== null ) { warning$1 ( false , 'Invalid attribute `ref` supplied to `React.Fragment`.' ) ; } setCurrentlyValidatingElement ( null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bucket 相关 查看是否存在该Bucket，是否有权限访问 [CODESPLIT] function headBucket ( params , callback ) { submitRequest . call ( this , { Action : 'name/cos:HeadBucket' , Bucket : params . Bucket , Region : params . Region , headers : params . Headers , method : 'HEAD' , } , function ( err , data ) { callback ( err , data ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取 Bucket 下的 object 列表 [CODESPLIT] function getBucket ( params , callback ) { var reqParams = { } ; reqParams [ 'prefix' ] = params [ 'Prefix' ] || '' ; reqParams [ 'delimiter' ] = params [ 'Delimiter' ] ; reqParams [ 'marker' ] = params [ 'Marker' ] ; reqParams [ 'max-keys' ] = params [ 'MaxKeys' ] ; reqParams [ 'encoding-type' ] = params [ 'EncodingType' ] ; submitRequest . call ( this , { Action : 'name/cos:GetBucket' , ResourceKey : reqParams [ 'prefix' ] , method : 'GET' , Bucket : params . Bucket , Region : params . Region , headers : params . Headers , qs : reqParams , } , function ( err , data ) { if ( err ) { return callback ( err ) ; } var ListBucketResult = data . ListBucketResult || { } ; var Contents = ListBucketResult . Contents || [ ] ; var CommonPrefixes = ListBucketResult . CommonPrefixes || [ ] ; Contents = util . isArray ( Contents ) ? Contents : [ Contents ] ; CommonPrefixes = util . isArray ( CommonPrefixes ) ? CommonPrefixes : [ CommonPrefixes ] ; var result = util . clone ( ListBucketResult ) ; util . extend ( result , { Contents : Contents , CommonPrefixes : CommonPrefixes , statusCode : data . statusCode , headers : data . headers , } ) ; callback ( null , result ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取 Bucket 的 权限列表 [CODESPLIT] function getBucketAcl ( params , callback ) { submitRequest . call ( this , { Action : 'name/cos:GetBucketACL' , method : 'GET' , Bucket : params . Bucket , Region : params . Region , headers : params . Headers , action : 'acl' , } , function ( err , data ) { if ( err ) { return callback ( err ) ; } var AccessControlPolicy = data . AccessControlPolicy || { } ; var Owner = AccessControlPolicy . Owner || { } ; var Grant = AccessControlPolicy . AccessControlList . Grant || [ ] ; Grant = util . isArray ( Grant ) ? Grant : [ Grant ] ; var result = decodeAcl ( AccessControlPolicy ) ; if ( data . headers && data . headers [ 'x-cos-acl' ] ) { result . ACL = data . headers [ 'x-cos-acl' ] ; } result = util . extend ( result , { Owner : Owner , Grants : Grant , statusCode : data . statusCode , headers : data . headers , } ) ; callback ( null , result ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取 Bucket 的 跨域设置 [CODESPLIT] function getBucketCors ( params , callback ) { submitRequest . call ( this , { Action : 'name/cos:GetBucketCORS' , method : 'GET' , Bucket : params . Bucket , Region : params . Region , headers : params . Headers , action : 'cors' , } , function ( err , data ) { if ( err ) { if ( err . statusCode === 404 && err . error && err . error . Code === 'NoSuchCORSConfiguration' ) { var result = { CORSRules : [ ] , statusCode : err . statusCode , } ; err . headers && ( result . headers = err . headers ) ; callback ( null , result ) ; } else { callback ( err ) ; } return ; } var CORSConfiguration = data . CORSConfiguration || { } ; var CORSRules = CORSConfiguration . CORSRules || CORSConfiguration . CORSRule || [ ] ; CORSRules = util . clone ( util . isArray ( CORSRules ) ? CORSRules : [ CORSRules ] ) ; util . each ( CORSRules , function ( rule ) { util . each ( [ 'AllowedOrigin' , 'AllowedHeader' , 'AllowedMethod' , 'ExposeHeader' ] , function ( key , j ) { var sKey = key + 's' ; var val = rule [ sKey ] || rule [ key ] || [ ] ; delete rule [ key ] ; rule [ sKey ] = util . isArray ( val ) ? val : [ val ] ; } ) ; } ) ; callback ( null , { CORSRules : CORSRules , statusCode : data . statusCode , headers : data . headers , } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置 Bucket 的 跨域设置 [CODESPLIT] function putBucketCors ( params , callback ) { var CORSConfiguration = params [ 'CORSConfiguration' ] || { } ; var CORSRules = CORSConfiguration [ 'CORSRules' ] || params [ 'CORSRules' ] || [ ] ; CORSRules = util . clone ( util . isArray ( CORSRules ) ? CORSRules : [ CORSRules ] ) ; util . each ( CORSRules , function ( rule ) { util . each ( [ 'AllowedOrigin' , 'AllowedHeader' , 'AllowedMethod' , 'ExposeHeader' ] , function ( key , k ) { var sKey = key + 's' ; var val = rule [ sKey ] || rule [ key ] || [ ] ; delete rule [ sKey ] ; rule [ key ] = util . isArray ( val ) ? val : [ val ] ; } ) ; } ) ; var xml = util . json2xml ( { CORSConfiguration : { CORSRule : CORSRules } } ) ; var headers = params . Headers ; headers [ 'Content-Type' ] = 'application/xml' ; headers [ 'Content-MD5' ] = util . binaryBase64 ( util . md5 ( xml ) ) ; submitRequest . call ( this , { Action : 'name/cos:PutBucketCORS' , method : 'PUT' , Bucket : params . Bucket , Region : params . Region , body : xml , action : 'cors' , headers : headers , } , function ( err , data ) { if ( err ) { return callback ( err ) ; } callback ( null , { statusCode : data . statusCode , headers : data . headers , } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "删除 Bucket 的 跨域设置 [CODESPLIT] function deleteBucketCors ( params , callback ) { submitRequest . call ( this , { Action : 'name/cos:DeleteBucketCORS' , method : 'DELETE' , Bucket : params . Bucket , Region : params . Region , headers : params . Headers , action : 'cors' , } , function ( err , data ) { if ( err && err . statusCode === 204 ) { return callback ( null , { statusCode : err . statusCode } ) ; } else if ( err ) { return callback ( err ) ; } callback ( null , { statusCode : data . statusCode || err . statusCode , headers : data . headers , } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取 Bucket 的 地域信息 [CODESPLIT] function getBucketLocation ( params , callback ) { submitRequest . call ( this , { Action : 'name/cos:GetBucketLocation' , method : 'GET' , Bucket : params . Bucket , Region : params . Region , headers : params . Headers , action : 'location' , } , function ( err , data ) { if ( err ) { return callback ( err ) ; } callback ( null , data ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取 Bucket 的读取权限策略 [CODESPLIT] function getBucketPolicy ( params , callback ) { submitRequest . call ( this , { Action : 'name/cos:GetBucketPolicy' , method : 'GET' , Bucket : params . Bucket , Region : params . Region , headers : params . Headers , action : 'policy' , rawBody : true , } , function ( err , data ) { if ( err ) { if ( err . statusCode && err . statusCode === 403 ) { return callback ( { ErrorStatus : 'Access Denied' } ) ; } if ( err . statusCode && err . statusCode === 405 ) { return callback ( { ErrorStatus : 'Method Not Allowed' } ) ; } if ( err . statusCode && err . statusCode === 404 ) { return callback ( { ErrorStatus : 'Policy Not Found' } ) ; } return callback ( err ) ; } var Policy = { } ; try { Policy = JSON . parse ( data . body ) ; } catch ( e ) { } callback ( null , { Policy : Policy , statusCode : data . statusCode , headers : data . headers , } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取 Bucket 的标签设置 [CODESPLIT] function getBucketTagging ( params , callback ) { submitRequest . call ( this , { Action : 'name/cos:GetBucketTagging' , method : 'GET' , Bucket : params . Bucket , Region : params . Region , headers : params . Headers , action : 'tagging' , } , function ( err , data ) { if ( err ) { if ( err . statusCode === 404 && err . error && ( err . error === \"Not Found\" || err . error . Code === 'NoSuchTagSet' ) ) { var result = { Tags : [ ] , statusCode : err . statusCode , } ; err . headers && ( result . headers = err . headers ) ; callback ( null , result ) ; } else { callback ( err ) ; } return ; } var Tags = [ ] ; try { Tags = data . Tagging . TagSet . Tag || [ ] ; } catch ( e ) { } Tags = util . clone ( util . isArray ( Tags ) ? Tags : [ Tags ] ) ; callback ( null , { Tags : Tags , statusCode : data . statusCode , headers : data . headers , } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置 Bucket 的标签 [CODESPLIT] function putBucketTagging ( params , callback ) { var Tagging = params [ 'Tagging' ] || { } ; var Tags = Tagging . TagSet || Tagging . Tags || params [ 'Tags' ] || [ ] ; Tags = util . clone ( util . isArray ( Tags ) ? Tags : [ Tags ] ) ; var xml = util . json2xml ( { Tagging : { TagSet : { Tag : Tags } } } ) ; var headers = params . Headers ; headers [ 'Content-Type' ] = 'application/xml' ; headers [ 'Content-MD5' ] = util . binaryBase64 ( util . md5 ( xml ) ) ; submitRequest . call ( this , { Action : 'name/cos:PutBucketTagging' , method : 'PUT' , Bucket : params . Bucket , Region : params . Region , body : xml , action : 'tagging' , headers : headers , } , function ( err , data ) { if ( err && err . statusCode === 204 ) { return callback ( null , { statusCode : err . statusCode } ) ; } else if ( err ) { return callback ( err ) ; } callback ( null , { statusCode : data . statusCode , headers : data . headers , } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Object 相关 取回对应Object的元数据，Head的权限与Get的权限一致 [CODESPLIT] function headObject ( params , callback ) { submitRequest . call ( this , { Action : 'name/cos:HeadObject' , method : 'HEAD' , Bucket : params . Bucket , Region : params . Region , Key : params . Key , VersionId : params . VersionId , headers : params . Headers , } , function ( err , data ) { if ( err ) { var statusCode = err . statusCode ; if ( params . Headers [ 'If-Modified-Since' ] && statusCode && statusCode === 304 ) { return callback ( null , { NotModified : true , statusCode : statusCode , } ) ; } return callback ( err ) ; } if ( data . headers && data . headers . etag ) { data . ETag = data . headers && data . headers . etag ; } callback ( null , data ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "下载 object [CODESPLIT] function getObject ( params , callback ) { var reqParams = { } ; reqParams [ 'response-content-type' ] = params [ 'ResponseContentType' ] ; reqParams [ 'response-content-language' ] = params [ 'ResponseContentLanguage' ] ; reqParams [ 'response-expires' ] = params [ 'ResponseExpires' ] ; reqParams [ 'response-cache-control' ] = params [ 'ResponseCacheControl' ] ; reqParams [ 'response-content-disposition' ] = params [ 'ResponseContentDisposition' ] ; reqParams [ 'response-content-encoding' ] = params [ 'ResponseContentEncoding' ] ; // 如果用户自己传入了 output submitRequest . call ( this , { Action : 'name/cos:GetObject' , method : 'GET' , Bucket : params . Bucket , Region : params . Region , Key : params . Key , VersionId : params . VersionId , headers : params . Headers , qs : reqParams , rawBody : true , } , function ( err , data ) { if ( err ) { var statusCode = err . statusCode ; if ( params . Headers [ 'If-Modified-Since' ] && statusCode && statusCode === 304 ) { return callback ( null , { NotModified : true } ) ; } return callback ( err ) ; } var result = { } ; result . Body = data . body ; if ( data . headers && data . headers . etag ) { result . ETag = data . headers && data . headers . etag ; } util . extend ( result , { statusCode : data . statusCode , headers : data . headers , } ) ; callback ( null , result ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "上传 object [CODESPLIT] function putObject ( params , callback ) { var self = this ; var FileSize = params . ContentLength ; var onProgress = util . throttleOnProgress . call ( self , FileSize , params . onProgress ) ; // 特殊处理 Cache-Control var headers = params . Headers ; ! headers [ 'Cache-Control' ] && ( headers [ 'Cache-Control' ] = '' ) ; // 获取 File 或 Blob 的 type 属性，如果有，作为文件 Content-Type var ContentType = headers [ 'Content-Type' ] || ( params . Body && params . Body . type ) ; ! headers [ 'Content-Type' ] && ContentType && ( headers [ 'Content-Type' ] = ContentType ) ; util . getBodyMd5 ( self . options . UploadCheckContentMd5 , params . Body , function ( md5 ) { md5 && ( params . Headers [ 'Content-MD5' ] = util . binaryBase64 ( md5 ) ) ; if ( params . ContentLength !== undefined ) { params . Headers [ 'Content-Length' ] = params . ContentLength ; } submitRequest . call ( self , { Action : 'name/cos:PutObject' , TaskId : params . TaskId , method : 'PUT' , Bucket : params . Bucket , Region : params . Region , Key : params . Key , headers : params . Headers , body : params . Body , onProgress : onProgress , } , function ( err , data ) { if ( err ) { onProgress ( null , true ) ; return callback ( err ) ; } onProgress ( { loaded : FileSize , total : FileSize } , true ) ; if ( data && data . headers && data . headers [ 'etag' ] ) { var url = getUrl ( { ForcePathStyle : self . options . ForcePathStyle , protocol : self . options . Protocol , domain : self . options . Domain , bucket : params . Bucket , region : params . Region , object : params . Key , } ) ; url = url . substr ( url . indexOf ( '://' ) + 3 ) ; return callback ( null , { Location : url , ETag : data . headers [ 'etag' ] , statusCode : data . statusCode , headers : data . headers , } ) ; } callback ( null , data ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "删除 object [CODESPLIT] function deleteObject ( params , callback ) { submitRequest . call ( this , { Action : 'name/cos:DeleteObject' , method : 'DELETE' , Bucket : params . Bucket , Region : params . Region , Key : params . Key , headers : params . Headers , VersionId : params . VersionId , } , function ( err , data ) { if ( err ) { var statusCode = err . statusCode ; if ( statusCode && statusCode === 204 ) { return callback ( null , { statusCode : statusCode } ) ; } else if ( statusCode && statusCode === 404 ) { return callback ( null , { BucketNotFound : true , statusCode : statusCode , } ) ; } else { return callback ( err ) ; } } callback ( null , { statusCode : data . statusCode , headers : data . headers , } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置 object 的 权限列表 [CODESPLIT] function putObjectAcl ( params , callback ) { var headers = params . Headers ; var xml = '' ; if ( params [ 'AccessControlPolicy' ] ) { var AccessControlPolicy = util . clone ( params [ 'AccessControlPolicy' ] || { } ) ; var Grants = AccessControlPolicy . Grants || AccessControlPolicy . Grant ; Grants = util . isArray ( Grants ) ? Grants : [ Grants ] ; delete AccessControlPolicy . Grant ; delete AccessControlPolicy . Grants ; AccessControlPolicy . AccessControlList = { Grant : Grants } ; xml = util . json2xml ( { AccessControlPolicy : AccessControlPolicy } ) ; headers [ 'Content-Type' ] = 'application/xml' ; headers [ 'Content-MD5' ] = util . binaryBase64 ( util . md5 ( xml ) ) ; } // Grant Header 去重 util . each ( headers , function ( val , key ) { if ( key . indexOf ( 'x-cos-grant-' ) === 0 ) { headers [ key ] = uniqGrant ( headers [ key ] ) ; } } ) ; submitRequest . call ( this , { Action : 'name/cos:PutObjectACL' , method : 'PUT' , Bucket : params . Bucket , Region : params . Region , Key : params . Key , action : 'acl' , headers : headers , body : xml , } , function ( err , data ) { if ( err ) { return callback ( err ) ; } callback ( null , { statusCode : data . statusCode , headers : data . headers , } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Options Object请求实现跨域访问的预请求。即发出一个 OPTIONS 请求给服务器以确认是否可以进行跨域操作。 [CODESPLIT] function optionsObject ( params , callback ) { var headers = params . Headers ; headers [ 'Origin' ] = params [ 'Origin' ] ; headers [ 'Access-Control-Request-Method' ] = params [ 'AccessControlRequestMethod' ] ; headers [ 'Access-Control-Request-Headers' ] = params [ 'AccessControlRequestHeaders' ] ; submitRequest . call ( this , { Action : 'name/cos:OptionsObject' , method : 'OPTIONS' , Bucket : params . Bucket , Region : params . Region , Key : params . Key , headers : headers , } , function ( err , data ) { if ( err ) { if ( err . statusCode && err . statusCode === 403 ) { return callback ( null , { OptionsForbidden : true , statusCode : err . statusCode } ) ; } return callback ( err ) ; } var headers = data . headers || { } ; callback ( null , { AccessControlAllowOrigin : headers [ 'access-control-allow-origin' ] , AccessControlAllowMethods : headers [ 'access-control-allow-methods' ] , AccessControlAllowHeaders : headers [ 'access-control-allow-headers' ] , AccessControlExposeHeaders : headers [ 'access-control-expose-headers' ] , AccessControlMaxAge : headers [ 'access-control-max-age' ] , statusCode : data . statusCode , headers : data . headers , } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "分块上传 初始化分块上传 [CODESPLIT] function multipartInit ( params , callback ) { var xml ; var headers = params . Headers ; var userAgent = navigator && navigator . userAgent || '' ; var m = userAgent . match ( /  TBS\\/(\\d{6})  / ) ; if ( location . protocol === 'http:' && m && m [ 1 ] . length <= 6 && m [ 1 ] < '044429' ) { xml = util . json2xml ( { } ) ; headers [ 'Content-MD5' ] = util . binaryBase64 ( util . md5 ( xml ) ) ; // 如果没有 Content-Type 指定一个 if ( ! headers [ 'Content-Type' ] ) { headers [ 'Content-Type' ] = ( params . Body && params . Body . type ) || 'application/octet-stream' ; } } // 特殊处理 Cache-Control ! headers [ 'Cache-Control' ] && ( headers [ 'Cache-Control' ] = '' ) ; submitRequest . call ( this , { Action : 'name/cos:InitiateMultipartUpload' , method : 'POST' , Bucket : params . Bucket , Region : params . Region , Key : params . Key , action : 'uploads' , headers : params . Headers , body : xml , } , function ( err , data ) { if ( err ) { return callback ( err ) ; } data = util . clone ( data || { } ) ; if ( data && data . InitiateMultipartUploadResult ) { return callback ( null , util . extend ( data . InitiateMultipartUploadResult , { statusCode : data . statusCode , headers : data . headers , } ) ) ; } callback ( null , data ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "完成分块上传 [CODESPLIT] function multipartComplete ( params , callback ) { var self = this ; var UploadId = params . UploadId ; var Parts = params [ 'Parts' ] ; for ( var i = 0 , len = Parts . length ; i < len ; i ++ ) { if ( Parts [ i ] [ 'ETag' ] . indexOf ( '\"' ) === 0 ) { continue ; } Parts [ i ] [ 'ETag' ] = '\"' + Parts [ i ] [ 'ETag' ] + '\"' ; } var xml = util . json2xml ( { CompleteMultipartUpload : { Part : Parts } } ) ; var headers = params . Headers ; headers [ 'Content-Type' ] = 'application/xml' ; headers [ 'Content-MD5' ] = util . binaryBase64 ( util . md5 ( xml ) ) ; submitRequest . call ( this , { Action : 'name/cos:CompleteMultipartUpload' , method : 'POST' , Bucket : params . Bucket , Region : params . Region , Key : params . Key , qs : { uploadId : UploadId } , body : xml , headers : headers , } , function ( err , data ) { if ( err ) { return callback ( err ) ; } var url = getUrl ( { ForcePathStyle : self . options . ForcePathStyle , protocol : self . options . Protocol , domain : self . options . Domain , bucket : params . Bucket , region : params . Region , object : params . Key , isLocation : true , } ) ; var CompleteMultipartUploadResult = data . CompleteMultipartUploadResult || { } ; var result = util . extend ( CompleteMultipartUploadResult , { Location : url , statusCode : data . statusCode , headers : data . headers , } ) ; callback ( null , result ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "分块上传任务列表查询 [CODESPLIT] function multipartList ( params , callback ) { var reqParams = { } ; reqParams [ 'delimiter' ] = params [ 'Delimiter' ] ; reqParams [ 'encoding-type' ] = params [ 'EncodingType' ] ; reqParams [ 'prefix' ] = params [ 'Prefix' ] || '' ; reqParams [ 'max-uploads' ] = params [ 'MaxUploads' ] ; reqParams [ 'key-marker' ] = params [ 'KeyMarker' ] ; reqParams [ 'upload-id-marker' ] = params [ 'UploadIdMarker' ] ; reqParams = util . clearKey ( reqParams ) ; submitRequest . call ( this , { Action : 'name/cos:ListMultipartUploads' , ResourceKey : reqParams [ 'prefix' ] , method : 'GET' , Bucket : params . Bucket , Region : params . Region , headers : params . Headers , qs : reqParams , action : 'uploads' , } , function ( err , data ) { if ( err ) { return callback ( err ) ; } if ( data && data . ListMultipartUploadsResult ) { var Upload = data . ListMultipartUploadsResult . Upload || [ ] ; var CommonPrefixes = data . ListMultipartUploadsResult . CommonPrefixes || [ ] ; CommonPrefixes = util . isArray ( CommonPrefixes ) ? CommonPrefixes : [ CommonPrefixes ] ; Upload = util . isArray ( Upload ) ? Upload : [ Upload ] ; data . ListMultipartUploadsResult . Upload = Upload ; data . ListMultipartUploadsResult . CommonPrefixes = CommonPrefixes ; } var result = util . clone ( data . ListMultipartUploadsResult || { } ) ; util . extend ( result , { statusCode : data . statusCode , headers : data . headers , } ) ; callback ( null , result ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "上传的分块列表查询 [CODESPLIT] function multipartListPart ( params , callback ) { var reqParams = { } ; reqParams [ 'uploadId' ] = params [ 'UploadId' ] ; reqParams [ 'encoding-type' ] = params [ 'EncodingType' ] ; reqParams [ 'max-parts' ] = params [ 'MaxParts' ] ; reqParams [ 'part-number-marker' ] = params [ 'PartNumberMarker' ] ; submitRequest . call ( this , { Action : 'name/cos:ListParts' , method : 'GET' , Bucket : params . Bucket , Region : params . Region , Key : params . Key , headers : params . Headers , qs : reqParams , } , function ( err , data ) { if ( err ) { return callback ( err ) ; } var ListPartsResult = data . ListPartsResult || { } ; var Part = ListPartsResult . Part || [ ] ; Part = util . isArray ( Part ) ? Part : [ Part ] ; ListPartsResult . Part = Part ; var result = util . clone ( ListPartsResult ) ; util . extend ( result , { statusCode : data . statusCode , headers : data . headers , } ) ; callback ( null , result ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "抛弃分块上传 [CODESPLIT] function multipartAbort ( params , callback ) { var reqParams = { } ; reqParams [ 'uploadId' ] = params [ 'UploadId' ] ; submitRequest . call ( this , { Action : 'name/cos:AbortMultipartUpload' , method : 'DELETE' , Bucket : params . Bucket , Region : params . Region , Key : params . Key , headers : params . Headers , qs : reqParams , } , function ( err , data ) { if ( err ) { return callback ( err ) ; } callback ( null , { statusCode : data . statusCode , headers : data . headers , } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取签名 [CODESPLIT] function getAuth ( params ) { var self = this ; return util . getAuth ( { SecretId : params . SecretId || this . options . SecretId || '' , SecretKey : params . SecretKey || this . options . SecretKey || '' , Method : params . Method , Key : params . Key , Query : params . Query , Headers : params . Headers , Expires : params . Expires , UseRawKey : self . options . UseRawKey , SystemClockOffset : self . options . SystemClockOffset , } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取文件下载链接 [CODESPLIT] function getObjectUrl ( params , callback ) { var self = this ; var url = getUrl ( { ForcePathStyle : self . options . ForcePathStyle , protocol : params . Protocol || self . options . Protocol , domain : self . options . Domain , bucket : params . Bucket , region : params . Region , object : params . Key , } ) ; if ( params . Sign !== undefined && ! params . Sign ) { callback ( null , { Url : url } ) ; return url ; } var AuthData = getAuthorizationAsync . call ( this , { Action : ( ( params . Method || '' ) . toUpperCase ( ) === 'PUT' ? 'name/cos:PutObject' : 'name/cos:GetObject' ) , Bucket : params . Bucket || '' , Region : params . Region || '' , Method : params . Method || 'get' , Key : params . Key , Expires : params . Expires , } , function ( err , AuthData ) { if ( ! callback ) return ; if ( err ) { callback ( err ) ; return ; } var signUrl = url ; signUrl += '?' + ( AuthData . Authorization . indexOf ( 'q-signature' ) > - 1 ? AuthData . Authorization : 'sign=' + encodeURIComponent ( AuthData . Authorization ) ) ; AuthData . XCosSecurityToken && ( signUrl += '&x-cos-security-token=' + AuthData . XCosSecurityToken ) ; AuthData . ClientIP && ( signUrl += '&clientIP=' + AuthData . ClientIP ) ; AuthData . ClientUA && ( signUrl += '&clientUA=' + AuthData . ClientUA ) ; AuthData . Token && ( signUrl += '&token=' + AuthData . Token ) ; setTimeout ( function ( ) { callback ( null , { Url : signUrl } ) ; } ) ; } ) ; if ( AuthData ) { return url + '?' + AuthData . Authorization + ( AuthData . XCosSecurityToken ? '&x-cos-security-token=' + AuthData . XCosSecurityToken : '' ) ; } else { return url ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "私有方法 [CODESPLIT] function decodeAcl ( AccessControlPolicy ) { var result = { GrantFullControl : [ ] , GrantWrite : [ ] , GrantRead : [ ] , GrantReadAcp : [ ] , GrantWriteAcp : [ ] , ACL : '' , } ; var GrantMap = { 'FULL_CONTROL' : 'GrantFullControl' , 'WRITE' : 'GrantWrite' , 'READ' : 'GrantRead' , 'READ_ACP' : 'GrantReadAcp' , 'WRITE_ACP' : 'GrantWriteAcp' , } ; var Grant = AccessControlPolicy . AccessControlList . Grant ; if ( Grant ) { Grant = util . isArray ( Grant ) ? Grant : [ Grant ] ; } var PublicAcl = { READ : 0 , WRITE : 0 , FULL_CONTROL : 0 } ; Grant . length && util . each ( Grant , function ( item ) { if ( item . Grantee . ID === 'qcs::cam::anyone:anyone' || item . Grantee . URI === 'http://cam.qcloud.com/groups/global/AllUsers' ) { PublicAcl [ item . Permission ] = 1 ; } else if ( item . Grantee . ID !== AccessControlPolicy . Owner . ID ) { result [ GrantMap [ item . Permission ] ] . push ( 'id=\"' + item . Grantee . ID + '\"' ) ; } } ) ; if ( PublicAcl . FULL_CONTROL || ( PublicAcl . WRITE && PublicAcl . READ ) ) { result . ACL = 'public-read-write' ; } else if ( PublicAcl . READ ) { result . ACL = 'public-read' ; } else { result . ACL = 'private' ; } util . each ( GrantMap , function ( item ) { result [ item ] = uniqGrant ( result [ item ] . join ( ',' ) ) ; } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grant 去重 [CODESPLIT] function uniqGrant ( str ) { var arr = str . split ( ',' ) ; var exist = { } ; var i , item ; for ( i = 0 ; i < arr . length ; ) { item = arr [ i ] . trim ( ) ; if ( exist [ item ] ) { arr . splice ( i , 1 ) ; } else { exist [ item ] = true ; arr [ i ] = item ; i ++ ; } } return arr . join ( ',' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "生成操作 url [CODESPLIT] function getUrl ( params ) { var longBucket = params . bucket ; var shortBucket = longBucket . substr ( 0 , longBucket . lastIndexOf ( '-' ) ) ; var appId = longBucket . substr ( longBucket . lastIndexOf ( '-' ) + 1 ) ; var domain = params . domain ; var region = params . region ; var object = params . object ; var protocol = params . protocol || ( util . isBrowser && location . protocol === 'http:' ? 'http:' : 'https:' ) ; if ( ! domain ) { if ( [ 'cn-south' , 'cn-south-2' , 'cn-north' , 'cn-east' , 'cn-southwest' , 'sg' ] . indexOf ( region ) > - 1 ) { domain = '{Region}.myqcloud.com' ; } else { domain = 'cos.{Region}.myqcloud.com' ; } if ( ! params . ForcePathStyle ) { domain = '{Bucket}.' + domain ; } } domain = domain . replace ( / \\{\\{AppId\\}\\} / ig , appId ) . replace ( / \\{\\{Bucket\\}\\} / ig , shortBucket ) . replace ( / \\{\\{Region\\}\\} / ig , region ) . replace ( / \\{\\{.*?\\}\\} / ig , '' ) ; domain = domain . replace ( / \\{AppId\\} / ig , appId ) . replace ( / \\{BucketName\\} / ig , shortBucket ) . replace ( / \\{Bucket\\} / ig , longBucket ) . replace ( / \\{Region\\} / ig , region ) . replace ( / \\{.*?\\} / ig , '' ) ; if ( ! / ^[a-zA-Z]+:\\/\\/ / . test ( domain ) ) { domain = protocol + '//' + domain ; } // 去掉域名最后的斜杆 if ( domain . slice ( - 1 ) === '/' ) { domain = domain . slice ( 0 , - 1 ) ; } var url = domain ; if ( params . ForcePathStyle ) { url += '/' + longBucket ; } url += '/' ; if ( object ) { url += util . camSafeUrlEncode ( object ) . replace ( / %2F / g , '/' ) ; } if ( params . isLocation ) { url = url . replace ( / ^https?:\\/\\/ / , '' ) ; } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取签名并发起请求 [CODESPLIT] function submitRequest ( params , callback ) { var self = this ; // 处理 headers ! params . headers && ( params . headers = { } ) ; // 处理 query ! params . qs && ( params . qs = { } ) ; params . VersionId && ( params . qs . versionId = params . VersionId ) ; params . qs = util . clearKey ( params . qs ) ; // 清理 undefined 和 null 字段 params . headers && ( params . headers = util . clearKey ( params . headers ) ) ; params . qs && ( params . qs = util . clearKey ( params . qs ) ) ; var Query = util . clone ( params . qs ) ; params . action && ( Query [ params . action ] = '' ) ; var next = function ( tryIndex ) { var oldClockOffset = self . options . SystemClockOffset ; getAuthorizationAsync . call ( self , { Bucket : params . Bucket || '' , Region : params . Region || '' , Method : params . method , Key : params . Key , Query : Query , Headers : params . headers , Action : params . Action , ResourceKey : params . ResourceKey , Scope : params . Scope , } , function ( err , AuthData ) { params . AuthData = AuthData ; _submitRequest . call ( self , params , function ( err , data ) { if ( err && tryIndex < 2 && ( oldClockOffset !== self . options . SystemClockOffset || allowRetry . call ( self , err ) ) ) { if ( params . headers ) { delete params . headers . Authorization ; delete params . headers [ 'token' ] ; delete params . headers [ 'clientIP' ] ; delete params . headers [ 'clientUA' ] ; delete params . headers [ 'x-cos-security-token' ] ; } next ( tryIndex + 1 ) ; } else { callback ( err , data ) ; } } ) ; } ) ; } ; next ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "发起请求 [CODESPLIT] function _submitRequest ( params , callback ) { var self = this ; var TaskId = params . TaskId ; if ( TaskId && ! self . _isRunningTask ( TaskId ) ) return ; var bucket = params . Bucket ; var region = params . Region ; var object = params . Key ; var method = params . method || 'GET' ; var url = params . url ; var body = params . body ; var json = params . json ; var rawBody = params . rawBody ; // url url = url || getUrl ( { ForcePathStyle : self . options . ForcePathStyle , protocol : self . options . Protocol , domain : self . options . Domain , bucket : bucket , region : region , object : object , } ) ; if ( params . action ) { url = url + '?' + params . action ; } var opt = { method : method , url : url , headers : params . headers , qs : params . qs , body : body , json : json , } ; // 获取签名 opt . headers . Authorization = params . AuthData . Authorization ; params . AuthData . Token && ( opt . headers [ 'token' ] = params . AuthData . Token ) ; params . AuthData . ClientIP && ( opt . headers [ 'clientIP' ] = params . AuthData . ClientIP ) ; params . AuthData . ClientUA && ( opt . headers [ 'clientUA' ] = params . AuthData . ClientUA ) ; params . AuthData . XCosSecurityToken && ( opt . headers [ 'x-cos-security-token' ] = params . AuthData . XCosSecurityToken ) ; // 清理 undefined 和 null 字段 opt . headers && ( opt . headers = util . clearKey ( opt . headers ) ) ; opt = util . clearKey ( opt ) ; // progress if ( params . onProgress && typeof params . onProgress === 'function' ) { var contentLength = body && ( body . size || body . length ) || 0 ; opt . onProgress = function ( e ) { if ( TaskId && ! self . _isRunningTask ( TaskId ) ) return ; var loaded = e ? e . loaded : 0 ; params . onProgress ( { loaded : loaded , total : contentLength } ) ; } ; } if ( this . options . Timeout ) { opt . timeout = this . options . Timeout ; } self . emit ( 'before-send' , opt ) ; var sender = REQUEST ( opt , function ( err , response , body ) { if ( err === 'abort' ) return ; // 返回内容添加 状态码 和 headers var hasReturned ; var cb = function ( err , data ) { TaskId && self . off ( 'inner-kill-task' , killTask ) ; if ( hasReturned ) return ; hasReturned = true ; var attrs = { } ; response && response . statusCode && ( attrs . statusCode = response . statusCode ) ; response && response . headers && ( attrs . headers = response . headers ) ; if ( err ) { err = util . extend ( err || { } , attrs ) ; callback ( err , null ) ; } else { data = util . extend ( data || { } , attrs ) ; callback ( null , data ) ; } sender = null ; } ; // 请求错误，发生网络错误 if ( err ) { cb ( { error : err } ) ; return ; } var jsonRes ; try { jsonRes = body && body . indexOf ( '<' ) > - 1 && body . indexOf ( '>' ) > - 1 && util . xml2json ( body ) || { } ; } catch ( e ) { jsonRes = body || { } ; } // 请求返回码不为 200 var statusCode = response . statusCode ; var statusSuccess = Math . floor ( statusCode / 100 ) === 2 ; // 200 202 204 206 if ( ! statusSuccess ) { cb ( { error : jsonRes . Error || jsonRes } ) ; return ; } // 不对 body 进行转换，body 直接挂载返回 if ( rawBody ) { jsonRes = { } ; jsonRes . body = body ; } if ( jsonRes . Error ) { cb ( { error : jsonRes . Error } ) ; return ; } cb ( null , jsonRes ) ; } ) ; // kill task var killTask = function ( data ) { if ( data . TaskId === TaskId ) { sender && sender . abort && sender . abort ( ) ; self . off ( 'inner-kill-task' , killTask ) ; } } ; TaskId && self . on ( 'inner-kill-task' , killTask ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "kill task [CODESPLIT] function ( data ) { if ( data . TaskId === TaskId ) { sender && sender . abort && sender . abort ( ) ; self . off ( 'inner-kill-task' , killTask ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "v4 签名 [CODESPLIT] function ( opt ) { var pathname = opt . Pathname || '/' ; var expires = opt . Expires ; var ShortBucketName = '' ; var AppId = '' ; var match = opt . Bucket . match ( / ^(.+)-(\\d+)$ / ) ; if ( match ) { ShortBucketName = match [ 1 ] ; AppId = match [ 2 ] ; } var random = parseInt ( Math . random ( ) * Math . pow ( 2 , 32 ) ) ; var now = parseInt ( Date . now ( ) / 1000 ) ; var e = now + ( expires === undefined ? 900 : ( expires * 1 || 0 ) ) ; // 默认签名过期时间为当前时间 + 900s var path = '/' + AppId + '/' + ShortBucketName + encodeURIComponent ( pathname ) . replace ( / %2F / g , '/' ) ; //多次签名这里填空 var plainText = 'a=' + AppId + '&b=' + ShortBucketName + '&k=' + opt . SecretId + '&e=' + e + '&t=' + now + '&r=' + random + '&f=' + path ; var sha1Res = CryptoJS . HmacSHA1 ( plainText , opt . SecretKey ) ; var strWordArray = CryptoJS . enc . Utf8 . parse ( plainText ) ; var resWordArray = sha1Res . concat ( strWordArray ) ; var sign = resWordArray . toString ( CryptoJS . enc . Base64 ) ; return sign ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "v5 签名 [CODESPLIT] function ( opt ) { if ( ! opt . SecretId ) return console . error ( 'missing param SecretId' ) ; if ( ! opt . SecretKey ) return console . error ( 'missing param SecretKey' ) ; if ( opt . Version === '4.0' ) { return CosAuthV4 ( opt ) ; } opt = opt || { } ; var SecretId = opt . SecretId ; var SecretKey = opt . SecretKey ; var method = ( opt . Method || 'get' ) . toLowerCase ( ) ; var query = opt . Query || { } ; var headers = opt . Headers || { } ; var pathname = opt . Pathname || '/' ; var expires = opt . Expires ; var getObjectKeys = function ( obj ) { var list = [ ] ; for ( var key in obj ) { if ( obj . hasOwnProperty ( key ) ) { list . push ( key ) ; } } return list . sort ( function ( a , b ) { a = a . toLowerCase ( ) ; b = b . toLowerCase ( ) ; return a === b ? 0 : ( a > b ? 1 : - 1 ) ; } ) ; } ; var obj2str = function ( obj ) { var i , key , val ; var list = [ ] ; var keyList = getObjectKeys ( obj ) ; for ( i = 0 ; i < keyList . length ; i ++ ) { key = keyList [ i ] ; val = ( obj [ key ] === undefined || obj [ key ] === null ) ? '' : ( '' + obj [ key ] ) ; key = key . toLowerCase ( ) ; key = camSafeUrlEncode ( key ) ; val = camSafeUrlEncode ( val ) || '' ; list . push ( key + '=' + val ) } return list . join ( '&' ) ; } ; // 签名有效起止时间 var now = parseInt ( new Date ( ) . getTime ( ) / 1000 ) - 1 ; var exp = now + ( expires === undefined ? 900 : ( expires * 1 || 0 ) ) ; // 默认签名过期时间为当前时间 + 900s // 要用到的 Authorization 参数列表 var qSignAlgorithm = 'sha1' ; var qAk = SecretId ; var qSignTime = now + ';' + exp ; var qKeyTime = now + ';' + exp ; var qHeaderList = getObjectKeys ( headers ) . join ( ';' ) . toLowerCase ( ) ; var qUrlParamList = getObjectKeys ( query ) . join ( ';' ) . toLowerCase ( ) ; // 签名算法说明文档：https://www.qcloud.com/document/product/436/7778 // 步骤一：计算 SignKey var signKey = CryptoJS . HmacSHA1 ( qKeyTime , SecretKey ) . toString ( ) ; // 步骤二：构成 FormatString var formatString = [ method , pathname , obj2str ( query ) , obj2str ( headers ) , '' ] . join ( '\\n' ) ; // 步骤三：计算 StringToSign var stringToSign = [ 'sha1' , qSignTime , CryptoJS . SHA1 ( formatString ) . toString ( ) , '' ] . join ( '\\n' ) ; // 步骤四：计算 Signature var qSignature = CryptoJS . HmacSHA1 ( stringToSign , signKey ) . toString ( ) ; // 步骤五：构造 Authorization var authorization = [ 'q-sign-algorithm=' + qSignAlgorithm , 'q-ak=' + qAk , 'q-sign-time=' + qSignTime , 'q-key-time=' + qKeyTime , 'q-header-list=' + qHeaderList , 'q-url-param-list=' + qUrlParamList , 'q-signature=' + qSignature ] . join ( '&' ) ; return authorization ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "测试用的key后面可以去掉 [CODESPLIT] function ( opt ) { opt = opt || { } ; var SecretId = opt . SecretId ; var SecretKey = opt . SecretKey ; var method = ( opt . method || opt . Method || 'get' ) . toLowerCase ( ) ; var queryParams = clone ( opt . Query || opt . params || { } ) ; var headers = clone ( opt . Headers || opt . headers || { } ) ; var Key = opt . Key || '' ; var pathname ; if ( opt . UseRawKey ) { pathname = opt . Pathname || opt . pathname || '/' + Key ; } else { pathname = opt . Pathname || opt . pathname || Key ; pathname . indexOf ( '/' ) !== 0 && ( pathname = '/' + pathname ) ; } if ( ! SecretId ) return console . error ( 'missing param SecretId' ) ; if ( ! SecretKey ) return console . error ( 'missing param SecretKey' ) ; var getObjectKeys = function ( obj ) { var list = [ ] ; for ( var key in obj ) { if ( obj . hasOwnProperty ( key ) ) { list . push ( key ) ; } } return list . sort ( function ( a , b ) { a = a . toLowerCase ( ) ; b = b . toLowerCase ( ) ; return a === b ? 0 : ( a > b ? 1 : - 1 ) ; } ) ; } ; var obj2str = function ( obj ) { var i , key , val ; var list = [ ] ; var keyList = getObjectKeys ( obj ) ; for ( i = 0 ; i < keyList . length ; i ++ ) { key = keyList [ i ] ; val = ( obj [ key ] === undefined || obj [ key ] === null ) ? '' : ( '' + obj [ key ] ) ; key = key . toLowerCase ( ) ; key = camSafeUrlEncode ( key ) ; val = camSafeUrlEncode ( val ) || '' ; list . push ( key + '=' + val ) } return list . join ( '&' ) ; } ; // 签名有效起止时间 var now = Math . round ( getSkewTime ( opt . SystemClockOffset ) / 1000 ) - 1 ; var exp = now ; var Expires = opt . Expires || opt . expires ; if ( Expires === undefined ) { exp += 900 ; // 签名过期时间为当前 + 900s } else { exp += ( Expires * 1 ) || 0 ; } // 要用到的 Authorization 参数列表 var qSignAlgorithm = 'sha1' ; var qAk = SecretId ; var qSignTime = now + ';' + exp ; var qKeyTime = now + ';' + exp ; var qHeaderList = getObjectKeys ( headers ) . join ( ';' ) . toLowerCase ( ) ; var qUrlParamList = getObjectKeys ( queryParams ) . join ( ';' ) . toLowerCase ( ) ; // 签名算法说明文档：https://www.qcloud.com/document/product/436/7778 // 步骤一：计算 SignKey var signKey = CryptoJS . HmacSHA1 ( qKeyTime , SecretKey ) . toString ( ) ; // 步骤二：构成 FormatString var formatString = [ method , pathname , obj2str ( queryParams ) , obj2str ( headers ) , '' ] . join ( '\\n' ) ; // 步骤三：计算 StringToSign var stringToSign = [ 'sha1' , qSignTime , CryptoJS . SHA1 ( formatString ) . toString ( ) , '' ] . join ( '\\n' ) ; // 步骤四：计算 Signature var qSignature = CryptoJS . HmacSHA1 ( stringToSign , signKey ) . toString ( ) ; // 步骤五：构造 Authorization var authorization = [ 'q-sign-algorithm=' + qSignAlgorithm , 'q-ak=' + qAk , 'q-sign-time=' + qSignTime , 'q-key-time=' + qKeyTime , 'q-header-list=' + qHeaderList , 'q-url-param-list=' + qUrlParamList , 'q-signature=' + qSignature ] . join ( '&' ) ; return authorization ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "清除对象里值为的 undefined 或 null 的属性 [CODESPLIT] function ( obj ) { var retObj = { } ; for ( var key in obj ) { if ( obj . hasOwnProperty ( key ) && obj [ key ] !== undefined && obj [ key ] !== null ) { retObj [ key ] = obj [ key ] ; } } return retObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取文件 md5 值 [CODESPLIT] function ( blob , callback ) { readAsBinaryString ( blob , function ( content ) { var hash = md5 ( content , true ) ; callback ( null , hash ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "代理回调函数 [CODESPLIT] function ( result ) { if ( result && result . headers ) { result . headers [ 'x-cos-version-id' ] && ( result . VersionId = result . headers [ 'x-cos-version-id' ] ) ; result . headers [ 'x-cos-delete-marker' ] && ( result . DeleteMarker = result . headers [ 'x-cos-delete-marker' ] ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取上传任务的 UploadId [CODESPLIT] function getUploadIdAndPartList ( params , callback ) { var TaskId = params . TaskId ; var Bucket = params . Bucket ; var Region = params . Region ; var Key = params . Key ; var StorageClass = params . StorageClass ; var self = this ; // 计算 ETag var ETagMap = { } ; var FileSize = params . FileSize ; var SliceSize = params . SliceSize ; var SliceCount = Math . ceil ( FileSize / SliceSize ) ; var FinishSliceCount = 0 ; var FinishSize = 0 ; var onHashProgress = util . throttleOnProgress . call ( self , FileSize , params . onHashProgress ) ; var getChunkETag = function ( PartNumber , callback ) { var start = SliceSize * ( PartNumber - 1 ) ; var end = Math . min ( start + SliceSize , FileSize ) ; var ChunkSize = end - start ; if ( ETagMap [ PartNumber ] ) { callback ( null , { PartNumber : PartNumber , ETag : ETagMap [ PartNumber ] , Size : ChunkSize } ) ; } else { util . fileSlice ( params . Body , start , end , false , function ( chunkItem ) { util . getFileMd5 ( chunkItem , function ( err , md5 ) { if ( err ) return callback ( err ) ; var ETag = '\"' + md5 + '\"' ; ETagMap [ PartNumber ] = ETag ; FinishSliceCount += 1 ; FinishSize += ChunkSize ; callback ( err , { PartNumber : PartNumber , ETag : ETag , Size : ChunkSize } ) ; onHashProgress ( { loaded : FinishSize , total : FileSize } ) ; } ) ; } ) ; } } ; // 通过和文件的 md5 对比，判断 UploadId 是否可用 var isAvailableUploadList = function ( PartList , callback ) { var PartCount = PartList . length ; // 如果没有分片，通过 if ( PartCount === 0 ) { return callback ( null , true ) ; } // 检查分片数量 if ( PartCount > SliceCount ) { return callback ( null , false ) ; } // 检查分片大小 if ( PartCount > 1 ) { var PartSliceSize = Math . max ( PartList [ 0 ] . Size , PartList [ 1 ] . Size ) ; if ( PartSliceSize !== SliceSize ) { return callback ( null , false ) ; } } // 逐个分片计算并检查 ETag 是否一致 var next = function ( index ) { if ( index < PartCount ) { var Part = PartList [ index ] ; getChunkETag ( Part . PartNumber , function ( err , chunk ) { if ( chunk && chunk . ETag === Part . ETag && chunk . Size === Part . Size ) { next ( index + 1 ) ; } else { callback ( null , false ) ; } } ) ; } else { callback ( null , true ) ; } } ; next ( 0 ) ; } ; var ep = new EventProxy ( ) ; ep . on ( 'error' , function ( errData ) { if ( ! self . _isRunningTask ( TaskId ) ) return ; return callback ( errData ) ; } ) ; // 存在 UploadId ep . on ( 'upload_id_ready' , function ( UploadData ) { // 转换成 map var map = { } ; var list = [ ] ; util . each ( UploadData . PartList , function ( item ) { map [ item . PartNumber ] = item ; } ) ; for ( var PartNumber = 1 ; PartNumber <= SliceCount ; PartNumber ++ ) { var item = map [ PartNumber ] ; if ( item ) { item . PartNumber = PartNumber ; item . Uploaded = true ; } else { item = { PartNumber : PartNumber , ETag : null , Uploaded : false } ; } list . push ( item ) ; } UploadData . PartList = list ; callback ( null , UploadData ) ; } ) ; // 不存在 UploadId, 初始化生成 UploadId ep . on ( 'no_available_upload_id' , function ( ) { if ( ! self . _isRunningTask ( TaskId ) ) return ; var _params = util . extend ( { Bucket : Bucket , Region : Region , Key : Key , Headers : util . clone ( params . Headers ) , StorageClass : StorageClass , Body : params . Body , } , params ) ; // 获取 File 或 Blob 的 type 属性，如果有，作为文件 Content-Type var ContentType = params . Headers [ 'Content-Type' ] || ( params . Body && params . Body . type ) ; if ( ContentType ) { _params . Headers [ 'Content-Type' ] = ContentType ; } self . multipartInit ( _params , function ( err , data ) { if ( ! self . _isRunningTask ( TaskId ) ) return ; if ( err ) return ep . emit ( 'error' , err ) ; var UploadId = data . UploadId ; if ( ! UploadId ) { return callback ( { Message : 'no upload id' } ) ; } ep . emit ( 'upload_id_ready' , { UploadId : UploadId , PartList : [ ] } ) ; } ) ; } ) ; // 如果已存在 UploadId，找一个可以用的 UploadId ep . on ( 'has_upload_id' , function ( UploadIdList ) { // 串行地，找一个内容一致的 UploadId UploadIdList = UploadIdList . reverse ( ) ; Async . eachLimit ( UploadIdList , 1 , function ( UploadId , asyncCallback ) { if ( ! self . _isRunningTask ( TaskId ) ) return ; // 如果正在上传，跳过 if ( uploadIdUsing [ UploadId ] ) { asyncCallback ( ) ; // 检查下一个 UploadId return ; } // 判断 UploadId 是否可用 wholeMultipartListPart . call ( self , { Bucket : Bucket , Region : Region , Key : Key , UploadId : UploadId , } , function ( err , PartListData ) { if ( ! self . _isRunningTask ( TaskId ) ) return ; if ( err ) { removeUploadId . call ( self , UploadId ) ; return ep . emit ( 'error' , err ) ; } var PartList = PartListData . PartList ; PartList . forEach ( function ( item ) { item . PartNumber *= 1 ; item . Size *= 1 ; item . ETag = item . ETag || '' ; } ) ; isAvailableUploadList ( PartList , function ( err , isAvailable ) { if ( ! self . _isRunningTask ( TaskId ) ) return ; if ( err ) return ep . emit ( 'error' , err ) ; if ( isAvailable ) { asyncCallback ( { UploadId : UploadId , PartList : PartList } ) ; // 马上结束 } else { asyncCallback ( ) ; // 检查下一个 UploadId } } ) ; } ) ; } , function ( AvailableUploadData ) { if ( ! self . _isRunningTask ( TaskId ) ) return ; onHashProgress ( null , true ) ; if ( AvailableUploadData && AvailableUploadData . UploadId ) { ep . emit ( 'upload_id_ready' , AvailableUploadData ) ; } else { ep . emit ( 'no_available_upload_id' ) ; } } ) ; } ) ; // 在本地缓存找可用的 UploadId ep . on ( 'seek_local_avail_upload_id' , function ( RemoteUploadIdList ) { // 在本地找可用的 UploadId var uuid = util . getFileUUID ( params . Body , params . ChunkSize ) , LocalUploadIdList ; if ( uuid && ( LocalUploadIdList = getUploadId . call ( self , uuid ) ) ) { var next = function ( index ) { // 如果本地找不到可用 UploadId，再一个个遍历校验远端 if ( index >= LocalUploadIdList . length ) { ep . emit ( 'has_upload_id' , RemoteUploadIdList ) ; return ; } var UploadId = LocalUploadIdList [ index ] ; // 如果不在远端 UploadId 列表里，跳过并删除 if ( ! util . isInArray ( RemoteUploadIdList , UploadId ) ) { removeUploadId . call ( self , UploadId ) ; next ( index + 1 ) ; return ; } // 如果正在上传，跳过 if ( uploadIdUsing [ UploadId ] ) { next ( index + 1 ) ; return ; } // 判断 UploadId 是否存在线上 wholeMultipartListPart . call ( self , { Bucket : Bucket , Region : Region , Key : Key , UploadId : UploadId , } , function ( err , PartListData ) { if ( ! self . _isRunningTask ( TaskId ) ) return ; if ( err ) { removeUploadId . call ( self , UploadId ) ; next ( index + 1 ) ; } else { // 找到可用 UploadId ep . emit ( 'upload_id_ready' , { UploadId : UploadId , PartList : PartListData . PartList , } ) ; } } ) ; } ; next ( 0 ) ; } else { ep . emit ( 'has_upload_id' , RemoteUploadIdList ) ; } } ) ; // 获取线上 UploadId 列表 ep . on ( 'get_remote_upload_id_list' , function ( RemoteUploadIdList ) { // 获取符合条件的 UploadId 列表，因为同一个文件可以有多个上传任务。 wholeMultipartList . call ( self , { Bucket : Bucket , Region : Region , Key : Key , } , function ( err , data ) { if ( ! self . _isRunningTask ( TaskId ) ) return ; if ( err ) { return ep . emit ( 'error' , err ) ; } // 整理远端 UploadId 列表 var RemoteUploadIdList = util . filter ( data . UploadList , function ( item ) { return item . Key === Key && ( ! StorageClass || item . StorageClass . toUpperCase ( ) === StorageClass . toUpperCase ( ) ) ; } ) . reverse ( ) . map ( function ( item ) { return item . UploadId || item . UploadID ; } ) ; if ( RemoteUploadIdList . length ) { ep . emit ( 'seek_local_avail_upload_id' , RemoteUploadIdList ) ; } else { var uuid = util . getFileUUID ( params . Body , params . ChunkSize ) , LocalUploadIdList ; if ( uuid && ( LocalUploadIdList = getUploadId . call ( self , uuid ) ) ) { util . each ( LocalUploadIdList , function ( UploadId ) { removeUploadId . call ( self , UploadId ) ; } ) ; } ep . emit ( 'no_available_upload_id' ) ; } } ) ; } ) ; // 开始找可用 UploadId ep . emit ( 'get_remote_upload_id_list' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "通过和文件的 md5 对比，判断 UploadId 是否可用 [CODESPLIT] function ( PartList , callback ) { var PartCount = PartList . length ; // 如果没有分片，通过 if ( PartCount === 0 ) { return callback ( null , true ) ; } // 检查分片数量 if ( PartCount > SliceCount ) { return callback ( null , false ) ; } // 检查分片大小 if ( PartCount > 1 ) { var PartSliceSize = Math . max ( PartList [ 0 ] . Size , PartList [ 1 ] . Size ) ; if ( PartSliceSize !== SliceSize ) { return callback ( null , false ) ; } } // 逐个分片计算并检查 ETag 是否一致 var next = function ( index ) { if ( index < PartCount ) { var Part = PartList [ index ] ; getChunkETag ( Part . PartNumber , function ( err , chunk ) { if ( chunk && chunk . ETag === Part . ETag && chunk . Size === Part . Size ) { next ( index + 1 ) ; } else { callback ( null , false ) ; } } ) ; } else { callback ( null , true ) ; } } ; next ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "逐个分片计算并检查 ETag 是否一致 [CODESPLIT] function ( index ) { if ( index < PartCount ) { var Part = PartList [ index ] ; getChunkETag ( Part . PartNumber , function ( err , chunk ) { if ( chunk && chunk . ETag === Part . ETag && chunk . Size === Part . Size ) { next ( index + 1 ) ; } else { callback ( null , false ) ; } } ) ; } else { callback ( null , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取符合条件的全部上传任务 ( 条件包括 Bucket Region Prefix ) [CODESPLIT] function wholeMultipartList ( params , callback ) { var self = this ; var UploadList = [ ] ; var sendParams = { Bucket : params . Bucket , Region : params . Region , Prefix : params . Key } ; var next = function ( ) { self . multipartList ( sendParams , function ( err , data ) { if ( err ) return callback ( err ) ; UploadList . push . apply ( UploadList , data . Upload || [ ] ) ; if ( data . IsTruncated === 'true' ) { // 列表不完整 sendParams . KeyMarker = data . NextKeyMarker ; sendParams . UploadIdMarker = data . NextUploadIdMarker ; next ( ) ; } else { callback ( null , { UploadList : UploadList } ) ; } } ) ; } ; next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取指定上传任务的分块列表 [CODESPLIT] function wholeMultipartListPart ( params , callback ) { var self = this ; var PartList = [ ] ; var sendParams = { Bucket : params . Bucket , Region : params . Region , Key : params . Key , UploadId : params . UploadId } ; var next = function ( ) { self . multipartListPart ( sendParams , function ( err , data ) { if ( err ) return callback ( err ) ; PartList . push . apply ( PartList , data . Part || [ ] ) ; if ( data . IsTruncated === 'true' ) { // 列表不完整 sendParams . PartNumberMarker = data . NextPartNumberMarker ; next ( ) ; } else { callback ( null , { PartList : PartList } ) ; } } ) ; } ; next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "上传文件分块，包括 / * UploadId ( 上传任务编号 ) AsyncLimit ( 并发量 ) ， SliceList ( 上传的分块数组 ) ， FilePath ( 本地文件的位置 ) ， SliceSize ( 文件分块大小 ) FileSize ( 文件大小 ) onProgress ( 上传成功之后的回调函数 ) [CODESPLIT] function uploadSliceList ( params , cb ) { var self = this ; var TaskId = params . TaskId ; var Bucket = params . Bucket ; var Region = params . Region ; var Key = params . Key ; var UploadData = params . UploadData ; var FileSize = params . FileSize ; var SliceSize = params . SliceSize ; var ChunkParallel = Math . min ( params . AsyncLimit || self . options . ChunkParallelLimit || 1 , 256 ) ; var Body = params . Body ; var SliceCount = Math . ceil ( FileSize / SliceSize ) ; var FinishSize = 0 ; var ServerSideEncryption = params . ServerSideEncryption ; var needUploadSlices = util . filter ( UploadData . PartList , function ( SliceItem ) { if ( SliceItem [ 'Uploaded' ] ) { FinishSize += SliceItem [ 'PartNumber' ] >= SliceCount ? ( FileSize % SliceSize || SliceSize ) : SliceSize ; } return ! SliceItem [ 'Uploaded' ] ; } ) ; var onProgress = params . onProgress ; Async . eachLimit ( needUploadSlices , ChunkParallel , function ( SliceItem , asyncCallback ) { if ( ! self . _isRunningTask ( TaskId ) ) return ; var PartNumber = SliceItem [ 'PartNumber' ] ; var currentSize = Math . min ( FileSize , SliceItem [ 'PartNumber' ] * SliceSize ) - ( SliceItem [ 'PartNumber' ] - 1 ) * SliceSize ; var preAddSize = 0 ; uploadSliceItem . call ( self , { TaskId : TaskId , Bucket : Bucket , Region : Region , Key : Key , SliceSize : SliceSize , FileSize : FileSize , PartNumber : PartNumber , ServerSideEncryption : ServerSideEncryption , Body : Body , UploadData : UploadData , onProgress : function ( data ) { FinishSize += data . loaded - preAddSize ; preAddSize = data . loaded ; onProgress ( { loaded : FinishSize , total : FileSize } ) ; } , } , function ( err , data ) { if ( ! self . _isRunningTask ( TaskId ) ) return ; if ( util . isBrowser && ! err && ! data . ETag ) { err = 'get ETag error, please add \"ETag\" to CORS ExposeHeader setting.' ; } if ( err ) { FinishSize -= preAddSize ; } else { FinishSize += currentSize - preAddSize ; SliceItem . ETag = data . ETag ; } asyncCallback ( err || null , data ) ; } ) ; } , function ( err ) { if ( ! self . _isRunningTask ( TaskId ) ) return ; if ( err ) return cb ( err ) ; cb ( null , { UploadId : UploadData . UploadId , SliceList : UploadData . PartList } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "完成分块上传 [CODESPLIT] function uploadSliceComplete ( params , callback ) { var Bucket = params . Bucket ; var Region = params . Region ; var Key = params . Key ; var UploadId = params . UploadId ; var SliceList = params . SliceList ; var self = this ; var ChunkRetryTimes = this . options . ChunkRetryTimes + 1 ; var Parts = SliceList . map ( function ( item ) { return { PartNumber : item . PartNumber , ETag : item . ETag } ; } ) ; // 完成上传的请求也做重试 Async . retry ( ChunkRetryTimes , function ( tryCallback ) { self . multipartComplete ( { Bucket : Bucket , Region : Region , Key : Key , UploadId : UploadId , Parts : Parts } , tryCallback ) ; } , function ( err , data ) { callback ( err , data ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "抛弃分块上传任务 / * AsyncLimit ( 抛弃上传任务的并发量 ) ， UploadId ( 上传任务的编号，当 Level 为 task 时候需要 ) Level ( 抛弃分块上传任务的级别，task : 抛弃指定的上传任务，file ： 抛弃指定的文件对应的上传任务，其他值 ：抛弃指定Bucket 的全部上传任务 ) [CODESPLIT] function abortUploadTask ( params , callback ) { var Bucket = params . Bucket ; var Region = params . Region ; var Key = params . Key ; var UploadId = params . UploadId ; var Level = params . Level || 'task' ; var AsyncLimit = params . AsyncLimit ; var self = this ; var ep = new EventProxy ( ) ; ep . on ( 'error' , function ( errData ) { return callback ( errData ) ; } ) ; // 已经获取到需要抛弃的任务列表 ep . on ( 'get_abort_array' , function ( AbortArray ) { abortUploadTaskArray . call ( self , { Bucket : Bucket , Region : Region , Key : Key , Headers : params . Headers , AsyncLimit : AsyncLimit , AbortArray : AbortArray } , function ( err , data ) { if ( err ) { return callback ( err ) ; } callback ( null , data ) ; } ) ; } ) ; if ( Level === 'bucket' ) { // Bucket 级别的任务抛弃，抛弃该 Bucket 下的全部上传任务 wholeMultipartList . call ( self , { Bucket : Bucket , Region : Region } , function ( err , data ) { if ( err ) { return callback ( err ) ; } ep . emit ( 'get_abort_array' , data . UploadList || [ ] ) ; } ) ; } else if ( Level === 'file' ) { // 文件级别的任务抛弃，抛弃该文件的全部上传任务 if ( ! Key ) return callback ( { error : 'abort_upload_task_no_key' } ) ; wholeMultipartList . call ( self , { Bucket : Bucket , Region : Region , Key : Key } , function ( err , data ) { if ( err ) { return callback ( err ) ; } ep . emit ( 'get_abort_array' , data . UploadList || [ ] ) ; } ) ; } else if ( Level === 'task' ) { // 单个任务级别的任务抛弃，抛弃指定 UploadId 的上传任务 if ( ! UploadId ) return callback ( { error : 'abort_upload_task_no_id' } ) ; if ( ! Key ) return callback ( { error : 'abort_upload_task_no_key' } ) ; ep . emit ( 'get_abort_array' , [ { Key : Key , UploadId : UploadId } ] ) ; } else { return callback ( { error : 'abort_unknown_level' } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "批量抛弃分块上传任务 [CODESPLIT] function abortUploadTaskArray ( params , callback ) { var Bucket = params . Bucket ; var Region = params . Region ; var Key = params . Key ; var AbortArray = params . AbortArray ; var AsyncLimit = params . AsyncLimit || 1 ; var self = this ; var index = 0 ; var resultList = new Array ( AbortArray . length ) ; Async . eachLimit ( AbortArray , AsyncLimit , function ( AbortItem , callback ) { var eachIndex = index ; if ( Key && Key !== AbortItem . Key ) { resultList [ eachIndex ] = { error : { KeyNotMatch : true } } ; callback ( null ) ; return ; } var UploadId = AbortItem . UploadId || AbortItem . UploadID ; self . multipartAbort ( { Bucket : Bucket , Region : Region , Key : AbortItem . Key , Headers : params . Headers , UploadId : UploadId } , function ( err , data ) { var task = { Bucket : Bucket , Region : Region , Key : AbortItem . Key , UploadId : UploadId } ; resultList [ eachIndex ] = { error : err , task : task } ; callback ( null ) ; } ) ; index ++ ; } , function ( err ) { if ( err ) { return callback ( err ) ; } var successList = [ ] ; var errorList = [ ] ; for ( var i = 0 , len = resultList . length ; i < len ; i ++ ) { var item = resultList [ i ] ; if ( item [ 'task' ] ) { if ( item [ 'error' ] ) { errorList . push ( item [ 'task' ] ) ; } else { successList . push ( item [ 'task' ] ) ; } } } return callback ( null , { successList : successList , errorList : errorList } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "分片复制文件 [CODESPLIT] function sliceCopyFile ( params , callback ) { var ep = new EventProxy ( ) ; var self = this ; var Bucket = params . Bucket ; var Region = params . Region ; var Key = params . Key ; var CopySource = params . CopySource ; var m = CopySource . match ( / ^([^.]+-\\d+)\\.cos(v6)?\\.([^.]+)\\.[^/]+\\/(.+)$ / ) ; if ( ! m ) { callback ( { error : 'CopySource format error' } ) ; return ; } var SourceBucket = m [ 1 ] ; var SourceRegion = m [ 3 ] ; var SourceKey = decodeURIComponent ( m [ 4 ] ) ; var CopySliceSize = params . SliceSize === undefined ? self . options . CopySliceSize : params . SliceSize ; CopySliceSize = Math . max ( 0 , Math . min ( CopySliceSize , 5 * 1024 * 1024 * 1024 ) ) ; var ChunkSize = params . ChunkSize || this . options . CopyChunkSize ; var ChunkParallel = this . options . CopyChunkParallelLimit ; var FinishSize = 0 ; var FileSize ; var onProgress ; // 分片复制完成，开始 multipartComplete 操作 ep . on ( 'copy_slice_complete' , function ( UploadData ) { self . multipartComplete ( { Bucket : Bucket , Region : Region , Key : Key , UploadId : UploadData . UploadId , Parts : UploadData . PartList , } , function ( err , data ) { if ( err ) { onProgress ( null , true ) ; return callback ( err ) ; } onProgress ( { loaded : FileSize , total : FileSize } , true ) ; callback ( null , data ) ; } ) ; } ) ; ep . on ( 'get_copy_data_finish' , function ( UploadData ) { Async . eachLimit ( UploadData . PartList , ChunkParallel , function ( SliceItem , asyncCallback ) { var PartNumber = SliceItem . PartNumber ; var CopySourceRange = SliceItem . CopySourceRange ; var currentSize = SliceItem . end - SliceItem . start ; var preAddSize = 0 ; copySliceItem . call ( self , { Bucket : Bucket , Region : Region , Key : Key , CopySource : CopySource , UploadId : UploadData . UploadId , PartNumber : PartNumber , CopySourceRange : CopySourceRange , onProgress : function ( data ) { FinishSize += data . loaded - preAddSize ; preAddSize = data . loaded ; onProgress ( { loaded : FinishSize , total : FileSize } ) ; } } , function ( err , data ) { if ( err ) { return asyncCallback ( err ) ; } onProgress ( { loaded : FinishSize , total : FileSize } ) ; FinishSize += currentSize - preAddSize ; SliceItem . ETag = data . ETag ; asyncCallback ( err || null , data ) ; } ) ; } , function ( err ) { if ( err ) { onProgress ( null , true ) ; return callback ( err ) ; } ep . emit ( 'copy_slice_complete' , UploadData ) ; } ) ; } ) ; ep . on ( 'get_file_size_finish' , function ( SourceHeaders ) { // 控制分片大小 ( function ( ) { var SIZE = [ 1 , 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 , 512 , 1024 , 1024 * 2 , 1024 * 4 , 1024 * 5 ] ; var AutoChunkSize = 1024 * 1024 ; for ( var i = 0 ; i < SIZE . length ; i ++ ) { AutoChunkSize = SIZE [ i ] * 1024 * 1024 ; if ( FileSize / AutoChunkSize <= self . options . MaxPartNumber ) break ; } params . ChunkSize = ChunkSize = Math . max ( ChunkSize , AutoChunkSize ) ; var ChunkCount = Math . ceil ( FileSize / ChunkSize ) ; var list = [ ] ; for ( var partNumber = 1 ; partNumber <= ChunkCount ; partNumber ++ ) { var start = ( partNumber - 1 ) * ChunkSize ; var end = partNumber * ChunkSize < FileSize ? ( partNumber * ChunkSize - 1 ) : FileSize - 1 ; var item = { PartNumber : partNumber , start : start , end : end , CopySourceRange : \"bytes=\" + start + \"-\" + end , } ; list . push ( item ) ; } params . PartList = list ; } ) ( ) ; var TargetHeader ; if ( params . Headers [ 'x-cos-metadata-directive' ] === 'Replaced' ) { TargetHeader = params . Headers ; } else { TargetHeader = SourceHeaders ; } TargetHeader [ 'x-cos-storage-class' ] = params . Headers [ 'x-cos-storage-class' ] || SourceHeaders [ 'x-cos-storage-class' ] ; TargetHeader = util . clearKey ( TargetHeader ) ; self . multipartInit ( { Bucket : Bucket , Region : Region , Key : Key , Headers : TargetHeader , } , function ( err , data ) { if ( err ) { return callback ( err ) ; } params . UploadId = data . UploadId ; ep . emit ( 'get_copy_data_finish' , params ) ; } ) ; } ) ; // 获取远端复制源文件的大小 self . headObject ( { Bucket : SourceBucket , Region : SourceRegion , Key : SourceKey , } , function ( err , data ) { if ( err ) { if ( err . statusCode && err . statusCode === 404 ) { callback ( { ErrorStatus : SourceKey + ' Not Exist' } ) ; } else { callback ( err ) ; } return ; } FileSize = params . FileSize = data . headers [ 'content-length' ] ; if ( FileSize === undefined || ! FileSize ) { callback ( { error : 'get Content-Length error, please add \"Content-Length\" to CORS ExposeHeader setting.' } ) ; return ; } onProgress = util . throttleOnProgress . call ( self , FileSize , params . onProgress ) ; // 开始上传 if ( FileSize <= CopySliceSize ) { if ( ! params . Headers [ 'x-cos-metadata-directive' ] ) { params . Headers [ 'x-cos-metadata-directive' ] = 'Copy' ; } self . putObjectCopy ( params , function ( err , data ) { if ( err ) { onProgress ( null , true ) ; return callback ( err ) ; } onProgress ( { loaded : FileSize , total : FileSize } , true ) ; callback ( err , data ) ; } ) ; } else { var resHeaders = data . headers ; var SourceHeaders = { 'Cache-Control' : resHeaders [ 'cache-control' ] , 'Content-Disposition' : resHeaders [ 'content-disposition' ] , 'Content-Encoding' : resHeaders [ 'content-encoding' ] , 'Content-Type' : resHeaders [ 'content-type' ] , 'Expires' : resHeaders [ 'expires' ] , 'x-cos-storage-class' : resHeaders [ 'x-cos-storage-class' ] , } ; util . each ( resHeaders , function ( v , k ) { var metaPrefix = 'x-cos-meta-' ; if ( k . indexOf ( metaPrefix ) === 0 && k . length > metaPrefix . length ) { SourceHeaders [ k ] = v ; } } ) ; ep . emit ( 'get_file_size_finish' , SourceHeaders ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "复制指定分片 [CODESPLIT] function copySliceItem ( params , callback ) { var TaskId = params . TaskId ; var Bucket = params . Bucket ; var Region = params . Region ; var Key = params . Key ; var CopySource = params . CopySource ; var UploadId = params . UploadId ; var PartNumber = params . PartNumber * 1 ; var CopySourceRange = params . CopySourceRange ; var ChunkRetryTimes = this . options . ChunkRetryTimes + 1 ; var self = this ; Async . retry ( ChunkRetryTimes , function ( tryCallback ) { self . uploadPartCopy ( { TaskId : TaskId , Bucket : Bucket , Region : Region , Key : Key , CopySource : CopySource , UploadId : UploadId , PartNumber : PartNumber , CopySourceRange : CopySourceRange , onProgress : params . onProgress , } , function ( err , data ) { tryCallback ( err || null , data ) ; } ) } , function ( err , data ) { return callback ( err , data ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If already stringified - return original content [CODESPLIT] function stringify ( content ) { if ( typeof content === 'string' && stringifiedRegexp . test ( content ) ) { return content ; } return JSON . stringify ( content , null , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find nearest module chunk ( not sure that is reliable method but who cares ) . [CODESPLIT] function getModuleChunk ( module , modules ) { let chunks ; if ( webpackVersion . IS_4 ) { chunks = Array . from ( module . chunksIterable ) ; } else if ( parseInt ( webpackVersion ( ) , 10 ) >= 3 ) { chunks = module . mapChunks ( ) ; } else { chunks = module . chunks ; } // webpack 1 compat const issuer = typeof module . issuer === 'string' ? modules . find ( m => m . request === module . issuer ) : module . issuer ; if ( Array . isArray ( chunks ) && chunks . length > 0 ) { return chunks [ chunks . length - 1 ] ; } else if ( issuer ) { return getModuleChunk ( issuer , modules ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "webpack 1 compat loader options finder . Returns normalized options . [CODESPLIT] function getLoaderOptions ( loaderPath , rule ) { let multiRuleProp ; if ( isWebpack1 ) { multiRuleProp = 'loaders' ; } else if ( rule . oneOf ) { multiRuleProp = 'oneOf' ; } else { multiRuleProp = 'use' ; } const multiRule = typeof rule === 'object' && Array . isArray ( rule [ multiRuleProp ] ) ? rule [ multiRuleProp ] : null ; let options ; if ( multiRule ) { const rules = [ ] . concat ( ... multiRule . map ( r => ( r . use || r ) ) ) ; options = rules . map ( normalizeRule ) . find ( r => loaderPath . includes ( r . loader ) ) . options ; } else { options = normalizeRule ( rule ) . options ; } return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "webpack 1 compat rule normalizer [CODESPLIT] function normalizeRule ( rule ) { if ( ! rule ) { throw new Error ( 'Rule should be string or object' ) ; } let data ; if ( typeof rule === 'string' ) { const parts = rule . split ( '?' ) ; data = { loader : parts [ 0 ] , options : parts [ 1 ] ? parseQuery ( ` ${ parts [ 1 ] } ` ) : null } ; } else { const options = isWebpack1 ? rule . query : rule . options ; data = { loader : rule . loader , options : options || null } ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find child excluding dragging node default [CODESPLIT] function findChild ( info , children , handler , reverse ) { const len = children . length if ( reverse ) { for ( let i = len - 1 ; i >= 0 ; i -- ) { const item = children [ i ] // excluding dragging node if ( item !== info . node ) { if ( handler ( item , i ) ) { return item } } } } else { for ( let i = 0 ; i < len ; i ++ ) { const item = children [ i ] // excluding dragging node if ( item !== info . node ) { if ( handler ( item , i ) ) { return item } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start from node self [CODESPLIT] function findParent ( node , handle ) { let current = node while ( current ) { if ( handle ( current ) ) { return current } current = current . parent } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pure node self [CODESPLIT] function pure ( node , withChildren , after ) { var _this2 = this ; var t = assign$1 ( { } , node ) ; delete t . _id ; delete t . parent ; delete t . children ; delete t . open ; delete t . active ; delete t . style ; delete t . class ; delete t . innerStyle ; delete t . innerClass ; delete t . innerBackStyle ; delete t . innerBackClass ; var _arr = keys$1 ( t ) ; for ( var _i = 0 ; _i < _arr . length ; _i ++ ) { var key = _arr [ _i ] ; if ( key [ 0 ] === '_' ) { delete t [ key ] ; } } if ( withChildren && node . children ) { t . children = node . children . slice ( ) ; t . children . forEach ( function ( v , k ) { t . children [ k ] = _this2 . pure ( v , withChildren ) ; } ) ; } if ( after ) { return after ( t , node ) || t ; } return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find child excluding dragging node default [CODESPLIT] function findChild ( info , children , handler , reverse ) { var len = children . length ; if ( reverse ) { for ( var i = len - 1 ; i >= 0 ; i -- ) { var item = children [ i ] ; // excluding dragging node if ( item !== info . node ) { if ( handler ( item , i ) ) { return item ; } } } } else { for ( var _i = 0 ; _i < len ; _i ++ ) { var _item = children [ _i ] ; // excluding dragging node if ( _item !== info . node ) { if ( handler ( _item , _i ) ) { return _item ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "当前树为空 ( 不包括占位节点 ) [CODESPLIT] function currentTreeEmpty ( info ) { return ! findChild ( info , info . currentTree . rootData . children , function ( v ) { return v ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "另一节点有子 ( 不包括占位节点 ) [CODESPLIT] function targetNodeHasChildrenExcludingPlaceholder ( info ) { return findChild ( info , info . targetNode . children , function ( v ) { return v !== info . dplh ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "另一节点是第一个节点 [CODESPLIT] function targetNodeIs1stChild ( info ) { return findChild ( info , info . targetNode . parent . children , function ( v ) { return v ; } ) === info . targetNode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "另一节点是最后节点 [CODESPLIT] function targetNodeIsLastChild ( info ) { return findChild ( info , info . targetNode . parent . children , function ( v ) { return v ; } , true ) === info . targetNode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "当前位置在另一节点innner indent位置右边 [CODESPLIT] function atIndentRight ( info ) { return info . offset . x > info . tiOffset . x + info . currentTree . indent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "context is vm [CODESPLIT] function autoMoveDragPlaceHolder ( draggableHelperInfo ) { var trees = this . store . trees ; var dhStore = draggableHelperInfo . store ; // make info var info = { event : draggableHelperInfo . event , el : dhStore . el , vm : this , node : this . data , store : this . store , dplh : this . store . dplh , draggableHelperData : { opt : draggableHelperInfo . options , store : dhStore } // } ; attachCache ( info , new Cache ( ) , { // dragging node coordinate // 拖动中的节点相关坐标 nodeInnerEl : function nodeInnerEl ( ) { return this . el . querySelector ( '.tree-node-inner' ) ; } , offset : function offset ( ) { return getOffset ( this . nodeInnerEl ) ; } , // left top point offset2 : function offset2 ( ) { return { x : this . offset . x + this . nodeInnerEl . offsetWidth , y : this . offset . y + this . nodeInnerEl . offsetHeight } ; } , // right bottom point offsetToViewPort : function offsetToViewPort ( ) { var r = this . nodeInnerEl . getBoundingClientRect ( ) ; r . x = r . left ; r . y = r . top ; return r ; } , // tree currentTree : function currentTree ( ) { // const currentTree = trees.find(tree => hp.isOffsetInEl(this.offset.x, this.offset.y, tree.$el)) var currentTree = getTreeByPoint ( this . offsetToViewPort . x , this . offsetToViewPort . y , trees ) ; if ( currentTree ) { var dragStartTree = this . store ; if ( prevTree == null ) { prevTree = dragStartTree ; } if ( prevTree !== currentTree ) { if ( ! isPropTrue ( dragStartTree . crossTree ) || ! isPropTrue ( currentTree . crossTree ) ) { return ; } prevTree = currentTree ; } if ( ! isPropTrue ( currentTree . droppable ) ) { return ; } return currentTree ; } } , currentTreeRootEl : function currentTreeRootEl ( ) { return document . getElementById ( this . currentTree . rootData . _id ) ; } , currentTreeRootOf4 : function currentTreeRootOf4 ( ) { return getOf4 ( this . currentTreeRootEl , this . currentTree . space ) ; } , // the second child of currentTree root, excluding dragging node currentTreeRootSecondChildExcludingDragging : function currentTreeRootSecondChildExcludingDragging ( ) { var _this = this ; return this . currentTree . rootData . children . slice ( 0 , 3 ) . filter ( function ( v ) { return v !== _this . node ; } ) [ 1 ] ; } , // placeholder dplhEl : function dplhEl ( ) { return document . getElementById ( this . dplh . _id ) ; } , dplhElInCurrentTree : function dplhElInCurrentTree ( ) { return Boolean ( this . currentTree . $el . querySelector ( \"#\" . concat ( this . dplh . _id ) ) ) ; } , dplhOf4 : function dplhOf4 ( ) { return getOf4 ( this . dplhEl , this . currentTree . space ) ; } , dplhAtTop : function dplhAtTop ( ) { return Math . abs ( this . dplhOf4 . y - this . currentTreeRootOf4 . y ) < 5 ; } , targetAtTop : function targetAtTop ( ) { return Math . abs ( this . tiOf4 . y - this . currentTreeRootOf4 . y ) < 5 ; } , targetAtBottom : function targetAtBottom ( ) { return Math . abs ( this . tiOf4 . y2 - this . currentTreeRootOf4 . y2 ) < 5 ; } , // most related node // 最相关的另一个节点 targetNode : function targetNode ( ) { var currentTree = this . currentTree ; if ( ! currentTree ) { throw 'no currentTree' ; } // var _this$offset = this . offset , x = _this$offset . x , y = _this$offset . y ; var currentNode = currentTree . rootData ; while ( true ) { var children = currentNode . children ; if ( ! children ) { break ; } if ( this . node . parent === currentNode ) { // dragging node is in currentNode children, remove it first children = children . slice ( ) ; children . splice ( children . indexOf ( this . node ) , 1 ) ; } if ( children . length === 0 ) { break ; } var t = binarySearch ( children , function ( node ) { var el = document . getElementById ( node . _id ) ; var ty = getOffset ( el ) . y ; var ty2 = ty + el . offsetHeight + currentTree . space ; if ( ty2 < y ) { return - 1 ; } else if ( ty <= y ) { return 0 ; } else { return 1 ; } } , null , null , true ) ; if ( t . hit ) { currentNode = t . value ; } else { if ( t . bigger ) { currentNode = children [ t . index - 1 ] ; } else { currentNode = t . value ; } } if ( ! currentNode ) { currentNode = children [ 0 ] ; break ; } if ( ! currentNode ) { break ; } var innerEl = document . getElementById ( currentNode . _id ) . querySelector ( '.tree-node-inner' ) ; var of = getOf4 ( innerEl , currentTree . space ) ; if ( of . y <= y && y <= of . y2 ) { break ; } } return currentNode ; } , targetNodeEl : function targetNodeEl ( ) { return document . getElementById ( this . targetNode . _id ) ; } , // targetNodeInnerElOffset tiInnerEl : function tiInnerEl ( ) { return this . targetNodeEl . querySelector ( '.tree-node-inner' ) ; } , tiOffset : function tiOffset ( ) { return getOffset ( this . tiInnerEl ) ; } , tiOf4 : function tiOf4 ( ) { return getOf4 ( this . tiInnerEl , this . currentTree . space ) ; } , tiMiddleY : function tiMiddleY ( ) { return this . tiOffset . y + this . tiInnerEl . offsetHeight / 2 ; } , // targetPrevEl : function targetPrevEl ( ) { // tree node 之间不要有其他元素, 否则这里会获取到错误的元素 var r = this . targetNodeEl . previousSibling ; if ( hasClass ( r , 'dragging' ) ) { r = r . previousSibling ; } return r ; } , targetPrev : function targetPrev ( ) { var id = this . targetPrevEl . getAttribute ( 'id' ) ; return this . currentTree . getNodeById ( id ) ; } } ) ; // attachCache end // decision start ================================= var executedRuleCache = { } ; // exec rule var exec = function exec ( ruleId ) { if ( ! executedRuleCache . hasOwnProperty ( ruleId ) ) { var r ; try { r = rules [ ruleId ] ( info ) ; } catch ( e ) { r = e ; try { if ( process . env . DEVELOPE_SELF ) { // only visible when develop its self console . warn ( \"failed to execute rule '\" . concat ( ruleId , \"'\" ) , e ) ; } } catch ( e2 ) { } } executedRuleCache [ ruleId ] = r ; } return executedRuleCache [ ruleId ] ; } ; if ( exec ( 'currentTree existed' ) === true ) { if ( exec ( 'targetNode is placeholder' ) === false ) { if ( exec ( 'targetNode is the second child of root' ) === true ) { if ( exec ( 'targetNode has children excluding placeholder' ) === false ) { if ( exec ( 'on targetNode middle' ) === true ) { targets [ 'before' ] ( info ) ; } else if ( exec ( 'on targetNode middle' ) === false ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) { targets [ 'after' ] ( info ) ; } } } else if ( exec ( 'targetNode has children excluding placeholder' ) === true ) { targets [ 'prepend' ] ( info ) ; } } else if ( exec ( 'targetNode is the second child of root' ) === false ) { if ( exec ( 'currentTree empty' ) === false ) { if ( exec ( 'targetNode at top' ) === true ) { if ( exec ( 'placeholder in currentTree' ) === true ) { if ( exec ( 'targetNode has children excluding placeholder' ) === false ) { if ( exec ( 'on targetNode middle' ) === false ) { if ( exec ( 'at indent right' ) === false ) { targets [ 'after' ] ( info ) ; } else if ( exec ( 'at indent right' ) === true ) { targets [ 'append' ] ( info ) ; } } else if ( exec ( 'on targetNode middle' ) === true ) { targets [ 'before' ] ( info ) ; } } else if ( exec ( 'targetNode has children excluding placeholder' ) === true ) { if ( exec ( 'on targetNode middle' ) === false ) { targets [ 'prepend' ] ( info ) ; } else if ( exec ( 'on targetNode middle' ) === true ) { targets [ 'before' ] ( info ) ; } } } else if ( exec ( 'placeholder in currentTree' ) === false ) { targets [ 'before' ] ( info ) ; } } else if ( exec ( 'targetNode at top' ) === false ) { if ( exec ( 'targetNode at bottom' ) === false ) { if ( exec ( 'placeholder at top' ) === true ) { targets [ 'prepend' ] ( info ) ; } else if ( exec ( 'placeholder at top' ) === false ) { if ( exec ( 'targetNode has children excluding placeholder' ) === true ) { targets [ 'prepend' ] ( info ) ; } else if ( exec ( 'targetNode has children excluding placeholder' ) === false ) { if ( exec ( 'targetNode is 1st child' ) === false ) { if ( exec ( 'targetNode is last child' ) === false ) { if ( exec ( 'on targetNode middle' ) === true ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) { targets [ 'after' ] ( info ) ; } } else if ( exec ( 'on targetNode middle' ) === false ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) { targets [ 'after' ] ( info ) ; } } } else if ( exec ( 'targetNode is last child' ) === true ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) { targets [ 'after' ] ( info ) ; } } } else if ( exec ( 'targetNode is 1st child' ) === true ) { if ( exec ( 'targetNode is last child' ) === true ) { targets [ 'append' ] ( info ) ; } else if ( exec ( 'targetNode is last child' ) === false ) { if ( exec ( 'on targetNode middle' ) === false ) { if ( exec ( 'at indent right' ) === false ) { targets [ 'after' ] ( info ) ; } else if ( exec ( 'at indent right' ) === true ) { targets [ 'append' ] ( info ) ; } } else if ( exec ( 'on targetNode middle' ) === true ) { if ( exec ( 'at indent right' ) === false ) { targets [ 'after' ] ( info ) ; } else if ( exec ( 'at indent right' ) === true ) { targets [ 'append' ] ( info ) ; } } } } } } } else if ( exec ( 'targetNode at bottom' ) === true ) { if ( exec ( 'placeholder in currentTree' ) === true ) { if ( exec ( 'on targetNode middle' ) === false ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) { targets [ 'after' ] ( info ) ; } } else if ( exec ( 'on targetNode middle' ) === true ) { targets [ 'append' ] ( info ) ; } } else if ( exec ( 'placeholder in currentTree' ) === false ) { targets [ 'append' ] ( info ) ; } } } } else if ( exec ( 'currentTree empty' ) === true ) { targets [ 'append current tree' ] ( info ) ; } } } else if ( exec ( 'targetNode is placeholder' ) === true ) { if ( exec ( 'targetNode at bottom' ) === false ) { if ( exec ( 'targetNode is the second child of root' ) === false ) { if ( exec ( 'targetNode is 1st child' ) === true ) { if ( exec ( 'targetNode is last child' ) === false ) ; else if ( exec ( 'targetNode is last child' ) === true ) { if ( exec ( 'on targetNode middle' ) === false ) { if ( exec ( 'at left' ) === true ) { targets [ 'after target parent' ] ( info ) ; } else if ( exec ( 'at left' ) === false ) ; } else if ( exec ( 'on targetNode middle' ) === true ) { if ( exec ( 'at left' ) === true ) { targets [ 'after target parent' ] ( info ) ; } else if ( exec ( 'at left' ) === false ) ; } } } else if ( exec ( 'targetNode is 1st child' ) === false ) { if ( exec ( 'targetNode is last child' ) === true ) { if ( exec ( 'on targetNode middle' ) === true ) { if ( exec ( 'at left' ) === true ) { targets [ 'after target parent' ] ( info ) ; } else if ( exec ( 'at left' ) === false ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append prev' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) ; } } else if ( exec ( 'on targetNode middle' ) === false ) { if ( exec ( 'at left' ) === true ) { targets [ 'after target parent' ] ( info ) ; } else if ( exec ( 'at left' ) === false ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append prev' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) ; } } } else if ( exec ( 'targetNode is last child' ) === false ) { if ( exec ( 'on targetNode middle' ) === true ) { if ( exec ( 'at left' ) === true ) ; else if ( exec ( 'at left' ) === false ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append prev' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) ; } } else if ( exec ( 'on targetNode middle' ) === false ) { if ( exec ( 'at left' ) === true ) ; else if ( exec ( 'at left' ) === false ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append prev' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) ; } } } } } else if ( exec ( 'targetNode is the second child of root' ) === true ) { if ( exec ( 'on targetNode middle' ) === true ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append prev' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) ; } else if ( exec ( 'on targetNode middle' ) === false ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append prev' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) ; } } } else if ( exec ( 'targetNode at bottom' ) === true ) { if ( exec ( 'targetNode is 1st child' ) === true ) { if ( exec ( 'on targetNode middle' ) === false ) { if ( exec ( 'at left' ) === true ) { targets [ 'after target parent' ] ( info ) ; } else if ( exec ( 'at left' ) === false ) ; } else if ( exec ( 'on targetNode middle' ) === true ) { if ( exec ( 'at left' ) === false ) ; else if ( exec ( 'at left' ) === true ) { targets [ 'after target parent' ] ( info ) ; } } } else if ( exec ( 'targetNode is 1st child' ) === false ) { if ( exec ( 'on targetNode middle' ) === false ) { if ( exec ( 'at left' ) === true ) { targets [ 'after target parent' ] ( info ) ; } else if ( exec ( 'at left' ) === false ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append prev' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) ; } } else if ( exec ( 'on targetNode middle' ) === true ) { if ( exec ( 'at left' ) === true ) { targets [ 'after target parent' ] ( info ) ; } else if ( exec ( 'at left' ) === false ) { if ( exec ( 'at indent right' ) === true ) { targets [ 'append prev' ] ( info ) ; } else if ( exec ( 'at indent right' ) === false ) ; } } } } } } else if ( exec ( 'currentTree existed' ) === false ) ; // decision end ================================= // }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "left top point [CODESPLIT] function offset2 ( ) { return { x : this . offset . x + this . nodeInnerEl . offsetWidth , y : this . offset . y + this . nodeInnerEl . offsetHeight } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "right bottom point [CODESPLIT] function offsetToViewPort ( ) { var r = this . nodeInnerEl . getBoundingClientRect ( ) ; r . x = r . left ; r . y = r . top ; return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the second child of currentTree root excluding dragging node [CODESPLIT] function currentTreeRootSecondChildExcludingDragging ( ) { var _this = this ; return this . currentTree . rootData . children . slice ( 0 , 3 ) . filter ( function ( v ) { return v !== _this . node ; } ) [ 1 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "exec rule [CODESPLIT] function exec ( ruleId ) { if ( ! executedRuleCache . hasOwnProperty ( ruleId ) ) { var r ; try { r = rules [ ruleId ] ( info ) ; } catch ( e ) { r = e ; try { if ( process . env . DEVELOPE_SELF ) { // only visible when develop its self console . warn ( \"failed to execute rule '\" . concat ( ruleId , \"'\" ) , e ) ; } } catch ( e2 ) { } } executedRuleCache [ ruleId ] = r ; } return executedRuleCache [ ruleId ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "append to prev sibling [CODESPLIT] function appendPrev ( info ) { if ( isNodeDroppable ( info . targetPrev ) ) { th . appendTo ( info . dplh , info . targetPrev ) ; if ( ! info . targetPrev . open ) info . store . toggleOpen ( info . targetPrev ) ; } else { insertDplhAfterTo ( info . dplh , info . targetPrev , info ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "append to current tree [CODESPLIT] function appendCurrentTree ( info ) { if ( isNodeDroppable ( info . currentTree . rootData ) ) { th . appendTo ( info . dplh , info . currentTree . rootData ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tree [CODESPLIT] function currentTree ( ) { // const currentTree = trees.find(tree => hp.isOffsetInEl(this.offset.x, this.offset.y, tree.$el)) var currentTree = getTreeByPoint ( this . offsetToViewPort . x , this . offsetToViewPort . y , trees ) ; if ( currentTree ) { var dragStartTree = this . store ; if ( prevTree == null ) { prevTree = dragStartTree ; } if ( prevTree !== currentTree ) { if ( ! vf . isPropTrue ( dragStartTree . crossTree ) || ! vf . isPropTrue ( currentTree . crossTree ) ) { return ; } prevTree = currentTree ; } if ( ! vf . isPropTrue ( currentTree . droppable ) ) { return ; } return currentTree ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "most related node 最相关的另一个节点 [CODESPLIT] function targetNode ( ) { var currentTree = this . currentTree ; if ( ! currentTree ) { throw 'no currentTree' ; } // var _this$offset = this . offset , x = _this$offset . x , y = _this$offset . y ; var currentNode = currentTree . rootData ; while ( true ) { var children = currentNode . children ; if ( ! children ) { break ; } if ( this . node . parent === currentNode ) { // dragging node is in currentNode children, remove it first children = children . slice ( ) ; children . splice ( children . indexOf ( this . node ) , 1 ) ; } if ( children . length === 0 ) { break ; } var t = hp . binarySearch ( children , function ( node ) { var el = document . getElementById ( node . _id ) ; var ty = hp . getOffset ( el ) . y ; var ty2 = ty + el . offsetHeight + currentTree . space ; if ( ty2 < y ) { return - 1 ; } else if ( ty <= y ) { return 0 ; } else { return 1 ; } } , null , null , true ) ; if ( t . hit ) { currentNode = t . value ; } else { if ( t . bigger ) { currentNode = children [ t . index - 1 ] ; } else { currentNode = t . value ; } } if ( ! currentNode ) { currentNode = children [ 0 ] ; break ; } if ( ! currentNode ) { break ; } var innerEl = document . getElementById ( currentNode . _id ) . querySelector ( '.tree-node-inner' ) ; var of = getOf4 ( innerEl , currentTree . space ) ; if ( of . y <= y && y <= of . y2 ) { break ; } } return currentNode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the word View is appended to selector and if it is strip it out [CODESPLIT] function stripViewFromSelector ( selector ) { // Don't strip it out if it's one of these 4 element types // (see https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Utilities/FBElementTypeTransformer.m for reference) const keepView = [ 'XCUIElementTypeScrollView' , 'XCUIElementTypeCollectionView' , 'XCUIElementTypeTextView' , 'XCUIElementTypeWebView' , ] . includes ( selector ) ; if ( ! keepView && selector . indexOf ( 'View' ) === selector . length - 4 ) { return selector . substr ( 0 , selector . length - 4 ) ; } else { return selector ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the process id of the most recent running application having the particular command line pattern . [CODESPLIT] async function getPidUsingPattern ( pgrepPattern ) { const args = [ '-nif' , pgrepPattern ] ; try { const { stdout } = await exec ( 'pgrep' , args ) ; const pid = parseInt ( stdout , 10 ) ; if ( isNaN ( pid ) ) { log . debug ( ` ${ args . join ( ' ' ) } ${ stdout } ` ) ; return null ; } return ` ${ pid } ` ; } catch ( err ) { log . debug ( ` ${ args . join ( ' ' ) } ${ err . code } ` ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Kill a process having the particular command line pattern . This method tries to send SIGINT SIGTERM and SIGKILL to the matched processes in this order if the process is still running . [CODESPLIT] async function killAppUsingPattern ( pgrepPattern ) { for ( const signal of [ 2 , 15 , 9 ] ) { if ( ! await getPidUsingPattern ( pgrepPattern ) ) { return ; } const args = [ ` ${ signal } ` , '-if' , pgrepPattern ] ; try { await exec ( 'pkill' , args ) ; } catch ( err ) { log . debug ( ` ${ args . join ( ' ' ) } ${ err . message } ` ) ; } await B . delay ( 100 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the IDs of processes listening on the particular system port . It is also possible to apply additional filtering based on the process command line . [CODESPLIT] async function getPIDsListeningOnPort ( port , filteringFunc = null ) { const result = [ ] ; try { // This only works since Mac OS X El Capitan const { stdout } = await exec ( 'lsof' , [ '-ti' , ` ${ port } ` ] ) ; result . push ( ... ( stdout . trim ( ) . split ( / \\n+ / ) ) ) ; } catch ( e ) { return result ; } if ( ! _ . isFunction ( filteringFunc ) ) { return result ; } return await B . filter ( result , async ( x ) => { const { stdout } = await exec ( 'ps' , [ '-p' , x , '-o' , 'command' ] ) ; return await filteringFunc ( stdout ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@typedef { Object } UploadOptions [CODESPLIT] async function encodeBase64OrUpload ( localFile , remotePath = null , uploadOptions = { } ) { if ( ! await fs . exists ( localFile ) ) { log . errorAndThrow ( ` ${ localFile } ` ) ; } const { size } = await fs . stat ( localFile ) ; log . debug ( ` ${ util . toReadableSizeString ( size ) } ` ) ; if ( _ . isEmpty ( remotePath ) ) { const maxMemoryLimit = v8 . getHeapStatistics ( ) . total_available_size / 2 ; if ( size >= maxMemoryLimit ) { log . info ( ` ` + ` ${ util . toReadableSizeString ( size ) } ${ util . toReadableSizeString ( maxMemoryLimit ) } ` + ` ` + ` ` ) ; } const content = await fs . readFile ( localFile ) ; return content . toString ( 'base64' ) ; } const remoteUrl = url . parse ( remotePath ) ; let options = { } ; const { user , pass , method } = uploadOptions ; if ( remoteUrl . protocol . startsWith ( 'http' ) ) { options = { url : remoteUrl . href , method : method || 'PUT' , multipart : [ { body : _fs . createReadStream ( localFile ) } ] , } ; if ( user && pass ) { options . auth = { user , pass } ; } } else if ( remoteUrl . protocol === 'ftp:' ) { options = { host : remoteUrl . hostname , port : remoteUrl . port || 21 , } ; if ( user && pass ) { options . user = user ; options . pass = pass ; } } await net . uploadFile ( localFile , remotePath , options ) ; return '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops and removes all web socket handlers that are listening in scope of the currect session . [CODESPLIT] async function removeAllSessionWebSocketHandlers ( server , sessionId ) { if ( ! server || ! _ . isFunction ( server . getWebSocketHandlers ) ) { return ; } const activeHandlers = await server . getWebSocketHandlers ( sessionId ) ; for ( const pathname of _ . keys ( activeHandlers ) ) { await server . removeWebSocketHandler ( pathname ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verify whether the given application is compatible to the platform where it is going to be installed and tested . [CODESPLIT] async function verifyApplicationPlatform ( app , isSimulator ) { log . debug ( 'Verifying application platform' ) ; const infoPlist = path . resolve ( app , 'Info.plist' ) ; if ( ! await fs . exists ( infoPlist ) ) { log . debug ( ` ${ infoPlist } ` ) ; return null ; } const { CFBundleSupportedPlatforms } = await plist . parsePlistFile ( infoPlist ) ; log . debug ( ` ${ JSON . stringify ( CFBundleSupportedPlatforms ) } ` ) ; if ( ! _ . isArray ( CFBundleSupportedPlatforms ) ) { log . debug ( ` ${ infoPlist } ` ) ; return null ; } const isAppSupported = ( isSimulator && CFBundleSupportedPlatforms . includes ( 'iPhoneSimulator' ) ) || ( ! isSimulator && CFBundleSupportedPlatforms . includes ( 'iPhoneOS' ) ) ; if ( isAppSupported ) { return true ; } throw new Error ( ` ${ isSimulator ? 'Simulator' : 'Real device' } ${ app } ` + ` ` ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the urlString is localhost [CODESPLIT] function isLocalHost ( urlString ) { try { const { hostname } = url . parse ( urlString ) ; return [ 'localhost' , '127.0.0.1' , '::1' , '::ffff:127.0.0.1' ] . includes ( hostname ) ; } catch { log . warn ( ` ${ urlString } ` ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalizes platformVersion to a valid iOS version string [CODESPLIT] function normalizePlatformVersion ( originalVersion ) { const normalizedVersion = util . coerceVersion ( originalVersion , false ) ; if ( ! normalizedVersion ) { throw new Error ( ` ${ originalVersion } ` ) ; } const { major , minor } = new semver . SemVer ( normalizedVersion ) ; return ` ${ major } ${ minor } ` ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update WebDriverAgentRunner project bundle ID with newBundleId . This method assumes project file is in the correct state . [CODESPLIT] async function updateProjectFile ( agentPath , newBundleId ) { let projectFilePath = ` ${ agentPath } ${ PROJECT_FILE } ` ; try { // Assuming projectFilePath is in the correct state, create .old from projectFilePath await fs . copyFile ( projectFilePath , ` ${ projectFilePath } ` ) ; await replaceInFile ( projectFilePath , new RegExp ( WDA_RUNNER_BUNDLE_ID . replace ( '.' , '\\.' ) , 'g' ) , newBundleId ) ; // eslint-disable-line no-useless-escape log . debug ( ` ${ projectFilePath } ${ newBundleId } ` ) ; } catch ( err ) { log . debug ( ` ${ err . message } ` ) ; log . warn ( ` ${ projectFilePath } ` + ` ${ newBundleId } ` ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset WebDriverAgentRunner project bundle ID to correct state . [CODESPLIT] async function resetProjectFile ( agentPath ) { let projectFilePath = ` ${ agentPath } ${ PROJECT_FILE } ` ; try { // restore projectFilePath from .old file if ( ! await fs . exists ( ` ${ projectFilePath } ` ) ) { return ; // no need to reset } await fs . mv ( ` ${ projectFilePath } ` , projectFilePath ) ; log . debug ( ` ${ projectFilePath } ${ WDA_RUNNER_BUNDLE_ID } ` ) ; } catch ( err ) { log . debug ( ` ${ err . message } ` ) ; log . warn ( ` ${ projectFilePath } ` + ` ${ WDA_RUNNER_BUNDLE_ID } ` + ` ` ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the WDA object which appends existing xctest runner content [CODESPLIT] function getAdditionalRunContent ( platformName , wdaRemotePort ) { const runner = ` ${ isTvOS ( platformName ) ? '_tvOS' : '' } ` ; return { [ runner ] : { EnvironmentVariables : { USE_PORT : wdaRemotePort } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves WDA upgrade timestamp [CODESPLIT] async function getWDAUpgradeTimestamp ( bootstrapPath ) { const carthageRootPath = path . resolve ( bootstrapPath , CARTHAGE_ROOT ) ; if ( await fs . exists ( carthageRootPath ) ) { const { mtime } = await fs . stat ( carthageRootPath ) ; return mtime . getTime ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates Apple s over - the - air configuration profile for certificate deployment based on the given PEM certificate content . Read https : // developer . apple . com / library / content / documentation / NetworkingInternet / Conceptual / iPhoneOTAConfiguration / Introduction / Introduction . html for more details on such profiles . [CODESPLIT] function toMobileConfig ( certBuffer , commonName ) { const getUUID = ( ) => UUID . create ( ) . hex . toUpperCase ( ) ; const contentUuid = getUUID ( ) ; return { PayloadContent : [ { PayloadCertificateFileName : ` ${ commonName } ` , PayloadContent : certBuffer , PayloadDescription : 'Adds a CA root certificate' , PayloadDisplayName : commonName , PayloadIdentifier : ` ${ contentUuid } ` , PayloadType : 'com.apple.security.root' , PayloadUUID : contentUuid , PayloadVersion : 1 } ] , PayloadDisplayName : commonName , PayloadIdentifier : ` ${ os . hostname ( ) . split ( '.' ) [ 0 ] } ${ getUUID ( ) } ` , PayloadRemovalDisallowed : false , PayloadType : 'Configuration' , PayloadUUID : getUUID ( ) , PayloadVersion : 1 } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Will get JSON of the form : { isEnabled : 1 isVisible : 1 frame : {{ 0 0 } { 375 667 }} children : [ { isEnabled : 1 isVisible : 1 frame : {{ 0 0 } { 375 667 }} children : [] rect : { x : 0 y : 0 width : 375 height : 667 } value : null label : null type : Other name : null rawIdentifier : null } rect : { origin : { x : 0 y : 0 } size : { width : 375 height : 667 } } value : null label : UICatalog type : Application name : UICatalog rawIdentifier : null } [CODESPLIT] function getTreeForXML ( srcTree ) { function getTree ( element , elementIndex , parentPath ) { let curPath = ` ${ parentPath } ${ elementIndex } ` ; let rect = element . rect || { } ; let subtree = { '@' : { type : ` ${ element . type } ` , enabled : parseInt ( element . isEnabled , 10 ) === 1 , visible : parseInt ( element . isVisible , 10 ) === 1 , x : rect . x , y : rect . y , width : rect . width , height : rect . height , } , '>' : [ ] } ; if ( element . name !== null ) { subtree [ '@' ] . name = element . name ; } if ( element . label !== null ) { subtree [ '@' ] . label = element . label ; } if ( element . value !== null ) { subtree [ '@' ] . value = element . value ; } for ( let i = 0 ; i < ( element . children || [ ] ) . length ; i ++ ) { subtree [ '>' ] . push ( getTree ( element . children [ i ] , i , curPath ) ) ; } return { [ ` ${ element . type } ` ] : subtree } ; } let tree = getTree ( srcTree , 0 , '' ) ; return tree ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the actual path and the bundle identifier from the given path string [CODESPLIT] async function parseContainerPath ( remotePath , containerRootSupplier ) { const match = CONTAINER_PATH_PATTERN . exec ( remotePath ) ; if ( ! match ) { log . errorAndThrow ( ` ` + ` ${ CONTAINER_PATH_MARKER } ` + ` ${ remotePath } ` ) ; } let [ , bundleId , relativePath ] = match ; let containerType = null ; const typeSeparatorPos = bundleId . indexOf ( CONTAINER_TYPE_SEPARATOR ) ; // We only consider container type exists if its length is greater than zero // not counting the colon if ( typeSeparatorPos > 0 && typeSeparatorPos < bundleId . length - 1 ) { containerType = bundleId . substring ( typeSeparatorPos + 1 ) ; log . debug ( ` ${ containerType } ` ) ; bundleId = bundleId . substring ( 0 , typeSeparatorPos ) ; } const containerRoot = _ . isFunction ( containerRootSupplier ) ? await containerRootSupplier ( bundleId , containerType ) : containerRootSupplier ; const resultPath = path . posix . resolve ( containerRoot , relativePath ) ; verifyIsSubPath ( resultPath , containerRoot ) ; return [ bundleId , resultPath ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the given base64 data chunk as a binary file on the Simulator under test . [CODESPLIT] async function pushFileToSimulator ( device , remotePath , base64Data ) { const buffer = Buffer . from ( base64Data , 'base64' ) ; if ( CONTAINER_PATH_PATTERN . test ( remotePath ) ) { const [ bundleId , dstPath ] = await parseContainerPath ( remotePath , async ( appBundle , containerType ) => await getAppContainer ( device . udid , appBundle , null , containerType ) ) ; log . info ( ` ${ bundleId } ${ remotePath } ` + ` ${ dstPath } ` ) ; if ( ! await fs . exists ( path . dirname ( dstPath ) ) ) { log . debug ( ` ${ path . dirname ( dstPath ) } ` ) ; await mkdirp ( path . dirname ( dstPath ) ) ; } await fs . writeFile ( dstPath , buffer ) ; return ; } const dstFolder = await tempDir . openDir ( ) ; const dstPath = path . resolve ( dstFolder , path . basename ( remotePath ) ) ; try { await fs . writeFile ( dstPath , buffer ) ; await addMedia ( device . udid , dstPath ) ; } finally { await fs . rimraf ( dstFolder ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the given base64 data chunk as a binary file on the device under test . ifuse / osxfuse should be installed and configured on the target machine in order for this function to work properly . Read https : // github . com / libimobiledevice / ifuse and https : // github . com / osxfuse / osxfuse / wiki / FAQ for more details . [CODESPLIT] async function pushFileToRealDevice ( device , remotePath , base64Data ) { await verifyIFusePresence ( ) ; const mntRoot = await tempDir . openDir ( ) ; let isUnmountSuccessful = true ; try { let dstPath = path . resolve ( mntRoot , remotePath ) ; let ifuseArgs = [ '-u' , device . udid , mntRoot ] ; if ( CONTAINER_PATH_PATTERN . test ( remotePath ) ) { const [ bundleId , pathInContainer ] = await parseContainerPath ( remotePath , mntRoot ) ; dstPath = pathInContainer ; log . info ( ` ${ bundleId } ${ remotePath } ` + ` ${ dstPath } ` ) ; ifuseArgs = [ '-u' , device . udid , '--container' , bundleId , mntRoot ] ; } else { verifyIsSubPath ( dstPath , mntRoot ) ; } await mountDevice ( device , ifuseArgs ) ; isUnmountSuccessful = false ; try { if ( ! await fs . exists ( path . dirname ( dstPath ) ) ) { log . debug ( ` ${ path . dirname ( dstPath ) } ` ) ; await mkdirp ( path . dirname ( dstPath ) ) ; } await fs . writeFile ( dstPath , Buffer . from ( base64Data , 'base64' ) ) ; } finally { await exec ( 'umount' , [ mntRoot ] ) ; isUnmountSuccessful = true ; } } finally { if ( isUnmountSuccessful ) { await fs . rimraf ( mntRoot ) ; } else { log . warn ( ` ${ mntRoot } ` ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the content of given file or folder from iOS Simulator and return it as base - 64 encoded string . Folder content is recursively packed into a zip archive . [CODESPLIT] async function pullFromSimulator ( device , remotePath , isFile ) { let pathOnServer ; if ( CONTAINER_PATH_PATTERN . test ( remotePath ) ) { const [ bundleId , dstPath ] = await parseContainerPath ( remotePath , async ( appBundle , containerType ) => await getAppContainer ( device . udid , appBundle , null , containerType ) ) ; log . info ( ` ${ bundleId } ${ remotePath } ` + ` ${ dstPath } ` ) ; pathOnServer = dstPath ; } else { const simRoot = device . getDir ( ) ; pathOnServer = path . posix . join ( simRoot , remotePath ) ; verifyIsSubPath ( pathOnServer , simRoot ) ; log . info ( ` ${ pathOnServer } ` ) ; } if ( ! await fs . exists ( pathOnServer ) ) { log . errorAndThrow ( ` ${ isFile ? 'file' : 'folder' } ${ pathOnServer } ` ) ; } const buffer = isFile ? await fs . readFile ( pathOnServer ) : await zip . toInMemoryZip ( pathOnServer ) ; return Buffer . from ( buffer ) . toString ( 'base64' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the content of given file or folder from the real device under test and return it as base - 64 encoded string . Folder content is recursively packed into a zip archive . [CODESPLIT] async function pullFromRealDevice ( device , remotePath , isFile ) { await verifyIFusePresence ( ) ; const mntRoot = await tempDir . openDir ( ) ; let isUnmountSuccessful = true ; try { let dstPath = path . resolve ( mntRoot , remotePath ) ; let ifuseArgs = [ '-u' , device . udid , mntRoot ] ; if ( CONTAINER_PATH_PATTERN . test ( remotePath ) ) { const [ bundleId , pathInContainer ] = await parseContainerPath ( remotePath , mntRoot ) ; dstPath = pathInContainer ; log . info ( ` ${ bundleId } ${ remotePath } ` + ` ${ dstPath } ` ) ; ifuseArgs = [ '-u' , device . udid , '--container' , bundleId , mntRoot ] ; } else { verifyIsSubPath ( dstPath , mntRoot ) ; } await mountDevice ( device , ifuseArgs ) ; isUnmountSuccessful = false ; try { if ( ! await fs . exists ( dstPath ) ) { log . errorAndThrow ( ` ${ isFile ? 'file' : 'folder' } ${ dstPath } ` ) ; } const buffer = isFile ? await fs . readFile ( dstPath ) : await zip . toInMemoryZip ( dstPath ) ; return Buffer . from ( buffer ) . toString ( 'base64' ) ; } finally { await exec ( 'umount' , [ mntRoot ] ) ; isUnmountSuccessful = true ; } } finally { if ( isUnmountSuccessful ) { await fs . rimraf ( mntRoot ) ; } else { log . warn ( ` ${ mntRoot } ` ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Capability set by a user [CODESPLIT] async function createSim ( caps , platform = PLATFORM_NAME_IOS ) { const appiumTestDeviceName = ` ${ UUID . create ( ) . toString ( ) . toUpperCase ( ) } ${ caps . deviceName } ` ; const udid = await createDevice ( appiumTestDeviceName , caps . deviceName , caps . platformVersion , { platform } ) ; return await getSimulator ( udid ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a simulator which is already running . [CODESPLIT] async function getExistingSim ( opts ) { const devices = await getDevices ( opts . platformVersion ) ; const appiumTestDeviceName = ` ${ opts . deviceName } ` ; let appiumTestDevice ; for ( const device of _ . values ( devices ) ) { if ( device . name === opts . deviceName ) { return await getSimulator ( device . udid ) ; } if ( device . name === appiumTestDeviceName ) { appiumTestDevice = device ; } } if ( appiumTestDevice ) { log . warn ( ` ${ opts . deviceName } ${ appiumTestDevice . name } ${ appiumTestDevice . udid } ` ) ; return await getSimulator ( appiumTestDevice . udid ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "***************************************************************** Lifecycle [CODESPLIT] function ( ) { const el = this . el ; this . velocityCtrl = null ; this . velocity = new THREE . Vector3 ( ) ; this . heading = new THREE . Quaternion ( ) ; // Navigation this . navGroup = null ; this . navNode = null ; if ( el . sceneEl . hasLoaded ) { this . injectControls ( ) ; } else { el . sceneEl . addEventListener ( 'loaded' , this . injectControls . bind ( this ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "***************************************************************** Movement [CODESPLIT] function ( ) { const data = this . data ; if ( data . enabled ) { for ( let i = 0 , l = data . controls . length ; i < l ; i ++ ) { const control = this . el . components [ data . controls [ i ] + COMPONENT_SUFFIX ] ; if ( control && control . isVelocityActive ( ) ) { this . velocityCtrl = control ; return ; } } this . velocityCtrl = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "physics [CODESPLIT] function parsePhysicsModel ( xml ) { var data = { name : xml . getAttribute ( 'name' ) || '' , rigidBodies : { } } ; for ( var i = 0 ; i < xml . childNodes . length ; i ++ ) { var child = xml . childNodes [ i ] ; if ( child . nodeType !== 1 ) continue ; switch ( child . nodeName ) { case 'rigid_body' : data . rigidBodies [ child . getAttribute ( 'name' ) ] = { } ; parsePhysicsRigidBody ( child , data . rigidBodies [ child . getAttribute ( 'name' ) ] ) ; break ; } } library . physicsModels [ xml . getAttribute ( 'id' ) ] = data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "nodes [CODESPLIT] function prepareNodes ( xml ) { var elements = xml . getElementsByTagName ( 'node' ) ; // ensure all node elements have id attributes for ( var i = 0 ; i < elements . length ; i ++ ) { var element = elements [ i ] ; if ( element . hasAttribute ( 'id' ) === false ) { element . setAttribute ( 'id' , generateId ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "visual scenes [CODESPLIT] function parseVisualScene ( xml ) { var data = { name : xml . getAttribute ( 'name' ) , children : [ ] } ; prepareNodes ( xml ) ; var elements = getElementsByTagName ( xml , 'node' ) ; for ( var i = 0 ; i < elements . length ; i ++ ) { data . children . push ( parseNode ( elements [ i ] ) ) ; } library . visualScenes [ xml . getAttribute ( 'id' ) ] = data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update list of entities to test for collision . [CODESPLIT] function ( ) { const data = this . data ; let objectEls ; // Push entities into list of els to intersect. if ( data . objects ) { objectEls = this . el . sceneEl . querySelectorAll ( data . objects ) ; } else { // If objects not defined, intersect with everything. objectEls = this . el . sceneEl . children ; } // Convert from NodeList to Array this . els = Array . prototype . slice . call ( objectEls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bounding sphere collision detection [CODESPLIT] function intersect ( el ) { let radius , mesh , distance , extent ; if ( ! el . isEntity ) { return ; } mesh = el . getObject3D ( 'mesh' ) ; if ( ! mesh ) { return ; } box . setFromObject ( mesh ) . getSize ( size ) ; extent = Math . max ( size . x , size . y , size . z ) / 2 ; radius = Math . sqrt ( 2 * extent * extent ) ; box . getCenter ( meshPosition ) ; if ( ! radius ) { return ; } distance = position . distanceTo ( meshPosition ) ; if ( distance < radius + colliderRadius ) { collisions . push ( el ) ; distanceMap . set ( el , distance ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "***************************************************************** Lifecycle [CODESPLIT] function ( ) { this . system = this . el . sceneEl . systems . physics ; this . system . addComponent ( this ) ; const el = this . el , data = this . data , position = ( new CANNON . Vec3 ( ) ) . copy ( el . object3D . getWorldPosition ( new THREE . Vector3 ( ) ) ) ; this . body = new CANNON . Body ( { material : this . system . getMaterial ( 'staticMaterial' ) , position : position , mass : data . mass , linearDamping : data . linearDamping , fixedRotation : true } ) ; this . body . addShape ( new CANNON . Sphere ( data . radius ) , new CANNON . Vec3 ( 0 , data . radius , 0 ) ) ; this . body . el = this . el ; this . el . body = this . body ; this . system . addBody ( this . body ) ; if ( el . hasAttribute ( 'wasd-controls' ) ) { console . warn ( '[kinematic-body] Not compatible with wasd-controls, use movement-controls.' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "***************************************************************** Update Checks CANNON . World for collisions and attempts to apply them to the element automatically in a player - friendly way . [CODESPLIT] function ( t , dt ) { if ( ! dt ) return ; const el = this . el ; const data = this . data const body = this . body ; if ( ! data . enableJumps ) body . velocity . set ( 0 , 0 , 0 ) ; body . position . copy ( el . getAttribute ( 'position' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When walking on complex surfaces ( trimeshes borders between two shapes ) the collision normals returned for the player sphere can be very inconsistent . To address this raycast straight down find the collision normal and return whichever normal is more vertical . [CODESPLIT] function ( groundBody , groundNormal ) { let ray , hitNormal , vFrom = this . body . position , vTo = this . body . position . clone ( ) ; ray = new CANNON . Ray ( vFrom , vTo ) ; ray . _updateDirection ( ) ; // TODO - Report bug. ray . intersectBody ( groundBody ) ; if ( ! ray . hasHit ) return groundNormal ; // Compare ABS, in case we're projecting against the inside of the face. hitNormal = ray . result . hitNormalWorld ; return Math . abs ( hitNormal . y ) > Math . abs ( groundNormal . y ) ? hitNormal : groundNormal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "***************************************************************** Core Called once when component is attached . Generally for initial setup . [CODESPLIT] function ( ) { const scene = this . el . sceneEl ; this . prevTime = window . performance . now ( ) ; // Button state this . buttons = { } ; // Rotation const rotation = this . el . object3D . rotation ; this . pitch = new THREE . Object3D ( ) ; this . pitch . rotation . x = THREE . Math . degToRad ( rotation . x ) ; this . yaw = new THREE . Object3D ( ) ; this . yaw . position . y = 10 ; this . yaw . rotation . y = THREE . Math . degToRad ( rotation . y ) ; this . yaw . add ( this . pitch ) ; scene . addBehavior ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "***************************************************************** Movement [CODESPLIT] function ( ) { if ( ! this . data . enabled || ! this . isConnected ( ) ) return false ; const dpad = this . getDpad ( ) , joystick0 = this . getJoystick ( 0 ) , inputX = dpad . x || joystick0 . x , inputY = dpad . y || joystick0 . y ; return Math . abs ( inputX ) > JOYSTICK_EPS || Math . abs ( inputY ) > JOYSTICK_EPS ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "***************************************************************** Rotation [CODESPLIT] function ( ) { if ( ! this . data . enabled || ! this . isConnected ( ) ) return false ; const joystick1 = this . getJoystick ( 1 ) ; return Math . abs ( joystick1 . x ) > JOYSTICK_EPS || Math . abs ( joystick1 . y ) > JOYSTICK_EPS ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the state of the given joystick ( 0 or 1 ) as a THREE . Vector2 . [CODESPLIT] function ( index ) { const gamepad = this . getGamepad ( ) ; switch ( index ) { case 0 : return new THREE . Vector2 ( gamepad . axes [ 0 ] , gamepad . axes [ 1 ] ) ; case 1 : return new THREE . Vector2 ( gamepad . axes [ 2 ] , gamepad . axes [ 3 ] ) ; default : throw new Error ( 'Unexpected joystick index \"%d\".' , index ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the state of the dpad as a THREE . Vector2 . [CODESPLIT] function ( ) { const gamepad = this . getGamepad ( ) ; if ( ! gamepad . buttons [ GamepadButton . DPAD_RIGHT ] ) { return new THREE . Vector2 ( ) ; } return new THREE . Vector2 ( ( gamepad . buttons [ GamepadButton . DPAD_RIGHT ] . pressed ? 1 : 0 ) + ( gamepad . buttons [ GamepadButton . DPAD_LEFT ] . pressed ? - 1 : 0 ) , ( gamepad . buttons [ GamepadButton . DPAD_UP ] . pressed ? - 1 : 0 ) + ( gamepad . buttons [ GamepadButton . DPAD_DOWN ] . pressed ? 1 : 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use play () instead of init () because component mappings – unavailable as dependencies – are not guaranteed to have parsed when this component is initialized . [CODESPLIT] function ( ) { const el = this . el , data = this . data ; let material = el . components . material ; const geometry = new THREE . PlaneGeometry ( data . width , data . depth , data . density , data . density ) ; geometry . mergeVertices ( ) ; this . waves = [ ] ; for ( let v , i = 0 , l = geometry . vertices . length ; i < l ; i ++ ) { v = geometry . vertices [ i ] ; this . waves . push ( { z : v . z , ang : Math . random ( ) * Math . PI * 2 , amp : data . amplitude + Math . random ( ) * data . amplitudeVariance , speed : ( data . speed + Math . random ( ) * data . speedVariance ) / 1000 // radians / frame } ) ; } if ( ! material ) { material = { } ; material . material = new THREE . MeshPhongMaterial ( { color : data . color , transparent : data . opacity < 1 , opacity : data . opacity , shading : THREE . FlatShading , } ) ; } this . mesh = new THREE . Mesh ( geometry , material . material ) ; el . setObject3D ( 'mesh' , this . mesh ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a URLSearchParams instance [CODESPLIT] function URLSearchParamsPolyfill ( search ) { search = search || \"\" ; // support construct object with another URLSearchParams instance if ( search instanceof URLSearchParams || search instanceof URLSearchParamsPolyfill ) { search = search . toString ( ) ; } this [ __URLSearchParams__ ] = parseToDict ( search ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function LDAPResult ( options ) { options = options || { } ; assert . object ( options ) ; assert . optionalNumber ( options . status ) ; assert . optionalString ( options . matchedDN ) ; assert . optionalString ( options . errorMessage ) ; assert . optionalArrayOfString ( options . referrals ) ; LDAPMessage . call ( this , options ) ; this . status = options . status || 0 ; // LDAP SUCCESS this . matchedDN = options . matchedDN || '' ; this . errorMessage = options . errorMessage || '' ; this . referrals = options . referrals || [ ] ; this . connection = options . connection || null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function BindResponse ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = Protocol . LDAP_REP_BIND ; LDAPResult . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function Change ( options ) { if ( options ) { assert . object ( options ) ; assert . optionalString ( options . operation ) ; } else { options = { } ; } this . _modification = false ; this . operation = options . operation || options . type || 'add' ; this . modification = options . modification || { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function DeleteResponse ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = Protocol . LDAP_REP_DELETE ; LDAPResult . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function Control ( options ) { assert . optionalObject ( options ) ; options = options || { } ; assert . optionalString ( options . type ) ; assert . optionalBool ( options . criticality ) ; if ( options . value ) { assert . buffer ( options . value ) ; } this . type = options . type || '' ; this . criticality = options . critical || options . criticality || false ; this . value = options . value || null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function UnbindRequest ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = Protocol . LDAP_REQ_UNBIND ; LDAPMessage . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function SearchResponse ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = Protocol . LDAP_REP_SEARCH ; LDAPResult . call ( this , options ) ; this . attributes = options . attributes ? options . attributes . slice ( ) : [ ] ; this . notAttributes = [ ] ; this . sentEntries = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function ModifyResponse ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = Protocol . LDAP_REP_MODIFY ; LDAPResult . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queue to contain LDAP requests . [CODESPLIT] function RequestQueue ( opts ) { if ( ! opts || typeof ( opts ) !== 'object' ) { opts = { } ; } this . size = ( opts . size > 0 ) ? opts . size : Infinity ; this . timeout = ( opts . timeout > 0 ) ? opts . timeout : 0 ; this . _queue = [ ] ; this . _timer = null ; this . _frozen = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Track message callback by messageID . [CODESPLIT] function MessageTracker ( opts ) { assert . object ( opts ) ; assert . string ( opts . id ) ; assert . object ( opts . parser ) ; this . id = opts . id ; this . _msgid = 0 ; this . _messages = { } ; this . _abandoned = { } ; this . parser = opts . parser ; var self = this ; this . __defineGetter__ ( 'pending' , function ( ) { return Object . keys ( self . _messages ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is ( comp > = ref ) according to sliding window [CODESPLIT] function geWindow ( ref , comp ) { var max = ref + ( MAX_MSGID / 2 ) ; var min = ref ; if ( max >= MAX_MSGID ) { // Handle roll-over max = max - MAX_MSGID - 1 ; return ( ( comp <= max ) || ( comp >= min ) ) ; } else { return ( ( comp <= max ) && ( comp >= min ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API Constructs a new client . [CODESPLIT] function Client ( options ) { assert . ok ( options ) ; EventEmitter . call ( this , options ) ; var self = this ; var _url ; if ( options . url ) _url = url . parse ( options . url ) ; this . host = _url ? _url . hostname : undefined ; this . port = _url ? _url . port : false ; this . secure = _url ? _url . secure : false ; this . url = _url ; this . tlsOptions = options . tlsOptions ; this . socketPath = options . socketPath || false ; this . log = options . log . child ( { clazz : 'Client' } , true ) ; this . timeout = parseInt ( ( options . timeout || 0 ) , 10 ) ; this . connectTimeout = parseInt ( ( options . connectTimeout || 0 ) , 10 ) ; this . idleTimeout = parseInt ( ( options . idleTimeout || 0 ) , 10 ) ; if ( options . reconnect ) { // Fall back to defaults if options.reconnect === true var rOpts = ( typeof ( options . reconnect ) === 'object' ) ? options . reconnect : { } ; this . reconnect = { initialDelay : parseInt ( rOpts . initialDelay || 100 , 10 ) , maxDelay : parseInt ( rOpts . maxDelay || 10000 , 10 ) , failAfter : parseInt ( rOpts . failAfter , 10 ) || Infinity } ; } this . strictDN = ( options . strictDN !== undefined ) ? options . strictDN : true ; this . queue = new RequestQueue ( { size : parseInt ( ( options . queueSize || 0 ) , 10 ) , timeout : parseInt ( ( options . queueTimeout || 0 ) , 10 ) } ) ; if ( options . queueDisable ) { this . queue . freeze ( ) ; } // Implicitly configure setup action to bind the client if bindDN and // bindCredentials are passed in.  This will more closely mimic PooledClient // auto-login behavior. if ( options . bindDN !== undefined && options . bindCredentials !== undefined ) { this . on ( 'setup' , function ( clt , cb ) { clt . bind ( options . bindDN , options . bindCredentials , function ( err ) { if ( err ) { self . emit ( 'error' , err ) ; } cb ( err ) ; } ) ; } ) ; } this . _socket = null ; this . connected = false ; this . connect ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Establish basic socket connection [CODESPLIT] function connectSocket ( cb ) { cb = once ( cb ) ; function onResult ( err , res ) { if ( err ) { if ( self . connectTimer ) { clearTimeout ( self . connectTimer ) ; self . connectTimer = null ; } self . emit ( 'connectError' , err ) ; } cb ( err , res ) ; } function onConnect ( ) { if ( self . connectTimer ) { clearTimeout ( self . connectTimer ) ; self . connectTimer = null ; } socket . removeAllListeners ( 'error' ) . removeAllListeners ( 'connect' ) . removeAllListeners ( 'secureConnect' ) ; tracker . id = nextClientId ( ) + '__' + tracker . id ; self . log = self . log . child ( { ldap_id : tracker . id } , true ) ; // Move on to client setup setupClient ( cb ) ; } var port = ( self . port || self . socketPath ) ; if ( self . secure ) { socket = tls . connect ( port , self . host , self . tlsOptions ) ; socket . once ( 'secureConnect' , onConnect ) ; } else { socket = net . connect ( port , self . host ) ; socket . once ( 'connect' , onConnect ) ; } socket . once ( 'error' , onResult ) ; initSocket ( ) ; // Setup connection timeout handling, if desired if ( self . connectTimeout ) { self . connectTimer = setTimeout ( function onConnectTimeout ( ) { if ( ! socket || ! socket . readable || ! socket . writeable ) { socket . destroy ( ) ; self . _socket = null ; onResult ( new ConnectionError ( 'connection timeout' ) ) ; } } , self . connectTimeout ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize socket events and LDAP parser . [CODESPLIT] function initSocket ( ) { tracker = new MessageTracker ( { id : self . url ? self . url . href : self . socketPath , parser : new Parser ( { log : log } ) } ) ; // This won't be set on TLS. So. Very. Annoying. if ( typeof ( socket . setKeepAlive ) !== 'function' ) { socket . setKeepAlive = function setKeepAlive ( enable , delay ) { return socket . socket ? socket . socket . setKeepAlive ( enable , delay ) : false ; } ; } socket . on ( 'data' , function onData ( data ) { if ( log . trace ( ) ) log . trace ( 'data event: %s' , util . inspect ( data ) ) ; tracker . parser . write ( data ) ; } ) ; // The \"router\" tracker . parser . on ( 'message' , function onMessage ( message ) { message . connection = self . _socket ; var callback = tracker . fetch ( message . messageID ) ; if ( ! callback ) { log . error ( { message : message . json } , 'unsolicited message' ) ; return false ; } return callback ( message ) ; } ) ; tracker . parser . on ( 'error' , function onParseError ( err ) { self . emit ( 'error' , new VError ( err , 'Parser error for %s' , tracker . id ) ) ; self . connected = false ; socket . end ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "After connect register socket event handlers and run any setup actions [CODESPLIT] function setupClient ( cb ) { cb = once ( cb ) ; // Indicate failure if anything goes awry during setup function bail ( err ) { socket . destroy ( ) ; cb ( err || new Error ( 'client error during setup' ) ) ; } // Work around lack of close event on tls.socket in node < 0.11 ( ( socket . socket ) ? socket . socket : socket ) . once ( 'close' , bail ) ; socket . once ( 'error' , bail ) ; socket . once ( 'end' , bail ) ; socket . once ( 'timeout' , bail ) ; self . _socket = socket ; self . _tracker = tracker ; // Run any requested setup (such as automatically performing a bind) on // socket before signalling successful connection. // This setup needs to bypass the request queue since all other activity is // blocked until the connection is considered fully established post-setup. // Only allow bind/search/starttls for now. var basicClient = { bind : function bindBypass ( name , credentials , controls , callback ) { return self . bind ( name , credentials , controls , callback , true ) ; } , search : function searchBypass ( base , options , controls , callback ) { return self . search ( base , options , controls , callback , true ) ; } , starttls : function starttlsBypass ( options , controls , callback ) { return self . starttls ( options , controls , callback , true ) ; } , unbind : self . unbind . bind ( self ) } ; vasync . forEachPipeline ( { func : function ( f , callback ) { f ( basicClient , callback ) ; } , inputs : self . listeners ( 'setup' ) } , function ( err , res ) { if ( err ) { self . emit ( 'setupError' , err ) ; } cb ( err ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wire up official event handlers after successful connect / setup [CODESPLIT] function postSetup ( ) { socket . removeAllListeners ( 'error' ) . removeAllListeners ( 'close' ) . removeAllListeners ( 'end' ) . removeAllListeners ( 'timeout' ) ; // Work around lack of close event on tls.socket in node < 0.11 ( ( socket . socket ) ? socket . socket : socket ) . once ( 'close' , self . _onClose . bind ( self ) ) ; socket . on ( 'end' , function onEnd ( ) { if ( log . trace ( ) ) log . trace ( 'end event' ) ; self . emit ( 'end' ) ; socket . end ( ) ; } ) ; socket . on ( 'error' , function onSocketError ( err ) { if ( log . trace ( ) ) log . trace ( { err : err } , 'error event: %s' , new Error ( ) . stack ) ; self . emit ( 'error' , err ) ; socket . destroy ( ) ; } ) ; socket . on ( 'timeout' , function onTimeout ( ) { if ( log . trace ( ) ) log . trace ( 'timeout event' ) ; self . emit ( 'socketTimeout' ) ; socket . end ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function SearchEntry ( options ) { options = options || { } ; assert . object ( options ) ; lassert . optionalStringDN ( options . objectName ) ; options . protocolOp = Protocol . LDAP_REP_SEARCH_ENTRY ; LDAPMessage . call ( this , options ) ; this . objectName = options . objectName || null ; this . setAttributes ( options . attributes || [ ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function Attribute ( options ) { if ( options ) { if ( typeof ( options ) !== 'object' ) throw new TypeError ( 'options must be an object' ) ; if ( options . type && typeof ( options . type ) !== 'string' ) throw new TypeError ( 'options.type must be a string' ) ; } else { options = { } ; } this . type = options . type || '' ; this . _vals = [ ] ; if ( options . vals !== undefined && options . vals !== null ) this . vals = options . vals ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function SearchRequest ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = Protocol . LDAP_REQ_SEARCH ; LDAPMessage . call ( this , options ) ; if ( options . baseObject !== undefined ) { this . baseObject = options . baseObject ; } else { this . baseObject = dn . parse ( '' ) ; } this . scope = options . scope || 'base' ; this . derefAliases = options . derefAliases || Protocol . NEVER_DEREF_ALIASES ; this . sizeLimit = options . sizeLimit || 0 ; this . timeLimit = options . timeLimit || 0 ; this . typesOnly = options . typesOnly || false ; this . filter = options . filter || null ; this . attributes = options . attributes ? options . attributes . slice ( 0 ) : [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- Helpers [CODESPLIT] function mergeFunctionArgs ( argv , start , end ) { assert . ok ( argv ) ; if ( ! start ) start = 0 ; if ( ! end ) end = argv . length ; var handlers = [ ] ; for ( var i = start ; i < end ; i ++ ) { if ( argv [ i ] instanceof Array ) { var arr = argv [ i ] ; for ( var j = 0 ; j < arr . length ; j ++ ) { if ( ! ( arr [ j ] instanceof Function ) ) { throw new TypeError ( 'Invalid argument type: ' + typeof ( arr [ j ] ) ) ; } handlers . push ( arr [ j ] ) ; } } else if ( argv [ i ] instanceof Function ) { handlers . push ( argv [ i ] ) ; } else { throw new TypeError ( 'Invalid argument type: ' + typeof ( argv [ i ] ) ) ; } } return handlers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API Constructs a new server that you can call . listen () on in the various forms node supports . You need to first assign some handlers to the various LDAP operations however . [CODESPLIT] function Server ( options ) { if ( options ) { if ( typeof ( options ) !== 'object' ) throw new TypeError ( 'options (object) required' ) ; if ( typeof ( options . log ) !== 'object' ) throw new TypeError ( 'options.log must be an object' ) ; if ( options . certificate || options . key ) { if ( ! ( options . certificate && options . key ) || ( typeof ( options . certificate ) !== 'string' && ! Buffer . isBuffer ( options . certificate ) ) || ( typeof ( options . key ) !== 'string' && ! Buffer . isBuffer ( options . key ) ) ) { throw new TypeError ( 'options.certificate and options.key ' + '(string or buffer) are both required for TLS' ) ; } } } else { options = { } ; } var self = this ; EventEmitter . call ( this , options ) ; this . _chain = [ ] ; this . log = options . log ; this . strictDN = ( options . strictDN !== undefined ) ? options . strictDN : true ; var log = this . log ; function setupConnection ( c ) { assert . ok ( c ) ; if ( c . type === 'unix' ) { c . remoteAddress = self . server . path ; c . remotePort = c . fd ; } else if ( c . socket ) { // TLS c . remoteAddress = c . socket . remoteAddress ; c . remotePort = c . socket . remotePort ; } var rdn = new dn . RDN ( { cn : 'anonymous' } ) ; c . ldap = { id : c . remoteAddress + ':' + c . remotePort , config : options , _bindDN : new DN ( [ rdn ] ) } ; c . addListener ( 'timeout' , function ( ) { log . trace ( '%s timed out' , c . ldap . id ) ; c . destroy ( ) ; } ) ; c . addListener ( 'end' , function ( ) { log . trace ( '%s shutdown' , c . ldap . id ) ; } ) ; c . addListener ( 'error' , function ( err ) { log . warn ( '%s unexpected connection error' , c . ldap . id , err ) ; self . emit ( 'clientError' , err ) ; c . destroy ( ) ; } ) ; c . addListener ( 'close' , function ( had_err ) { log . trace ( '%s close; had_err=%j' , c . ldap . id , had_err ) ; c . end ( ) ; } ) ; c . ldap . __defineGetter__ ( 'bindDN' , function ( ) { return c . ldap . _bindDN ; } ) ; c . ldap . __defineSetter__ ( 'bindDN' , function ( val ) { if ( ! ( val instanceof DN ) ) throw new TypeError ( 'DN required' ) ; c . ldap . _bindDN = val ; return val ; } ) ; return c ; } function newConnection ( c ) { setupConnection ( c ) ; log . trace ( 'new connection from %s' , c . ldap . id ) ; dtrace . fire ( 'server-connection' , function ( ) { return [ c . remoteAddress ] ; } ) ; c . parser = new Parser ( { log : options . log } ) ; c . parser . on ( 'message' , function ( req ) { req . connection = c ; req . logId = c . ldap . id + '::' + req . messageID ; req . startTime = new Date ( ) . getTime ( ) ; if ( log . debug ( ) ) log . debug ( '%s: message received: req=%j' , c . ldap . id , req . json ) ; var res = getResponse ( req ) ; if ( ! res ) { log . warn ( 'Unimplemented server method: %s' , req . type ) ; c . destroy ( ) ; return false ; } // parse string DNs for routing/etc try { switch ( req . protocolOp ) { case Protocol . LDAP_REQ_BIND : req . name = dn . parse ( req . name ) ; break ; case Protocol . LDAP_REQ_ADD : case Protocol . LDAP_REQ_COMPARE : case Protocol . LDAP_REQ_DELETE : req . entry = dn . parse ( req . entry ) ; break ; case Protocol . LDAP_REQ_MODIFY : req . object = dn . parse ( req . object ) ; break ; case Protocol . LDAP_REQ_MODRDN : req . entry = dn . parse ( req . entry ) ; // TODO: handle newRdn/Superior break ; case Protocol . LDAP_REQ_SEARCH : req . baseObject = dn . parse ( req . baseObject ) ; break ; default : break ; } } catch ( e ) { if ( self . strictDN ) { return res . end ( errors . LDAP_INVALID_DN_SYNTAX ) ; } } res . connection = c ; res . logId = req . logId ; res . requestDN = req . dn ; var chain = self . _getHandlerChain ( req , res ) ; var i = 0 ; return function ( err ) { function sendError ( err ) { res . status = err . code || errors . LDAP_OPERATIONS_ERROR ; res . matchedDN = req . suffix ? req . suffix . toString ( ) : '' ; res . errorMessage = err . message || '' ; return res . end ( ) ; } function after ( ) { if ( ! self . _postChain || ! self . _postChain . length ) return ; function next ( ) { } // stub out next for the post chain self . _postChain . forEach ( function ( c ) { c . call ( self , req , res , next ) ; } ) ; } if ( err ) { log . trace ( '%s sending error: %s' , req . logId , err . stack || err ) ; self . emit ( 'clientError' , err ) ; sendError ( err ) ; return after ( ) ; } try { var next = arguments . callee ; if ( chain . handlers [ i ] ) return chain . handlers [ i ++ ] . call ( chain . backend , req , res , next ) ; if ( req . protocolOp === Protocol . LDAP_REQ_BIND && res . status === 0 ) c . ldap . bindDN = req . dn ; return after ( ) ; } catch ( e ) { if ( ! e . stack ) e . stack = e . toString ( ) ; log . error ( '%s uncaught exception: %s' , req . logId , e . stack ) ; return sendError ( new errors . OperationsError ( e . message ) ) ; } } ( ) ; } ) ; c . parser . on ( 'error' , function ( err , message ) { self . emit ( 'error' , new VError ( err , 'Parser error for %s' , c . ldap . id ) ) ; if ( ! message ) return c . destroy ( ) ; var res = getResponse ( message ) ; if ( ! res ) return c . destroy ( ) ; res . status = 0x02 ; // protocol error res . errorMessage = err . toString ( ) ; return c . end ( res . toBer ( ) ) ; } ) ; c . on ( 'data' , function ( data ) { if ( log . trace ( ) ) log . trace ( 'data on %s: %s' , c . ldap . id , util . inspect ( data ) ) ; c . parser . write ( data ) ; } ) ; } // end newConnection this . routes = { } ; if ( ( options . cert || options . certificate ) && options . key ) { options . cert = options . cert || options . certificate ; this . server = tls . createServer ( options , newConnection ) ; } else { this . server = net . createServer ( newConnection ) ; } this . server . log = options . log ; this . server . ldap = { config : options } ; this . server . on ( 'close' , function ( ) { self . emit ( 'close' ) ; } ) ; this . server . on ( 'error' , function ( err ) { self . emit ( 'error' , err ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- Helpers Copied from mcavage / node - assert - plus [CODESPLIT] function _assert ( arg , type , name ) { name = name || type ; throw new assert . AssertionError ( { message : util . format ( '%s (%s) required' , name , type ) , actual : typeof ( arg ) , expected : type , operator : '===' , stackStartFunction : _assert . caller } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function AddResponse ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = Protocol . LDAP_REP_ADD ; LDAPResult . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function Parser ( options ) { assert . object ( options ) ; assert . object ( options . log ) ; EventEmitter . call ( this ) ; this . buffer = null ; this . log = options . log ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function ModifyRequest ( options ) { options = options || { } ; assert . object ( options ) ; lassert . optionalStringDN ( options . object ) ; lassert . optionalArrayOfAttribute ( options . attributes ) ; options . protocolOp = Protocol . LDAP_REQ_MODIFY ; LDAPMessage . call ( this , options ) ; this . object = options . object || null ; this . changes = options . changes ? options . changes . slice ( 0 ) : [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function ServerSideSortingRequestControl ( options ) { assert . optionalObject ( options ) ; options = options || { } ; options . type = ServerSideSortingRequestControl . OID ; if ( options . value ) { if ( Buffer . isBuffer ( options . value ) ) { this . parse ( options . value ) ; } else if ( Array . isArray ( options . value ) ) { assert . arrayOfObject ( options . value , 'options.value must be Objects' ) ; for ( var i = 0 ; i < options . value . length ; i ++ ) { if ( ! options . value [ i ] . hasOwnProperty ( 'attributeType' ) ) { throw new Error ( 'Missing required key: attributeType' ) ; } } this . _value = options . value ; } else if ( typeof ( options . value ) === 'object' ) { if ( ! options . value . hasOwnProperty ( 'attributeType' ) ) { throw new Error ( 'Missing required key: attributeType' ) ; } this . _value = [ options . value ] ; } else { throw new TypeError ( 'options.value must be a Buffer, Array or Object' ) ; } options . value = null ; } Control . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- Error Base class [CODESPLIT] function LDAPError ( message , dn , caller ) { if ( Error . captureStackTrace ) Error . captureStackTrace ( this , caller || LDAPError ) ; this . lde_message = message ; this . lde_dn = dn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API Ok so there s really no such thing as an unbind response but to make the framework not suck I just made this up and have it stubbed so it s not such a one - off . [CODESPLIT] function UnbindResponse ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = 0 ; LDAPMessage . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function ExtendedRequest ( options ) { options = options || { } ; assert . object ( options ) ; assert . optionalString ( options . requestName ) ; if ( options . requestValue && ! ( Buffer . isBuffer ( options . requestValue ) || typeof ( options . requestValue ) === 'string' ) ) { throw new TypeError ( 'options.requestValue must be a buffer or a string' ) ; } options . protocolOp = Protocol . LDAP_REQ_EXTENSION ; LDAPMessage . call ( this , options ) ; this . requestName = options . requestName || '' ; this . requestValue = options . requestValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- Internal Parsers / * A filter looks like this coming in : Filter :: = CHOICE { and [ 0 ] SET OF Filter or [ 1 ] SET OF Filter not [ 2 ] Filter equalityMatch [ 3 ] AttributeValueAssertion substrings [ 4 ] SubstringFilter greaterOrEqual [ 5 ] AttributeValueAssertion lessOrEqual [ 6 ] AttributeValueAssertion present [ 7 ] AttributeType approxMatch [ 8 ] AttributeValueAssertion extensibleMatch [ 9 ] MatchingRuleAssertion -- v3 only } [CODESPLIT] function _parse ( ber ) { assert . ok ( ber ) ; function parseSet ( f ) { var end = ber . offset + ber . length ; while ( ber . offset < end ) f . addFilter ( _parse ( ber ) ) ; } var f ; var type = ber . readSequence ( ) ; switch ( type ) { case Protocol . FILTER_AND : f = new AndFilter ( ) ; parseSet ( f ) ; break ; case Protocol . FILTER_APPROX : f = new ApproximateFilter ( ) ; f . parse ( ber ) ; break ; case Protocol . FILTER_EQUALITY : f = new EqualityFilter ( ) ; f . parse ( ber ) ; return f ; case Protocol . FILTER_EXT : f = new ExtensibleFilter ( ) ; f . parse ( ber ) ; return f ; case Protocol . FILTER_GE : f = new GreaterThanEqualsFilter ( ) ; f . parse ( ber ) ; return f ; case Protocol . FILTER_LE : f = new LessThanEqualsFilter ( ) ; f . parse ( ber ) ; return f ; case Protocol . FILTER_NOT : var _f = _parse ( ber ) ; f = new NotFilter ( { filter : _f } ) ; break ; case Protocol . FILTER_OR : f = new OrFilter ( ) ; parseSet ( f ) ; break ; case Protocol . FILTER_PRESENT : f = new PresenceFilter ( ) ; f . parse ( ber ) ; break ; case Protocol . FILTER_SUBSTRINGS : f = new SubstringFilter ( ) ; f . parse ( ber ) ; break ; default : throw new Error ( 'Invalid search filter type: 0x' + type . toString ( 16 ) ) ; } assert . ok ( f ) ; return f ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function SearchReference ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = Protocol . LDAP_REP_SEARCH_REF ; LDAPMessage . call ( this , options ) ; this . uris = options . uris || [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function ExtendedResponse ( options ) { options = options || { } ; assert . object ( options ) ; assert . optionalString ( options . responseName ) ; assert . optionalString ( options . responsevalue ) ; this . responseName = options . responseName || undefined ; this . responseValue = options . responseValue || undefined ; options . protocolOp = Protocol . LDAP_REP_EXTENSION ; LDAPResult . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function CompareResponse ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = Protocol . LDAP_REP_COMPARE ; LDAPResult . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function ModifyDNRequest ( options ) { options = options || { } ; assert . object ( options ) ; assert . optionalBool ( options . deleteOldRdn ) ; lassert . optionalStringDN ( options . entry ) ; lassert . optionalDN ( options . newRdn ) ; lassert . optionalDN ( options . newSuperior ) ; options . protocolOp = Protocol . LDAP_REQ_MODRDN ; LDAPMessage . call ( this , options ) ; this . entry = options . entry || null ; this . newRdn = options . newRdn || null ; this . deleteOldRdn = options . deleteOldRdn || true ; this . newSuperior = options . newSuperior || null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function AbandonRequest ( options ) { options = options || { } ; assert . object ( options ) ; assert . optionalNumber ( options . abandonID ) ; options . protocolOp = Protocol . LDAP_REQ_ABANDON ; LDAPMessage . call ( this , options ) ; this . abandonID = options . abandonID || 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- Shared handlers [CODESPLIT] function authorize ( req , res , next ) { /* Any user may search after bind, only cn=root has full power */ var isSearch = ( req instanceof ldap . SearchRequest ) ; if ( ! req . connection . ldap . bindDN . equals ( 'cn=root' ) && ! isSearch ) return next ( new ldap . InsufficientAccessRightsError ( ) ) ; return next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- Helpers [CODESPLIT] function invalidDN ( name ) { var e = new Error ( ) ; e . name = 'InvalidDistinguishedNameError' ; e . message = name ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function RDN ( obj ) { var self = this ; this . attrs = { } ; if ( obj ) { Object . keys ( obj ) . forEach ( function ( k ) { self . set ( k , obj [ k ] ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Thank you OpenJDK! [CODESPLIT] function parse ( name ) { if ( typeof ( name ) !== 'string' ) throw new TypeError ( 'name (string) required' ) ; var cur = 0 ; var len = name . length ; function parseRdn ( ) { var rdn = new RDN ( ) ; var order = 0 ; rdn . spLead = trim ( ) ; while ( cur < len ) { var opts = { order : order } ; var attr = parseAttrType ( ) ; trim ( ) ; if ( cur >= len || name [ cur ++ ] !== '=' ) throw invalidDN ( name ) ; trim ( ) ; // Parameters about RDN value are set in 'opts' by parseAttrValue var value = parseAttrValue ( opts ) ; rdn . set ( attr , value , opts ) ; rdn . spTrail = trim ( ) ; if ( cur >= len || name [ cur ] !== '+' ) break ; ++ cur ; ++ order ; } return rdn ; } function trim ( ) { var count = 0 ; while ( ( cur < len ) && isWhitespace ( name [ cur ] ) ) { ++ cur ; count ++ ; } return count ; } function parseAttrType ( ) { var beg = cur ; while ( cur < len ) { var c = name [ cur ] ; if ( isAlphaNumeric ( c ) || c == '.' || c == '-' || c == ' ' ) { ++ cur ; } else { break ; } } // Back out any trailing spaces. while ( ( cur > beg ) && ( name [ cur - 1 ] == ' ' ) ) -- cur ; if ( beg == cur ) throw invalidDN ( name ) ; return name . slice ( beg , cur ) ; } function parseAttrValue ( opts ) { if ( cur < len && name [ cur ] == '#' ) { opts . binary = true ; return parseBinaryAttrValue ( ) ; } else if ( cur < len && name [ cur ] == '\"' ) { opts . quoted = true ; return parseQuotedAttrValue ( ) ; } else { return parseStringAttrValue ( ) ; } } function parseBinaryAttrValue ( ) { var beg = cur ++ ; while ( cur < len && isAlphaNumeric ( name [ cur ] ) ) ++ cur ; return name . slice ( beg , cur ) ; } function parseQuotedAttrValue ( ) { var str = '' ; ++ cur ; // Consume the first quote while ( ( cur < len ) && name [ cur ] != '\"' ) { if ( name [ cur ] === '\\\\' ) cur ++ ; str += name [ cur ++ ] ; } if ( cur ++ >= len ) // no closing quote throw invalidDN ( name ) ; return str ; } function parseStringAttrValue ( ) { var beg = cur ; var str = '' ; var esc = - 1 ; while ( ( cur < len ) && ! atTerminator ( ) ) { if ( name [ cur ] === '\\\\' ) { // Consume the backslash and mark its place just in case it's escaping // whitespace which needs to be preserved. esc = cur ++ ; } if ( cur === len ) // backslash followed by nothing throw invalidDN ( name ) ; str += name [ cur ++ ] ; } // Trim off (unescaped) trailing whitespace and rewind cursor to the end of // the AttrValue to record whitespace length. for ( ; cur > beg ; cur -- ) { if ( ! isWhitespace ( name [ cur - 1 ] ) || ( esc === ( cur - 1 ) ) ) break ; } return str . slice ( 0 , cur - beg ) ; } function atTerminator ( ) { return ( cur < len && ( name [ cur ] === ',' || name [ cur ] === ';' || name [ cur ] === '+' ) ) ; } var rdns = [ ] ; // Short-circuit for empty DNs if ( len === 0 ) return new DN ( rdns ) ; rdns . push ( parseRdn ( ) ) ; while ( cur < len ) { if ( name [ cur ] === ',' || name [ cur ] === ';' ) { ++ cur ; rdns . push ( parseRdn ( ) ) ; } else { throw invalidDN ( name ) ; } } return new DN ( rdns ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API Handler object for paged search operations . [CODESPLIT] function SearchPager ( opts ) { assert . object ( opts ) ; assert . func ( opts . callback ) ; assert . number ( opts . pageSize ) ; EventEmitter . call ( this , { } ) ; this . callback = opts . callback ; this . controls = opts . controls ; this . pageSize = opts . pageSize ; this . pagePause = opts . pagePause ; this . controls . forEach ( function ( control ) { if ( control . type === PagedControl . OID ) { // The point of using SearchPager is not having to do this. // Toss an error if the pagedResultsControl is present throw new Error ( 'redundant pagedResultControl' ) ; } } ) ; this . finished = false ; this . started = false ; var emitter = new EventEmitter ( ) ; emitter . on ( 'searchEntry' , this . emit . bind ( this , 'searchEntry' ) ) ; emitter . on ( 'end' , this . _onEnd . bind ( this ) ) ; emitter . on ( 'error' , this . _onError . bind ( this ) ) ; this . childEmitter = emitter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function ModifyDNResponse ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = Protocol . LDAP_REP_MODRDN ; LDAPResult . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function DeleteRequest ( options ) { options = options || { } ; assert . object ( options ) ; lassert . optionalStringDN ( options . entry ) ; options . protocolOp = Protocol . LDAP_REQ_DELETE ; LDAPMessage . call ( this , options ) ; this . entry = options . entry || null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function AddRequest ( options ) { options = options || { } ; assert . object ( options ) ; lassert . optionalStringDN ( options . entry ) ; lassert . optionalArrayOfAttribute ( options . attributes ) ; options . protocolOp = Protocol . LDAP_REQ_ADD ; LDAPMessage . call ( this , options ) ; this . entry = options . entry || null ; this . attributes = options . attributes ? options . attributes . slice ( 0 ) : [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- Functions [CODESPLIT] function xor ( ) { var b = false ; for ( var i = 0 ; i < arguments . length ; i ++ ) { if ( arguments [ i ] && ! b ) { b = true ; } else if ( arguments [ i ] && b ) { return false ; } } return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function CompareRequest ( options ) { options = options || { } ; assert . object ( options ) ; assert . optionalString ( options . attribute ) ; assert . optionalString ( options . value ) ; lassert . optionalStringDN ( options . entry ) ; options . protocolOp = Protocol . LDAP_REQ_COMPARE ; LDAPMessage . call ( this , options ) ; this . entry = options . entry || null ; this . attribute = options . attribute || '' ; this . value = options . value || '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function BindRequest ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = Protocol . LDAP_REQ_BIND ; LDAPMessage . call ( this , options ) ; this . version = options . version || 0x03 ; this . name = options . name || null ; this . authentication = options . authentication || LDAP_BIND_SIMPLE ; this . credentials = options . credentials || '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function AbandonResponse ( options ) { options = options || { } ; assert . object ( options ) ; options . protocolOp = 0 ; LDAPMessage . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function PagedResultsControl ( options ) { assert . optionalObject ( options ) ; options = options || { } ; options . type = PagedResultsControl . OID ; if ( options . value ) { if ( Buffer . isBuffer ( options . value ) ) { this . parse ( options . value ) ; } else if ( typeof ( options . value ) === 'object' ) { this . _value = options . value ; } else { throw new TypeError ( 'options.value must be a Buffer or Object' ) ; } options . value = null ; } Control . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function isFilter ( filter ) { if ( ! filter || typeof ( filter ) !== 'object' ) { return false ; } // Do our best to duck-type it if ( typeof ( filter . toBer ) === 'function' && typeof ( filter . matches ) === 'function' && TYPES [ filter . type ] !== undefined ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API LDAPMessage structure . [CODESPLIT] function LDAPMessage ( options ) { assert . object ( options ) ; this . messageID = options . messageID || 0 ; this . protocolOp = options . protocolOp || undefined ; this . controls = options . controls ? options . controls . slice ( 0 ) : [ ] ; this . log = options . log ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform an A * Search on a graph given a start and end node . [CODESPLIT] function ( graph , start , end , options ) { graph . cleanDirty ( ) ; options = options || { } ; var heuristic = options . heuristic || astar . heuristics . manhattan ; var closest = options . closest || false ; var openHeap = getHeap ( ) ; var closestNode = start ; // set the start node to be the closest if required start . h = heuristic ( start , end ) ; graph . markDirty ( start ) ; openHeap . push ( start ) ; while ( openHeap . size ( ) > 0 ) { // Grab the lowest f(x) to process next.  Heap keeps this sorted for us. var currentNode = openHeap . pop ( ) ; // End case -- result has been found, return the traced path. if ( currentNode === end ) { return pathTo ( currentNode ) ; } // Normal case -- move currentNode from open to closed, process each of its neighbors. currentNode . closed = true ; // Find all neighbors for the current node. var neighbors = graph . neighbors ( currentNode ) ; for ( var i = 0 , il = neighbors . length ; i < il ; ++ i ) { var neighbor = neighbors [ i ] ; if ( neighbor . closed || neighbor . isWall ( ) ) { // Not a valid node to process, skip to next neighbor. continue ; } // The g score is the shortest distance from start to current node. // We need to check if the path we have arrived at this neighbor is the shortest one we have seen yet. var gScore = currentNode . g + neighbor . getCost ( currentNode ) ; var beenVisited = neighbor . visited ; if ( ! beenVisited || gScore < neighbor . g ) { // Found an optimal (so far) path to this node.  Take score for node to see how good it is. neighbor . visited = true ; neighbor . parent = currentNode ; neighbor . h = neighbor . h || heuristic ( neighbor , end ) ; neighbor . g = gScore ; neighbor . f = neighbor . g + neighbor . h ; graph . markDirty ( neighbor ) ; if ( closest ) { // If the neighbour is closer than the current closestNode or if it's equally close but has // a cheaper path than the current closest node then it becomes the closest node if ( neighbor . h < closestNode . h || ( neighbor . h === closestNode . h && neighbor . g < closestNode . g ) ) { closestNode = neighbor ; } } if ( ! beenVisited ) { // Pushing to heap will put it in proper place based on the 'f' value. openHeap . push ( neighbor ) ; } else { // Already seen the node, but since it has been rescored we need to reorder it in the heap openHeap . rescoreElement ( neighbor ) ; } } } } if ( closest ) { return pathTo ( closestNode ) ; } // No result was found - empty array signifies failure to find path. return [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A graph memory structure [CODESPLIT] function Graph ( gridIn , options ) { options = options || { } ; this . nodes = [ ] ; this . diagonal = ! ! options . diagonal ; this . grid = [ ] ; for ( var x = 0 ; x < gridIn . length ; x ++ ) { this . grid [ x ] = [ ] ; for ( var y = 0 , row = gridIn [ x ] ; y < row . length ; y ++ ) { var node = new GridNode ( x , y , row [ y ] ) ; this . grid [ x ] [ y ] = node ; this . nodes . push ( node ) ; } } this . init ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "will add start class if final [CODESPLIT] function ( path , i ) { if ( i >= path . length ) { // finished removing path, set start positions return setStartClass ( path , i ) ; } elementFromNode ( path [ i ] ) . removeClass ( css . active ) ; setTimeout ( function ( ) { removeClass ( path , i + 1 ) ; } , timeout * path [ i ] . getCost ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! Register virtuals for this model [CODESPLIT] function ( model , schema ) { debug ( 'applying virtuals' ) ; for ( const i in schema . virtuals ) { schema . virtuals [ i ] . applyVirtuals ( model ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! Register methods for this model [CODESPLIT] function ( model , schema ) { debug ( 'applying methods' ) ; for ( const i in schema . methods ) { model . prototype [ i ] = schema . methods [ i ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! Register statics for this model [CODESPLIT] function ( model , schema ) { debug ( 'applying statics' ) ; for ( const i in schema . statics ) { model [ i ] = schema . statics [ i ] . bind ( model ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "determine the set of operations to be executed [CODESPLIT] function Operations ( ) { this . ifNotExistsSet = { } ; this . SET = { } ; this . ADD = { } ; this . REMOVE = { } ; this . LISTAPPEND = { } ; this . addIfNotExistsSet = function ( name , item ) { this . ifNotExistsSet [ name ] = item ; } ; this . addSet = function ( name , item ) { if ( schema . hashKey . name !== name && ( schema . rangeKey || { } ) . name !== name ) { this . SET [ name ] = item ; } } ; this . addListAppend = function ( name , item ) { if ( schema . hashKey . name !== name && ( schema . rangeKey || { } ) . name !== name ) { this . LISTAPPEND [ name ] = item ; } } ; this . addAdd = function ( name , item ) { if ( schema . hashKey . name !== name && ( schema . rangeKey || { } ) . name !== name ) { this . ADD [ name ] = item ; } } ; this . addRemove = function ( name , item ) { if ( schema . hashKey . name !== name && ( schema . rangeKey || { } ) . name !== name ) { this . REMOVE [ name ] = item ; } } ; this . getUpdateExpression = function ( getUpdateReq ) { let attrCount = 0 ; let updateExpression = '' ; let attrName ; let valName ; let name ; let item ; const setExpressions = [ ] ; for ( name in this . ifNotExistsSet ) { item = this . ifNotExistsSet [ name ] ; attrName = ` ${ attrCount } ` ; valName = ` ${ attrCount } ` ; getUpdateReq . ExpressionAttributeNames [ attrName ] = name ; getUpdateReq . ExpressionAttributeValues [ valName ] = item ; setExpressions . push ( ` ${ attrName } ${ attrName } ${ valName } ` ) ; attrCount += 1 ; } for ( name in this . SET ) { item = this . SET [ name ] ; attrName = ` ${ attrCount } ` ; valName = ` ${ attrCount } ` ; getUpdateReq . ExpressionAttributeNames [ attrName ] = name ; getUpdateReq . ExpressionAttributeValues [ valName ] = item ; setExpressions . push ( ` ${ attrName } ${ valName } ` ) ; attrCount += 1 ; } for ( name in this . LISTAPPEND ) { item = this . LISTAPPEND [ name ] ; attrName = ` ${ attrCount } ` ; valName = ` ${ attrCount } ` ; getUpdateReq . ExpressionAttributeNames [ attrName ] = name ; getUpdateReq . ExpressionAttributeValues [ valName ] = item ; setExpressions . push ( ` ${ attrName } ${ attrName } ${ valName } ` ) ; attrCount += 1 ; } if ( setExpressions . length > 0 ) { updateExpression += ` ${ setExpressions . join ( ',' ) } ` ; } const addExpressions = [ ] ; for ( name in this . ADD ) { item = this . ADD [ name ] ; attrName = ` ${ attrCount } ` ; valName = ` ${ attrCount } ` ; getUpdateReq . ExpressionAttributeNames [ attrName ] = name ; getUpdateReq . ExpressionAttributeValues [ valName ] = item ; addExpressions . push ( ` ${ attrName } ${ valName } ` ) ; attrCount += 1 ; } if ( addExpressions . length > 0 ) { updateExpression += ` ${ addExpressions . join ( ',' ) } ` ; } const removeExpressions = [ ] ; for ( name in this . REMOVE ) { item = this . REMOVE [ name ] ; attrName = ` ${ attrCount } ` ; getUpdateReq . ExpressionAttributeNames [ attrName ] = name ; removeExpressions . push ( attrName ) ; attrCount += 1 ; } if ( removeExpressions . length > 0 ) { updateExpression += ` ${ removeExpressions . join ( ',' ) } ` ; } getUpdateReq . UpdateExpression = updateExpression ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Converts DynamoDB document types ( Map and List ) to dynamoose attribute definition map and ist types [CODESPLIT] function createAttrDefFromDynamo ( dynamoAttribute ) { let dynamoType ; const attrDef = { 'type' : module . exports . lookupType ( dynamoAttribute ) } ; if ( attrDef . type === Object ) { attrDef . type = 'map' ; for ( dynamoType in dynamoAttribute ) { attrDef . map = { } ; for ( const subAttrName in dynamoAttribute [ dynamoType ] ) { attrDef . map [ subAttrName ] = createAttrDefFromDynamo ( dynamoAttribute [ dynamoType ] [ subAttrName ] ) ; } } } else if ( attrDef . type === Array ) { attrDef . type = 'list' ; for ( dynamoType in dynamoAttribute ) { attrDef . list = dynamoAttribute [ dynamoType ] . map ( createAttrDefFromDynamo ) ; } } return attrDef ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private method [CODESPLIT] function parseAnchorOption ( anchor ) { let horizontal = anchor . match ( / left|center|right / gi ) || [ ] ; horizontal = horizontal . length === 0 ? 'left' : horizontal [ 0 ] ; let vertical = anchor . match ( / baseline|top|bottom|middle / gi ) || [ ] ; vertical = vertical . length === 0 ? 'baseline' : vertical [ 0 ] ; return { horizontal , vertical } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates through array by index and performs the callback on each element of array until the callback returns a truthy value then returns that value . If no such value is found the callback is applied to each element of array and undefined is returned . [CODESPLIT] function forEach ( array , callback ) { if ( array ) { for ( var i = 0 , len = array . length ; i < len ; i ++ ) { var result = callback ( array [ i ] , i ) ; if ( result ) { return result ; } } } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a binary search finding the index at which value occurs in array . If no such index is found returns the 2 s - complement of first index at which number [ index ] exceeds number . [CODESPLIT] function binarySearch ( array , value ) { var low = 0 ; var high = array . length - 1 ; while ( low <= high ) { var middle = low + ( ( high - low ) >> 1 ) ; var midValue = array [ middle ] ; if ( midValue === value ) { return middle ; } else if ( midValue > value ) { high = middle - 1 ; } else { low = middle + 1 ; } } return ~ low ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a map from the elements of an array . [CODESPLIT] function arrayToMap ( array , makeKey ) { var result = { } ; forEach ( array , function ( value ) { result [ makeKey ( value ) ] = value ; } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns length of path root ( i . e . length of / x : / // server / share / file : /// user / files ) [CODESPLIT] function getRootLength ( path ) { if ( path . charCodeAt ( 0 ) === 47 /* slash */ ) { if ( path . charCodeAt ( 1 ) !== 47 /* slash */ ) return 1 ; var p1 = path . indexOf ( \"/\" , 2 ) ; if ( p1 < 0 ) return 2 ; var p2 = path . indexOf ( \"/\" , p1 + 1 ) ; if ( p2 < 0 ) return p1 + 1 ; return p2 + 1 ; } if ( path . charCodeAt ( 1 ) === 58 /* colon */ ) { if ( path . charCodeAt ( 2 ) === 47 /* slash */ ) return 3 ; return 2 ; } // Per RFC 1738 'file' URI schema has the shape file://<host>/<path> // if <host> is omitted then it is assumed that host value is 'localhost', // however slash after the omitted <host> is not removed. // file:///folder1/file1 - this is a correct URI // file://folder2/file2 - this is an incorrect URI if ( path . lastIndexOf ( \"file:///\" , 0 ) === 0 ) { return \"file:///\" . length ; } var idx = path . indexOf ( \"://\" ) ; if ( idx !== - 1 ) { return idx + \"://\" . length ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "average async stat takes about 30 microseconds set chunk size to do 30 files in < 1 millisecond [CODESPLIT] function createWatchedFileSet ( interval , chunkSize ) { if ( interval === void 0 ) { interval = 2500 ; } if ( chunkSize === void 0 ) { chunkSize = 30 ; } var watchedFiles = [ ] ; var nextFileToCheck = 0 ; var watchTimer ; function getModifiedTime ( fileName ) { return _fs . statSync ( fileName ) . mtime ; } function poll ( checkedIndex ) { var watchedFile = watchedFiles [ checkedIndex ] ; if ( ! watchedFile ) { return ; } _fs . stat ( watchedFile . fileName , function ( err , stats ) { if ( err ) { watchedFile . callback ( watchedFile . fileName ) ; } else if ( watchedFile . mtime . getTime ( ) !== stats . mtime . getTime ( ) ) { watchedFile . mtime = getModifiedTime ( watchedFile . fileName ) ; watchedFile . callback ( watchedFile . fileName , watchedFile . mtime . getTime ( ) === 0 ) ; } } ) ; } // this implementation uses polling and // stat due to inconsistencies of fs.watch // and efficiency of stat on modern filesystems function startWatchTimer ( ) { watchTimer = setInterval ( function ( ) { var count = 0 ; var nextToCheck = nextFileToCheck ; var firstCheck = - 1 ; while ( ( count < chunkSize ) && ( nextToCheck !== firstCheck ) ) { poll ( nextToCheck ) ; if ( firstCheck < 0 ) { firstCheck = nextToCheck ; } nextToCheck ++ ; if ( nextToCheck === watchedFiles . length ) { nextToCheck = 0 ; } count ++ ; } nextFileToCheck = nextToCheck ; } , interval ) ; } function addFile ( fileName , callback ) { var file = { fileName : fileName , callback : callback , mtime : getModifiedTime ( fileName ) } ; watchedFiles . push ( file ) ; if ( watchedFiles . length === 1 ) { startWatchTimer ( ) ; } return file ; } function removeFile ( file ) { watchedFiles = ts . copyListRemovingItem ( file , watchedFiles ) ; } return { getModifiedTime : getModifiedTime , poll : poll , startWatchTimer : startWatchTimer , addFile : addFile , removeFile : removeFile } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this implementation uses polling and stat due to inconsistencies of fs . watch and efficiency of stat on modern filesystems [CODESPLIT] function startWatchTimer ( ) { watchTimer = setInterval ( function ( ) { var count = 0 ; var nextToCheck = nextFileToCheck ; var firstCheck = - 1 ; while ( ( count < chunkSize ) && ( nextToCheck !== firstCheck ) ) { poll ( nextToCheck ) ; if ( firstCheck < 0 ) { firstCheck = nextToCheck ; } nextToCheck ++ ; if ( nextToCheck === watchedFiles . length ) { nextToCheck = 0 ; } count ++ ; } nextFileToCheck = nextToCheck ; } , interval ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function isUnicodeIdentifierStart ( code , languageVersion ) { return languageVersion >= 1 /* ES5 */ ? lookupInUnicodeMap ( code , unicodeES5IdentifierStart ) : lookupInUnicodeMap ( code , unicodeES3IdentifierStart ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function computeLineStarts ( text ) { var result = new Array ( ) ; var pos = 0 ; var lineStart = 0 ; while ( pos < text . length ) { var ch = text . charCodeAt ( pos ++ ) ; switch ( ch ) { case 13 /* carriageReturn */ : if ( text . charCodeAt ( pos ) === 10 /* lineFeed */ ) { pos ++ ; } case 10 /* lineFeed */ : result . push ( lineStart ) ; lineStart = pos ; break ; default : if ( ch > 127 /* maxAsciiCharacter */ && isLineBreak ( ch ) ) { result . push ( lineStart ) ; lineStart = pos ; } break ; } } result . push ( lineStart ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function computePositionOfLineAndCharacter ( lineStarts , line , character ) { ts . Debug . assert ( line >= 0 && line < lineStarts . length ) ; return lineStarts [ line ] + character ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function computeLineAndCharacterOfPosition ( lineStarts , position ) { var lineNumber = ts . binarySearch ( lineStarts , position ) ; if ( lineNumber < 0 ) { // If the actual position was not found, // the binary search returns the 2's-complement of the next line start // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20 // then the search will return -2. // // We want the index of the previous line start, so we subtract 1. // Review 2's-complement if this is confusing. lineNumber = ~ lineNumber - 1 ; ts . Debug . assert ( lineNumber !== - 1 , \"position cannot precede the beginning of the file\" ) ; } return { line : lineNumber , character : position - lineStarts [ lineNumber ] } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a scanner over a ( possibly unspecified ) range of a piece of text . [CODESPLIT] function createScanner ( languageVersion , skipTrivia , languageVariant , text , onError , start , length ) { if ( languageVariant === void 0 ) { languageVariant = 0 /* Standard */ ; } // Current position (end position of text of current token) var pos ; // end of text var end ; // Start position of whitespace before current token var startPos ; // Start position of text of current token var tokenPos ; var token ; var tokenValue ; var precedingLineBreak ; var hasExtendedUnicodeEscape ; var tokenIsUnterminated ; setText ( text , start , length ) ; return { getStartPos : function ( ) { return startPos ; } , getTextPos : function ( ) { return pos ; } , getToken : function ( ) { return token ; } , getTokenPos : function ( ) { return tokenPos ; } , getTokenText : function ( ) { return text . substring ( tokenPos , pos ) ; } , getTokenValue : function ( ) { return tokenValue ; } , hasExtendedUnicodeEscape : function ( ) { return hasExtendedUnicodeEscape ; } , hasPrecedingLineBreak : function ( ) { return precedingLineBreak ; } , isIdentifier : function ( ) { return token === 69 /* Identifier */ || token > 105 /* LastReservedWord */ ; } , isReservedWord : function ( ) { return token >= 70 /* FirstReservedWord */ && token <= 105 /* LastReservedWord */ ; } , isUnterminated : function ( ) { return tokenIsUnterminated ; } , reScanGreaterToken : reScanGreaterToken , reScanSlashToken : reScanSlashToken , reScanTemplateToken : reScanTemplateToken , scanJsxIdentifier : scanJsxIdentifier , reScanJsxToken : reScanJsxToken , scanJsxToken : scanJsxToken , scan : scan , setText : setText , setScriptTarget : setScriptTarget , setLanguageVariant : setLanguageVariant , setOnError : setOnError , setTextPos : setTextPos , tryScan : tryScan , lookAhead : lookAhead } ; function error ( message , length ) { if ( onError ) { onError ( message , length || 0 ) ; } } function scanNumber ( ) { var start = pos ; while ( isDigit ( text . charCodeAt ( pos ) ) ) pos ++ ; if ( text . charCodeAt ( pos ) === 46 /* dot */ ) { pos ++ ; while ( isDigit ( text . charCodeAt ( pos ) ) ) pos ++ ; } var end = pos ; if ( text . charCodeAt ( pos ) === 69 /* E */ || text . charCodeAt ( pos ) === 101 /* e */ ) { pos ++ ; if ( text . charCodeAt ( pos ) === 43 /* plus */ || text . charCodeAt ( pos ) === 45 /* minus */ ) pos ++ ; if ( isDigit ( text . charCodeAt ( pos ) ) ) { pos ++ ; while ( isDigit ( text . charCodeAt ( pos ) ) ) pos ++ ; end = pos ; } else { error ( ts . Diagnostics . Digit_expected ) ; } } return + ( text . substring ( start , end ) ) ; } function scanOctalDigits ( ) { var start = pos ; while ( isOctalDigit ( text . charCodeAt ( pos ) ) ) { pos ++ ; } return + ( text . substring ( start , pos ) ) ; } /**\n         * Scans the given number of hexadecimal digits in the text,\n         * returning -1 if the given number is unavailable.\n         */ function scanExactNumberOfHexDigits ( count ) { return scanHexDigits ( /*minCount*/ count , /*scanAsManyAsPossible*/ false ) ; } /**\n         * Scans as many hexadecimal digits as are available in the text,\n         * returning -1 if the given number of digits was unavailable.\n         */ function scanMinimumNumberOfHexDigits ( count ) { return scanHexDigits ( /*minCount*/ count , /*scanAsManyAsPossible*/ true ) ; } function scanHexDigits ( minCount , scanAsManyAsPossible ) { var digits = 0 ; var value = 0 ; while ( digits < minCount || scanAsManyAsPossible ) { var ch = text . charCodeAt ( pos ) ; if ( ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ) { value = value * 16 + ch - 48 /* _0 */ ; } else if ( ch >= 65 /* A */ && ch <= 70 /* F */ ) { value = value * 16 + ch - 65 /* A */ + 10 ; } else if ( ch >= 97 /* a */ && ch <= 102 /* f */ ) { value = value * 16 + ch - 97 /* a */ + 10 ; } else { break ; } pos ++ ; digits ++ ; } if ( digits < minCount ) { value = - 1 ; } return value ; } function scanString ( ) { var quote = text . charCodeAt ( pos ++ ) ; var result = \"\" ; var start = pos ; while ( true ) { if ( pos >= end ) { result += text . substring ( start , pos ) ; tokenIsUnterminated = true ; error ( ts . Diagnostics . Unterminated_string_literal ) ; break ; } var ch = text . charCodeAt ( pos ) ; if ( ch === quote ) { result += text . substring ( start , pos ) ; pos ++ ; break ; } if ( ch === 92 /* backslash */ ) { result += text . substring ( start , pos ) ; result += scanEscapeSequence ( ) ; start = pos ; continue ; } if ( isLineBreak ( ch ) ) { result += text . substring ( start , pos ) ; tokenIsUnterminated = true ; error ( ts . Diagnostics . Unterminated_string_literal ) ; break ; } pos ++ ; } return result ; } /**\n         * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or\n         * a literal component of a TemplateExpression.\n         */ function scanTemplateAndSetTokenValue ( ) { var startedWithBacktick = text . charCodeAt ( pos ) === 96 /* backtick */ ; pos ++ ; var start = pos ; var contents = \"\" ; var resultingToken ; while ( true ) { if ( pos >= end ) { contents += text . substring ( start , pos ) ; tokenIsUnterminated = true ; error ( ts . Diagnostics . Unterminated_template_literal ) ; resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */ ; break ; } var currChar = text . charCodeAt ( pos ) ; // '`' if ( currChar === 96 /* backtick */ ) { contents += text . substring ( start , pos ) ; pos ++ ; resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */ ; break ; } // '${' if ( currChar === 36 /* $ */ && pos + 1 < end && text . charCodeAt ( pos + 1 ) === 123 /* openBrace */ ) { contents += text . substring ( start , pos ) ; pos += 2 ; resultingToken = startedWithBacktick ? 12 /* TemplateHead */ : 13 /* TemplateMiddle */ ; break ; } // Escape character if ( currChar === 92 /* backslash */ ) { contents += text . substring ( start , pos ) ; contents += scanEscapeSequence ( ) ; start = pos ; continue ; } // Speculated ECMAScript 6 Spec 11.8.6.1: // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values if ( currChar === 13 /* carriageReturn */ ) { contents += text . substring ( start , pos ) ; pos ++ ; if ( pos < end && text . charCodeAt ( pos ) === 10 /* lineFeed */ ) { pos ++ ; } contents += \"\\n\" ; start = pos ; continue ; } pos ++ ; } ts . Debug . assert ( resultingToken !== undefined ) ; tokenValue = contents ; return resultingToken ; } function scanEscapeSequence ( ) { pos ++ ; if ( pos >= end ) { error ( ts . Diagnostics . Unexpected_end_of_text ) ; return \"\" ; } var ch = text . charCodeAt ( pos ++ ) ; switch ( ch ) { case 48 /* _0 */ : return \"\\0\" ; case 98 /* b */ : return \"\\b\" ; case 116 /* t */ : return \"\\t\" ; case 110 /* n */ : return \"\\n\" ; case 118 /* v */ : return \"\\v\" ; case 102 /* f */ : return \"\\f\" ; case 114 /* r */ : return \"\\r\" ; case 39 /* singleQuote */ : return \"\\'\" ; case 34 /* doubleQuote */ : return \"\\\"\" ; case 117 /* u */ : // '\\u{DDDDDDDD}' if ( pos < end && text . charCodeAt ( pos ) === 123 /* openBrace */ ) { hasExtendedUnicodeEscape = true ; pos ++ ; return scanExtendedUnicodeEscape ( ) ; } // '\\uDDDD' return scanHexadecimalEscape ( /*numDigits*/ 4 ) ; case 120 /* x */ : // '\\xDD' return scanHexadecimalEscape ( /*numDigits*/ 2 ) ; // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), // the line terminator is interpreted to be \"the empty code unit sequence\". case 13 /* carriageReturn */ : if ( pos < end && text . charCodeAt ( pos ) === 10 /* lineFeed */ ) { pos ++ ; } // fall through case 10 /* lineFeed */ : case 8232 /* lineSeparator */ : case 8233 /* paragraphSeparator */ : return \"\" ; default : return String . fromCharCode ( ch ) ; } } function scanHexadecimalEscape ( numDigits ) { var escapedValue = scanExactNumberOfHexDigits ( numDigits ) ; if ( escapedValue >= 0 ) { return String . fromCharCode ( escapedValue ) ; } else { error ( ts . Diagnostics . Hexadecimal_digit_expected ) ; return \"\" ; } } function scanExtendedUnicodeEscape ( ) { var escapedValue = scanMinimumNumberOfHexDigits ( 1 ) ; var isInvalidExtendedEscape = false ; // Validate the value of the digit if ( escapedValue < 0 ) { error ( ts . Diagnostics . Hexadecimal_digit_expected ) ; isInvalidExtendedEscape = true ; } else if ( escapedValue > 0x10FFFF ) { error ( ts . Diagnostics . An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive ) ; isInvalidExtendedEscape = true ; } if ( pos >= end ) { error ( ts . Diagnostics . Unexpected_end_of_text ) ; isInvalidExtendedEscape = true ; } else if ( text . charCodeAt ( pos ) === 125 /* closeBrace */ ) { // Only swallow the following character up if it's a '}'. pos ++ ; } else { error ( ts . Diagnostics . Unterminated_Unicode_escape_sequence ) ; isInvalidExtendedEscape = true ; } if ( isInvalidExtendedEscape ) { return \"\" ; } return utf16EncodeAsString ( escapedValue ) ; } // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec. function utf16EncodeAsString ( codePoint ) { ts . Debug . assert ( 0x0 <= codePoint && codePoint <= 0x10FFFF ) ; if ( codePoint <= 65535 ) { return String . fromCharCode ( codePoint ) ; } var codeUnit1 = Math . floor ( ( codePoint - 65536 ) / 1024 ) + 0xD800 ; var codeUnit2 = ( ( codePoint - 65536 ) % 1024 ) + 0xDC00 ; return String . fromCharCode ( codeUnit1 , codeUnit2 ) ; } // Current character is known to be a backslash. Check for Unicode escape of the form '\\uXXXX' // and return code point value if valid Unicode escape is found. Otherwise return -1. function peekUnicodeEscape ( ) { if ( pos + 5 < end && text . charCodeAt ( pos + 1 ) === 117 /* u */ ) { var start_1 = pos ; pos += 2 ; var value = scanExactNumberOfHexDigits ( 4 ) ; pos = start_1 ; return value ; } return - 1 ; } function scanIdentifierParts ( ) { var result = \"\" ; var start = pos ; while ( pos < end ) { var ch = text . charCodeAt ( pos ) ; if ( isIdentifierPart ( ch , languageVersion ) ) { pos ++ ; } else if ( ch === 92 /* backslash */ ) { ch = peekUnicodeEscape ( ) ; if ( ! ( ch >= 0 && isIdentifierPart ( ch , languageVersion ) ) ) { break ; } result += text . substring ( start , pos ) ; result += String . fromCharCode ( ch ) ; // Valid Unicode escape is always six characters pos += 6 ; start = pos ; } else { break ; } } result += text . substring ( start , pos ) ; return result ; } function getIdentifierToken ( ) { // Reserved words are between 2 and 11 characters long and start with a lowercase letter var len = tokenValue . length ; if ( len >= 2 && len <= 11 ) { var ch = tokenValue . charCodeAt ( 0 ) ; if ( ch >= 97 /* a */ && ch <= 122 /* z */ && hasOwnProperty . call ( textToToken , tokenValue ) ) { return token = textToToken [ tokenValue ] ; } } return token = 69 /* Identifier */ ; } function scanBinaryOrOctalDigits ( base ) { ts . Debug . assert ( base !== 2 || base !== 8 , \"Expected either base 2 or base 8\" ) ; var value = 0 ; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. var numberOfDigits = 0 ; while ( true ) { var ch = text . charCodeAt ( pos ) ; var valueOfCh = ch - 48 /* _0 */ ; if ( ! isDigit ( ch ) || valueOfCh >= base ) { break ; } value = value * base + valueOfCh ; pos ++ ; numberOfDigits ++ ; } // Invalid binaryIntegerLiteral or octalIntegerLiteral if ( numberOfDigits === 0 ) { return - 1 ; } return value ; } function scan ( ) { startPos = pos ; hasExtendedUnicodeEscape = false ; precedingLineBreak = false ; tokenIsUnterminated = false ; while ( true ) { tokenPos = pos ; if ( pos >= end ) { return token = 1 /* EndOfFileToken */ ; } var ch = text . charCodeAt ( pos ) ; // Special handling for shebang if ( ch === 35 /* hash */ && pos === 0 && isShebangTrivia ( text , pos ) ) { pos = scanShebangTrivia ( text , pos ) ; if ( skipTrivia ) { continue ; } else { return token = 6 /* ShebangTrivia */ ; } } switch ( ch ) { case 10 /* lineFeed */ : case 13 /* carriageReturn */ : precedingLineBreak = true ; if ( skipTrivia ) { pos ++ ; continue ; } else { if ( ch === 13 /* carriageReturn */ && pos + 1 < end && text . charCodeAt ( pos + 1 ) === 10 /* lineFeed */ ) { // consume both CR and LF pos += 2 ; } else { pos ++ ; } return token = 4 /* NewLineTrivia */ ; } case 9 /* tab */ : case 11 /* verticalTab */ : case 12 /* formFeed */ : case 32 /* space */ : if ( skipTrivia ) { pos ++ ; continue ; } else { while ( pos < end && isWhiteSpace ( text . charCodeAt ( pos ) ) ) { pos ++ ; } return token = 5 /* WhitespaceTrivia */ ; } case 33 /* exclamation */ : if ( text . charCodeAt ( pos + 1 ) === 61 /* equals */ ) { if ( text . charCodeAt ( pos + 2 ) === 61 /* equals */ ) { return pos += 3 , token = 33 /* ExclamationEqualsEqualsToken */ ; } return pos += 2 , token = 31 /* ExclamationEqualsToken */ ; } return pos ++ , token = 49 /* ExclamationToken */ ; case 34 /* doubleQuote */ : case 39 /* singleQuote */ : tokenValue = scanString ( ) ; return token = 9 /* StringLiteral */ ; case 96 /* backtick */ : return token = scanTemplateAndSetTokenValue ( ) ; case 37 /* percent */ : if ( text . charCodeAt ( pos + 1 ) === 61 /* equals */ ) { return pos += 2 , token = 62 /* PercentEqualsToken */ ; } return pos ++ , token = 40 /* PercentToken */ ; case 38 /* ampersand */ : if ( text . charCodeAt ( pos + 1 ) === 38 /* ampersand */ ) { return pos += 2 , token = 51 /* AmpersandAmpersandToken */ ; } if ( text . charCodeAt ( pos + 1 ) === 61 /* equals */ ) { return pos += 2 , token = 66 /* AmpersandEqualsToken */ ; } return pos ++ , token = 46 /* AmpersandToken */ ; case 40 /* openParen */ : return pos ++ , token = 17 /* OpenParenToken */ ; case 41 /* closeParen */ : return pos ++ , token = 18 /* CloseParenToken */ ; case 42 /* asterisk */ : if ( text . charCodeAt ( pos + 1 ) === 61 /* equals */ ) { return pos += 2 , token = 59 /* AsteriskEqualsToken */ ; } if ( text . charCodeAt ( pos + 1 ) === 42 /* asterisk */ ) { if ( text . charCodeAt ( pos + 2 ) === 61 /* equals */ ) { return pos += 3 , token = 60 /* AsteriskAsteriskEqualsToken */ ; } return pos += 2 , token = 38 /* AsteriskAsteriskToken */ ; } return pos ++ , token = 37 /* AsteriskToken */ ; case 43 /* plus */ : if ( text . charCodeAt ( pos + 1 ) === 43 /* plus */ ) { return pos += 2 , token = 41 /* PlusPlusToken */ ; } if ( text . charCodeAt ( pos + 1 ) === 61 /* equals */ ) { return pos += 2 , token = 57 /* PlusEqualsToken */ ; } return pos ++ , token = 35 /* PlusToken */ ; case 44 /* comma */ : return pos ++ , token = 24 /* CommaToken */ ; case 45 /* minus */ : if ( text . charCodeAt ( pos + 1 ) === 45 /* minus */ ) { return pos += 2 , token = 42 /* MinusMinusToken */ ; } if ( text . charCodeAt ( pos + 1 ) === 61 /* equals */ ) { return pos += 2 , token = 58 /* MinusEqualsToken */ ; } return pos ++ , token = 36 /* MinusToken */ ; case 46 /* dot */ : if ( isDigit ( text . charCodeAt ( pos + 1 ) ) ) { tokenValue = \"\" + scanNumber ( ) ; return token = 8 /* NumericLiteral */ ; } if ( text . charCodeAt ( pos + 1 ) === 46 /* dot */ && text . charCodeAt ( pos + 2 ) === 46 /* dot */ ) { return pos += 3 , token = 22 /* DotDotDotToken */ ; } return pos ++ , token = 21 /* DotToken */ ; case 47 /* slash */ : // Single-line comment if ( text . charCodeAt ( pos + 1 ) === 47 /* slash */ ) { pos += 2 ; while ( pos < end ) { if ( isLineBreak ( text . charCodeAt ( pos ) ) ) { break ; } pos ++ ; } if ( skipTrivia ) { continue ; } else { return token = 2 /* SingleLineCommentTrivia */ ; } } // Multi-line comment if ( text . charCodeAt ( pos + 1 ) === 42 /* asterisk */ ) { pos += 2 ; var commentClosed = false ; while ( pos < end ) { var ch_2 = text . charCodeAt ( pos ) ; if ( ch_2 === 42 /* asterisk */ && text . charCodeAt ( pos + 1 ) === 47 /* slash */ ) { pos += 2 ; commentClosed = true ; break ; } if ( isLineBreak ( ch_2 ) ) { precedingLineBreak = true ; } pos ++ ; } if ( ! commentClosed ) { error ( ts . Diagnostics . Asterisk_Slash_expected ) ; } if ( skipTrivia ) { continue ; } else { tokenIsUnterminated = ! commentClosed ; return token = 3 /* MultiLineCommentTrivia */ ; } } if ( text . charCodeAt ( pos + 1 ) === 61 /* equals */ ) { return pos += 2 , token = 61 /* SlashEqualsToken */ ; } return pos ++ , token = 39 /* SlashToken */ ; case 48 /* _0 */ : if ( pos + 2 < end && ( text . charCodeAt ( pos + 1 ) === 88 /* X */ || text . charCodeAt ( pos + 1 ) === 120 /* x */ ) ) { pos += 2 ; var value = scanMinimumNumberOfHexDigits ( 1 ) ; if ( value < 0 ) { error ( ts . Diagnostics . Hexadecimal_digit_expected ) ; value = 0 ; } tokenValue = \"\" + value ; return token = 8 /* NumericLiteral */ ; } else if ( pos + 2 < end && ( text . charCodeAt ( pos + 1 ) === 66 /* B */ || text . charCodeAt ( pos + 1 ) === 98 /* b */ ) ) { pos += 2 ; var value = scanBinaryOrOctalDigits ( /* base */ 2 ) ; if ( value < 0 ) { error ( ts . Diagnostics . Binary_digit_expected ) ; value = 0 ; } tokenValue = \"\" + value ; return token = 8 /* NumericLiteral */ ; } else if ( pos + 2 < end && ( text . charCodeAt ( pos + 1 ) === 79 /* O */ || text . charCodeAt ( pos + 1 ) === 111 /* o */ ) ) { pos += 2 ; var value = scanBinaryOrOctalDigits ( /* base */ 8 ) ; if ( value < 0 ) { error ( ts . Diagnostics . Octal_digit_expected ) ; value = 0 ; } tokenValue = \"\" + value ; return token = 8 /* NumericLiteral */ ; } // Try to parse as an octal if ( pos + 1 < end && isOctalDigit ( text . charCodeAt ( pos + 1 ) ) ) { tokenValue = \"\" + scanOctalDigits ( ) ; return token = 8 /* NumericLiteral */ ; } // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do). case 49 /* _1 */ : case 50 /* _2 */ : case 51 /* _3 */ : case 52 /* _4 */ : case 53 /* _5 */ : case 54 /* _6 */ : case 55 /* _7 */ : case 56 /* _8 */ : case 57 /* _9 */ : tokenValue = \"\" + scanNumber ( ) ; return token = 8 /* NumericLiteral */ ; case 58 /* colon */ : return pos ++ , token = 54 /* ColonToken */ ; case 59 /* semicolon */ : return pos ++ , token = 23 /* SemicolonToken */ ; case 60 /* lessThan */ : if ( isConflictMarkerTrivia ( text , pos ) ) { pos = scanConflictMarkerTrivia ( text , pos , error ) ; if ( skipTrivia ) { continue ; } else { return token = 7 /* ConflictMarkerTrivia */ ; } } if ( text . charCodeAt ( pos + 1 ) === 60 /* lessThan */ ) { if ( text . charCodeAt ( pos + 2 ) === 61 /* equals */ ) { return pos += 3 , token = 63 /* LessThanLessThanEqualsToken */ ; } return pos += 2 , token = 43 /* LessThanLessThanToken */ ; } if ( text . charCodeAt ( pos + 1 ) === 61 /* equals */ ) { return pos += 2 , token = 28 /* LessThanEqualsToken */ ; } if ( languageVariant === 1 /* JSX */ && text . charCodeAt ( pos + 1 ) === 47 /* slash */ && text . charCodeAt ( pos + 2 ) !== 42 /* asterisk */ ) { return pos += 2 , token = 26 /* LessThanSlashToken */ ; } return pos ++ , token = 25 /* LessThanToken */ ; case 61 /* equals */ : if ( isConflictMarkerTrivia ( text , pos ) ) { pos = scanConflictMarkerTrivia ( text , pos , error ) ; if ( skipTrivia ) { continue ; } else { return token = 7 /* ConflictMarkerTrivia */ ; } } if ( text . charCodeAt ( pos + 1 ) === 61 /* equals */ ) { if ( text . charCodeAt ( pos + 2 ) === 61 /* equals */ ) { return pos += 3 , token = 32 /* EqualsEqualsEqualsToken */ ; } return pos += 2 , token = 30 /* EqualsEqualsToken */ ; } if ( text . charCodeAt ( pos + 1 ) === 62 /* greaterThan */ ) { return pos += 2 , token = 34 /* EqualsGreaterThanToken */ ; } return pos ++ , token = 56 /* EqualsToken */ ; case 62 /* greaterThan */ : if ( isConflictMarkerTrivia ( text , pos ) ) { pos = scanConflictMarkerTrivia ( text , pos , error ) ; if ( skipTrivia ) { continue ; } else { return token = 7 /* ConflictMarkerTrivia */ ; } } return pos ++ , token = 27 /* GreaterThanToken */ ; case 63 /* question */ : return pos ++ , token = 53 /* QuestionToken */ ; case 91 /* openBracket */ : return pos ++ , token = 19 /* OpenBracketToken */ ; case 93 /* closeBracket */ : return pos ++ , token = 20 /* CloseBracketToken */ ; case 94 /* caret */ : if ( text . charCodeAt ( pos + 1 ) === 61 /* equals */ ) { return pos += 2 , token = 68 /* CaretEqualsToken */ ; } return pos ++ , token = 48 /* CaretToken */ ; case 123 /* openBrace */ : return pos ++ , token = 15 /* OpenBraceToken */ ; case 124 /* bar */ : if ( text . charCodeAt ( pos + 1 ) === 124 /* bar */ ) { return pos += 2 , token = 52 /* BarBarToken */ ; } if ( text . charCodeAt ( pos + 1 ) === 61 /* equals */ ) { return pos += 2 , token = 67 /* BarEqualsToken */ ; } return pos ++ , token = 47 /* BarToken */ ; case 125 /* closeBrace */ : return pos ++ , token = 16 /* CloseBraceToken */ ; case 126 /* tilde */ : return pos ++ , token = 50 /* TildeToken */ ; case 64 /* at */ : return pos ++ , token = 55 /* AtToken */ ; case 92 /* backslash */ : var cookedChar = peekUnicodeEscape ( ) ; if ( cookedChar >= 0 && isIdentifierStart ( cookedChar , languageVersion ) ) { pos += 6 ; tokenValue = String . fromCharCode ( cookedChar ) + scanIdentifierParts ( ) ; return token = getIdentifierToken ( ) ; } error ( ts . Diagnostics . Invalid_character ) ; return pos ++ , token = 0 /* Unknown */ ; default : if ( isIdentifierStart ( ch , languageVersion ) ) { pos ++ ; while ( pos < end && isIdentifierPart ( ch = text . charCodeAt ( pos ) , languageVersion ) ) pos ++ ; tokenValue = text . substring ( tokenPos , pos ) ; if ( ch === 92 /* backslash */ ) { tokenValue += scanIdentifierParts ( ) ; } return token = getIdentifierToken ( ) ; } else if ( isWhiteSpace ( ch ) ) { pos ++ ; continue ; } else if ( isLineBreak ( ch ) ) { precedingLineBreak = true ; pos ++ ; continue ; } error ( ts . Diagnostics . Invalid_character ) ; return pos ++ , token = 0 /* Unknown */ ; } } } function reScanGreaterToken ( ) { if ( token === 27 /* GreaterThanToken */ ) { if ( text . charCodeAt ( pos ) === 62 /* greaterThan */ ) { if ( text . charCodeAt ( pos + 1 ) === 62 /* greaterThan */ ) { if ( text . charCodeAt ( pos + 2 ) === 61 /* equals */ ) { return pos += 3 , token = 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */ ; } return pos += 2 , token = 45 /* GreaterThanGreaterThanGreaterThanToken */ ; } if ( text . charCodeAt ( pos + 1 ) === 61 /* equals */ ) { return pos += 2 , token = 64 /* GreaterThanGreaterThanEqualsToken */ ; } return pos ++ , token = 44 /* GreaterThanGreaterThanToken */ ; } if ( text . charCodeAt ( pos ) === 61 /* equals */ ) { return pos ++ , token = 29 /* GreaterThanEqualsToken */ ; } } return token ; } function reScanSlashToken ( ) { if ( token === 39 /* SlashToken */ || token === 61 /* SlashEqualsToken */ ) { var p = tokenPos + 1 ; var inEscape = false ; var inCharacterClass = false ; while ( true ) { // If we reach the end of a file, or hit a newline, then this is an unterminated // regex.  Report error and return what we have so far. if ( p >= end ) { tokenIsUnterminated = true ; error ( ts . Diagnostics . Unterminated_regular_expression_literal ) ; break ; } var ch = text . charCodeAt ( p ) ; if ( isLineBreak ( ch ) ) { tokenIsUnterminated = true ; error ( ts . Diagnostics . Unterminated_regular_expression_literal ) ; break ; } if ( inEscape ) { // Parsing an escape character; // reset the flag and just advance to the next char. inEscape = false ; } else if ( ch === 47 /* slash */ && ! inCharacterClass ) { // A slash within a character class is permissible, // but in general it signals the end of the regexp literal. p ++ ; break ; } else if ( ch === 91 /* openBracket */ ) { inCharacterClass = true ; } else if ( ch === 92 /* backslash */ ) { inEscape = true ; } else if ( ch === 93 /* closeBracket */ ) { inCharacterClass = false ; } p ++ ; } while ( p < end && isIdentifierPart ( text . charCodeAt ( p ) , languageVersion ) ) { p ++ ; } pos = p ; tokenValue = text . substring ( tokenPos , pos ) ; token = 10 /* RegularExpressionLiteral */ ; } return token ; } /**\n         * Unconditionally back up and scan a template expression portion.\n         */ function reScanTemplateToken ( ) { ts . Debug . assert ( token === 16 /* CloseBraceToken */ , \"'reScanTemplateToken' should only be called on a '}'\" ) ; pos = tokenPos ; return token = scanTemplateAndSetTokenValue ( ) ; } function reScanJsxToken ( ) { pos = tokenPos = startPos ; return token = scanJsxToken ( ) ; } function scanJsxToken ( ) { startPos = tokenPos = pos ; if ( pos >= end ) { return token = 1 /* EndOfFileToken */ ; } var char = text . charCodeAt ( pos ) ; if ( char === 60 /* lessThan */ ) { if ( text . charCodeAt ( pos + 1 ) === 47 /* slash */ ) { pos += 2 ; return token = 26 /* LessThanSlashToken */ ; } pos ++ ; return token = 25 /* LessThanToken */ ; } if ( char === 123 /* openBrace */ ) { pos ++ ; return token = 15 /* OpenBraceToken */ ; } while ( pos < end ) { pos ++ ; char = text . charCodeAt ( pos ) ; if ( ( char === 123 /* openBrace */ ) || ( char === 60 /* lessThan */ ) ) { break ; } } return token = 236 /* JsxText */ ; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes function scanJsxIdentifier ( ) { if ( tokenIsIdentifierOrKeyword ( token ) ) { var firstCharPosition = pos ; while ( pos < end ) { var ch = text . charCodeAt ( pos ) ; if ( ch === 45 /* minus */ || ( ( firstCharPosition === pos ) ? isIdentifierStart ( ch , languageVersion ) : isIdentifierPart ( ch , languageVersion ) ) ) { pos ++ ; } else { break ; } } tokenValue += text . substr ( firstCharPosition , pos - firstCharPosition ) ; } return token ; } function speculationHelper ( callback , isLookahead ) { var savePos = pos ; var saveStartPos = startPos ; var saveTokenPos = tokenPos ; var saveToken = token ; var saveTokenValue = tokenValue ; var savePrecedingLineBreak = precedingLineBreak ; var result = callback ( ) ; // If our callback returned something 'falsy' or we're just looking ahead, // then unconditionally restore us to where we were. if ( ! result || isLookahead ) { pos = savePos ; startPos = saveStartPos ; tokenPos = saveTokenPos ; token = saveToken ; tokenValue = saveTokenValue ; precedingLineBreak = savePrecedingLineBreak ; } return result ; } function lookAhead ( callback ) { return speculationHelper ( callback , /*isLookahead:*/ true ) ; } function tryScan ( callback ) { return speculationHelper ( callback , /*isLookahead:*/ false ) ; } function setText ( newText , start , length ) { text = newText || \"\" ; end = length === undefined ? text . length : start + length ; setTextPos ( start || 0 ) ; } function setOnError ( errorCallback ) { onError = errorCallback ; } function setScriptTarget ( scriptTarget ) { languageVersion = scriptTarget ; } function setLanguageVariant ( variant ) { languageVariant = variant ; } function setTextPos ( textPos ) { ts . Debug . assert ( textPos >= 0 ) ; pos = textPos ; startPos = textPos ; tokenPos = textPos ; token = 0 /* Unknown */ ; precedingLineBreak = false ; tokenValue = undefined ; hasExtendedUnicodeEscape = false ; tokenIsUnterminated = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the current tokenValue and returns a NoSubstitutionTemplateLiteral or a literal component of a TemplateExpression . [CODESPLIT] function scanTemplateAndSetTokenValue ( ) { var startedWithBacktick = text . charCodeAt ( pos ) === 96 /* backtick */ ; pos ++ ; var start = pos ; var contents = \"\" ; var resultingToken ; while ( true ) { if ( pos >= end ) { contents += text . substring ( start , pos ) ; tokenIsUnterminated = true ; error ( ts . Diagnostics . Unterminated_template_literal ) ; resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */ ; break ; } var currChar = text . charCodeAt ( pos ) ; // '`' if ( currChar === 96 /* backtick */ ) { contents += text . substring ( start , pos ) ; pos ++ ; resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */ ; break ; } // '${' if ( currChar === 36 /* $ */ && pos + 1 < end && text . charCodeAt ( pos + 1 ) === 123 /* openBrace */ ) { contents += text . substring ( start , pos ) ; pos += 2 ; resultingToken = startedWithBacktick ? 12 /* TemplateHead */ : 13 /* TemplateMiddle */ ; break ; } // Escape character if ( currChar === 92 /* backslash */ ) { contents += text . substring ( start , pos ) ; contents += scanEscapeSequence ( ) ; start = pos ; continue ; } // Speculated ECMAScript 6 Spec 11.8.6.1: // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values if ( currChar === 13 /* carriageReturn */ ) { contents += text . substring ( start , pos ) ; pos ++ ; if ( pos < end && text . charCodeAt ( pos ) === 10 /* lineFeed */ ) { pos ++ ; } contents += \"\\n\" ; start = pos ; continue ; } pos ++ ; } ts . Debug . assert ( resultingToken !== undefined ) ; tokenValue = contents ; return resultingToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Derived from the 10 . 1 . 1 UTF16Encoding of the ES6 Spec . [CODESPLIT] function utf16EncodeAsString ( codePoint ) { ts . Debug . assert ( 0x0 <= codePoint && codePoint <= 0x10FFFF ) ; if ( codePoint <= 65535 ) { return String . fromCharCode ( codePoint ) ; } var codeUnit1 = Math . floor ( ( codePoint - 65536 ) / 1024 ) + 0xD800 ; var codeUnit2 = ( ( codePoint - 65536 ) % 1024 ) + 0xDC00 ; return String . fromCharCode ( codeUnit1 , codeUnit2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Current character is known to be a backslash . Check for Unicode escape of the form \\ uXXXX and return code point value if valid Unicode escape is found . Otherwise return - 1 . [CODESPLIT] function peekUnicodeEscape ( ) { if ( pos + 5 < end && text . charCodeAt ( pos + 1 ) === 117 /* u */ ) { var start_1 = pos ; pos += 2 ; var value = scanExactNumberOfHexDigits ( 4 ) ; pos = start_1 ; return value ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans a JSX identifier ; these differ from normal identifiers in that they allow dashes [CODESPLIT] function scanJsxIdentifier ( ) { if ( tokenIsIdentifierOrKeyword ( token ) ) { var firstCharPosition = pos ; while ( pos < end ) { var ch = text . charCodeAt ( pos ) ; if ( ch === 45 /* minus */ || ( ( firstCharPosition === pos ) ? isIdentifierStart ( ch , languageVersion ) : isIdentifierPart ( ch , languageVersion ) ) ) { pos ++ ; } else { break ; } } tokenValue += text . substr ( firstCharPosition , pos - firstCharPosition ) ; } return token ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Should not be called on a declaration with a computed property name unless it is a well known Symbol . [CODESPLIT] function getDeclarationName ( node ) { if ( node . name ) { if ( node . kind === 218 /* ModuleDeclaration */ && node . name . kind === 9 /* StringLiteral */ ) { return \"\\\"\" + node . name . text + \"\\\"\" ; } if ( node . name . kind === 136 /* ComputedPropertyName */ ) { var nameExpression = node . name . expression ; ts . Debug . assert ( ts . isWellKnownSymbolSyntactically ( nameExpression ) ) ; return ts . getPropertyNameForKnownSymbolName ( nameExpression . name . text ) ; } return node . name . text ; } switch ( node . kind ) { case 144 /* Constructor */ : return \"__constructor\" ; case 152 /* FunctionType */ : case 147 /* CallSignature */ : return \"__call\" ; case 153 /* ConstructorType */ : case 148 /* ConstructSignature */ : return \"__new\" ; case 149 /* IndexSignature */ : return \"__index\" ; case 228 /* ExportDeclaration */ : return \"__export\" ; case 227 /* ExportAssignment */ : return node . isExportEquals ? \"export=\" : \"default\" ; case 213 /* FunctionDeclaration */ : case 214 /* ClassDeclaration */ : return node . flags & 1024 /* Default */ ? \"default\" : undefined ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "All container nodes are kept on a linked list in declaration order . This list is used by the getLocalNameOfContainer function in the type checker to validate that the local name used for a container is unique . [CODESPLIT] function bindChildren ( node ) { // Before we recurse into a node's chilren, we first save the existing parent, container // and block-container.  Then after we pop out of processing the children, we restore // these saved values. var saveParent = parent ; var saveContainer = container ; var savedBlockScopeContainer = blockScopeContainer ; // This node will now be set as the parent of all of its children as we recurse into them. parent = node ; // Depending on what kind of node this is, we may have to adjust the current container // and block-container.   If the current node is a container, then it is automatically // considered the current block-container as well.  Also, for containers that we know // may contain locals, we proactively initialize the .locals field. We do this because // it's highly likely that the .locals will be needed to place some child in (for example, // a parameter, or variable declaration). // // However, we do not proactively create the .locals for block-containers because it's // totally normal and common for block-containers to never actually have a block-scoped // variable in them.  We don't want to end up allocating an object for every 'block' we // run into when most of them won't be necessary. // // Finally, if this is a block-container, then we clear out any existing .locals object // it may contain within it.  This happens in incremental scenarios.  Because we can be // reusing a node from a previous compilation, that node may have had 'locals' created // for it.  We must clear this so we don't accidently move any stale data forward from // a previous compilation. var containerFlags = getContainerFlags ( node ) ; if ( containerFlags & 1 /* IsContainer */ ) { container = blockScopeContainer = node ; if ( containerFlags & 4 /* HasLocals */ ) { container . locals = { } ; } addToContainerChain ( container ) ; } else if ( containerFlags & 2 /* IsBlockScopedContainer */ ) { blockScopeContainer = node ; blockScopeContainer . locals = undefined ; } if ( node . kind === 215 /* InterfaceDeclaration */ ) { seenThisKeyword = false ; ts . forEachChild ( node , bind ) ; node . flags = seenThisKeyword ? node . flags | 524288 /* ContainsThis */ : node . flags & ~ 524288 /* ContainsThis */ ; } else { ts . forEachChild ( node , bind ) ; } container = saveContainer ; parent = saveParent ; blockScopeContainer = savedBlockScopeContainer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a useful function for debugging purposes . [CODESPLIT] function nodePosToString ( node ) { var file = getSourceFileOfNode ( node ) ; var loc = ts . getLineAndCharacterOfPosition ( file , node . pos ) ; return file . fileName + \"(\" + ( loc . line + 1 ) + \",\" + ( loc . character + 1 ) + \")\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this node is missing from the actual source code . A missing node is different from undefined / defined . When a node is undefined ( which can happen for optional nodes in the tree ) it is definitely missing . However a node may be defined but still be missing . This happens whenever the parser knows it needs to parse something but can t get anything in the source code that it expects at that location . For example : let a : ; Here the Type in the Type - Annotation is not - optional ( as there is a colon in the source code ) . So the parser will attempt to parse out a type and will create an actual node . However this node will be missing in the sense that no actual source - code / tokens are contained within it . [CODESPLIT] function nodeIsMissing ( node ) { if ( ! node ) { return true ; } return node . pos === node . end && node . pos >= 0 && node . kind !== 1 /* EndOfFileToken */ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like __proto__ [CODESPLIT] function escapeIdentifier ( identifier ) { return identifier . length >= 2 && identifier . charCodeAt ( 0 ) === 95 /* _ */ && identifier . charCodeAt ( 1 ) === 95 /* _ */ ? \"_\" + identifier : identifier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove extra underscore from escaped identifier [CODESPLIT] function unescapeIdentifier ( identifier ) { return identifier . length >= 3 && identifier . charCodeAt ( 0 ) === 95 /* _ */ && identifier . charCodeAt ( 1 ) === 95 /* _ */ && identifier . charCodeAt ( 2 ) === 95 /* _ */ ? identifier . substr ( 1 ) : identifier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the nearest enclosing block scope container that has the provided node as a descendant that is not the provided node . [CODESPLIT] function getEnclosingBlockScopeContainer ( node ) { var current = node . parent ; while ( current ) { if ( isFunctionLike ( current ) ) { return current ; } switch ( current . kind ) { case 248 /* SourceFile */ : case 220 /* CaseBlock */ : case 244 /* CatchClause */ : case 218 /* ModuleDeclaration */ : case 199 /* ForStatement */ : case 200 /* ForInStatement */ : case 201 /* ForOfStatement */ : return current ; case 192 /* Block */ : // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block if ( ! isFunctionLike ( current . parent ) ) { return current ; } } current = current . parent ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the node flags for this node and all relevant parent nodes . This is done so that nodes like variable declarations and binding elements can returned a view of their flags that includes the modifiers from their container . i . e . flags like export / declare aren t stored on the variable declaration directly but on the containing variable statement ( if it has one ) . Similarly flags for let / const are store on the variable declaration list . By calling this function all those flags are combined so that the client can treat the node as if it actually had those flags . [CODESPLIT] function getCombinedNodeFlags ( node ) { node = walkUpBindingElementsAndPatterns ( node ) ; var flags = node . flags ; if ( node . kind === 211 /* VariableDeclaration */ ) { node = node . parent ; } if ( node && node . kind === 212 /* VariableDeclarationList */ ) { flags |= node . flags ; node = node . parent ; } if ( node && node . kind === 193 /* VariableStatement */ ) { flags |= node . flags ; } return flags ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Warning : This has the same semantics as the forEach family of functions in that traversal terminates in the event that visitor supplies a truthy value . [CODESPLIT] function forEachReturnStatement ( body , visitor ) { return traverse ( body ) ; function traverse ( node ) { switch ( node . kind ) { case 204 /* ReturnStatement */ : return visitor ( node ) ; case 220 /* CaseBlock */ : case 192 /* Block */ : case 196 /* IfStatement */ : case 197 /* DoStatement */ : case 198 /* WhileStatement */ : case 199 /* ForStatement */ : case 200 /* ForInStatement */ : case 201 /* ForOfStatement */ : case 205 /* WithStatement */ : case 206 /* SwitchStatement */ : case 241 /* CaseClause */ : case 242 /* DefaultClause */ : case 207 /* LabeledStatement */ : case 209 /* TryStatement */ : case 244 /* CatchClause */ : return ts . forEachChild ( node , traverse ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "True if the given identifier string literal or number literal is the name of a declaration node [CODESPLIT] function isDeclarationName ( name ) { if ( name . kind !== 69 /* Identifier */ && name . kind !== 9 /* StringLiteral */ && name . kind !== 8 /* NumericLiteral */ ) { return false ; } var parent = name . parent ; if ( parent . kind === 226 /* ImportSpecifier */ || parent . kind === 230 /* ExportSpecifier */ ) { if ( parent . propertyName ) { return true ; } } if ( isDeclaration ( parent ) ) { return parent . name === name ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given identifier is classified as an IdentifierName [CODESPLIT] function isIdentifierName ( node ) { var parent = node . parent ; switch ( parent . kind ) { case 141 /* PropertyDeclaration */ : case 140 /* PropertySignature */ : case 143 /* MethodDeclaration */ : case 142 /* MethodSignature */ : case 145 /* GetAccessor */ : case 146 /* SetAccessor */ : case 247 /* EnumMember */ : case 245 /* PropertyAssignment */ : case 166 /* PropertyAccessExpression */ : // Name in member declaration or property name in property access return parent . name === node ; case 135 /* QualifiedName */ : // Name on right hand side of dot in a type query if ( parent . right === node ) { while ( parent . kind === 135 /* QualifiedName */ ) { parent = parent . parent ; } return parent . kind === 154 /* TypeQuery */ ; } return false ; case 163 /* BindingElement */ : case 226 /* ImportSpecifier */ : // Property name in binding element or import specifier return parent . propertyName === node ; case 230 /* ExportSpecifier */ : // Any name in an export specifier return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An alias symbol is created by one of the following declarations : import <symbol > = ... import <symbol > from ... import * as <symbol > from ... import { x as <symbol > } from ... export { x as <symbol > } from ... export = ... export default ... [CODESPLIT] function isAliasSymbolDeclaration ( node ) { return node . kind === 221 /* ImportEqualsDeclaration */ || node . kind === 223 /* ImportClause */ && ! ! node . name || node . kind === 224 /* NamespaceImport */ || node . kind === 226 /* ImportSpecifier */ || node . kind === 230 /* ExportSpecifier */ || node . kind === 227 /* ExportAssignment */ && node . expression . kind === 69 /* Identifier */ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A declaration has a dynamic name if both of the following are true : 1 . The declaration has a computed property name 2 . The computed name is * not * expressed as Symbol . <name > where name is a property of the Symbol constructor that denotes a built in Symbol . [CODESPLIT] function hasDynamicName ( declaration ) { return declaration . name && declaration . name . kind === 136 /* ComputedPropertyName */ && ! isWellKnownSymbolSyntactically ( declaration . name . expression ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Based heavily on the abstract Quote / QuoteJSONString operation from ECMA - 262 ( 24 . 3 . 2 . 2 ) but augmented for a few select characters ( e . g . lineSeparator paragraphSeparator nextLine ) Note that this doesn t actually wrap the input in double quotes . [CODESPLIT] function escapeString ( s ) { s = escapedCharsRegExp . test ( s ) ? s . replace ( escapedCharsRegExp , getReplacement ) : s ; return s ; function getReplacement ( c ) { return escapedCharsMap [ c ] || get16BitUnicodeEscapeSequence ( c . charCodeAt ( 0 ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace each instance of non - ascii characters by one two three or four escape sequences representing the UTF - 8 encoding of the character and return the expanded char code list . [CODESPLIT] function getExpandedCharCodes ( input ) { var output = [ ] ; var length = input . length ; for ( var i = 0 ; i < length ; i ++ ) { var charCode = input . charCodeAt ( i ) ; // handel utf8 if ( charCode < 0x80 ) { output . push ( charCode ) ; } else if ( charCode < 0x800 ) { output . push ( ( charCode >> 6 ) | 192 ) ; output . push ( ( charCode & 63 ) | 128 ) ; } else if ( charCode < 0x10000 ) { output . push ( ( charCode >> 12 ) | 224 ) ; output . push ( ( ( charCode >> 6 ) & 63 ) | 128 ) ; output . push ( ( charCode & 63 ) | 128 ) ; } else if ( charCode < 0x20000 ) { output . push ( ( charCode >> 18 ) | 240 ) ; output . push ( ( ( charCode >> 12 ) & 63 ) | 128 ) ; output . push ( ( ( charCode >> 6 ) & 63 ) | 128 ) ; output . push ( ( charCode & 63 ) | 128 ) ; } else { ts . Debug . assert ( false , \"Unexpected code point\" ) ; } } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if span contains other . [CODESPLIT] function textSpanContainsTextSpan ( span , other ) { return other . start >= span . start && textSpanEnd ( other ) <= textSpanEnd ( span ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes a callback for each child of the given node . The cbNode callback is invoked for all child nodes stored in properties . If a cbNodes callback is specified it is invoked for embedded arrays ; otherwise embedded arrays are flattened and the cbNode callback is invoked for each element . If a callback returns a truthy value iteration stops and that value is returned . Otherwise undefined is returned . [CODESPLIT] function forEachChild ( node , cbNode , cbNodeArray ) { if ( ! node ) { return ; } // The visitXXX functions could be written as local functions that close over the cbNode and cbNodeArray // callback parameters, but that causes a closure allocation for each invocation with noticeable effects // on performance. var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode ; var cbNodes = cbNodeArray || cbNode ; switch ( node . kind ) { case 135 /* QualifiedName */ : return visitNode ( cbNode , node . left ) || visitNode ( cbNode , node . right ) ; case 137 /* TypeParameter */ : return visitNode ( cbNode , node . name ) || visitNode ( cbNode , node . constraint ) || visitNode ( cbNode , node . expression ) ; case 246 /* ShorthandPropertyAssignment */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . name ) || visitNode ( cbNode , node . questionToken ) || visitNode ( cbNode , node . equalsToken ) || visitNode ( cbNode , node . objectAssignmentInitializer ) ; case 138 /* Parameter */ : case 141 /* PropertyDeclaration */ : case 140 /* PropertySignature */ : case 245 /* PropertyAssignment */ : case 211 /* VariableDeclaration */ : case 163 /* BindingElement */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . propertyName ) || visitNode ( cbNode , node . dotDotDotToken ) || visitNode ( cbNode , node . name ) || visitNode ( cbNode , node . questionToken ) || visitNode ( cbNode , node . type ) || visitNode ( cbNode , node . initializer ) ; case 152 /* FunctionType */ : case 153 /* ConstructorType */ : case 147 /* CallSignature */ : case 148 /* ConstructSignature */ : case 149 /* IndexSignature */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNodes ( cbNodes , node . typeParameters ) || visitNodes ( cbNodes , node . parameters ) || visitNode ( cbNode , node . type ) ; case 143 /* MethodDeclaration */ : case 142 /* MethodSignature */ : case 144 /* Constructor */ : case 145 /* GetAccessor */ : case 146 /* SetAccessor */ : case 173 /* FunctionExpression */ : case 213 /* FunctionDeclaration */ : case 174 /* ArrowFunction */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . asteriskToken ) || visitNode ( cbNode , node . name ) || visitNode ( cbNode , node . questionToken ) || visitNodes ( cbNodes , node . typeParameters ) || visitNodes ( cbNodes , node . parameters ) || visitNode ( cbNode , node . type ) || visitNode ( cbNode , node . equalsGreaterThanToken ) || visitNode ( cbNode , node . body ) ; case 151 /* TypeReference */ : return visitNode ( cbNode , node . typeName ) || visitNodes ( cbNodes , node . typeArguments ) ; case 150 /* TypePredicate */ : return visitNode ( cbNode , node . parameterName ) || visitNode ( cbNode , node . type ) ; case 154 /* TypeQuery */ : return visitNode ( cbNode , node . exprName ) ; case 155 /* TypeLiteral */ : return visitNodes ( cbNodes , node . members ) ; case 156 /* ArrayType */ : return visitNode ( cbNode , node . elementType ) ; case 157 /* TupleType */ : return visitNodes ( cbNodes , node . elementTypes ) ; case 158 /* UnionType */ : case 159 /* IntersectionType */ : return visitNodes ( cbNodes , node . types ) ; case 160 /* ParenthesizedType */ : return visitNode ( cbNode , node . type ) ; case 161 /* ObjectBindingPattern */ : case 162 /* ArrayBindingPattern */ : return visitNodes ( cbNodes , node . elements ) ; case 164 /* ArrayLiteralExpression */ : return visitNodes ( cbNodes , node . elements ) ; case 165 /* ObjectLiteralExpression */ : return visitNodes ( cbNodes , node . properties ) ; case 166 /* PropertyAccessExpression */ : return visitNode ( cbNode , node . expression ) || visitNode ( cbNode , node . dotToken ) || visitNode ( cbNode , node . name ) ; case 167 /* ElementAccessExpression */ : return visitNode ( cbNode , node . expression ) || visitNode ( cbNode , node . argumentExpression ) ; case 168 /* CallExpression */ : case 169 /* NewExpression */ : return visitNode ( cbNode , node . expression ) || visitNodes ( cbNodes , node . typeArguments ) || visitNodes ( cbNodes , node . arguments ) ; case 170 /* TaggedTemplateExpression */ : return visitNode ( cbNode , node . tag ) || visitNode ( cbNode , node . template ) ; case 171 /* TypeAssertionExpression */ : return visitNode ( cbNode , node . type ) || visitNode ( cbNode , node . expression ) ; case 172 /* ParenthesizedExpression */ : return visitNode ( cbNode , node . expression ) ; case 175 /* DeleteExpression */ : return visitNode ( cbNode , node . expression ) ; case 176 /* TypeOfExpression */ : return visitNode ( cbNode , node . expression ) ; case 177 /* VoidExpression */ : return visitNode ( cbNode , node . expression ) ; case 179 /* PrefixUnaryExpression */ : return visitNode ( cbNode , node . operand ) ; case 184 /* YieldExpression */ : return visitNode ( cbNode , node . asteriskToken ) || visitNode ( cbNode , node . expression ) ; case 178 /* AwaitExpression */ : return visitNode ( cbNode , node . expression ) ; case 180 /* PostfixUnaryExpression */ : return visitNode ( cbNode , node . operand ) ; case 181 /* BinaryExpression */ : return visitNode ( cbNode , node . left ) || visitNode ( cbNode , node . operatorToken ) || visitNode ( cbNode , node . right ) ; case 189 /* AsExpression */ : return visitNode ( cbNode , node . expression ) || visitNode ( cbNode , node . type ) ; case 182 /* ConditionalExpression */ : return visitNode ( cbNode , node . condition ) || visitNode ( cbNode , node . questionToken ) || visitNode ( cbNode , node . whenTrue ) || visitNode ( cbNode , node . colonToken ) || visitNode ( cbNode , node . whenFalse ) ; case 185 /* SpreadElementExpression */ : return visitNode ( cbNode , node . expression ) ; case 192 /* Block */ : case 219 /* ModuleBlock */ : return visitNodes ( cbNodes , node . statements ) ; case 248 /* SourceFile */ : return visitNodes ( cbNodes , node . statements ) || visitNode ( cbNode , node . endOfFileToken ) ; case 193 /* VariableStatement */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . declarationList ) ; case 212 /* VariableDeclarationList */ : return visitNodes ( cbNodes , node . declarations ) ; case 195 /* ExpressionStatement */ : return visitNode ( cbNode , node . expression ) ; case 196 /* IfStatement */ : return visitNode ( cbNode , node . expression ) || visitNode ( cbNode , node . thenStatement ) || visitNode ( cbNode , node . elseStatement ) ; case 197 /* DoStatement */ : return visitNode ( cbNode , node . statement ) || visitNode ( cbNode , node . expression ) ; case 198 /* WhileStatement */ : return visitNode ( cbNode , node . expression ) || visitNode ( cbNode , node . statement ) ; case 199 /* ForStatement */ : return visitNode ( cbNode , node . initializer ) || visitNode ( cbNode , node . condition ) || visitNode ( cbNode , node . incrementor ) || visitNode ( cbNode , node . statement ) ; case 200 /* ForInStatement */ : return visitNode ( cbNode , node . initializer ) || visitNode ( cbNode , node . expression ) || visitNode ( cbNode , node . statement ) ; case 201 /* ForOfStatement */ : return visitNode ( cbNode , node . initializer ) || visitNode ( cbNode , node . expression ) || visitNode ( cbNode , node . statement ) ; case 202 /* ContinueStatement */ : case 203 /* BreakStatement */ : return visitNode ( cbNode , node . label ) ; case 204 /* ReturnStatement */ : return visitNode ( cbNode , node . expression ) ; case 205 /* WithStatement */ : return visitNode ( cbNode , node . expression ) || visitNode ( cbNode , node . statement ) ; case 206 /* SwitchStatement */ : return visitNode ( cbNode , node . expression ) || visitNode ( cbNode , node . caseBlock ) ; case 220 /* CaseBlock */ : return visitNodes ( cbNodes , node . clauses ) ; case 241 /* CaseClause */ : return visitNode ( cbNode , node . expression ) || visitNodes ( cbNodes , node . statements ) ; case 242 /* DefaultClause */ : return visitNodes ( cbNodes , node . statements ) ; case 207 /* LabeledStatement */ : return visitNode ( cbNode , node . label ) || visitNode ( cbNode , node . statement ) ; case 208 /* ThrowStatement */ : return visitNode ( cbNode , node . expression ) ; case 209 /* TryStatement */ : return visitNode ( cbNode , node . tryBlock ) || visitNode ( cbNode , node . catchClause ) || visitNode ( cbNode , node . finallyBlock ) ; case 244 /* CatchClause */ : return visitNode ( cbNode , node . variableDeclaration ) || visitNode ( cbNode , node . block ) ; case 139 /* Decorator */ : return visitNode ( cbNode , node . expression ) ; case 214 /* ClassDeclaration */ : case 186 /* ClassExpression */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . name ) || visitNodes ( cbNodes , node . typeParameters ) || visitNodes ( cbNodes , node . heritageClauses ) || visitNodes ( cbNodes , node . members ) ; case 215 /* InterfaceDeclaration */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . name ) || visitNodes ( cbNodes , node . typeParameters ) || visitNodes ( cbNodes , node . heritageClauses ) || visitNodes ( cbNodes , node . members ) ; case 216 /* TypeAliasDeclaration */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . name ) || visitNodes ( cbNodes , node . typeParameters ) || visitNode ( cbNode , node . type ) ; case 217 /* EnumDeclaration */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . name ) || visitNodes ( cbNodes , node . members ) ; case 247 /* EnumMember */ : return visitNode ( cbNode , node . name ) || visitNode ( cbNode , node . initializer ) ; case 218 /* ModuleDeclaration */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . name ) || visitNode ( cbNode , node . body ) ; case 221 /* ImportEqualsDeclaration */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . name ) || visitNode ( cbNode , node . moduleReference ) ; case 222 /* ImportDeclaration */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . importClause ) || visitNode ( cbNode , node . moduleSpecifier ) ; case 223 /* ImportClause */ : return visitNode ( cbNode , node . name ) || visitNode ( cbNode , node . namedBindings ) ; case 224 /* NamespaceImport */ : return visitNode ( cbNode , node . name ) ; case 225 /* NamedImports */ : case 229 /* NamedExports */ : return visitNodes ( cbNodes , node . elements ) ; case 228 /* ExportDeclaration */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . exportClause ) || visitNode ( cbNode , node . moduleSpecifier ) ; case 226 /* ImportSpecifier */ : case 230 /* ExportSpecifier */ : return visitNode ( cbNode , node . propertyName ) || visitNode ( cbNode , node . name ) ; case 227 /* ExportAssignment */ : return visitNodes ( cbNodes , node . decorators ) || visitNodes ( cbNodes , node . modifiers ) || visitNode ( cbNode , node . expression ) ; case 183 /* TemplateExpression */ : return visitNode ( cbNode , node . head ) || visitNodes ( cbNodes , node . templateSpans ) ; case 190 /* TemplateSpan */ : return visitNode ( cbNode , node . expression ) || visitNode ( cbNode , node . literal ) ; case 136 /* ComputedPropertyName */ : return visitNode ( cbNode , node . expression ) ; case 243 /* HeritageClause */ : return visitNodes ( cbNodes , node . types ) ; case 188 /* ExpressionWithTypeArguments */ : return visitNode ( cbNode , node . expression ) || visitNodes ( cbNodes , node . typeArguments ) ; case 232 /* ExternalModuleReference */ : return visitNode ( cbNode , node . expression ) ; case 231 /* MissingDeclaration */ : return visitNodes ( cbNodes , node . decorators ) ; case 233 /* JsxElement */ : return visitNode ( cbNode , node . openingElement ) || visitNodes ( cbNodes , node . children ) || visitNode ( cbNode , node . closingElement ) ; case 234 /* JsxSelfClosingElement */ : case 235 /* JsxOpeningElement */ : return visitNode ( cbNode , node . tagName ) || visitNodes ( cbNodes , node . attributes ) ; case 238 /* JsxAttribute */ : return visitNode ( cbNode , node . name ) || visitNode ( cbNode , node . initializer ) ; case 239 /* JsxSpreadAttribute */ : return visitNode ( cbNode , node . expression ) ; case 240 /* JsxExpression */ : return visitNode ( cbNode , node . expression ) ; case 237 /* JsxClosingElement */ : return visitNode ( cbNode , node . tagName ) ; case 249 /* JSDocTypeExpression */ : return visitNode ( cbNode , node . type ) ; case 253 /* JSDocUnionType */ : return visitNodes ( cbNodes , node . types ) ; case 254 /* JSDocTupleType */ : return visitNodes ( cbNodes , node . types ) ; case 252 /* JSDocArrayType */ : return visitNode ( cbNode , node . elementType ) ; case 256 /* JSDocNonNullableType */ : return visitNode ( cbNode , node . type ) ; case 255 /* JSDocNullableType */ : return visitNode ( cbNode , node . type ) ; case 257 /* JSDocRecordType */ : return visitNodes ( cbNodes , node . members ) ; case 259 /* JSDocTypeReference */ : return visitNode ( cbNode , node . name ) || visitNodes ( cbNodes , node . typeArguments ) ; case 260 /* JSDocOptionalType */ : return visitNode ( cbNode , node . type ) ; case 261 /* JSDocFunctionType */ : return visitNodes ( cbNodes , node . parameters ) || visitNode ( cbNode , node . type ) ; case 262 /* JSDocVariadicType */ : return visitNode ( cbNode , node . type ) ; case 263 /* JSDocConstructorType */ : return visitNode ( cbNode , node . type ) ; case 264 /* JSDocThisType */ : return visitNode ( cbNode , node . type ) ; case 258 /* JSDocRecordMember */ : return visitNode ( cbNode , node . name ) || visitNode ( cbNode , node . type ) ; case 265 /* JSDocComment */ : return visitNodes ( cbNodes , node . tags ) ; case 267 /* JSDocParameterTag */ : return visitNode ( cbNode , node . preParameterName ) || visitNode ( cbNode , node . typeExpression ) || visitNode ( cbNode , node . postParameterName ) ; case 268 /* JSDocReturnTag */ : return visitNode ( cbNode , node . typeExpression ) ; case 269 /* JSDocTypeTag */ : return visitNode ( cbNode , node . typeExpression ) ; case 270 /* JSDocTemplateTag */ : return visitNodes ( cbNodes , node . typeParameters ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Produces a new SourceFile for the newText provided . The textChangeRange parameter indicates what changed between the text that this SourceFile has and the newText . The SourceFile will be created with the compiler attempting to reuse as many nodes from this file as possible . Note : this function mutates nodes from this SourceFile . That means any existing nodes from this SourceFile that are being held onto may change as a result ( including becoming detached from any SourceFile ) . It is recommended that this SourceFile not be used once update is called on it . [CODESPLIT] function updateSourceFile ( sourceFile , newText , textChangeRange , aggressiveChecks ) { return IncrementalParser . updateSourceFile ( sourceFile , newText , textChangeRange , aggressiveChecks ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function parseIsolatedJSDocComment ( content , start , length ) { return Parser . JSDocParser . parseIsolatedJSDocComment ( content , start , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues with magic property names like __proto__ . The identifiers object is used to share a single string instance for each identifier in order to reduce memory consumption . [CODESPLIT] function createIdentifier ( isIdentifier , diagnosticMessage ) { identifierCount ++ ; if ( isIdentifier ) { var node = createNode ( 69 /* Identifier */ ) ; // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker if ( token !== 69 /* Identifier */ ) { node . originalKeywordKind = token ; } node . text = internIdentifier ( scanner . getTokenValue ( ) ) ; nextToken ( ) ; return finishNode ( node ) ; } return createMissingNode ( 69 /* Identifier */ , /*reportAtCurrentPosition*/ false , diagnosticMessage || ts . Diagnostics . Identifier_expected ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "True if positioned at a list terminator [CODESPLIT] function isListTerminator ( kind ) { if ( token === 1 /* EndOfFileToken */ ) { // Being at the end of the file ends all lists. return true ; } switch ( kind ) { case 1 /* BlockStatements */ : case 2 /* SwitchClauses */ : case 4 /* TypeMembers */ : case 5 /* ClassMembers */ : case 6 /* EnumMembers */ : case 12 /* ObjectLiteralMembers */ : case 9 /* ObjectBindingElements */ : case 21 /* ImportOrExportSpecifiers */ : return token === 16 /* CloseBraceToken */ ; case 3 /* SwitchClauseStatements */ : return token === 16 /* CloseBraceToken */ || token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */ ; case 7 /* HeritageClauseElement */ : return token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */ ; case 8 /* VariableDeclarations */ : return isVariableDeclaratorListTerminator ( ) ; case 17 /* TypeParameters */ : // Tokens other than '>' are here for better error recovery return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */ || token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */ ; case 11 /* ArgumentExpressions */ : // Tokens other than ')' are here for better error recovery return token === 18 /* CloseParenToken */ || token === 23 /* SemicolonToken */ ; case 15 /* ArrayLiteralMembers */ : case 19 /* TupleElementTypes */ : case 10 /* ArrayBindingElements */ : return token === 20 /* CloseBracketToken */ ; case 16 /* Parameters */ : // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token === 18 /* CloseParenToken */ || token === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/ ; case 18 /* TypeArguments */ : // Tokens other than '>' are here for better error recovery return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */ ; case 20 /* HeritageClauses */ : return token === 15 /* OpenBraceToken */ || token === 16 /* CloseBraceToken */ ; case 13 /* JsxAttributes */ : return token === 27 /* GreaterThanToken */ || token === 39 /* SlashToken */ ; case 14 /* JsxChildren */ : return token === 25 /* LessThanToken */ && lookAhead ( nextTokenIsSlash ) ; case 22 /* JSDocFunctionParameters */ : return token === 18 /* CloseParenToken */ || token === 54 /* ColonToken */ || token === 16 /* CloseBraceToken */ ; case 23 /* JSDocTypeArguments */ : return token === 27 /* GreaterThanToken */ || token === 16 /* CloseBraceToken */ ; case 25 /* JSDocTupleTypes */ : return token === 20 /* CloseBracketToken */ || token === 16 /* CloseBraceToken */ ; case 24 /* JSDocRecordMembers */ : return token === 16 /* CloseBraceToken */ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The allowReservedWords parameter controls whether reserved words are permitted after the first dot [CODESPLIT] function parseEntityName ( allowReservedWords , diagnosticMessage ) { var entity = parseIdentifier ( diagnosticMessage ) ; while ( parseOptional ( 21 /* DotToken */ ) ) { var node = createNode ( 135 /* QualifiedName */ , entity . pos ) ; node . left = entity ; node . right = parseRightSideOfDot ( allowReservedWords ) ; entity = finishNode ( node ) ; } return entity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TYPES [CODESPLIT] function parseTypeReferenceOrTypePredicate ( ) { var typeName = parseEntityName ( /*allowReservedWords*/ false , ts . Diagnostics . Type_expected ) ; if ( typeName . kind === 69 /* Identifier */ && token === 124 /* IsKeyword */ && ! scanner . hasPrecedingLineBreak ( ) ) { nextToken ( ) ; var node_1 = createNode ( 150 /* TypePredicate */ , typeName . pos ) ; node_1 . parameterName = typeName ; node_1 . type = parseType ( ) ; return finishNode ( node_1 ) ; } var node = createNode ( 151 /* TypeReference */ , typeName . pos ) ; node . typeName = typeName ; if ( ! scanner . hasPrecedingLineBreak ( ) && token === 25 /* LessThanToken */ ) { node . typeArguments = parseBracketedList ( 18 /* TypeArguments */ , parseType , 25 /* LessThanToken */ , 27 /* GreaterThanToken */ ) ; } return finishNode ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "STATEMENTS [CODESPLIT] function parseBlock ( ignoreMissingOpenBrace , diagnosticMessage ) { var node = createNode ( 192 /* Block */ ) ; if ( parseExpected ( 15 /* OpenBraceToken */ , diagnosticMessage ) || ignoreMissingOpenBrace ) { node . statements = parseList ( 1 /* BlockStatements */ , parseStatement ) ; parseExpected ( 16 /* CloseBraceToken */ ) ; } else { node . statements = createMissingList ( ) ; } return finishNode ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Review for error recovery [CODESPLIT] function parseTryStatement ( ) { var node = createNode ( 209 /* TryStatement */ ) ; parseExpected ( 100 /* TryKeyword */ ) ; node . tryBlock = parseBlock ( /*ignoreMissingOpenBrace*/ false ) ; node . catchClause = token === 72 /* CatchKeyword */ ? parseCatchClause ( ) : undefined ; // If we don't have a catch clause, then we must have a finally clause.  Try to parse // one out no matter what. if ( ! node . catchClause || token === 85 /* FinallyKeyword */ ) { parseExpected ( 85 /* FinallyKeyword */ ) ; node . finallyBlock = parseBlock ( /*ignoreMissingOpenBrace*/ false ) ; } return finishNode ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DECLARATIONS [CODESPLIT] function parseArrayBindingElement ( ) { if ( token === 24 /* CommaToken */ ) { return createNode ( 187 /* OmittedExpression */ ) ; } var node = createNode ( 163 /* BindingElement */ ) ; node . dotDotDotToken = parseOptionalToken ( 22 /* DotDotDotToken */ ) ; node . name = parseIdentifierOrPattern ( ) ; node . initializer = parseBindingElementInitializer ( /*inParameter*/ false ) ; return finishNode ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses out a JSDoc type expression . The starting position should be right at the open curly in the type expression . Returns undefined if it encounters any errors while parsing . / * [CODESPLIT] function parseJSDocTypeExpression ( start , length ) { scanner . setText ( sourceText , start , length ) ; // Prime the first token for us to start processing. token = nextToken ( ) ; var result = createNode ( 249 /* JSDocTypeExpression */ ) ; parseExpected ( 15 /* OpenBraceToken */ ) ; result . type = parseJSDocTopLevelType ( ) ; parseExpected ( 16 /* CloseBraceToken */ ) ; fixupParentReferences ( result ) ; return finishNode ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the highest element in the tree we can find that starts at the provided position . The element must be a direct child of some node list in the tree . This way after we return it we can easily return its next sibling in the list . [CODESPLIT] function findHighestListElementThatStartsAtPosition ( position ) { // Clear out any cached state about the last node we found. currentArray = undefined ; currentArrayIndex = - 1 /* Value */ ; current = undefined ; // Recurse into the source file to find the highest node at this position. forEachChild ( sourceFile , visitNode , visitArray ) ; return ; function visitNode ( node ) { if ( position >= node . pos && position < node . end ) { // Position was within this node.  Keep searching deeper to find the node. forEachChild ( node , visitNode , visitArray ) ; // don't procede any futher in the search. return true ; } // position wasn't in this node, have to keep searching. return false ; } function visitArray ( array ) { if ( position >= array . pos && position < array . end ) { // position was in this array.  Search through this array to see if we find a // viable element. for ( var i = 0 , n = array . length ; i < n ; i ++ ) { var child = array [ i ] ; if ( child ) { if ( child . pos === position ) { // Found the right node.  We're done. currentArray = array ; currentArrayIndex = i ; current = child ; return true ; } else { if ( child . pos < position && position < child . end ) { // Position in somewhere within this child.  Search in it and // stop searching in this array. forEachChild ( child , visitNode , visitArray ) ; return true ; } } } } } // position wasn't in this array, have to keep searching. return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve a given name for a given meaning at a given location . An error is reported if the name was not found and the nameNotFoundMessage argument is not undefined . Returns the resolved symbol or undefined if no symbol with the given name can be found . [CODESPLIT] function resolveName ( location , name , meaning , nameNotFoundMessage , nameArg ) { var result ; var lastLocation ; var propertyWithInvalidInitializer ; var errorLocation = location ; var grandparent ; loop : while ( location ) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if ( location . locals && ! isGlobalSourceFile ( location ) ) { if ( result = getSymbol ( location . locals , name , meaning ) ) { // Type parameters of a function are in scope in the entire function declaration, including the parameter // list and return type. However, local types are only in scope in the function body. if ( ! ( meaning & 793056 /* Type */ ) || ! ( result . flags & ( 793056 /* Type */ & ~ 262144 /* TypeParameter */ ) ) || ! ts . isFunctionLike ( location ) || lastLocation === location . body ) { break loop ; } result = undefined ; } } switch ( location . kind ) { case 248 /* SourceFile */ : if ( ! ts . isExternalModule ( location ) ) break ; case 218 /* ModuleDeclaration */ : var moduleExports = getSymbolOfNode ( location ) . exports ; if ( location . kind === 248 /* SourceFile */ || ( location . kind === 218 /* ModuleDeclaration */ && location . name . kind === 9 /* StringLiteral */ ) ) { // It's an external module. Because of module/namespace merging, a module's exports are in scope, // yet we never want to treat an export specifier as putting a member in scope. Therefore, // if the name we find is purely an export specifier, it is not actually considered in scope. // Two things to note about this: //     1. We have to check this without calling getSymbol. The problem with calling getSymbol //        on an export specifier is that it might find the export specifier itself, and try to //        resolve it as an alias. This will cause the checker to consider the export specifier //        a circular alias reference when it might not be. //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects, //        which is not the desired behavior. if ( ts . hasProperty ( moduleExports , name ) && moduleExports [ name ] . flags === 8388608 /* Alias */ && ts . getDeclarationOfKind ( moduleExports [ name ] , 230 /* ExportSpecifier */ ) ) { break ; } result = moduleExports [ \"default\" ] ; var localSymbol = ts . getLocalSymbolForExportDefault ( result ) ; if ( result && localSymbol && ( result . flags & meaning ) && localSymbol . name === name ) { break loop ; } result = undefined ; } if ( result = getSymbol ( moduleExports , name , meaning & 8914931 /* ModuleMember */ ) ) { break loop ; } break ; case 217 /* EnumDeclaration */ : if ( result = getSymbol ( getSymbolOfNode ( location ) . exports , name , meaning & 8 /* EnumMember */ ) ) { break loop ; } break ; case 141 /* PropertyDeclaration */ : case 140 /* PropertySignature */ : // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. if ( ts . isClassLike ( location . parent ) && ! ( location . flags & 128 /* Static */ ) ) { var ctor = findConstructorDeclaration ( location . parent ) ; if ( ctor && ctor . locals ) { if ( getSymbol ( ctor . locals , name , meaning & 107455 /* Value */ ) ) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location ; } } } break ; case 214 /* ClassDeclaration */ : case 186 /* ClassExpression */ : case 215 /* InterfaceDeclaration */ : if ( result = getSymbol ( getSymbolOfNode ( location ) . members , name , meaning & 793056 /* Type */ ) ) { if ( lastLocation && lastLocation . flags & 128 /* Static */ ) { // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type // parameter list is associated, with the exception of static member declarations in classes. error ( errorLocation , ts . Diagnostics . Static_members_cannot_reference_class_type_parameters ) ; return undefined ; } break loop ; } if ( location . kind === 186 /* ClassExpression */ && meaning & 32 /* Class */ ) { var className = location . name ; if ( className && name === className . text ) { result = location . symbol ; break loop ; } } break ; // It is not legal to reference a class's own type parameters from a computed property name that // belongs to the class. For example: // //   function foo<T>() { return '' } //   class C<T> { // <-- Class's own type parameter T //       [foo<T>()]() { } // <-- Reference to T from class's own computed property //   } // case 136 /* ComputedPropertyName */ : grandparent = location . parent . parent ; if ( ts . isClassLike ( grandparent ) || grandparent . kind === 215 /* InterfaceDeclaration */ ) { // A reference to this grandparent's type parameters would be an error if ( result = getSymbol ( getSymbolOfNode ( grandparent ) . members , name , meaning & 793056 /* Type */ ) ) { error ( errorLocation , ts . Diagnostics . A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type ) ; return undefined ; } } break ; case 143 /* MethodDeclaration */ : case 142 /* MethodSignature */ : case 144 /* Constructor */ : case 145 /* GetAccessor */ : case 146 /* SetAccessor */ : case 213 /* FunctionDeclaration */ : case 174 /* ArrowFunction */ : if ( meaning & 3 /* Variable */ && name === \"arguments\" ) { result = argumentsSymbol ; break loop ; } break ; case 173 /* FunctionExpression */ : if ( meaning & 3 /* Variable */ && name === \"arguments\" ) { result = argumentsSymbol ; break loop ; } if ( meaning & 16 /* Function */ ) { var functionName = location . name ; if ( functionName && name === functionName . text ) { result = location . symbol ; break loop ; } } break ; case 139 /* Decorator */ : // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // //   function y() {} //   class C { //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. //   } // if ( location . parent && location . parent . kind === 138 /* Parameter */ ) { location = location . parent ; } // //   function y() {} //   class C { //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. //   } // if ( location . parent && ts . isClassElement ( location . parent ) ) { location = location . parent ; } break ; } lastLocation = location ; location = location . parent ; } if ( ! result ) { result = getSymbol ( globals , name , meaning ) ; } if ( ! result ) { if ( nameNotFoundMessage ) { error ( errorLocation , nameNotFoundMessage , typeof nameArg === \"string\" ? nameArg : ts . declarationNameToString ( nameArg ) ) ; } return undefined ; } // Perform extra checks only if error reporting was requested if ( nameNotFoundMessage ) { if ( propertyWithInvalidInitializer ) { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. var propertyName = propertyWithInvalidInitializer . name ; error ( errorLocation , ts . Diagnostics . Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor , ts . declarationNameToString ( propertyName ) , typeof nameArg === \"string\" ? nameArg : ts . declarationNameToString ( nameArg ) ) ; return undefined ; } // Only check for block-scoped variable if we are looking for the // name with variable meaning //      For example, //          declare module foo { //              interface bar {} //          } //      let foo/*1*/: foo/*2*/.bar; // The foo at /*1*/ and /*2*/ will share same symbol with two meaning // block - scope variable and namespace module. However, only when we // try to resolve name in /*1*/ which is used in variable position, // we want to check for block- scoped if ( meaning & 2 /* BlockScopedVariable */ ) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported ( result ) ; if ( exportOrLocalSymbol . flags & 2 /* BlockScopedVariable */ ) { checkResolvedBlockScopedVariable ( exportOrLocalSymbol , errorLocation ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Starting from initial node walk up the parent chain until stopAt node is reached . If at any point current node is equal to parent node - return true . Return false if stopAt node is reached or isFunctionLike ( current ) === true . [CODESPLIT] function isSameScopeDescendentOf ( initial , parent , stopAt ) { if ( ! parent ) { return false ; } for ( var current = initial ; current && current !== stopAt && ! ts . isFunctionLike ( current ) ; current = current . parent ) { if ( current === parent ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function creates a synthetic symbol that combines the value side of one symbol with the type / namespace side of another symbol . Consider this example : declare module graphics { interface Point { x : number ; y : number ; } } declare var graphics : { Point : new ( x : number y : number ) = > graphics . Point ; } declare module graphics { export = graphics ; } An import { Point } from graphics needs to create a symbol that combines the value side Point property with the type / namespace side interface Point . [CODESPLIT] function combineValueAndTypeSymbols ( valueSymbol , typeSymbol ) { if ( valueSymbol . flags & ( 793056 /* Type */ | 1536 /* Namespace */ ) ) { return valueSymbol ; } var result = createSymbol ( valueSymbol . flags | typeSymbol . flags , valueSymbol . name ) ; result . declarations = ts . concatenate ( valueSymbol . declarations , typeSymbol . declarations ) ; result . parent = valueSymbol . parent || typeSymbol . parent ; if ( valueSymbol . valueDeclaration ) result . valueDeclaration = valueSymbol . valueDeclaration ; if ( typeSymbol . members ) result . members = typeSymbol . members ; if ( valueSymbol . exports ) result . exports = valueSymbol . exports ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When an alias symbol is referenced we need to mark the entity it references as referenced and in turn repeat that until we reach a non - alias or an exported entity ( which is always considered referenced ) . We do this by checking the target of the alias as an expression ( which recursively takes us back here if the target references another alias ) . [CODESPLIT] function markAliasSymbolAsReferenced ( symbol ) { var links = getSymbolLinks ( symbol ) ; if ( ! links . referenced ) { links . referenced = true ; var node = getDeclarationOfAliasSymbol ( symbol ) ; if ( node . kind === 227 /* ExportAssignment */ ) { // export default <symbol> checkExpressionCached ( node . expression ) ; } else if ( node . kind === 230 /* ExportSpecifier */ ) { // export { <symbol> } or export { <symbol> as foo } checkExpressionCached ( node . propertyName || node . name ) ; } else if ( ts . isInternalModuleImportEqualsDeclaration ( node ) ) { // import foo = <symbol> checkExpressionCached ( node . moduleReference ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function is only for imports with entity names [CODESPLIT] function getSymbolOfPartOfRightHandSideOfImportEquals ( entityName , importDeclaration ) { if ( ! importDeclaration ) { importDeclaration = ts . getAncestor ( entityName , 221 /* ImportEqualsDeclaration */ ) ; ts . Debug . assert ( importDeclaration !== undefined ) ; } // There are three things we might try to look for. In the following examples, // the search term is enclosed in |...|: // //     import a = |b|; // Namespace //     import a = |b.c|; // Value, type, namespace //     import a = |b.c|.d; // Namespace if ( entityName . kind === 69 /* Identifier */ && ts . isRightSideOfQualifiedNameOrPropertyAccess ( entityName ) ) { entityName = entityName . parent ; } // Check for case 1 and 3 in the above example if ( entityName . kind === 69 /* Identifier */ || entityName . parent . kind === 135 /* QualifiedName */ ) { return resolveEntityName ( entityName , 1536 /* Namespace */ ) ; } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts . Debug . assert ( entityName . parent . kind === 221 /* ImportEqualsDeclaration */ ) ; return resolveEntityName ( entityName , 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves a qualified name and any involved aliases [CODESPLIT] function resolveEntityName ( name , meaning , ignoreErrors ) { if ( ts . nodeIsMissing ( name ) ) { return undefined ; } var symbol ; if ( name . kind === 69 /* Identifier */ ) { var message = meaning === 1536 /* Namespace */ ? ts . Diagnostics . Cannot_find_namespace_0 : ts . Diagnostics . Cannot_find_name_0 ; symbol = resolveName ( name , name . text , meaning , ignoreErrors ? undefined : message , name ) ; if ( ! symbol ) { return undefined ; } } else if ( name . kind === 135 /* QualifiedName */ || name . kind === 166 /* PropertyAccessExpression */ ) { var left = name . kind === 135 /* QualifiedName */ ? name . left : name . expression ; var right = name . kind === 135 /* QualifiedName */ ? name . right : name . name ; var namespace = resolveEntityName ( left , 1536 /* Namespace */ , ignoreErrors ) ; if ( ! namespace || namespace === unknownSymbol || ts . nodeIsMissing ( right ) ) { return undefined ; } symbol = getSymbol ( getExportsOfSymbol ( namespace ) , right . text , meaning ) ; if ( ! symbol ) { if ( ! ignoreErrors ) { error ( right , ts . Diagnostics . Module_0_has_no_exported_member_1 , getFullyQualifiedName ( namespace ) , ts . declarationNameToString ( right ) ) ; } return undefined ; } } else { ts . Debug . fail ( \"Unknown entity name kind.\" ) ; } ts . Debug . assert ( ( symbol . flags & 16777216 /* Instantiated */ ) === 0 , \"Should never get an instantiated symbol here.\" ) ; return symbol . flags & meaning ? symbol : resolveAlias ( symbol ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An external module with an export = declaration may be referenced as an ES6 module provided the export = references a symbol that is at least declared as a module or a variable . The target of the export = may combine other declarations with the module or variable ( e . g . a class / module function / module interface / variable ) . [CODESPLIT] function resolveESModuleSymbol ( moduleSymbol , moduleReferenceExpression ) { var symbol = resolveExternalModuleSymbol ( moduleSymbol ) ; if ( symbol && ! ( symbol . flags & ( 1536 /* Module */ | 3 /* Variable */ ) ) ) { error ( moduleReferenceExpression , ts . Diagnostics . Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct , symbolToString ( moduleSymbol ) ) ; symbol = undefined ; } return symbol ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A reserved member name starts with two underscores but the third character cannot be an underscore or the [CODESPLIT] function isReservedMemberName ( name ) { return name . charCodeAt ( 0 ) === 95 /* _ */ && name . charCodeAt ( 1 ) === 95 /* _ */ && name . charCodeAt ( 2 ) !== 95 /* _ */ && name . charCodeAt ( 2 ) !== 64 /* at */ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the symbol is used in export assignment [CODESPLIT] function isSymbolUsedInExportAssignment ( symbol ) { if ( exportAssignmentSymbol === symbol ) { return true ; } if ( exportAssignmentSymbol && ! ! ( exportAssignmentSymbol . flags & 8388608 /* Alias */ ) ) { // if export assigned symbol is alias declaration, resolve the alias resolvedExportSymbol = resolvedExportSymbol || resolveAlias ( exportAssignmentSymbol ) ; if ( resolvedExportSymbol === symbol ) { return true ; } // Container of resolvedExportSymbol is visible return ts . forEach ( resolvedExportSymbol . declarations , function ( current ) { while ( current ) { if ( current === node ) { return true ; } current = current . parent ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the type of the given property in the given type or undefined if no such property exists [CODESPLIT] function getTypeOfPropertyOfType ( type , name ) { var prop = getPropertyOfType ( type , name ) ; return prop ? getTypeOfSymbol ( prop ) : undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the type of a binding element parent . We check SymbolLinks first to see if a type has been assigned by contextual typing . [CODESPLIT] function getTypeForBindingElementParent ( node ) { var symbol = getSymbolOfNode ( node ) ; return symbol && getSymbolLinks ( symbol ) . type || getTypeForVariableLikeDeclaration ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the inferred type for a binding element [CODESPLIT] function getTypeForBindingElement ( declaration ) { var pattern = declaration . parent ; var parentType = getTypeForBindingElementParent ( pattern . parent ) ; // If parent has the unknown (error) type, then so does this binding element if ( parentType === unknownType ) { return unknownType ; } // If no type was specified or inferred for parent, or if the specified or inferred type is any, // infer from the initializer of the binding element if one is present. Otherwise, go with the // undefined or any type of the parent. if ( ! parentType || isTypeAny ( parentType ) ) { if ( declaration . initializer ) { return checkExpressionCached ( declaration . initializer ) ; } return parentType ; } var type ; if ( pattern . kind === 161 /* ObjectBindingPattern */ ) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name_10 = declaration . propertyName || declaration . name ; // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. type = getTypeOfPropertyOfType ( parentType , name_10 . text ) || isNumericLiteralName ( name_10 . text ) && getIndexTypeOfType ( parentType , 1 /* Number */ ) || getIndexTypeOfType ( parentType , 0 /* String */ ) ; if ( ! type ) { error ( name_10 , ts . Diagnostics . Type_0_has_no_property_1_and_no_string_index_signature , typeToString ( parentType ) , ts . declarationNameToString ( name_10 ) ) ; return unknownType ; } } else { // This elementType will be used if the specific property corresponding to this index is not // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType ( parentType , pattern , /*allowStringInput*/ false ) ; if ( ! declaration . dotDotDotToken ) { // Use specific property type when parent is a tuple or numeric index type when parent is an array var propName = \"\" + ts . indexOf ( pattern . elements , declaration ) ; type = isTupleLikeType ( parentType ) ? getTypeOfPropertyOfType ( parentType , propName ) : elementType ; if ( ! type ) { if ( isTupleType ( parentType ) ) { error ( declaration , ts . Diagnostics . Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2 , typeToString ( parentType ) , parentType . elementTypes . length , pattern . elements . length ) ; } else { error ( declaration , ts . Diagnostics . Type_0_has_no_property_1 , typeToString ( parentType ) , propName ) ; } return unknownType ; } } else { // Rest element has an array type with the same element type as the parent type type = createArrayType ( elementType ) ; } } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the inferred type for a variable parameter or property declaration [CODESPLIT] function getTypeForVariableLikeDeclaration ( declaration ) { // A variable declared in a for..in statement is always of type any if ( declaration . parent . parent . kind === 200 /* ForInStatement */ ) { return anyType ; } if ( declaration . parent . parent . kind === 201 /* ForOfStatement */ ) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, // or it may have led to an error inside getElementTypeOfIterable. return checkRightHandSideOfForOf ( declaration . parent . parent . expression ) || anyType ; } if ( ts . isBindingPattern ( declaration . parent ) ) { return getTypeForBindingElement ( declaration ) ; } // Use type from type annotation if one is present if ( declaration . type ) { return getTypeFromTypeNode ( declaration . type ) ; } if ( declaration . kind === 138 /* Parameter */ ) { var func = declaration . parent ; // For a parameter of a set accessor, use the type of the get accessor if one is present if ( func . kind === 146 /* SetAccessor */ && ! ts . hasDynamicName ( func ) ) { var getter = ts . getDeclarationOfKind ( declaration . parent . symbol , 145 /* GetAccessor */ ) ; if ( getter ) { return getReturnTypeOfSignature ( getSignatureFromDeclaration ( getter ) ) ; } } // Use contextual parameter type if one is available var type = getContextuallyTypedParameterType ( declaration ) ; if ( type ) { return type ; } } // Use the type of the initializer expression if one is present if ( declaration . initializer ) { return checkExpressionCached ( declaration . initializer ) ; } // If it is a short-hand property assignment, use the type of the identifier if ( declaration . kind === 246 /* ShorthandPropertyAssignment */ ) { return checkIdentifier ( declaration . name ) ; } // If the declaration specifies a binding pattern, use the type implied by the binding pattern if ( ts . isBindingPattern ( declaration . name ) ) { return getTypeFromBindingPattern ( declaration . name , /*includePatternInType*/ false ) ; } // No type specified and nothing can be inferred return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the type implied by a binding pattern element . This is the type of the initializer of the element if one is present . Otherwise if the element is itself a binding pattern it is the type implied by the binding pattern . Otherwise it is the type any . [CODESPLIT] function getTypeFromBindingElement ( element , includePatternInType ) { if ( element . initializer ) { return getWidenedType ( checkExpressionCached ( element . initializer ) ) ; } if ( ts . isBindingPattern ( element . name ) ) { return getTypeFromBindingPattern ( element . name , includePatternInType ) ; } return anyType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the type implied by an object binding pattern [CODESPLIT] function getTypeFromObjectBindingPattern ( pattern , includePatternInType ) { var members = { } ; ts . forEach ( pattern . elements , function ( e ) { var flags = 4 /* Property */ | 67108864 /* Transient */ | ( e . initializer ? 536870912 /* Optional */ : 0 ) ; var name = e . propertyName || e . name ; var symbol = createSymbol ( flags , name . text ) ; symbol . type = getTypeFromBindingElement ( e , includePatternInType ) ; symbol . bindingElement = e ; members [ symbol . name ] = symbol ; } ) ; var result = createAnonymousType ( undefined , members , emptyArray , emptyArray , undefined , undefined ) ; if ( includePatternInType ) { result . pattern = pattern ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the type implied by a binding pattern . This is the type implied purely by the binding pattern itself and without regard to its context ( i . e . without regard any type annotation or initializer associated with the declaration in which the binding pattern is contained ) . For example the implied type of [ x y ] is [ any any ] and the implied type of { x y : z = 1 } is { x : any ; y : number ; } . The type implied by a binding pattern is used as the contextual type of an initializer associated with the binding pattern . Also for a destructuring parameter with no type annotation or initializer the type implied by the binding pattern becomes the type of the parameter . [CODESPLIT] function getTypeFromBindingPattern ( pattern , includePatternInType ) { return pattern . kind === 161 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern ( pattern , includePatternInType ) : getTypeFromArrayBindingPattern ( pattern , includePatternInType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the type associated with a variable parameter or property declaration . In the simple case this is the type specified in a type annotation or inferred from an initializer . However in the case of a destructuring declaration it is a bit more involved . For example : var [ x s = ] = [ 1 one ] ; Here the array literal [ 1 one ] is contextually typed by the type [ any string ] which is the implied type of the binding pattern [ x s = ] . Because the contextual type is a tuple type the resulting type of [ 1 one ] is the tuple type [ number string ] . Thus the type inferred for x is number and the type inferred for s is string . [CODESPLIT] function getWidenedTypeForVariableLikeDeclaration ( declaration , reportErrors ) { var type = getTypeForVariableLikeDeclaration ( declaration ) ; if ( type ) { if ( reportErrors ) { reportErrorsFromWidening ( declaration , type ) ; } // During a normal type check we'll never get to here with a property assignment (the check of the containing // object literal uses a different path). We exclude widening only so that language services and type verification // tools see the actual type. return declaration . kind !== 245 /* PropertyAssignment */ ? getWidenedType ( type ) : type ; } // Rest parameters default to type any[], other parameters default to type any type = declaration . dotDotDotToken ? anyArrayType : anyType ; // Report implicit any errors unless this is a private property within an ambient declaration if ( reportErrors && compilerOptions . noImplicitAny ) { var root = ts . getRootDeclaration ( declaration ) ; if ( ! isPrivateWithinAmbient ( root ) && ! ( root . kind === 138 /* Parameter */ && isPrivateWithinAmbient ( root . parent ) ) ) { reportImplicitAnyError ( declaration , type ) ; } } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The local type parameters are the combined set of type parameters from all declarations of the class interface or type alias . [CODESPLIT] function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias ( symbol ) { var result ; for ( var _i = 0 , _a = symbol . declarations ; _i < _a . length ; _i ++ ) { var node = _a [ _i ] ; if ( node . kind === 215 /* InterfaceDeclaration */ || node . kind === 214 /* ClassDeclaration */ || node . kind === 186 /* ClassExpression */ || node . kind === 216 /* TypeAliasDeclaration */ ) { var declaration = node ; if ( declaration . typeParameters ) { result = appendTypeParameters ( result , declaration . typeParameters ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The base constructor of a class can resolve to undefinedType if the class has no extends clause unknownType if an error occurred during resolution of the extends expression nullType if the extends expression is the null value or an object type with at least one construct signature . [CODESPLIT] function getBaseConstructorTypeOfClass ( type ) { if ( ! type . resolvedBaseConstructorType ) { var baseTypeNode = getBaseTypeNodeOfClass ( type ) ; if ( ! baseTypeNode ) { return type . resolvedBaseConstructorType = undefinedType ; } if ( ! pushTypeResolution ( type , 1 /* ResolvedBaseConstructorType */ ) ) { return unknownType ; } var baseConstructorType = checkExpression ( baseTypeNode . expression ) ; if ( baseConstructorType . flags & 80896 /* ObjectType */ ) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers ( baseConstructorType ) ; } if ( ! popTypeResolution ( ) ) { error ( type . symbol . valueDeclaration , ts . Diagnostics . _0_is_referenced_directly_or_indirectly_in_its_own_base_expression , symbolToString ( type . symbol ) ) ; return type . resolvedBaseConstructorType = unknownType ; } if ( baseConstructorType !== unknownType && baseConstructorType !== nullType && ! isConstructorType ( baseConstructorType ) ) { error ( baseTypeNode . expression , ts . Diagnostics . Type_0_is_not_a_constructor_function_type , typeToString ( baseConstructorType ) ) ; return type . resolvedBaseConstructorType = unknownType ; } type . resolvedBaseConstructorType = baseConstructorType ; } return type . resolvedBaseConstructorType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A type reference is considered independent if each type argument is considered independent . [CODESPLIT] function isIndependentTypeReference ( node ) { if ( node . typeArguments ) { for ( var _i = 0 , _a = node . typeArguments ; _i < _a . length ; _i ++ ) { var typeNode = _a [ _i ] ; if ( ! isIndependentType ( typeNode ) ) { return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A variable - like declaration is considered independent ( free of this references ) if it has a type annotation that specifies an independent type or if it has no type annotation and no initializer ( and thus of type any ) . [CODESPLIT] function isIndependentVariableLikeDeclaration ( node ) { return node . type && isIndependentType ( node . type ) || ! node . type && ! node . initializer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A function - like declaration is considered independent ( free of this references ) if it has a return type annotation that is considered independent and if each parameter is considered independent . [CODESPLIT] function isIndependentFunctionLikeDeclaration ( node ) { if ( node . kind !== 144 /* Constructor */ && ( ! node . type || ! isIndependentType ( node . type ) ) ) { return false ; } for ( var _i = 0 , _a = node . parameters ; _i < _a . length ; _i ++ ) { var parameter = _a [ _i ] ; if ( ! isIndependentVariableLikeDeclaration ( parameter ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The mappingThisOnly flag indicates that the only type parameter being mapped is this . When the flag is true we check symbols to see if we can quickly conclude they are free of this references thus needing no instantiation . [CODESPLIT] function createInstantiatedSymbolTable ( symbols , mapper , mappingThisOnly ) { var result = { } ; for ( var _i = 0 ; _i < symbols . length ; _i ++ ) { var symbol = symbols [ _i ] ; result [ symbol . name ] = mappingThisOnly && isIndependentMember ( symbol ) ? symbol : instantiateSymbol ( symbol , mapper ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The signatures of a union type are those signatures that are present in each of the constituent types . Generic signatures must match exactly but non - generic signatures are allowed to have extra optional parameters and may differ in return types . When signatures differ in return types the resulting return type is the union of the constituent return types . [CODESPLIT] function getUnionSignatures ( types , kind ) { var signatureLists = ts . map ( types , function ( t ) { return getSignaturesOfType ( t , kind ) ; } ) ; var result = undefined ; for ( var i = 0 ; i < signatureLists . length ; i ++ ) { for ( var _i = 0 , _a = signatureLists [ i ] ; _i < _a . length ; _i ++ ) { var signature = _a [ _i ] ; // Only process signatures with parameter lists that aren't already in the result list if ( ! result || ! findMatchingSignature ( result , signature , /*partialMatch*/ false , /*ignoreReturnTypes*/ true ) ) { var unionSignatures = findMatchingSignatures ( signatureLists , signature , i ) ; if ( unionSignatures ) { var s = signature ; // Union the result types when more than one signature matches if ( unionSignatures . length > 1 ) { s = cloneSignature ( signature ) ; // Clear resolved return type we possibly got from cloneSignature s . resolvedReturnType = undefined ; s . unionSignatures = unionSignatures ; } ( result || ( result = [ ] ) ) . push ( s ) ; } } } } return result || emptyArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the given type is an object type and that type has a property by the given name return the symbol for that property . Otherwise return undefined . [CODESPLIT] function getPropertyOfObjectType ( type , name ) { if ( type . flags & 80896 /* ObjectType */ ) { var resolved = resolveStructuredTypeMembers ( type ) ; if ( ts . hasProperty ( resolved . members , name ) ) { var symbol = resolved . members [ name ] ; if ( symbolIsValue ( symbol ) ) { return symbol ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a type parameter return the base constraint of the type parameter . For the string number boolean and symbol primitive types return the corresponding object types . Otherwise return the type itself . Note that the apparent type of a union type is the union type itself . [CODESPLIT] function getApparentType ( type ) { if ( type . flags & 512 /* TypeParameter */ ) { do { type = getConstraintOfTypeParameter ( type ) ; } while ( type && type . flags & 512 /* TypeParameter */ ) ; if ( ! type ) { type = emptyObjectType ; } } if ( type . flags & 258 /* StringLike */ ) { type = globalStringType ; } else if ( type . flags & 132 /* NumberLike */ ) { type = globalNumberType ; } else if ( type . flags & 8 /* Boolean */ ) { type = globalBooleanType ; } else if ( type . flags & 16777216 /* ESSymbol */ ) { type = globalESSymbolType ; } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the symbol for the property with the given name in the given type . Creates synthetic union properties when necessary maps primitive types and type parameters are to their apparent types and augments with properties from Object and Function as appropriate . [CODESPLIT] function getPropertyOfType ( type , name ) { type = getApparentType ( type ) ; if ( type . flags & 80896 /* ObjectType */ ) { var resolved = resolveStructuredTypeMembers ( type ) ; if ( ts . hasProperty ( resolved . members , name ) ) { var symbol = resolved . members [ name ] ; if ( symbolIsValue ( symbol ) ) { return symbol ; } } if ( resolved === anyFunctionType || resolved . callSignatures . length || resolved . constructSignatures . length ) { var symbol = getPropertyOfObjectType ( globalFunctionType , name ) ; if ( symbol ) { return symbol ; } } return getPropertyOfObjectType ( globalObjectType , name ) ; } if ( type . flags & 49152 /* UnionOrIntersection */ ) { return getPropertyOfUnionOrIntersectionType ( type , name ) ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return list of type parameters with duplicates removed ( duplicate identifier errors are generated in the actual type checking functions ) . [CODESPLIT] function getTypeParametersFromDeclaration ( typeParameterDeclarations ) { var result = [ ] ; ts . forEach ( typeParameterDeclarations , function ( node ) { var tp = getDeclaredTypeOfTypeParameter ( node . symbol ) ; if ( ! ts . contains ( result , tp ) ) { result . push ( tp ) ; } } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function is used to propagate certain flags when creating new object type references and union types . It is only necessary to do so if a constituent type might be the undefined type the null type the type of an object literal or the anyFunctionType . This is because there are operations in the type checker that care about the presence of such types at arbitrary depth in a containing type . [CODESPLIT] function getPropagatingFlagsOfTypes ( types ) { var result = 0 ; for ( var _i = 0 ; _i < types . length ; _i ++ ) { var type = types [ _i ] ; result |= type . flags ; } return result & 14680064 /* PropagatingFlags */ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get type from reference to class or interface [CODESPLIT] function getTypeFromClassOrInterfaceReference ( node , symbol ) { var type = getDeclaredTypeOfSymbol ( symbol ) ; var typeParameters = type . localTypeParameters ; if ( typeParameters ) { if ( ! node . typeArguments || node . typeArguments . length !== typeParameters . length ) { error ( node , ts . Diagnostics . Generic_type_0_requires_1_type_argument_s , typeToString ( type , /*enclosingDeclaration*/ undefined , 1 /* WriteArrayAsGenericType */ ) , typeParameters . length ) ; return unknownType ; } // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. return createTypeReference ( type , ts . concatenate ( type . outerTypeParameters , ts . map ( node . typeArguments , getTypeFromTypeNode ) ) ) ; } if ( node . typeArguments ) { error ( node , ts . Diagnostics . Type_0_is_not_generic , typeToString ( type ) ) ; return unknownType ; } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get type from reference to type alias . When a type alias is generic the declared type of the type alias may include references to the type parameters of the alias . We replace those with the actual type arguments by instantiating the declared type . Instantiations are cached using the type identities of the type arguments as the key . [CODESPLIT] function getTypeFromTypeAliasReference ( node , symbol ) { var type = getDeclaredTypeOfSymbol ( symbol ) ; var links = getSymbolLinks ( symbol ) ; var typeParameters = links . typeParameters ; if ( typeParameters ) { if ( ! node . typeArguments || node . typeArguments . length !== typeParameters . length ) { error ( node , ts . Diagnostics . Generic_type_0_requires_1_type_argument_s , symbolToString ( symbol ) , typeParameters . length ) ; return unknownType ; } var typeArguments = ts . map ( node . typeArguments , getTypeFromTypeNode ) ; var id = getTypeListId ( typeArguments ) ; return links . instantiations [ id ] || ( links . instantiations [ id ] = instantiateType ( type , createTypeMapper ( typeParameters , typeArguments ) ) ) ; } if ( node . typeArguments ) { error ( node , ts . Diagnostics . Type_0_is_not_generic , symbolToString ( symbol ) ) ; return unknownType ; } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get type from reference to named type that cannot be generic ( enum or type parameter ) [CODESPLIT] function getTypeFromNonGenericTypeReference ( node , symbol ) { if ( symbol . flags & 262144 /* TypeParameter */ && isTypeParameterReferenceIllegalInConstraint ( node , symbol ) ) { // TypeScript 1.0 spec (April 2014): 3.4.1 // Type parameters declared in a particular type parameter list // may not be referenced in constraints in that type parameter list // Implementation: such type references are resolved to 'unknown' type that usually denotes error return unknownType ; } if ( node . typeArguments ) { error ( node , ts . Diagnostics . Type_0_is_not_generic , symbolToString ( symbol ) ) ; return unknownType ; } return getDeclaredTypeOfSymbol ( symbol ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a type that is inside a namespace at the global scope e . g . getExportedTypeFromNamespace ( JSX Element ) returns the JSX . Element type [CODESPLIT] function getExportedTypeFromNamespace ( namespace , name ) { var namespaceSymbol = getGlobalSymbol ( namespace , 1536 /* Namespace */ , /*diagnosticMessage*/ undefined ) ; var typeSymbol = namespaceSymbol && getSymbol ( namespaceSymbol . exports , name , 793056 /* Type */ ) ; return typeSymbol && getDeclaredTypeOfSymbol ( typeSymbol ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a TypeReference for a generic TypedPropertyDescriptor<T > . [CODESPLIT] function createTypedPropertyDescriptorType ( propertyType ) { var globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType ( ) ; return globalTypedPropertyDescriptorType !== emptyGenericType ? createTypeReference ( globalTypedPropertyDescriptorType , [ propertyType ] ) : emptyObjectType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the given types to the given type set . Order is preserved duplicates are removed and nested types of the given kind are flattened into the set . [CODESPLIT] function addTypesToSet ( typeSet , types , typeSetKind ) { for ( var _i = 0 ; _i < types . length ; _i ++ ) { var type = types [ _i ] ; addTypeToSet ( typeSet , type , typeSetKind ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We reduce the constituent type set to only include types that aren t subtypes of other types unless the noSubtypeReduction flag is specified in which case we perform a simple deduplication based on object identity . Subtype reduction is possible only when union types are known not to circularly reference themselves ( as is the case with union types created by expression constructs such as array literals and the || and ? : operators ) . Named types can circularly reference themselves and therefore cannot be deduplicated during their declaration . For example type Item = string | (( ) = > Item is a named type that circularly references itself . [CODESPLIT] function getUnionType ( types , noSubtypeReduction ) { if ( types . length === 0 ) { return emptyObjectType ; } var typeSet = [ ] ; addTypesToSet ( typeSet , types , 16384 /* Union */ ) ; if ( containsTypeAny ( typeSet ) ) { return anyType ; } if ( noSubtypeReduction ) { removeAllButLast ( typeSet , undefinedType ) ; removeAllButLast ( typeSet , nullType ) ; } else { removeSubtypes ( typeSet ) ; } if ( typeSet . length === 1 ) { return typeSet [ 0 ] ; } var id = getTypeListId ( typeSet ) ; var type = unionTypes [ id ] ; if ( ! type ) { type = unionTypes [ id ] = createObjectType ( 16384 /* Union */ | getPropagatingFlagsOfTypes ( typeSet ) ) ; type . types = typeSet ; } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We do not perform structural deduplication on intersection types . Intersection types are created only by the & type operator and we can t reduce those because we want to support recursive intersection types . For example a type alias of the form type List<T > = T & { next : List<T > } cannot be reduced during its declaration . Also unlike union types the order of the constituent types is preserved in order that overload resolution for intersections of types with signatures can be deterministic . [CODESPLIT] function getIntersectionType ( types ) { if ( types . length === 0 ) { return emptyObjectType ; } var typeSet = [ ] ; addTypesToSet ( typeSet , types , 32768 /* Intersection */ ) ; if ( containsTypeAny ( typeSet ) ) { return anyType ; } if ( typeSet . length === 1 ) { return typeSet [ 0 ] ; } var id = getTypeListId ( typeSet ) ; var type = intersectionTypes [ id ] ; if ( ! type ) { type = intersectionTypes [ id ] = createObjectType ( 32768 /* Intersection */ | getPropagatingFlagsOfTypes ( typeSet ) ) ; type . types = typeSet ; } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if source is related to target ( e . g . : is a assignable to ) . [CODESPLIT] function checkTypeRelatedTo ( source , target , relation , errorNode , headMessage , containingMessageChain ) { var errorInfo ; var sourceStack ; var targetStack ; var maybeStack ; var expandingFlags ; var depth = 0 ; var overflow = false ; var elaborateErrors = false ; ts . Debug . assert ( relation !== identityRelation || ! errorNode , \"no error reporting in identity checking\" ) ; var result = isRelatedTo ( source , target , errorNode !== undefined , headMessage ) ; if ( overflow ) { error ( errorNode , ts . Diagnostics . Excessive_stack_depth_comparing_types_0_and_1 , typeToString ( source ) , typeToString ( target ) ) ; } else if ( errorInfo ) { // If we already computed this relation, but in a context where we didn't want to report errors (e.g. overload resolution), // then we'll only have a top-level error (e.g. 'Class X does not implement interface Y') without any details. If this happened, // request a recompuation to get a complete error message. This will be skipped if we've already done this computation in a context // where errors were being reported. if ( errorInfo . next === undefined ) { errorInfo = undefined ; elaborateErrors = true ; isRelatedTo ( source , target , errorNode !== undefined , headMessage ) ; } if ( containingMessageChain ) { errorInfo = ts . concatenateDiagnosticMessageChains ( containingMessageChain , errorInfo ) ; } diagnostics . add ( ts . createDiagnosticForNodeFromMessageChain ( errorNode , errorInfo ) ) ; } return result !== 0 /* False */ ; function reportError ( message , arg0 , arg1 , arg2 ) { errorInfo = ts . chainDiagnosticMessages ( errorInfo , message , arg0 , arg1 , arg2 ) ; } function reportRelationError ( message , source , target ) { var sourceType = typeToString ( source ) ; var targetType = typeToString ( target ) ; if ( sourceType === targetType ) { sourceType = typeToString ( source , /*enclosingDeclaration*/ undefined , 128 /* UseFullyQualifiedType */ ) ; targetType = typeToString ( target , /*enclosingDeclaration*/ undefined , 128 /* UseFullyQualifiedType */ ) ; } reportError ( message || ts . Diagnostics . Type_0_is_not_assignable_to_type_1 , sourceType , targetType ) ; } // Compare two types and return // Ternary.True if they are related with no assumptions, // Ternary.Maybe if they are related with assumptions of other relationships, or // Ternary.False if they are not related. function isRelatedTo ( source , target , reportErrors , headMessage ) { var result ; // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases if ( source === target ) return - 1 /* True */ ; if ( relation === identityRelation ) { return isIdenticalTo ( source , target ) ; } if ( isTypeAny ( target ) ) return - 1 /* True */ ; if ( source === undefinedType ) return - 1 /* True */ ; if ( source === nullType && target !== undefinedType ) return - 1 /* True */ ; if ( source . flags & 128 /* Enum */ && target === numberType ) return - 1 /* True */ ; if ( source . flags & 256 /* StringLiteral */ && target === stringType ) return - 1 /* True */ ; if ( relation === assignableRelation ) { if ( isTypeAny ( source ) ) return - 1 /* True */ ; if ( source === numberType && target . flags & 128 /* Enum */ ) return - 1 /* True */ ; } if ( source . flags & 1048576 /* FreshObjectLiteral */ ) { if ( hasExcessProperties ( source , target , reportErrors ) ) { if ( reportErrors ) { reportRelationError ( headMessage , source , target ) ; } return 0 /* False */ ; } // Above we check for excess properties with respect to the entire target type. When union // and intersection types are further deconstructed on the target side, we don't want to // make the check again (as it might fail for a partial target type). Therefore we obtain // the regular source type and proceed with that. if ( target . flags & 49152 /* UnionOrIntersection */ ) { source = getRegularTypeOfObjectLiteral ( source ) ; } } var saveErrorInfo = errorInfo ; // Note that the \"each\" checks must precede the \"some\" checks to produce the correct results if ( source . flags & 16384 /* Union */ ) { if ( result = eachTypeRelatedToType ( source , target , reportErrors ) ) { return result ; } } else if ( target . flags & 32768 /* Intersection */ ) { if ( result = typeRelatedToEachType ( source , target , reportErrors ) ) { return result ; } } else { // It is necessary to try \"some\" checks on both sides because there may be nested \"each\" checks // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or // A & B = (A & B) | (C & D). if ( source . flags & 32768 /* Intersection */ ) { // If target is a union type the following check will report errors so we suppress them here if ( result = someTypeRelatedToType ( source , target , reportErrors && ! ( target . flags & 16384 /* Union */ ) ) ) { return result ; } } if ( target . flags & 16384 /* Union */ ) { if ( result = typeRelatedToSomeType ( source , target , reportErrors ) ) { return result ; } } } if ( source . flags & 512 /* TypeParameter */ ) { var constraint = getConstraintOfTypeParameter ( source ) ; if ( ! constraint || constraint . flags & 1 /* Any */ ) { constraint = emptyObjectType ; } // Report constraint errors only if the constraint is not the empty object type var reportConstraintErrors = reportErrors && constraint !== emptyObjectType ; if ( result = isRelatedTo ( constraint , target , reportConstraintErrors ) ) { errorInfo = saveErrorInfo ; return result ; } } else { if ( source . flags & 4096 /* Reference */ && target . flags & 4096 /* Reference */ && source . target === target . target ) { // We have type references to same target type, see if relationship holds for all type arguments if ( result = typeArgumentsRelatedTo ( source , target , reportErrors ) ) { return result ; } } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. var apparentType = getApparentType ( source ) ; // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if ( apparentType . flags & ( 80896 /* ObjectType */ | 32768 /* Intersection */ ) && target . flags & 80896 /* ObjectType */ ) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo ; if ( result = objectTypeRelatedTo ( apparentType , target , reportStructuralErrors ) ) { errorInfo = saveErrorInfo ; return result ; } } } if ( reportErrors ) { reportRelationError ( headMessage , source , target ) ; } return 0 /* False */ ; } function isIdenticalTo ( source , target ) { var result ; if ( source . flags & 80896 /* ObjectType */ && target . flags & 80896 /* ObjectType */ ) { if ( source . flags & 4096 /* Reference */ && target . flags & 4096 /* Reference */ && source . target === target . target ) { // We have type references to same target type, see if all type arguments are identical if ( result = typeArgumentsRelatedTo ( source , target , /*reportErrors*/ false ) ) { return result ; } } return objectTypeRelatedTo ( source , target , /*reportErrors*/ false ) ; } if ( source . flags & 512 /* TypeParameter */ && target . flags & 512 /* TypeParameter */ ) { return typeParameterIdenticalTo ( source , target ) ; } if ( source . flags & 16384 /* Union */ && target . flags & 16384 /* Union */ || source . flags & 32768 /* Intersection */ && target . flags & 32768 /* Intersection */ ) { if ( result = eachTypeRelatedToSomeType ( source , target ) ) { if ( result &= eachTypeRelatedToSomeType ( target , source ) ) { return result ; } } } return 0 /* False */ ; } // Check if a property with the given name is known anywhere in the given type. In an object type, a property // is considered known if the object type is empty and the check is for assignability, if the object type has // index signatures, or if the property is actually declared in the object type. In a union or intersection // type, a property is considered known if it is known in any constituent type. function isKnownProperty ( type , name ) { if ( type . flags & 80896 /* ObjectType */ ) { var resolved = resolveStructuredTypeMembers ( type ) ; if ( relation === assignableRelation && ( type === globalObjectType || resolved . properties . length === 0 ) || resolved . stringIndexType || resolved . numberIndexType || getPropertyOfType ( type , name ) ) { return true ; } return false ; } if ( type . flags & 49152 /* UnionOrIntersection */ ) { for ( var _i = 0 , _a = type . types ; _i < _a . length ; _i ++ ) { var t = _a [ _i ] ; if ( isKnownProperty ( t , name ) ) { return true ; } } return false ; } return true ; } function hasExcessProperties ( source , target , reportErrors ) { for ( var _i = 0 , _a = getPropertiesOfObjectType ( source ) ; _i < _a . length ; _i ++ ) { var prop = _a [ _i ] ; if ( ! isKnownProperty ( target , prop . name ) ) { if ( reportErrors ) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. errorNode = prop . valueDeclaration ; reportError ( ts . Diagnostics . Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1 , symbolToString ( prop ) , typeToString ( target ) ) ; } return true ; } } } function eachTypeRelatedToSomeType ( source , target ) { var result = - 1 /* True */ ; var sourceTypes = source . types ; for ( var _i = 0 ; _i < sourceTypes . length ; _i ++ ) { var sourceType = sourceTypes [ _i ] ; var related = typeRelatedToSomeType ( sourceType , target , false ) ; if ( ! related ) { return 0 /* False */ ; } result &= related ; } return result ; } function typeRelatedToSomeType ( source , target , reportErrors ) { var targetTypes = target . types ; for ( var i = 0 , len = targetTypes . length ; i < len ; i ++ ) { var related = isRelatedTo ( source , targetTypes [ i ] , reportErrors && i === len - 1 ) ; if ( related ) { return related ; } } return 0 /* False */ ; } function typeRelatedToEachType ( source , target , reportErrors ) { var result = - 1 /* True */ ; var targetTypes = target . types ; for ( var _i = 0 ; _i < targetTypes . length ; _i ++ ) { var targetType = targetTypes [ _i ] ; var related = isRelatedTo ( source , targetType , reportErrors ) ; if ( ! related ) { return 0 /* False */ ; } result &= related ; } return result ; } function someTypeRelatedToType ( source , target , reportErrors ) { var sourceTypes = source . types ; for ( var i = 0 , len = sourceTypes . length ; i < len ; i ++ ) { var related = isRelatedTo ( sourceTypes [ i ] , target , reportErrors && i === len - 1 ) ; if ( related ) { return related ; } } return 0 /* False */ ; } function eachTypeRelatedToType ( source , target , reportErrors ) { var result = - 1 /* True */ ; var sourceTypes = source . types ; for ( var _i = 0 ; _i < sourceTypes . length ; _i ++ ) { var sourceType = sourceTypes [ _i ] ; var related = isRelatedTo ( sourceType , target , reportErrors ) ; if ( ! related ) { return 0 /* False */ ; } result &= related ; } return result ; } function typeArgumentsRelatedTo ( source , target , reportErrors ) { var sources = source . typeArguments || emptyArray ; var targets = target . typeArguments || emptyArray ; if ( sources . length !== targets . length && relation === identityRelation ) { return 0 /* False */ ; } var result = - 1 /* True */ ; for ( var i = 0 ; i < targets . length ; i ++ ) { var related = isRelatedTo ( sources [ i ] , targets [ i ] , reportErrors ) ; if ( ! related ) { return 0 /* False */ ; } result &= related ; } return result ; } function typeParameterIdenticalTo ( source , target ) { if ( source . symbol . name !== target . symbol . name ) { return 0 /* False */ ; } // covers case when both type parameters does not have constraint (both equal to noConstraintType) if ( source . constraint === target . constraint ) { return - 1 /* True */ ; } if ( source . constraint === noConstraintType || target . constraint === noConstraintType ) { return 0 /* False */ ; } return isIdenticalTo ( source . constraint , target . constraint ) ; } // Determine if two object types are related by structure. First, check if the result is already available in the global cache. // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. function objectTypeRelatedTo ( source , target , reportErrors ) { if ( overflow ) { return 0 /* False */ ; } var id = relation !== identityRelation || source . id < target . id ? source . id + \",\" + target . id : target . id + \",\" + source . id ; var related = relation [ id ] ; if ( related !== undefined ) { // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate // errors, we can use the cached value. Otherwise, recompute the relation if ( ! elaborateErrors || ( related === 3 /* FailedAndReported */ ) ) { return related === 1 /* Succeeded */ ? - 1 /* True */ : 0 /* False */ ; } } if ( depth > 0 ) { for ( var i = 0 ; i < depth ; i ++ ) { // If source and target are already being compared, consider them related with assumptions if ( maybeStack [ i ] [ id ] ) { return 1 /* Maybe */ ; } } if ( depth === 100 ) { overflow = true ; return 0 /* False */ ; } } else { sourceStack = [ ] ; targetStack = [ ] ; maybeStack = [ ] ; expandingFlags = 0 ; } sourceStack [ depth ] = source ; targetStack [ depth ] = target ; maybeStack [ depth ] = { } ; maybeStack [ depth ] [ id ] = 1 /* Succeeded */ ; depth ++ ; var saveExpandingFlags = expandingFlags ; if ( ! ( expandingFlags & 1 ) && isDeeplyNestedGeneric ( source , sourceStack , depth ) ) expandingFlags |= 1 ; if ( ! ( expandingFlags & 2 ) && isDeeplyNestedGeneric ( target , targetStack , depth ) ) expandingFlags |= 2 ; var result ; if ( expandingFlags === 3 ) { result = 1 /* Maybe */ ; } else { result = propertiesRelatedTo ( source , target , reportErrors ) ; if ( result ) { result &= signaturesRelatedTo ( source , target , 0 /* Call */ , reportErrors ) ; if ( result ) { result &= signaturesRelatedTo ( source , target , 1 /* Construct */ , reportErrors ) ; if ( result ) { result &= stringIndexTypesRelatedTo ( source , target , reportErrors ) ; if ( result ) { result &= numberIndexTypesRelatedTo ( source , target , reportErrors ) ; } } } } } expandingFlags = saveExpandingFlags ; depth -- ; if ( result ) { var maybeCache = maybeStack [ depth ] ; // If result is definitely true, copy assumptions to global cache, else copy to next level up var destinationCache = ( result === - 1 /* True */ || depth === 0 ) ? relation : maybeStack [ depth - 1 ] ; ts . copyMap ( maybeCache , destinationCache ) ; } else { // A false result goes straight into global cache (when something is false under assumptions it // will also be false without assumptions) relation [ id ] = reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */ ; } return result ; } function propertiesRelatedTo ( source , target , reportErrors ) { if ( relation === identityRelation ) { return propertiesIdenticalTo ( source , target ) ; } var result = - 1 /* True */ ; var properties = getPropertiesOfObjectType ( target ) ; var requireOptionalProperties = relation === subtypeRelation && ! ( source . flags & 524288 /* ObjectLiteral */ ) ; for ( var _i = 0 ; _i < properties . length ; _i ++ ) { var targetProp = properties [ _i ] ; var sourceProp = getPropertyOfType ( source , targetProp . name ) ; if ( sourceProp !== targetProp ) { if ( ! sourceProp ) { if ( ! ( targetProp . flags & 536870912 /* Optional */ ) || requireOptionalProperties ) { if ( reportErrors ) { reportError ( ts . Diagnostics . Property_0_is_missing_in_type_1 , symbolToString ( targetProp ) , typeToString ( source ) ) ; } return 0 /* False */ ; } } else if ( ! ( targetProp . flags & 134217728 /* Prototype */ ) ) { var sourcePropFlags = getDeclarationFlagsFromSymbol ( sourceProp ) ; var targetPropFlags = getDeclarationFlagsFromSymbol ( targetProp ) ; if ( sourcePropFlags & 32 /* Private */ || targetPropFlags & 32 /* Private */ ) { if ( sourceProp . valueDeclaration !== targetProp . valueDeclaration ) { if ( reportErrors ) { if ( sourcePropFlags & 32 /* Private */ && targetPropFlags & 32 /* Private */ ) { reportError ( ts . Diagnostics . Types_have_separate_declarations_of_a_private_property_0 , symbolToString ( targetProp ) ) ; } else { reportError ( ts . Diagnostics . Property_0_is_private_in_type_1_but_not_in_type_2 , symbolToString ( targetProp ) , typeToString ( sourcePropFlags & 32 /* Private */ ? source : target ) , typeToString ( sourcePropFlags & 32 /* Private */ ? target : source ) ) ; } } return 0 /* False */ ; } } else if ( targetPropFlags & 64 /* Protected */ ) { var sourceDeclaredInClass = sourceProp . parent && sourceProp . parent . flags & 32 /* Class */ ; var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol ( sourceProp . parent ) : undefined ; var targetClass = getDeclaredTypeOfSymbol ( targetProp . parent ) ; if ( ! sourceClass || ! hasBaseType ( sourceClass , targetClass ) ) { if ( reportErrors ) { reportError ( ts . Diagnostics . Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2 , symbolToString ( targetProp ) , typeToString ( sourceClass || source ) , typeToString ( targetClass ) ) ; } return 0 /* False */ ; } } else if ( sourcePropFlags & 64 /* Protected */ ) { if ( reportErrors ) { reportError ( ts . Diagnostics . Property_0_is_protected_in_type_1_but_public_in_type_2 , symbolToString ( targetProp ) , typeToString ( source ) , typeToString ( target ) ) ; } return 0 /* False */ ; } var related = isRelatedTo ( getTypeOfSymbol ( sourceProp ) , getTypeOfSymbol ( targetProp ) , reportErrors ) ; if ( ! related ) { if ( reportErrors ) { reportError ( ts . Diagnostics . Types_of_property_0_are_incompatible , symbolToString ( targetProp ) ) ; } return 0 /* False */ ; } result &= related ; if ( sourceProp . flags & 536870912 /* Optional */ && ! ( targetProp . flags & 536870912 /* Optional */ ) ) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. // M is a property and S' contains a property N where // if M is a required property, N is also a required property // (M - property in T) // (N - property in S) if ( reportErrors ) { reportError ( ts . Diagnostics . Property_0_is_optional_in_type_1_but_required_in_type_2 , symbolToString ( targetProp ) , typeToString ( source ) , typeToString ( target ) ) ; } return 0 /* False */ ; } } } } return result ; } function propertiesIdenticalTo ( source , target ) { if ( ! ( source . flags & 80896 /* ObjectType */ && target . flags & 80896 /* ObjectType */ ) ) { return 0 /* False */ ; } var sourceProperties = getPropertiesOfObjectType ( source ) ; var targetProperties = getPropertiesOfObjectType ( target ) ; if ( sourceProperties . length !== targetProperties . length ) { return 0 /* False */ ; } var result = - 1 /* True */ ; for ( var _i = 0 ; _i < sourceProperties . length ; _i ++ ) { var sourceProp = sourceProperties [ _i ] ; var targetProp = getPropertyOfObjectType ( target , sourceProp . name ) ; if ( ! targetProp ) { return 0 /* False */ ; } var related = compareProperties ( sourceProp , targetProp , isRelatedTo ) ; if ( ! related ) { return 0 /* False */ ; } result &= related ; } return result ; } function signaturesRelatedTo ( source , target , kind , reportErrors ) { if ( relation === identityRelation ) { return signaturesIdenticalTo ( source , target , kind ) ; } if ( target === anyFunctionType || source === anyFunctionType ) { return - 1 /* True */ ; } var sourceSignatures = getSignaturesOfType ( source , kind ) ; var targetSignatures = getSignaturesOfType ( target , kind ) ; var result = - 1 /* True */ ; var saveErrorInfo = errorInfo ; if ( kind === 1 /* Construct */ ) { // Only want to compare the construct signatures for abstractness guarantees. // Because the \"abstractness\" of a class is the same across all construct signatures // (internally we are checking the corresponding declaration), it is enough to perform // the check and report an error once over all pairs of source and target construct signatures. // // sourceSig and targetSig are (possibly) undefined. // // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds. var sourceSig = sourceSignatures [ 0 ] ; var targetSig = targetSignatures [ 0 ] ; result &= abstractSignatureRelatedTo ( source , sourceSig , target , targetSig ) ; if ( result !== - 1 /* True */ ) { return result ; } } outer : for ( var _i = 0 ; _i < targetSignatures . length ; _i ++ ) { var t = targetSignatures [ _i ] ; if ( ! t . hasStringLiterals || target . flags & 262144 /* FromSignature */ ) { var localErrors = reportErrors ; var checkedAbstractAssignability = false ; for ( var _a = 0 ; _a < sourceSignatures . length ; _a ++ ) { var s = sourceSignatures [ _a ] ; if ( ! s . hasStringLiterals || source . flags & 262144 /* FromSignature */ ) { var related = signatureRelatedTo ( s , t , localErrors ) ; if ( related ) { result &= related ; errorInfo = saveErrorInfo ; continue outer ; } // Only report errors from the first failure localErrors = false ; } } return 0 /* False */ ; } } return result ; function abstractSignatureRelatedTo ( source , sourceSig , target , targetSig ) { if ( sourceSig && targetSig ) { var sourceDecl = source . symbol && getClassLikeDeclarationOfSymbol ( source . symbol ) ; var targetDecl = target . symbol && getClassLikeDeclarationOfSymbol ( target . symbol ) ; if ( ! sourceDecl ) { // If the source object isn't itself a class declaration, it can be freely assigned, regardless // of whether the constructed object is abstract or not. return - 1 /* True */ ; } var sourceErasedSignature = getErasedSignature ( sourceSig ) ; var targetErasedSignature = getErasedSignature ( targetSig ) ; var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature ( sourceErasedSignature ) ; var targetReturnType = targetErasedSignature && getReturnTypeOfSignature ( targetErasedSignature ) ; var sourceReturnDecl = sourceReturnType && sourceReturnType . symbol && getClassLikeDeclarationOfSymbol ( sourceReturnType . symbol ) ; var targetReturnDecl = targetReturnType && targetReturnType . symbol && getClassLikeDeclarationOfSymbol ( targetReturnType . symbol ) ; var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl . flags & 256 /* Abstract */ ; var targetIsAbstract = targetReturnDecl && targetReturnDecl . flags & 256 /* Abstract */ ; if ( sourceIsAbstract && ! ( targetIsAbstract && targetDecl ) ) { // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment. if ( reportErrors ) { reportError ( ts . Diagnostics . Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type ) ; } return 0 /* False */ ; } } return - 1 /* True */ ; } } function signatureRelatedTo ( source , target , reportErrors ) { if ( source === target ) { return - 1 /* True */ ; } if ( ! target . hasRestParameter && source . minArgumentCount > target . parameters . length ) { return 0 /* False */ ; } var sourceMax = source . parameters . length ; var targetMax = target . parameters . length ; var checkCount ; if ( source . hasRestParameter && target . hasRestParameter ) { checkCount = sourceMax > targetMax ? sourceMax : targetMax ; sourceMax -- ; targetMax -- ; } else if ( source . hasRestParameter ) { sourceMax -- ; checkCount = targetMax ; } else if ( target . hasRestParameter ) { targetMax -- ; checkCount = sourceMax ; } else { checkCount = sourceMax < targetMax ? sourceMax : targetMax ; } // Spec 1.0 Section 3.8.3 & 3.8.4: // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N source = getErasedSignature ( source ) ; target = getErasedSignature ( target ) ; var result = - 1 /* True */ ; for ( var i = 0 ; i < checkCount ; i ++ ) { var s = i < sourceMax ? getTypeOfSymbol ( source . parameters [ i ] ) : getRestTypeOfSignature ( source ) ; var t = i < targetMax ? getTypeOfSymbol ( target . parameters [ i ] ) : getRestTypeOfSignature ( target ) ; var saveErrorInfo = errorInfo ; var related = isRelatedTo ( s , t , reportErrors ) ; if ( ! related ) { related = isRelatedTo ( t , s , false ) ; if ( ! related ) { if ( reportErrors ) { reportError ( ts . Diagnostics . Types_of_parameters_0_and_1_are_incompatible , source . parameters [ i < sourceMax ? i : sourceMax ] . name , target . parameters [ i < targetMax ? i : targetMax ] . name ) ; } return 0 /* False */ ; } errorInfo = saveErrorInfo ; } result &= related ; } if ( source . typePredicate && target . typePredicate ) { var hasDifferentParameterIndex = source . typePredicate . parameterIndex !== target . typePredicate . parameterIndex ; var hasDifferentTypes ; if ( hasDifferentParameterIndex || ( hasDifferentTypes = ! isTypeIdenticalTo ( source . typePredicate . type , target . typePredicate . type ) ) ) { if ( reportErrors ) { var sourceParamText = source . typePredicate . parameterName ; var targetParamText = target . typePredicate . parameterName ; var sourceTypeText = typeToString ( source . typePredicate . type ) ; var targetTypeText = typeToString ( target . typePredicate . type ) ; if ( hasDifferentParameterIndex ) { reportError ( ts . Diagnostics . Parameter_0_is_not_in_the_same_position_as_parameter_1 , sourceParamText , targetParamText ) ; } else if ( hasDifferentTypes ) { reportError ( ts . Diagnostics . Type_0_is_not_assignable_to_type_1 , sourceTypeText , targetTypeText ) ; } reportError ( ts . Diagnostics . Type_predicate_0_is_not_assignable_to_1 , sourceParamText + \" is \" + sourceTypeText , targetParamText + \" is \" + targetTypeText ) ; } return 0 /* False */ ; } } else if ( ! source . typePredicate && target . typePredicate ) { if ( reportErrors ) { reportError ( ts . Diagnostics . Signature_0_must_have_a_type_predicate , signatureToString ( source ) ) ; } return 0 /* False */ ; } var targetReturnType = getReturnTypeOfSignature ( target ) ; if ( targetReturnType === voidType ) return result ; var sourceReturnType = getReturnTypeOfSignature ( source ) ; return result & isRelatedTo ( sourceReturnType , targetReturnType , reportErrors ) ; } function signaturesIdenticalTo ( source , target , kind ) { var sourceSignatures = getSignaturesOfType ( source , kind ) ; var targetSignatures = getSignaturesOfType ( target , kind ) ; if ( sourceSignatures . length !== targetSignatures . length ) { return 0 /* False */ ; } var result = - 1 /* True */ ; for ( var i = 0 , len = sourceSignatures . length ; i < len ; ++ i ) { var related = compareSignatures ( sourceSignatures [ i ] , targetSignatures [ i ] , /*partialMatch*/ false , /*ignoreReturnTypes*/ false , isRelatedTo ) ; if ( ! related ) { return 0 /* False */ ; } result &= related ; } return result ; } function stringIndexTypesRelatedTo ( source , target , reportErrors ) { if ( relation === identityRelation ) { return indexTypesIdenticalTo ( 0 /* String */ , source , target ) ; } var targetType = getIndexTypeOfType ( target , 0 /* String */ ) ; if ( targetType && ! ( targetType . flags & 1 /* Any */ ) ) { var sourceType = getIndexTypeOfType ( source , 0 /* String */ ) ; if ( ! sourceType ) { if ( reportErrors ) { reportError ( ts . Diagnostics . Index_signature_is_missing_in_type_0 , typeToString ( source ) ) ; } return 0 /* False */ ; } var related = isRelatedTo ( sourceType , targetType , reportErrors ) ; if ( ! related ) { if ( reportErrors ) { reportError ( ts . Diagnostics . Index_signatures_are_incompatible ) ; } return 0 /* False */ ; } return related ; } return - 1 /* True */ ; } function numberIndexTypesRelatedTo ( source , target , reportErrors ) { if ( relation === identityRelation ) { return indexTypesIdenticalTo ( 1 /* Number */ , source , target ) ; } var targetType = getIndexTypeOfType ( target , 1 /* Number */ ) ; if ( targetType && ! ( targetType . flags & 1 /* Any */ ) ) { var sourceStringType = getIndexTypeOfType ( source , 0 /* String */ ) ; var sourceNumberType = getIndexTypeOfType ( source , 1 /* Number */ ) ; if ( ! ( sourceStringType || sourceNumberType ) ) { if ( reportErrors ) { reportError ( ts . Diagnostics . Index_signature_is_missing_in_type_0 , typeToString ( source ) ) ; } return 0 /* False */ ; } var related ; if ( sourceStringType && sourceNumberType ) { // If we know for sure we're testing both string and numeric index types then only report errors from the second one related = isRelatedTo ( sourceStringType , targetType , false ) || isRelatedTo ( sourceNumberType , targetType , reportErrors ) ; } else { related = isRelatedTo ( sourceStringType || sourceNumberType , targetType , reportErrors ) ; } if ( ! related ) { if ( reportErrors ) { reportError ( ts . Diagnostics . Index_signatures_are_incompatible ) ; } return 0 /* False */ ; } return related ; } return - 1 /* True */ ; } function indexTypesIdenticalTo ( indexKind , source , target ) { var targetType = getIndexTypeOfType ( target , indexKind ) ; var sourceType = getIndexTypeOfType ( source , indexKind ) ; if ( ! sourceType && ! targetType ) { return - 1 /* True */ ; } if ( sourceType && targetType ) { return isRelatedTo ( sourceType , targetType ) ; } return 0 /* False */ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare two types and return Ternary . True if they are related with no assumptions Ternary . Maybe if they are related with assumptions of other relationships or Ternary . False if they are not related . [CODESPLIT] function isRelatedTo ( source , target , reportErrors , headMessage ) { var result ; // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases if ( source === target ) return - 1 /* True */ ; if ( relation === identityRelation ) { return isIdenticalTo ( source , target ) ; } if ( isTypeAny ( target ) ) return - 1 /* True */ ; if ( source === undefinedType ) return - 1 /* True */ ; if ( source === nullType && target !== undefinedType ) return - 1 /* True */ ; if ( source . flags & 128 /* Enum */ && target === numberType ) return - 1 /* True */ ; if ( source . flags & 256 /* StringLiteral */ && target === stringType ) return - 1 /* True */ ; if ( relation === assignableRelation ) { if ( isTypeAny ( source ) ) return - 1 /* True */ ; if ( source === numberType && target . flags & 128 /* Enum */ ) return - 1 /* True */ ; } if ( source . flags & 1048576 /* FreshObjectLiteral */ ) { if ( hasExcessProperties ( source , target , reportErrors ) ) { if ( reportErrors ) { reportRelationError ( headMessage , source , target ) ; } return 0 /* False */ ; } // Above we check for excess properties with respect to the entire target type. When union // and intersection types are further deconstructed on the target side, we don't want to // make the check again (as it might fail for a partial target type). Therefore we obtain // the regular source type and proceed with that. if ( target . flags & 49152 /* UnionOrIntersection */ ) { source = getRegularTypeOfObjectLiteral ( source ) ; } } var saveErrorInfo = errorInfo ; // Note that the \"each\" checks must precede the \"some\" checks to produce the correct results if ( source . flags & 16384 /* Union */ ) { if ( result = eachTypeRelatedToType ( source , target , reportErrors ) ) { return result ; } } else if ( target . flags & 32768 /* Intersection */ ) { if ( result = typeRelatedToEachType ( source , target , reportErrors ) ) { return result ; } } else { // It is necessary to try \"some\" checks on both sides because there may be nested \"each\" checks // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or // A & B = (A & B) | (C & D). if ( source . flags & 32768 /* Intersection */ ) { // If target is a union type the following check will report errors so we suppress them here if ( result = someTypeRelatedToType ( source , target , reportErrors && ! ( target . flags & 16384 /* Union */ ) ) ) { return result ; } } if ( target . flags & 16384 /* Union */ ) { if ( result = typeRelatedToSomeType ( source , target , reportErrors ) ) { return result ; } } } if ( source . flags & 512 /* TypeParameter */ ) { var constraint = getConstraintOfTypeParameter ( source ) ; if ( ! constraint || constraint . flags & 1 /* Any */ ) { constraint = emptyObjectType ; } // Report constraint errors only if the constraint is not the empty object type var reportConstraintErrors = reportErrors && constraint !== emptyObjectType ; if ( result = isRelatedTo ( constraint , target , reportConstraintErrors ) ) { errorInfo = saveErrorInfo ; return result ; } } else { if ( source . flags & 4096 /* Reference */ && target . flags & 4096 /* Reference */ && source . target === target . target ) { // We have type references to same target type, see if relationship holds for all type arguments if ( result = typeArgumentsRelatedTo ( source , target , reportErrors ) ) { return result ; } } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. var apparentType = getApparentType ( source ) ; // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if ( apparentType . flags & ( 80896 /* ObjectType */ | 32768 /* Intersection */ ) && target . flags & 80896 /* ObjectType */ ) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo ; if ( result = objectTypeRelatedTo ( apparentType , target , reportStructuralErrors ) ) { errorInfo = saveErrorInfo ; return result ; } } } if ( reportErrors ) { reportRelationError ( headMessage , source , target ) ; } return 0 /* False */ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a property with the given name is known anywhere in the given type . In an object type a property is considered known if the object type is empty and the check is for assignability if the object type has index signatures or if the property is actually declared in the object type . In a union or intersection type a property is considered known if it is known in any constituent type . [CODESPLIT] function isKnownProperty ( type , name ) { if ( type . flags & 80896 /* ObjectType */ ) { var resolved = resolveStructuredTypeMembers ( type ) ; if ( relation === assignableRelation && ( type === globalObjectType || resolved . properties . length === 0 ) || resolved . stringIndexType || resolved . numberIndexType || getPropertyOfType ( type , name ) ) { return true ; } return false ; } if ( type . flags & 49152 /* UnionOrIntersection */ ) { for ( var _i = 0 , _a = type . types ; _i < _a . length ; _i ++ ) { var t = _a [ _i ] ; if ( isKnownProperty ( t , name ) ) { return true ; } } return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if two object types are related by structure . First check if the result is already available in the global cache . Second check if we have already started a comparison of the given two types in which case we assume the result to be true . Third check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are equal and infinitely expanding . Fourth if we have reached a depth of 100 nested comparisons assume we have runaway recursion and issue an error . Otherwise actually compare the structure of the two types . [CODESPLIT] function objectTypeRelatedTo ( source , target , reportErrors ) { if ( overflow ) { return 0 /* False */ ; } var id = relation !== identityRelation || source . id < target . id ? source . id + \",\" + target . id : target . id + \",\" + source . id ; var related = relation [ id ] ; if ( related !== undefined ) { // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate // errors, we can use the cached value. Otherwise, recompute the relation if ( ! elaborateErrors || ( related === 3 /* FailedAndReported */ ) ) { return related === 1 /* Succeeded */ ? - 1 /* True */ : 0 /* False */ ; } } if ( depth > 0 ) { for ( var i = 0 ; i < depth ; i ++ ) { // If source and target are already being compared, consider them related with assumptions if ( maybeStack [ i ] [ id ] ) { return 1 /* Maybe */ ; } } if ( depth === 100 ) { overflow = true ; return 0 /* False */ ; } } else { sourceStack = [ ] ; targetStack = [ ] ; maybeStack = [ ] ; expandingFlags = 0 ; } sourceStack [ depth ] = source ; targetStack [ depth ] = target ; maybeStack [ depth ] = { } ; maybeStack [ depth ] [ id ] = 1 /* Succeeded */ ; depth ++ ; var saveExpandingFlags = expandingFlags ; if ( ! ( expandingFlags & 1 ) && isDeeplyNestedGeneric ( source , sourceStack , depth ) ) expandingFlags |= 1 ; if ( ! ( expandingFlags & 2 ) && isDeeplyNestedGeneric ( target , targetStack , depth ) ) expandingFlags |= 2 ; var result ; if ( expandingFlags === 3 ) { result = 1 /* Maybe */ ; } else { result = propertiesRelatedTo ( source , target , reportErrors ) ; if ( result ) { result &= signaturesRelatedTo ( source , target , 0 /* Call */ , reportErrors ) ; if ( result ) { result &= signaturesRelatedTo ( source , target , 1 /* Construct */ , reportErrors ) ; if ( result ) { result &= stringIndexTypesRelatedTo ( source , target , reportErrors ) ; if ( result ) { result &= numberIndexTypesRelatedTo ( source , target , reportErrors ) ; } } } } } expandingFlags = saveExpandingFlags ; depth -- ; if ( result ) { var maybeCache = maybeStack [ depth ] ; // If result is definitely true, copy assumptions to global cache, else copy to next level up var destinationCache = ( result === - 1 /* True */ || depth === 0 ) ? relation : maybeStack [ depth - 1 ] ; ts . copyMap ( maybeCache , destinationCache ) ; } else { // A false result goes straight into global cache (when something is false under assumptions it // will also be false without assumptions) relation [ id ] = reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */ ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given type is part of a deeply nested chain of generic instantiations . We consider this to be the case when structural type comparisons have been started for 10 or more instantiations of the same generic type . It is possible though highly unlikely for this test to be true in a situation where a chain of instantiations is not infinitely expanding . Effectively we will generate a false positive when two types are structurally equal to at least 10 levels but unequal at some level beyond that . [CODESPLIT] function isDeeplyNestedGeneric ( type , stack , depth ) { // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) if ( type . flags & ( 4096 /* Reference */ | 131072 /* Instantiated */ ) && depth >= 5 ) { var symbol = type . symbol ; var count = 0 ; for ( var i = 0 ; i < depth ; i ++ ) { var t = stack [ i ] ; if ( t . flags & ( 4096 /* Reference */ | 131072 /* Instantiated */ ) && t . symbol === symbol ) { count ++ ; if ( count >= 5 ) return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a union type remove all constituent types that are of the given type kind ( when isOfTypeKind is true ) or not of the given type kind ( when isOfTypeKind is false ) [CODESPLIT] function removeTypesFromUnionType ( type , typeKind , isOfTypeKind , allowEmptyUnionResult ) { if ( type . flags & 16384 /* Union */ ) { var types = type . types ; if ( ts . forEach ( types , function ( t ) { return ! ! ( t . flags & typeKind ) === isOfTypeKind ; } ) ) { // Above we checked if we have anything to remove, now use the opposite test to do the removal var narrowedType = getUnionType ( ts . filter ( types , function ( t ) { return ! ( t . flags & typeKind ) === isOfTypeKind ; } ) ) ; if ( allowEmptyUnionResult || narrowedType !== emptyObjectType ) { return narrowedType ; } } } else if ( allowEmptyUnionResult && ! ! ( type . flags & typeKind ) === isOfTypeKind ) { // Use getUnionType(emptyArray) instead of emptyObjectType in case the way empty union types // are represented ever changes. return getUnionType ( emptyArray ) ; } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a given variable is assigned within a given syntax node [CODESPLIT] function isVariableAssignedWithin ( symbol , node ) { var links = getNodeLinks ( node ) ; if ( links . assignmentChecks ) { var cachedResult = links . assignmentChecks [ symbol . id ] ; if ( cachedResult !== undefined ) { return cachedResult ; } } else { links . assignmentChecks = { } ; } return links . assignmentChecks [ symbol . id ] = isAssignedIn ( node ) ; function isAssignedInBinaryExpression ( node ) { if ( node . operatorToken . kind >= 56 /* FirstAssignment */ && node . operatorToken . kind <= 68 /* LastAssignment */ ) { var n = node . left ; while ( n . kind === 172 /* ParenthesizedExpression */ ) { n = n . expression ; } if ( n . kind === 69 /* Identifier */ && getResolvedSymbol ( n ) === symbol ) { return true ; } } return ts . forEachChild ( node , isAssignedIn ) ; } function isAssignedInVariableDeclaration ( node ) { if ( ! ts . isBindingPattern ( node . name ) && getSymbolOfNode ( node ) === symbol && hasInitializer ( node ) ) { return true ; } return ts . forEachChild ( node , isAssignedIn ) ; } function isAssignedIn ( node ) { switch ( node . kind ) { case 181 /* BinaryExpression */ : return isAssignedInBinaryExpression ( node ) ; case 211 /* VariableDeclaration */ : case 163 /* BindingElement */ : return isAssignedInVariableDeclaration ( node ) ; case 161 /* ObjectBindingPattern */ : case 162 /* ArrayBindingPattern */ : case 164 /* ArrayLiteralExpression */ : case 165 /* ObjectLiteralExpression */ : case 166 /* PropertyAccessExpression */ : case 167 /* ElementAccessExpression */ : case 168 /* CallExpression */ : case 169 /* NewExpression */ : case 171 /* TypeAssertionExpression */ : case 189 /* AsExpression */ : case 172 /* ParenthesizedExpression */ : case 179 /* PrefixUnaryExpression */ : case 175 /* DeleteExpression */ : case 178 /* AwaitExpression */ : case 176 /* TypeOfExpression */ : case 177 /* VoidExpression */ : case 180 /* PostfixUnaryExpression */ : case 184 /* YieldExpression */ : case 182 /* ConditionalExpression */ : case 185 /* SpreadElementExpression */ : case 192 /* Block */ : case 193 /* VariableStatement */ : case 195 /* ExpressionStatement */ : case 196 /* IfStatement */ : case 197 /* DoStatement */ : case 198 /* WhileStatement */ : case 199 /* ForStatement */ : case 200 /* ForInStatement */ : case 201 /* ForOfStatement */ : case 204 /* ReturnStatement */ : case 205 /* WithStatement */ : case 206 /* SwitchStatement */ : case 241 /* CaseClause */ : case 242 /* DefaultClause */ : case 207 /* LabeledStatement */ : case 208 /* ThrowStatement */ : case 209 /* TryStatement */ : case 244 /* CatchClause */ : case 233 /* JsxElement */ : case 234 /* JsxSelfClosingElement */ : case 238 /* JsxAttribute */ : case 239 /* JsxSpreadAttribute */ : case 235 /* JsxOpeningElement */ : case 240 /* JsxExpression */ : return ts . forEachChild ( node , isAssignedIn ) ; } return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the narrowed type of a given symbol at a given location [CODESPLIT] function getNarrowedTypeOfSymbol ( symbol , node ) { var type = getTypeOfSymbol ( symbol ) ; // Only narrow when symbol is variable of type any or an object, union, or type parameter type if ( node && symbol . flags & 3 /* Variable */ ) { if ( isTypeAny ( type ) || type . flags & ( 80896 /* ObjectType */ | 16384 /* Union */ | 512 /* TypeParameter */ ) ) { loop : while ( node . parent ) { var child = node ; node = node . parent ; var narrowedType = type ; switch ( node . kind ) { case 196 /* IfStatement */ : // In a branch of an if statement, narrow based on controlling expression if ( child !== node . expression ) { narrowedType = narrowType ( type , node . expression , /*assumeTrue*/ child === node . thenStatement ) ; } break ; case 182 /* ConditionalExpression */ : // In a branch of a conditional expression, narrow based on controlling condition if ( child !== node . condition ) { narrowedType = narrowType ( type , node . condition , /*assumeTrue*/ child === node . whenTrue ) ; } break ; case 181 /* BinaryExpression */ : // In the right operand of an && or ||, narrow based on left operand if ( child === node . right ) { if ( node . operatorToken . kind === 51 /* AmpersandAmpersandToken */ ) { narrowedType = narrowType ( type , node . left , /*assumeTrue*/ true ) ; } else if ( node . operatorToken . kind === 52 /* BarBarToken */ ) { narrowedType = narrowType ( type , node . left , /*assumeTrue*/ false ) ; } } break ; case 248 /* SourceFile */ : case 218 /* ModuleDeclaration */ : case 213 /* FunctionDeclaration */ : case 143 /* MethodDeclaration */ : case 142 /* MethodSignature */ : case 145 /* GetAccessor */ : case 146 /* SetAccessor */ : case 144 /* Constructor */ : // Stop at the first containing function or module declaration break loop ; } // Use narrowed type if construct contains no assignments to variable if ( narrowedType !== type ) { if ( isVariableAssignedWithin ( symbol , node ) ) { break ; } type = narrowedType ; } } } } return type ; function narrowTypeByEquality ( type , expr , assumeTrue ) { // Check that we have 'typeof <symbol>' on the left and string literal on the right if ( expr . left . kind !== 176 /* TypeOfExpression */ || expr . right . kind !== 9 /* StringLiteral */ ) { return type ; } var left = expr . left ; var right = expr . right ; if ( left . expression . kind !== 69 /* Identifier */ || getResolvedSymbol ( left . expression ) !== symbol ) { return type ; } var typeInfo = primitiveTypeInfo [ right . text ] ; if ( expr . operatorToken . kind === 33 /* ExclamationEqualsEqualsToken */ ) { assumeTrue = ! assumeTrue ; } if ( assumeTrue ) { // Assumed result is true. If check was not for a primitive type, remove all primitive types if ( ! typeInfo ) { return removeTypesFromUnionType ( type , /*typeKind*/ 258 /* StringLike */ | 132 /* NumberLike */ | 8 /* Boolean */ | 16777216 /* ESSymbol */ , /*isOfTypeKind*/ true , /*allowEmptyUnionResult*/ false ) ; } // Check was for a primitive type, return that primitive type if it is a subtype if ( isTypeSubtypeOf ( typeInfo . type , type ) ) { return typeInfo . type ; } // Otherwise, remove all types that aren't of the primitive type kind. This can happen when the type is // union of enum types and other types. return removeTypesFromUnionType ( type , /*typeKind*/ typeInfo . flags , /*isOfTypeKind*/ false , /*allowEmptyUnionResult*/ false ) ; } else { // Assumed result is false. If check was for a primitive type, remove that primitive type if ( typeInfo ) { return removeTypesFromUnionType ( type , /*typeKind*/ typeInfo . flags , /*isOfTypeKind*/ true , /*allowEmptyUnionResult*/ false ) ; } // Otherwise we don't have enough information to do anything. return type ; } } function narrowTypeByAnd ( type , expr , assumeTrue ) { if ( assumeTrue ) { // The assumed result is true, therefore we narrow assuming each operand to be true. return narrowType ( narrowType ( type , expr . left , /*assumeTrue*/ true ) , expr . right , /*assumeTrue*/ true ) ; } else { // The assumed result is false. This means either the first operand was false, or the first operand was true // and the second operand was false. We narrow with those assumptions and union the two resulting types. return getUnionType ( [ narrowType ( type , expr . left , /*assumeTrue*/ false ) , narrowType ( narrowType ( type , expr . left , /*assumeTrue*/ true ) , expr . right , /*assumeTrue*/ false ) ] ) ; } } function narrowTypeByOr ( type , expr , assumeTrue ) { if ( assumeTrue ) { // The assumed result is true. This means either the first operand was true, or the first operand was false // and the second operand was true. We narrow with those assumptions and union the two resulting types. return getUnionType ( [ narrowType ( type , expr . left , /*assumeTrue*/ true ) , narrowType ( narrowType ( type , expr . left , /*assumeTrue*/ false ) , expr . right , /*assumeTrue*/ true ) ] ) ; } else { // The assumed result is false, therefore we narrow assuming each operand to be false. return narrowType ( narrowType ( type , expr . left , /*assumeTrue*/ false ) , expr . right , /*assumeTrue*/ false ) ; } } function narrowTypeByInstanceof ( type , expr , assumeTrue ) { // Check that type is not any, assumed result is true, and we have variable symbol on the left if ( isTypeAny ( type ) || ! assumeTrue || expr . left . kind !== 69 /* Identifier */ || getResolvedSymbol ( expr . left ) !== symbol ) { return type ; } // Check that right operand is a function type with a prototype property var rightType = checkExpression ( expr . right ) ; if ( ! isTypeSubtypeOf ( rightType , globalFunctionType ) ) { return type ; } var targetType ; var prototypeProperty = getPropertyOfType ( rightType , \"prototype\" ) ; if ( prototypeProperty ) { // Target type is type of the prototype property var prototypePropertyType = getTypeOfSymbol ( prototypeProperty ) ; if ( ! isTypeAny ( prototypePropertyType ) ) { targetType = prototypePropertyType ; } } if ( ! targetType ) { // Target type is type of construct signature var constructSignatures ; if ( rightType . flags & 2048 /* Interface */ ) { constructSignatures = resolveDeclaredMembers ( rightType ) . declaredConstructSignatures ; } else if ( rightType . flags & 65536 /* Anonymous */ ) { constructSignatures = getSignaturesOfType ( rightType , 1 /* Construct */ ) ; } if ( constructSignatures && constructSignatures . length ) { targetType = getUnionType ( ts . map ( constructSignatures , function ( signature ) { return getReturnTypeOfSignature ( getErasedSignature ( signature ) ) ; } ) ) ; } } if ( targetType ) { return getNarrowedType ( type , targetType ) ; } return type ; } function getNarrowedType ( originalType , narrowedTypeCandidate ) { // If the current type is a union type, remove all constituents that aren't assignable to target. If that produces // 0 candidates, fall back to the assignability check if ( originalType . flags & 16384 /* Union */ ) { var assignableConstituents = ts . filter ( originalType . types , function ( t ) { return isTypeAssignableTo ( t , narrowedTypeCandidate ) ; } ) ; if ( assignableConstituents . length ) { return getUnionType ( assignableConstituents ) ; } } if ( isTypeAssignableTo ( narrowedTypeCandidate , originalType ) ) { // Narrow to the target type if it's assignable to the current type return narrowedTypeCandidate ; } return originalType ; } function narrowTypeByTypePredicate ( type , expr , assumeTrue ) { if ( type . flags & 1 /* Any */ ) { return type ; } var signature = getResolvedSignature ( expr ) ; if ( signature . typePredicate && expr . arguments [ signature . typePredicate . parameterIndex ] && getSymbolAtLocation ( expr . arguments [ signature . typePredicate . parameterIndex ] ) === symbol ) { if ( ! assumeTrue ) { if ( type . flags & 16384 /* Union */ ) { return getUnionType ( ts . filter ( type . types , function ( t ) { return ! isTypeSubtypeOf ( t , signature . typePredicate . type ) ; } ) ) ; } return type ; } return getNarrowedType ( type , signature . typePredicate . type ) ; } return type ; } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType ( type , expr , assumeTrue ) { switch ( expr . kind ) { case 168 /* CallExpression */ : return narrowTypeByTypePredicate ( type , expr , assumeTrue ) ; case 172 /* ParenthesizedExpression */ : return narrowType ( type , expr . expression , assumeTrue ) ; case 181 /* BinaryExpression */ : var operator = expr . operatorToken . kind ; if ( operator === 32 /* EqualsEqualsEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */ ) { return narrowTypeByEquality ( type , expr , assumeTrue ) ; } else if ( operator === 51 /* AmpersandAmpersandToken */ ) { return narrowTypeByAnd ( type , expr , assumeTrue ) ; } else if ( operator === 52 /* BarBarToken */ ) { return narrowTypeByOr ( type , expr , assumeTrue ) ; } else if ( operator === 91 /* InstanceOfKeyword */ ) { return narrowTypeByInstanceof ( type , expr , assumeTrue ) ; } break ; case 179 /* PrefixUnaryExpression */ : if ( expr . operator === 49 /* ExclamationToken */ ) { return narrowType ( type , expr . operand , ! assumeTrue ) ; } break ; } return type ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Narrow the given type based on the given expression having the assumed boolean value . The returned type will be a subtype or the same type as the argument . [CODESPLIT] function narrowType ( type , expr , assumeTrue ) { switch ( expr . kind ) { case 168 /* CallExpression */ : return narrowTypeByTypePredicate ( type , expr , assumeTrue ) ; case 172 /* ParenthesizedExpression */ : return narrowType ( type , expr . expression , assumeTrue ) ; case 181 /* BinaryExpression */ : var operator = expr . operatorToken . kind ; if ( operator === 32 /* EqualsEqualsEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */ ) { return narrowTypeByEquality ( type , expr , assumeTrue ) ; } else if ( operator === 51 /* AmpersandAmpersandToken */ ) { return narrowTypeByAnd ( type , expr , assumeTrue ) ; } else if ( operator === 52 /* BarBarToken */ ) { return narrowTypeByOr ( type , expr , assumeTrue ) ; } else if ( operator === 91 /* InstanceOfKeyword */ ) { return narrowTypeByInstanceof ( type , expr , assumeTrue ) ; } break ; case 179 /* PrefixUnaryExpression */ : if ( expr . operator === 49 /* ExclamationToken */ ) { return narrowType ( type , expr . operand , ! assumeTrue ) ; } break ; } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return contextual type of parameter or undefined if no contextual type is available [CODESPLIT] function getContextuallyTypedParameterType ( parameter ) { var func = parameter . parent ; if ( isFunctionExpressionOrArrowFunction ( func ) || ts . isObjectLiteralMethod ( func ) ) { if ( isContextSensitive ( func ) ) { var contextualSignature = getContextualSignature ( func ) ; if ( contextualSignature ) { var funcHasRestParameters = ts . hasRestParameter ( func ) ; var len = func . parameters . length - ( funcHasRestParameters ? 1 : 0 ) ; var indexOfParameter = ts . indexOf ( func . parameters , parameter ) ; if ( indexOfParameter < len ) { return getTypeAtPosition ( contextualSignature , indexOfParameter ) ; } // If last parameter is contextually rest parameter get its type if ( funcHasRestParameters && indexOfParameter === ( func . parameters . length - 1 ) && isRestParameterIndex ( contextualSignature , func . parameters . length - 1 ) ) { return getTypeOfSymbol ( ts . lastOrUndefined ( contextualSignature . parameters ) ) ; } } } } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In a variable parameter or property declaration with a type annotation the contextual type of an initializer expression is the type of the variable parameter or property . Otherwise in a parameter declaration of a contextually typed function expression the contextual type of an initializer expression is the contextual type of the parameter . Otherwise in a variable or parameter declaration with a binding pattern name the contextual type of an initializer expression is the type implied by the binding pattern . [CODESPLIT] function getContextualTypeForInitializerExpression ( node ) { var declaration = node . parent ; if ( node === declaration . initializer ) { if ( declaration . type ) { return getTypeFromTypeNode ( declaration . type ) ; } if ( declaration . kind === 138 /* Parameter */ ) { var type = getContextuallyTypedParameterType ( declaration ) ; if ( type ) { return type ; } } if ( ts . isBindingPattern ( declaration . name ) ) { return getTypeFromBindingPattern ( declaration . name , /*includePatternInType*/ true ) ; } } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply a mapping function to a contextual type and return the resulting type . If the contextual type is a union type the mapping function is applied to each constituent type and a union of the resulting types is returned . [CODESPLIT] function applyToContextualType ( type , mapper ) { if ( ! ( type . flags & 16384 /* Union */ ) ) { return mapper ( type ) ; } var types = type . types ; var mappedType ; var mappedTypes ; for ( var _i = 0 ; _i < types . length ; _i ++ ) { var current = types [ _i ] ; var t = mapper ( current ) ; if ( t ) { if ( ! mappedType ) { mappedType = t ; } else if ( ! mappedTypes ) { mappedTypes = [ mappedType , t ] ; } else { mappedTypes . push ( t ) ; } } } return mappedTypes ? getUnionType ( mappedTypes ) : mappedType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given contextual type provides an index signature of the given kind [CODESPLIT] function contextualTypeHasIndexSignature ( type , kind ) { return ! ! ( type . flags & 16384 /* Union */ ? ts . forEach ( type . types , function ( t ) { return getIndexTypeOfStructuredType ( t , kind ) ; } ) : getIndexTypeOfStructuredType ( type , kind ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In an object literal contextually typed by a type T the contextual type of a property assignment is the type of the matching property in T if one exists . Otherwise it is the type of the numeric index signature in T if one exists . Otherwise it is the type of the string index signature in T if one exists . [CODESPLIT] function getContextualTypeForObjectLiteralMethod ( node ) { ts . Debug . assert ( ts . isObjectLiteralMethod ( node ) ) ; if ( isInsideWithStatementBody ( node ) ) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined ; } return getContextualTypeForObjectLiteralElement ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In an array literal contextually typed by a type T the contextual type of an element expression at index N is the type of the property with the numeric name N in T if one exists . Otherwise if T has a numeric index signature it is the type of the numeric index signature in T . Otherwise in ES6 and higher the contextual type is the iterated type of T . [CODESPLIT] function getContextualTypeForElementExpression ( node ) { var arrayLiteral = node . parent ; var type = getContextualType ( arrayLiteral ) ; if ( type ) { var index = ts . indexOf ( arrayLiteral . elements , node ) ; return getTypeOfPropertyOfContextualType ( type , \"\" + index ) || getIndexTypeOfContextualType ( type , 1 /* Number */ ) || ( languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable ( type , /*errorNode*/ undefined ) : undefined ) ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In a contextually typed conditional expression the true / false expressions are contextually typed by the same type . [CODESPLIT] function getContextualTypeForConditionalOperand ( node ) { var conditional = node . parent ; return node === conditional . whenTrue || node === conditional . whenFalse ? getContextualType ( conditional ) : undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the given type is an object or union type if that type has a single signature and if that signature is non - generic return the signature . Otherwise return undefined . [CODESPLIT] function getNonGenericSignature ( type ) { var signatures = getSignaturesOfStructuredType ( type , 0 /* Call */ ) ; if ( signatures . length === 1 ) { var signature = signatures [ 0 ] ; if ( ! signature . typeParameters ) { return signature ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the contextual signature for a given expression node . A contextual type provides a contextual signature if it has a single call signature and if that call signature is non - generic . If the contextual type is a union type get the signature from each type possible and if they are all identical ignoring their return type the result is same signature but with return type as union type of return types from these signatures [CODESPLIT] function getContextualSignature ( node ) { ts . Debug . assert ( node . kind !== 143 /* MethodDeclaration */ || ts . isObjectLiteralMethod ( node ) ) ; var type = ts . isObjectLiteralMethod ( node ) ? getContextualTypeForObjectLiteralMethod ( node ) : getContextualType ( node ) ; if ( ! type ) { return undefined ; } if ( ! ( type . flags & 16384 /* Union */ ) ) { return getNonGenericSignature ( type ) ; } var signatureList ; var types = type . types ; for ( var _i = 0 ; _i < types . length ; _i ++ ) { var current = types [ _i ] ; var signature = getNonGenericSignature ( current ) ; if ( signature ) { if ( ! signatureList ) { // This signature will contribute to contextual union signature signatureList = [ signature ] ; } else if ( ! compareSignatures ( signatureList [ 0 ] , signature , /*partialMatch*/ false , /*ignoreReturnTypes*/ true , compareTypes ) ) { // Signatures aren't identical, do not use return undefined ; } else { // Use this signature for contextual union signature signatureList . push ( signature ) ; } } } // Result is union of signatures collected (return type is union of return types of this signature set) var result ; if ( signatureList ) { result = cloneSignature ( signatureList [ 0 ] ) ; // Clear resolved return type we possibly got from cloneSignature result . resolvedReturnType = undefined ; result . unionSignatures = signatureList ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A node is an assignment target if it is on the left hand side of an = token if it is parented by a property assignment in an object literal that is an assignment target or if it is parented by an array literal that is an assignment target . Examples include a = xxx { p : a } = xxx [ { p : a } ] = xxx . [CODESPLIT] function isAssignmentTarget ( node ) { var parent = node . parent ; if ( parent . kind === 181 /* BinaryExpression */ && parent . operatorToken . kind === 56 /* EqualsToken */ && parent . left === node ) { return true ; } if ( parent . kind === 245 /* PropertyAssignment */ ) { return isAssignmentTarget ( parent . parent ) ; } if ( parent . kind === 164 /* ArrayLiteralExpression */ ) { return isAssignmentTarget ( parent ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ Returns the type JSX . IntrinsicElements . May return unknownType if that type is not present . [CODESPLIT] function getJsxIntrinsicElementsType ( ) { if ( ! jsxIntrinsicElementsType ) { jsxIntrinsicElementsType = getExportedTypeFromNamespace ( JsxNames . JSX , JsxNames . IntrinsicElements ) || unknownType ; } return jsxIntrinsicElementsType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ Given a JSX opening element or self - closing element return the symbol of the property that the tag name points to if / this is an intrinsic tag . This might be a named / property of the IntrinsicElements interface or its string indexer . / If this is a class - based tag ( otherwise returns undefined ) returns the symbol of the class / type or factory function . / Otherwise returns unknownSymbol . [CODESPLIT] function getJsxElementTagSymbol ( node ) { var flags = 8 /* UnknownElement */ ; var links = getNodeLinks ( node ) ; if ( ! links . resolvedSymbol ) { if ( isJsxIntrinsicIdentifier ( node . tagName ) ) { links . resolvedSymbol = lookupIntrinsicTag ( node ) ; } else { links . resolvedSymbol = lookupClassTag ( node ) ; } } return links . resolvedSymbol ; function lookupIntrinsicTag ( node ) { var intrinsicElementsType = getJsxIntrinsicElementsType ( ) ; if ( intrinsicElementsType !== unknownType ) { // Property case var intrinsicProp = getPropertyOfType ( intrinsicElementsType , node . tagName . text ) ; if ( intrinsicProp ) { links . jsxFlags |= 1 /* IntrinsicNamedElement */ ; return intrinsicProp ; } // Intrinsic string indexer case var indexSignatureType = getIndexTypeOfType ( intrinsicElementsType , 0 /* String */ ) ; if ( indexSignatureType ) { links . jsxFlags |= 2 /* IntrinsicIndexedElement */ ; return intrinsicElementsType . symbol ; } // Wasn't found error ( node , ts . Diagnostics . Property_0_does_not_exist_on_type_1 , node . tagName . text , \"JSX.\" + JsxNames . IntrinsicElements ) ; return unknownSymbol ; } else { if ( compilerOptions . noImplicitAny ) { error ( node , ts . Diagnostics . JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists , JsxNames . IntrinsicElements ) ; } } } function lookupClassTag ( node ) { var valueSymbol = resolveJsxTagName ( node ) ; // Look up the value in the current scope if ( valueSymbol && valueSymbol !== unknownSymbol ) { links . jsxFlags |= 4 /* ClassElement */ ; if ( valueSymbol . flags & 8388608 /* Alias */ ) { markAliasSymbolAsReferenced ( valueSymbol ) ; } } return valueSymbol || unknownSymbol ; } function resolveJsxTagName ( node ) { if ( node . tagName . kind === 69 /* Identifier */ ) { var tag = node . tagName ; var sym = getResolvedSymbol ( tag ) ; return sym . exportSymbol || sym ; } else { return checkQualifiedName ( node . tagName ) . symbol ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a JSX element that is a class element finds the Element Instance Type . If the element is not a class element or the class element type cannot be determined returns undefined . For example in the element <MyClass > the element instance type is MyClass ( not typeof MyClass ) . [CODESPLIT] function getJsxElementInstanceType ( node ) { // There is no such thing as an instance type for a non-class element. This // line shouldn't be hit. ts . Debug . assert ( ! ! ( getNodeLinks ( node ) . jsxFlags & 4 /* ClassElement */ ) , \"Should not call getJsxElementInstanceType on non-class Element\" ) ; var classSymbol = getJsxElementTagSymbol ( node ) ; if ( classSymbol === unknownSymbol ) { // Couldn't find the class instance type. Error has already been issued return anyType ; } var valueType = getTypeOfSymbol ( classSymbol ) ; if ( isTypeAny ( valueType ) ) { // Short-circuit if the class tag is using an element type 'any' return anyType ; } // Resolve the signatures, preferring constructors var signatures = getSignaturesOfType ( valueType , 1 /* Construct */ ) ; if ( signatures . length === 0 ) { // No construct signatures, try call signatures signatures = getSignaturesOfType ( valueType , 0 /* Call */ ) ; if ( signatures . length === 0 ) { // We found no signatures at all, which is an error error ( node . tagName , ts . Diagnostics . JSX_element_type_0_does_not_have_any_construct_or_call_signatures , ts . getTextOfNode ( node . tagName ) ) ; return unknownType ; } } var returnType = getUnionType ( signatures . map ( getReturnTypeOfSignature ) ) ; // Issue an error if this return type isn't assignable to JSX.ElementClass var elemClassType = getJsxGlobalElementClassType ( ) ; if ( elemClassType ) { checkTypeRelatedTo ( returnType , elemClassType , assignableRelation , node , ts . Diagnostics . JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements ) ; } return returnType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given an opening / self - closing element get the element attributes type i . e . the type that tells us which attributes are valid on a given element . [CODESPLIT] function getJsxElementAttributesType ( node ) { var links = getNodeLinks ( node ) ; if ( ! links . resolvedJsxType ) { var sym = getJsxElementTagSymbol ( node ) ; if ( links . jsxFlags & 4 /* ClassElement */ ) { var elemInstanceType = getJsxElementInstanceType ( node ) ; if ( isTypeAny ( elemInstanceType ) ) { return links . resolvedJsxType = elemInstanceType ; } var propsName = getJsxElementPropertiesName ( ) ; if ( propsName === undefined ) { // There is no type ElementAttributesProperty, return 'any' return links . resolvedJsxType = anyType ; } else if ( propsName === \"\" ) { // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead return links . resolvedJsxType = elemInstanceType ; } else { var attributesType = getTypeOfPropertyOfType ( elemInstanceType , propsName ) ; if ( ! attributesType ) { // There is no property named 'props' on this instance type return links . resolvedJsxType = emptyObjectType ; } else if ( isTypeAny ( attributesType ) || ( attributesType === unknownType ) ) { return links . resolvedJsxType = attributesType ; } else if ( ! ( attributesType . flags & 80896 /* ObjectType */ ) ) { error ( node . tagName , ts . Diagnostics . JSX_element_attributes_type_0_must_be_an_object_type , typeToString ( attributesType ) ) ; return links . resolvedJsxType = anyType ; } else { return links . resolvedJsxType = attributesType ; } } } else if ( links . jsxFlags & 1 /* IntrinsicNamedElement */ ) { return links . resolvedJsxType = getTypeOfSymbol ( sym ) ; } else if ( links . jsxFlags & 2 /* IntrinsicIndexedElement */ ) { return links . resolvedJsxType = getIndexTypeOfSymbol ( sym , 0 /* String */ ) ; } else { // Resolution failed, so we don't know return links . resolvedJsxType = anyType ; } } return links . resolvedJsxType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a JSX attribute returns the symbol for the corresponds property of the element attributes type . Will return unknownSymbol for attributes that have no matching element attributes type property . [CODESPLIT] function getJsxAttributePropertySymbol ( attrib ) { var attributesType = getJsxElementAttributesType ( attrib . parent ) ; var prop = getPropertyOfType ( attributesType , attrib . name . text ) ; return prop || unknownSymbol ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether the requested property access is valid . Returns true if node is a valid property access and false otherwise . [CODESPLIT] function checkClassPropertyAccess ( node , left , type , prop ) { var flags = getDeclarationFlagsFromSymbol ( prop ) ; var declaringClass = getDeclaredTypeOfSymbol ( prop . parent ) ; if ( left . kind === 95 /* SuperKeyword */ ) { var errorNode = node . kind === 166 /* PropertyAccessExpression */ ? node . name : node . right ; // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or //   instance member variable initializer where this references a derived class instance, //   a super property access is permitted and must specify a public instance member function of the base class. // - In a static member function or static member accessor //   where this references the constructor function object of a derived class, //   a super property access is permitted and must specify a public static member function of the base class. if ( getDeclarationKindFromSymbol ( prop ) !== 143 /* MethodDeclaration */ ) { // `prop` refers to a *property* declared in the super class // rather than a *method*, so it does not satisfy the above criteria. error ( errorNode , ts . Diagnostics . Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword ) ; return false ; } if ( flags & 256 /* Abstract */ ) { // A method cannot be accessed in a super property access if the method is abstract. // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an // additional error elsewhere. error ( errorNode , ts . Diagnostics . Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression , symbolToString ( prop ) , typeToString ( declaringClass ) ) ; return false ; } } // Public properties are otherwise accessible. if ( ! ( flags & ( 32 /* Private */ | 64 /* Protected */ ) ) ) { return true ; } // Property is known to be private or protected at this point // Get the declaring and enclosing class instance types var enclosingClassDeclaration = ts . getContainingClass ( node ) ; var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol ( getSymbolOfNode ( enclosingClassDeclaration ) ) : undefined ; // Private property is accessible if declaring and enclosing class are the same if ( flags & 32 /* Private */ ) { if ( declaringClass !== enclosingClass ) { error ( node , ts . Diagnostics . Property_0_is_private_and_only_accessible_within_class_1 , symbolToString ( prop ) , typeToString ( declaringClass ) ) ; return false ; } return true ; } // Property is known to be protected at this point // All protected properties of a supertype are accessible in a super access if ( left . kind === 95 /* SuperKeyword */ ) { return true ; } // A protected property is accessible in the declaring class and classes derived from it if ( ! enclosingClass || ! hasBaseType ( enclosingClass , declaringClass ) ) { error ( node , ts . Diagnostics . Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses , symbolToString ( prop ) , typeToString ( declaringClass ) ) ; return false ; } // No further restrictions for static properties if ( flags & 128 /* Static */ ) { return true ; } // An instance property must be accessed through an instance of the enclosing class if ( type . flags & 33554432 /* ThisType */ ) { // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter ( type ) ; } // TODO: why is the first part of this check here? if ( ! ( getTargetType ( type ) . flags & ( 1024 /* Class */ | 2048 /* Interface */ ) && hasBaseType ( type , enclosingClass ) ) ) { error ( node , ts . Diagnostics . Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1 , symbolToString ( prop ) , typeToString ( enclosingClass ) ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If indexArgumentExpression is a string literal or number literal returns its text . If indexArgumentExpression is a constant value returns its string value . If indexArgumentExpression is a well known symbol returns the property name corresponding to this symbol as long as it is a proper symbol reference . Otherwise returns undefined . [CODESPLIT] function getPropertyNameForIndexedAccess ( indexArgumentExpression , indexArgumentType ) { if ( indexArgumentExpression . kind === 9 /* StringLiteral */ || indexArgumentExpression . kind === 8 /* NumericLiteral */ ) { return indexArgumentExpression . text ; } if ( indexArgumentExpression . kind === 167 /* ElementAccessExpression */ || indexArgumentExpression . kind === 166 /* PropertyAccessExpression */ ) { var value = getConstantValue ( indexArgumentExpression ) ; if ( value !== undefined ) { return value . toString ( ) ; } } if ( checkThatExpressionIsProperSymbolReference ( indexArgumentExpression , indexArgumentType , /*reportError*/ false ) ) { var rightHandSideName = indexArgumentExpression . name . text ; return ts . getPropertyNameForKnownSymbolName ( rightHandSideName ) ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - order candidate signatures into the result array . Assumes the result array to be empty . The candidate list orders groups in reverse but within a group signatures are kept in declaration order A nit here is that we reorder only signatures that belong to the same symbol so order how inherited signatures are processed is still preserved . interface A { ( x : string ) : void } interface B extends A { ( x : foo ) : string } let b : B ; b ( foo ) // < - here overloads should be processed as [ ( x : foo ) : string ( x : string ) : void ] [CODESPLIT] function reorderCandidates ( signatures , result ) { var lastParent ; var lastSymbol ; var cutoffIndex = 0 ; var index ; var specializedIndex = - 1 ; var spliceIndex ; ts . Debug . assert ( ! result . length ) ; for ( var _i = 0 ; _i < signatures . length ; _i ++ ) { var signature = signatures [ _i ] ; var symbol = signature . declaration && getSymbolOfNode ( signature . declaration ) ; var parent_5 = signature . declaration && signature . declaration . parent ; if ( ! lastSymbol || symbol === lastSymbol ) { if ( lastParent && parent_5 === lastParent ) { index ++ ; } else { lastParent = parent_5 ; index = cutoffIndex ; } } else { // current declaration belongs to a different symbol // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex index = cutoffIndex = result . length ; lastParent = parent_5 ; } lastSymbol = symbol ; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 if ( signature . hasStringLiterals ) { specializedIndex ++ ; spliceIndex = specializedIndex ; // The cutoff index always needs to be greater than or equal to the specialized signature index // in order to prevent non-specialized signatures from being added before a specialized // signature. cutoffIndex ++ ; } else { spliceIndex = index ; } result . splice ( spliceIndex , 0 , signature ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If type has a single call signature and no other members return that signature . Otherwise return undefined . [CODESPLIT] function getSingleCallSignature ( type ) { if ( type . flags & 80896 /* ObjectType */ ) { var resolved = resolveStructuredTypeMembers ( type ) ; if ( resolved . callSignatures . length === 1 && resolved . constructSignatures . length === 0 && resolved . properties . length === 0 && ! resolved . stringIndexType && ! resolved . numberIndexType ) { return resolved . callSignatures [ 0 ] ; } } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiate a generic signature in the context of a non - generic signature ( section 3 . 8 . 5 in TypeScript spec ) [CODESPLIT] function instantiateSignatureInContextOf ( signature , contextualSignature , contextualMapper ) { var context = createInferenceContext ( signature . typeParameters , /*inferUnionTypes*/ true ) ; forEachMatchingParameterType ( contextualSignature , signature , function ( source , target ) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes ( context , instantiateType ( source , contextualMapper ) , target ) ; } ) ; return getSignatureInstantiation ( signature , getInferredTypes ( context ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the effective arguments for an expression that works like a function invocation . [CODESPLIT] function getEffectiveCallArguments ( node ) { var args ; if ( node . kind === 170 /* TaggedTemplateExpression */ ) { var template = node . template ; args = [ undefined ] ; if ( template . kind === 183 /* TemplateExpression */ ) { ts . forEach ( template . templateSpans , function ( span ) { args . push ( span . expression ) ; } ) ; } } else if ( node . kind === 139 /* Decorator */ ) { // For a decorator, we return undefined as we will determine // the number and types of arguments for a decorator using // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. return undefined ; } else { args = node . arguments || emptyArray ; } return args ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the effective argument count for a node that works like a function invocation . If node is a Decorator the number of arguments is derived from the decoration target and the signature : If node . target is a class declaration or class expression the effective argument count is 1 . If node . target is a parameter declaration the effective argument count is 3 . If node . target is a property declaration the effective argument count is 2 . If node . target is a method or accessor declaration the effective argument count is 3 although it can be 2 if the signature only accepts two arguments allowing us to match a property decorator . Otherwise the argument count is the length of the args array . [CODESPLIT] function getEffectiveArgumentCount ( node , args , signature ) { if ( node . kind === 139 /* Decorator */ ) { switch ( node . parent . kind ) { case 214 /* ClassDeclaration */ : case 186 /* ClassExpression */ : // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1 ; case 141 /* PropertyDeclaration */ : // A property declaration decorator will have two arguments (see // `PropertyDecorator` in core.d.ts) return 2 ; case 143 /* MethodDeclaration */ : case 145 /* GetAccessor */ : case 146 /* SetAccessor */ : // A method or accessor declaration decorator will have two or three arguments (see // `PropertyDecorator` and `MethodDecorator` in core.d.ts) // If we are emitting decorators for ES3, we will only pass two arguments. if ( languageVersion === 0 /* ES3 */ ) { return 2 ; } // If the method decorator signature only accepts a target and a key, we will only // type check those arguments. return signature . parameters . length >= 3 ? 3 : 2 ; case 138 /* Parameter */ : // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3 ; } } else { return args . length ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the effective type for the second argument to a decorator . If node is a parameter its effective argument type is one of the following : If node . parent is a constructor the effective argument type is any as we will emit undefined . If node . parent is a member with an identifier numeric or string literal name the effective argument type will be a string literal type for the member name . If node . parent is a computed property name the effective argument type will either be a symbol type or the string type . If node is a member with an identifier numeric or string literal name the effective argument type will be a string literal type for the member name . If node is a computed property name the effective argument type will either be a symbol type or the string type . A class decorator does not have a second argument type . [CODESPLIT] function getEffectiveDecoratorSecondArgumentType ( node ) { // The second argument to a decorator is its `propertyKey` if ( node . kind === 214 /* ClassDeclaration */ ) { ts . Debug . fail ( \"Class decorators should not have a second synthetic argument.\" ) ; return unknownType ; } if ( node . kind === 138 /* Parameter */ ) { node = node . parent ; if ( node . kind === 144 /* Constructor */ ) { // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType ; } } if ( node . kind === 141 /* PropertyDeclaration */ || node . kind === 143 /* MethodDeclaration */ || node . kind === 145 /* GetAccessor */ || node . kind === 146 /* SetAccessor */ ) { // The `propertyKey` for a property or method decorator will be a // string literal type if the member name is an identifier, number, or string; // otherwise, if the member name is a computed property name it will // be either string or symbol. var element = node ; switch ( element . name . kind ) { case 69 /* Identifier */ : case 8 /* NumericLiteral */ : case 9 /* StringLiteral */ : return getStringLiteralType ( element . name ) ; case 136 /* ComputedPropertyName */ : var nameType = checkComputedPropertyName ( element . name ) ; if ( allConstituentTypesHaveKind ( nameType , 16777216 /* ESSymbol */ ) ) { return nameType ; } else { return stringType ; } default : ts . Debug . fail ( \"Unsupported property name.\" ) ; return unknownType ; } } ts . Debug . fail ( \"Unsupported decorator target.\" ) ; return unknownType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the effective argument type for the provided argument to a decorator . [CODESPLIT] function getEffectiveDecoratorArgumentType ( node , argIndex ) { if ( argIndex === 0 ) { return getEffectiveDecoratorFirstArgumentType ( node . parent ) ; } else if ( argIndex === 1 ) { return getEffectiveDecoratorSecondArgumentType ( node . parent ) ; } else if ( argIndex === 2 ) { return getEffectiveDecoratorThirdArgumentType ( node . parent ) ; } ts . Debug . fail ( \"Decorators should not have a fourth synthetic argument.\" ) ; return unknownType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the effective argument type for an argument in a call expression . [CODESPLIT] function getEffectiveArgumentType ( node , argIndex , arg ) { // Decorators provide special arguments, a tagged template expression provides // a special first argument, and string literals get string literal types // unless we're reporting errors if ( node . kind === 139 /* Decorator */ ) { return getEffectiveDecoratorArgumentType ( node , argIndex ) ; } else if ( argIndex === 0 && node . kind === 170 /* TaggedTemplateExpression */ ) { return globalTemplateStringsArrayType ; } // This is not a synthetic argument, so we return 'undefined' // to signal that the caller needs to check the argument. return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the effective argument expression for an argument in a call expression . [CODESPLIT] function getEffectiveArgument ( node , args , argIndex ) { // For a decorator or the first argument of a tagged template expression we return undefined. if ( node . kind === 139 /* Decorator */ || ( argIndex === 0 && node . kind === 170 /* TaggedTemplateExpression */ ) ) { return undefined ; } return args [ argIndex ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the error node to use when reporting errors for an effective argument . [CODESPLIT] function getEffectiveArgumentErrorNode ( node , argIndex , arg ) { if ( node . kind === 139 /* Decorator */ ) { // For a decorator, we use the expression of the decorator for error reporting. return node . expression ; } else if ( argIndex === 0 && node . kind === 170 /* TaggedTemplateExpression */ ) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node . template ; } else { return arg ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression . [CODESPLIT] function getDiagnosticHeadMessageForDecoratorResolution ( node ) { switch ( node . parent . kind ) { case 214 /* ClassDeclaration */ : case 186 /* ClassExpression */ : return ts . Diagnostics . Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression ; case 138 /* Parameter */ : return ts . Diagnostics . Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression ; case 141 /* PropertyDeclaration */ : return ts . Diagnostics . Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression ; case 143 /* MethodDeclaration */ : case 145 /* GetAccessor */ : case 146 /* SetAccessor */ : return ts . Diagnostics . Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves a decorator as if it were a call expression . [CODESPLIT] function resolveDecorator ( node , candidatesOutArray ) { var funcType = checkExpression ( node . expression ) ; var apparentType = getApparentType ( funcType ) ; if ( apparentType === unknownType ) { return resolveErrorCall ( node ) ; } var callSignatures = getSignaturesOfType ( apparentType , 0 /* Call */ ) ; if ( funcType === anyType || ( ! callSignatures . length && ! ( funcType . flags & 16384 /* Union */ ) && isTypeAssignableTo ( funcType , globalFunctionType ) ) ) { return resolveUntypedCall ( node ) ; } var headMessage = getDiagnosticHeadMessageForDecoratorResolution ( node ) ; if ( ! callSignatures . length ) { var errorInfo ; errorInfo = ts . chainDiagnosticMessages ( errorInfo , ts . Diagnostics . Cannot_invoke_an_expression_whose_type_lacks_a_call_signature ) ; errorInfo = ts . chainDiagnosticMessages ( errorInfo , headMessage ) ; diagnostics . add ( ts . createDiagnosticForNodeFromMessageChain ( node , errorInfo ) ) ; return resolveErrorCall ( node ) ; } return resolveCall ( node , callSignatures , candidatesOutArray , headMessage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "candidatesOutArray is passed by signature help in the language service and collectCandidates must fill it up with the appropriate candidate signatures [CODESPLIT] function getResolvedSignature ( node , candidatesOutArray ) { var links = getNodeLinks ( node ) ; // If getResolvedSignature has already been called, we will have cached the resolvedSignature. // However, it is possible that either candidatesOutArray was not passed in the first time, // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work // to correctly fill the candidatesOutArray. if ( ! links . resolvedSignature || candidatesOutArray ) { links . resolvedSignature = anySignature ; if ( node . kind === 168 /* CallExpression */ ) { links . resolvedSignature = resolveCallExpression ( node , candidatesOutArray ) ; } else if ( node . kind === 169 /* NewExpression */ ) { links . resolvedSignature = resolveNewExpression ( node , candidatesOutArray ) ; } else if ( node . kind === 170 /* TaggedTemplateExpression */ ) { links . resolvedSignature = resolveTaggedTemplateExpression ( node , candidatesOutArray ) ; } else if ( node . kind === 139 /* Decorator */ ) { links . resolvedSignature = resolveDecorator ( node , candidatesOutArray ) ; } else { ts . Debug . fail ( \"Branch in 'getResolvedSignature' should be unreachable.\" ) ; } } return links . resolvedSignature ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Syntactically and semantically checks a call or new expression . [CODESPLIT] function checkCallExpression ( node ) { // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true checkGrammarTypeArguments ( node , node . typeArguments ) || checkGrammarArguments ( node , node . arguments ) ; var signature = getResolvedSignature ( node ) ; if ( node . expression . kind === 95 /* SuperKeyword */ ) { return voidType ; } if ( node . kind === 169 /* NewExpression */ ) { var declaration = signature . declaration ; if ( declaration && declaration . kind !== 144 /* Constructor */ && declaration . kind !== 148 /* ConstructSignature */ && declaration . kind !== 153 /* ConstructorType */ ) { // When resolved signature is a call signature (and not a construct signature) the result type is any if ( compilerOptions . noImplicitAny ) { error ( node , ts . Diagnostics . new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type ) ; } return anyType ; } } return getReturnTypeOfSignature ( signature ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When contextual typing assigns a type to a parameter that contains a binding pattern we also need to push the destructured type into the contained binding elements . [CODESPLIT] function assignBindingElementTypes ( node ) { if ( ts . isBindingPattern ( node . name ) ) { for ( var _i = 0 , _a = node . name . elements ; _i < _a . length ; _i ++ ) { var element = _a [ _i ] ; if ( element . kind !== 187 /* OmittedExpression */ ) { if ( element . name . kind === 69 /* Identifier */ ) { getSymbolLinks ( getSymbolOfNode ( element ) ) . type = getTypeForBindingElement ( element ) ; } assignBindingElementTypes ( element ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TypeScript Specification 1 . 0 ( 6 . 3 ) - July 2014 An explicitly typed function whose return type isn t the Void or the Any type must have at least one return statement somewhere in its body . An exception to this rule is if the function implementation consists of a single throw statement . [CODESPLIT] function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment ( func , returnType ) { if ( ! produceDiagnostics ) { return ; } // Functions that return 'void' or 'any' don't need any return expressions. if ( returnType === voidType || isTypeAny ( returnType ) ) { return ; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. if ( ts . nodeIsMissing ( func . body ) || func . body . kind !== 192 /* Block */ ) { return ; } var bodyBlock = func . body ; // Ensure the body has at least one return expression. if ( bodyContainsAReturnStatement ( bodyBlock ) ) { return ; } // If there are no return expressions, then we need to check if // the function body consists solely of a throw statement; // this is to make an exception for unimplemented functions. if ( bodyContainsSingleThrowStatement ( bodyBlock ) ) { return ; } // This function does not conform to the specification. error ( func . type , ts . Diagnostics . A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Just like isTypeOfKind below except that it returns true if * any * constituent has this kind . [CODESPLIT] function someConstituentTypeHasKind ( type , kind ) { if ( type . flags & kind ) { return true ; } if ( type . flags & 49152 /* UnionOrIntersection */ ) { var types = type . types ; for ( var _i = 0 ; _i < types . length ; _i ++ ) { var current = types [ _i ] ; if ( current . flags & kind ) { return true ; } } return false ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DECLARATION AND STATEMENT TYPE CHECKING [CODESPLIT] function checkTypeParameter ( node ) { // Grammar Checking if ( node . expression ) { grammarErrorOnFirstToken ( node . expression , ts . Diagnostics . Type_expected ) ; } checkSourceElement ( node . constraint ) ; if ( produceDiagnostics ) { checkTypeParameterHasIllegalReferencesInConstraint ( node ) ; checkTypeNameIsReserved ( node . name , ts . Diagnostics . Type_parameter_name_cannot_be_0 ) ; } // TODO: Check multiple declarations are identical }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the promised type of a promise . [CODESPLIT] function getPromisedType ( promise ) { // //  { // promise //      then( // thenFunction //          onfulfilled: ( // onfulfilledParameterType //              value: T // valueParameterType //          ) => any //      ): any; //  } // if ( promise . flags & 1 /* Any */ ) { return undefined ; } if ( ( promise . flags & 4096 /* Reference */ ) && promise . target === tryGetGlobalPromiseType ( ) ) { return promise . typeArguments [ 0 ] ; } var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType ( ) ; if ( globalPromiseLikeType === emptyObjectType || ! isTypeAssignableTo ( promise , globalPromiseLikeType ) ) { return undefined ; } var thenFunction = getTypeOfPropertyOfType ( promise , \"then\" ) ; if ( thenFunction && ( thenFunction . flags & 1 /* Any */ ) ) { return undefined ; } var thenSignatures = thenFunction ? getSignaturesOfType ( thenFunction , 0 /* Call */ ) : emptyArray ; if ( thenSignatures . length === 0 ) { return undefined ; } var onfulfilledParameterType = getUnionType ( ts . map ( thenSignatures , getTypeOfFirstParameterOfSignature ) ) ; if ( onfulfilledParameterType . flags & 1 /* Any */ ) { return undefined ; } var onfulfilledParameterSignatures = getSignaturesOfType ( onfulfilledParameterType , 0 /* Call */ ) ; if ( onfulfilledParameterSignatures . length === 0 ) { return undefined ; } var valueParameterType = getUnionType ( ts . map ( onfulfilledParameterSignatures , getTypeOfFirstParameterOfSignature ) ) ; return valueParameterType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check a decorator [CODESPLIT] function checkDecorator ( node ) { var signature = getResolvedSignature ( node ) ; var returnType = getReturnTypeOfSignature ( signature ) ; if ( returnType . flags & 1 /* Any */ ) { return ; } var expectedReturnType ; var headMessage = getDiagnosticHeadMessageForDecoratorResolution ( node ) ; var errorInfo ; switch ( node . parent . kind ) { case 214 /* ClassDeclaration */ : var classSymbol = getSymbolOfNode ( node . parent ) ; var classConstructorType = getTypeOfSymbol ( classSymbol ) ; expectedReturnType = getUnionType ( [ classConstructorType , voidType ] ) ; break ; case 138 /* Parameter */ : expectedReturnType = voidType ; errorInfo = ts . chainDiagnosticMessages ( errorInfo , ts . Diagnostics . The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any ) ; break ; case 141 /* PropertyDeclaration */ : expectedReturnType = voidType ; errorInfo = ts . chainDiagnosticMessages ( errorInfo , ts . Diagnostics . The_return_type_of_a_property_decorator_function_must_be_either_void_or_any ) ; break ; case 143 /* MethodDeclaration */ : case 145 /* GetAccessor */ : case 146 /* SetAccessor */ : var methodType = getTypeOfNode ( node . parent ) ; var descriptorType = createTypedPropertyDescriptorType ( methodType ) ; expectedReturnType = getUnionType ( [ descriptorType , voidType ] ) ; break ; } checkTypeAssignableTo ( returnType , expectedReturnType , node , headMessage , errorInfo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks a type reference node as an expression . [CODESPLIT] function checkTypeNodeAsExpression ( node ) { // When we are emitting type metadata for decorators, we need to try to check the type // as if it were an expression so that we can emit the type in a value position when we // serialize the type metadata. if ( node && node . kind === 151 /* TypeReference */ ) { var root = getFirstIdentifier ( node . typeName ) ; var meaning = root . parent . kind === 151 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */ ; // Resolve type so we know which symbol is referenced var rootSymbol = resolveName ( root , root . text , meaning | 8388608 /* Alias */ , /*nameNotFoundMessage*/ undefined , /*nameArg*/ undefined ) ; // Resolved symbol is alias if ( rootSymbol && rootSymbol . flags & 8388608 /* Alias */ ) { var aliasTarget = resolveAlias ( rootSymbol ) ; // If alias has value symbol - mark alias as referenced if ( aliasTarget . flags & 107455 /* Value */ && ! isConstEnumOrConstEnumOnlyModule ( resolveAlias ( rootSymbol ) ) ) { markAliasSymbolAsReferenced ( rootSymbol ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the type annotation of an accessor declaration or property declaration as an expression if it is a type reference to a type with a value declaration . [CODESPLIT] function checkTypeAnnotationAsExpression ( node ) { switch ( node . kind ) { case 141 /* PropertyDeclaration */ : checkTypeNodeAsExpression ( node . type ) ; break ; case 138 /* Parameter */ : checkTypeNodeAsExpression ( node . type ) ; break ; case 143 /* MethodDeclaration */ : checkTypeNodeAsExpression ( node . type ) ; break ; case 145 /* GetAccessor */ : checkTypeNodeAsExpression ( node . type ) ; break ; case 146 /* SetAccessor */ : checkTypeNodeAsExpression ( ts . getSetAccessorTypeAnnotationNode ( node ) ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the type annotation of the parameters of a function / method or the constructor of a class as expressions [CODESPLIT] function checkParameterTypeAnnotationsAsExpressions ( node ) { // ensure all type annotations with a value declaration are checked as an expression for ( var _i = 0 , _a = node . parameters ; _i < _a . length ; _i ++ ) { var parameter = _a [ _i ] ; checkTypeAnnotationAsExpression ( parameter ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the decorators of a node [CODESPLIT] function checkDecorators ( node ) { if ( ! node . decorators ) { return ; } // skip this check for nodes that cannot have decorators. These should have already had an error reported by // checkGrammarDecorators. if ( ! ts . nodeCanBeDecorated ( node ) ) { return ; } if ( ! compilerOptions . experimentalDecorators ) { error ( node , ts . Diagnostics . Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_to_remove_this_warning ) ; } if ( compilerOptions . emitDecoratorMetadata ) { // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch ( node . kind ) { case 214 /* ClassDeclaration */ : var constructor = ts . getFirstConstructorWithBody ( node ) ; if ( constructor ) { checkParameterTypeAnnotationsAsExpressions ( constructor ) ; } break ; case 143 /* MethodDeclaration */ : checkParameterTypeAnnotationsAsExpressions ( node ) ; // fall-through case 146 /* SetAccessor */ : case 145 /* GetAccessor */ : case 141 /* PropertyDeclaration */ : case 138 /* Parameter */ : checkTypeAnnotationAsExpression ( node ) ; break ; } } emitDecorate = true ; if ( node . kind === 138 /* Parameter */ ) { emitParam = true ; } ts . forEach ( node . decorators , checkDecorator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this function will run after checking the source file so CaptureThis is correct for all nodes [CODESPLIT] function checkIfThisIsCapturedInEnclosingScope ( node ) { var current = node ; while ( current ) { if ( getNodeCheckFlags ( current ) & 4 /* CaptureThis */ ) { var isDeclaration_1 = node . kind !== 69 /* Identifier */ ; if ( isDeclaration_1 ) { error ( node . name , ts . Diagnostics . Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference ) ; } else { error ( node , ts . Diagnostics . Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference ) ; } return ; } current = current . parent ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check that a parameter initializer contains no references to parameters declared to the right of itself [CODESPLIT] function checkParameterInitializer ( node ) { if ( ts . getRootDeclaration ( node ) . kind !== 138 /* Parameter */ ) { return ; } var func = ts . getContainingFunction ( node ) ; visit ( node . initializer ) ; function visit ( n ) { if ( n . kind === 69 /* Identifier */ ) { var referencedSymbol = getNodeLinks ( n ) . resolvedSymbol ; // check FunctionLikeDeclaration.locals (stores parameters\\function local variable) // if it contains entry with a specified name and if this entry matches the resolved symbol if ( referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol ( func . locals , referencedSymbol . name , 107455 /* Value */ ) === referencedSymbol ) { if ( referencedSymbol . valueDeclaration . kind === 138 /* Parameter */ ) { if ( referencedSymbol . valueDeclaration === node ) { error ( n , ts . Diagnostics . Parameter_0_cannot_be_referenced_in_its_initializer , ts . declarationNameToString ( node . name ) ) ; return ; } if ( referencedSymbol . valueDeclaration . pos < node . pos ) { // legal case - parameter initializer references some parameter strictly on left of current parameter declaration return ; } } error ( n , ts . Diagnostics . Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it , ts . declarationNameToString ( node . name ) , ts . declarationNameToString ( n ) ) ; } } else { ts . forEachChild ( n , visit ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check variable parameter or property declaration [CODESPLIT] function checkVariableLikeDeclaration ( node ) { checkDecorators ( node ) ; checkSourceElement ( node . type ) ; // For a computed property, just check the initializer and exit // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. if ( node . name . kind === 136 /* ComputedPropertyName */ ) { checkComputedPropertyName ( node . name ) ; if ( node . initializer ) { checkExpressionCached ( node . initializer ) ; } } // For a binding pattern, check contained binding elements if ( ts . isBindingPattern ( node . name ) ) { ts . forEach ( node . name . elements , checkSourceElement ) ; } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body if ( node . initializer && ts . getRootDeclaration ( node ) . kind === 138 /* Parameter */ && ts . nodeIsMissing ( ts . getContainingFunction ( node ) . body ) ) { error ( node , ts . Diagnostics . A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation ) ; return ; } // For a binding pattern, validate the initializer and exit if ( ts . isBindingPattern ( node . name ) ) { if ( node . initializer ) { checkTypeAssignableTo ( checkExpressionCached ( node . initializer ) , getWidenedTypeForVariableLikeDeclaration ( node ) , node , /*headMessage*/ undefined ) ; checkParameterInitializer ( node ) ; } return ; } var symbol = getSymbolOfNode ( node ) ; var type = getTypeOfVariableOrParameterOrProperty ( symbol ) ; if ( node === symbol . valueDeclaration ) { // Node is the primary declaration of the symbol, just validate the initializer if ( node . initializer ) { checkTypeAssignableTo ( checkExpressionCached ( node . initializer ) , type , node , /*headMessage*/ undefined ) ; checkParameterInitializer ( node ) ; } } else { // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node var declarationType = getWidenedTypeForVariableLikeDeclaration ( node ) ; if ( type !== unknownType && declarationType !== unknownType && ! isTypeIdenticalTo ( type , declarationType ) ) { error ( node . name , ts . Diagnostics . Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2 , ts . declarationNameToString ( node . name ) , typeToString ( type ) , typeToString ( declarationType ) ) ; } if ( node . initializer ) { checkTypeAssignableTo ( checkExpressionCached ( node . initializer ) , declarationType , node , /*headMessage*/ undefined ) ; } } if ( node . kind !== 141 /* PropertyDeclaration */ && node . kind !== 140 /* PropertySignature */ ) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations ( node ) ; if ( node . kind === 211 /* VariableDeclaration */ || node . kind === 163 /* BindingElement */ ) { checkVarDeclaredNamesNotShadowed ( node ) ; } checkCollisionWithCapturedSuperVariable ( node , node . name ) ; checkCollisionWithCapturedThisVariable ( node , node . name ) ; checkCollisionWithRequireExportsInGeneratedCode ( node , node . name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When errorNode is undefined it means we should not report any errors . [CODESPLIT] function checkElementTypeOfIterable ( iterable , errorNode ) { var elementType = getElementTypeOfIterable ( iterable , errorNode ) ; // Now even though we have extracted the iteratedType, we will have to validate that the type // passed in is actually an Iterable. if ( errorNode && elementType ) { checkTypeAssignableTo ( iterable , createIterableType ( elementType ) , errorNode ) ; } return elementType || anyType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check each type parameter and check that list has no duplicate type parameter declarations [CODESPLIT] function checkTypeParameters ( typeParameterDeclarations ) { if ( typeParameterDeclarations ) { for ( var i = 0 , n = typeParameterDeclarations . length ; i < n ; i ++ ) { var node = typeParameterDeclarations [ i ] ; checkTypeParameter ( node ) ; if ( produceDiagnostics ) { for ( var j = 0 ; j < i ; j ++ ) { if ( typeParameterDeclarations [ j ] . symbol === node . symbol ) { error ( node . name , ts . Diagnostics . Duplicate_identifier_0 , ts . declarationNameToString ( node . name ) ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function and class expression bodies are checked after all statements in the enclosing body . This is to ensure constructs like the following are permitted : let foo = function () { let s = foo () ; return hello ; } Here performing a full type check of the body of the function expression whilst in the process of determining the type of foo would cause foo to be given type any because of the recursive reference . Delaying the type check of the body ensures foo has been assigned a type . [CODESPLIT] function checkFunctionAndClassExpressionBodies ( node ) { switch ( node . kind ) { case 173 /* FunctionExpression */ : case 174 /* ArrowFunction */ : ts . forEach ( node . parameters , checkFunctionAndClassExpressionBodies ) ; checkFunctionExpressionOrObjectLiteralMethodBody ( node ) ; break ; case 186 /* ClassExpression */ : ts . forEach ( node . members , checkSourceElement ) ; ts . forEachChild ( node , checkFunctionAndClassExpressionBodies ) ; break ; case 143 /* MethodDeclaration */ : case 142 /* MethodSignature */ : ts . forEach ( node . decorators , checkFunctionAndClassExpressionBodies ) ; ts . forEach ( node . parameters , checkFunctionAndClassExpressionBodies ) ; if ( ts . isObjectLiteralMethod ( node ) ) { checkFunctionExpressionOrObjectLiteralMethodBody ( node ) ; } break ; case 144 /* Constructor */ : case 145 /* GetAccessor */ : case 146 /* SetAccessor */ : case 213 /* FunctionDeclaration */ : ts . forEach ( node . parameters , checkFunctionAndClassExpressionBodies ) ; break ; case 205 /* WithStatement */ : checkFunctionAndClassExpressionBodies ( node . expression ) ; break ; case 139 /* Decorator */ : case 138 /* Parameter */ : case 141 /* PropertyDeclaration */ : case 140 /* PropertySignature */ : case 161 /* ObjectBindingPattern */ : case 162 /* ArrayBindingPattern */ : case 163 /* BindingElement */ : case 164 /* ArrayLiteralExpression */ : case 165 /* ObjectLiteralExpression */ : case 245 /* PropertyAssignment */ : case 166 /* PropertyAccessExpression */ : case 167 /* ElementAccessExpression */ : case 168 /* CallExpression */ : case 169 /* NewExpression */ : case 170 /* TaggedTemplateExpression */ : case 183 /* TemplateExpression */ : case 190 /* TemplateSpan */ : case 171 /* TypeAssertionExpression */ : case 189 /* AsExpression */ : case 172 /* ParenthesizedExpression */ : case 176 /* TypeOfExpression */ : case 177 /* VoidExpression */ : case 178 /* AwaitExpression */ : case 175 /* DeleteExpression */ : case 179 /* PrefixUnaryExpression */ : case 180 /* PostfixUnaryExpression */ : case 181 /* BinaryExpression */ : case 182 /* ConditionalExpression */ : case 185 /* SpreadElementExpression */ : case 184 /* YieldExpression */ : case 192 /* Block */ : case 219 /* ModuleBlock */ : case 193 /* VariableStatement */ : case 195 /* ExpressionStatement */ : case 196 /* IfStatement */ : case 197 /* DoStatement */ : case 198 /* WhileStatement */ : case 199 /* ForStatement */ : case 200 /* ForInStatement */ : case 201 /* ForOfStatement */ : case 202 /* ContinueStatement */ : case 203 /* BreakStatement */ : case 204 /* ReturnStatement */ : case 206 /* SwitchStatement */ : case 220 /* CaseBlock */ : case 241 /* CaseClause */ : case 242 /* DefaultClause */ : case 207 /* LabeledStatement */ : case 208 /* ThrowStatement */ : case 209 /* TryStatement */ : case 244 /* CatchClause */ : case 211 /* VariableDeclaration */ : case 212 /* VariableDeclarationList */ : case 214 /* ClassDeclaration */ : case 243 /* HeritageClause */ : case 188 /* ExpressionWithTypeArguments */ : case 217 /* EnumDeclaration */ : case 247 /* EnumMember */ : case 227 /* ExportAssignment */ : case 248 /* SourceFile */ : case 240 /* JsxExpression */ : case 233 /* JsxElement */ : case 234 /* JsxSelfClosingElement */ : case 238 /* JsxAttribute */ : case 239 /* JsxSpreadAttribute */ : case 235 /* JsxOpeningElement */ : ts . forEachChild ( node , checkFunctionAndClassExpressionBodies ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fully type check a source file and collect the relevant diagnostics . [CODESPLIT] function checkSourceFileWorker ( node ) { var links = getNodeLinks ( node ) ; if ( ! ( links . flags & 1 /* TypeChecked */ ) ) { // Check whether the file has declared it is the default lib, // and whether the user has specifically chosen to avoid checking it. if ( node . isDefaultLib && compilerOptions . skipDefaultLibCheck ) { return ; } // Grammar checking checkGrammarSourceFile ( node ) ; emitExtends = false ; emitDecorate = false ; emitParam = false ; potentialThisCollisions . length = 0 ; ts . forEach ( node . statements , checkSourceElement ) ; checkFunctionAndClassExpressionBodies ( node ) ; if ( ts . isExternalModule ( node ) ) { checkExternalModuleExports ( node ) ; } if ( potentialThisCollisions . length ) { ts . forEach ( potentialThisCollisions , checkIfThisIsCapturedInEnclosingScope ) ; potentialThisCollisions . length = 0 ; } if ( emitExtends ) { links . flags |= 8 /* EmitExtends */ ; } if ( emitDecorate ) { links . flags |= 16 /* EmitDecorate */ ; } if ( emitParam ) { links . flags |= 32 /* EmitParam */ ; } if ( emitAwaiter ) { links . flags |= 64 /* EmitAwaiter */ ; } if ( emitGenerator || ( emitAwaiter && languageVersion < 2 /* ES6 */ ) ) { links . flags |= 128 /* EmitGenerator */ ; } links . flags |= 1 /* TypeChecked */ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy the given symbol into symbol tables if the symbol has the given meaning and it doesn t already existed in the symbol table [CODESPLIT] function copySymbol ( symbol , meaning ) { if ( symbol . flags & meaning ) { var id = symbol . name ; // We will copy all symbol regardless of its reserved name because // symbolsToArray will check whether the key is a reserved name and // it will not copy symbol with reserved name to the array if ( ! ts . hasProperty ( symbols , id ) ) { symbols [ id ] = symbol ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets either the static or instance type of a class element based on whether the element is declared as static . [CODESPLIT] function getParentTypeOfClassElement ( node ) { var classSymbol = getSymbolOfNode ( node . parent ) ; return node . flags & 128 /* Static */ ? getTypeOfSymbol ( classSymbol ) : getDeclaredTypeOfSymbol ( classSymbol ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the list of properties of the given type augmented with properties from Function if the type has call or construct signatures [CODESPLIT] function getAugmentedPropertiesOfType ( type ) { type = getApparentType ( type ) ; var propsByName = createSymbolTable ( getPropertiesOfType ( type ) ) ; if ( getSignaturesOfType ( type , 0 /* Call */ ) . length || getSignaturesOfType ( type , 1 /* Construct */ ) . length ) { ts . forEach ( getPropertiesOfType ( globalFunctionType ) , function ( p ) { if ( ! ts . hasProperty ( propsByName , p . name ) ) { propsByName [ p . name ] = p ; } } ) ; } return getNamedMembers ( propsByName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Emitter support When resolved as an expression identifier if the given node references an exported entity return the declaration node of the exported entity s container . Otherwise return undefined . [CODESPLIT] function getReferencedExportContainer ( node ) { var symbol = getReferencedValueSymbol ( node ) ; if ( symbol ) { if ( symbol . flags & 1048576 /* ExportValue */ ) { // If we reference an exported entity within the same module declaration, then whether // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the // kinds that we do NOT prefix. var exportSymbol = getMergedSymbol ( symbol . exportSymbol ) ; if ( exportSymbol . flags & 944 /* ExportHasLocal */ ) { return undefined ; } symbol = exportSymbol ; } var parentSymbol = getParentOfSymbol ( symbol ) ; if ( parentSymbol ) { if ( parentSymbol . flags & 512 /* ValueModule */ && parentSymbol . valueDeclaration . kind === 248 /* SourceFile */ ) { return parentSymbol . valueDeclaration ; } for ( var n = node . parent ; n ; n = n . parent ) { if ( ( n . kind === 218 /* ModuleDeclaration */ || n . kind === 217 /* EnumDeclaration */ ) && getSymbolOfNode ( n ) === parentSymbol ) { return n ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When resolved as an expression identifier if the given node references an import return the declaration of that import . Otherwise return undefined . [CODESPLIT] function getReferencedImportDeclaration ( node ) { var symbol = getReferencedValueSymbol ( node ) ; return symbol && symbol . flags & 8388608 /* Alias */ ? getDeclarationOfAliasSymbol ( symbol ) : undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When resolved as an expression identifier if the given node references a nested block scoped entity with a name that hides an existing name return the declaration of that entity . Otherwise return undefined . [CODESPLIT] function getReferencedNestedRedeclaration ( node ) { var symbol = getReferencedValueSymbol ( node ) ; return symbol && isNestedRedeclarationSymbol ( symbol ) ? symbol . valueDeclaration : undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GRAMMAR CHECKING [CODESPLIT] function checkGrammarDecorators ( node ) { if ( ! node . decorators ) { return false ; } if ( ! ts . nodeCanBeDecorated ( node ) ) { return grammarErrorOnFirstToken ( node , ts . Diagnostics . Decorators_are_not_valid_here ) ; } else if ( node . kind === 145 /* GetAccessor */ || node . kind === 146 /* SetAccessor */ ) { var accessors = ts . getAllAccessorDeclarations ( node . parent . members , node ) ; if ( accessors . firstAccessor . decorators && node === accessors . secondAccessor ) { return grammarErrorOnFirstToken ( node , ts . Diagnostics . Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a temp variable name to be used in export default statements . The temp name will be of the form _default_counter . Note that export default is only allowed at most once in a module so we do not need to keep track of created temp names . [CODESPLIT] function getExportDefaultTempVariableName ( ) { var baseName = \"_default\" ; if ( ! ts . hasProperty ( currentSourceFile . identifiers , baseName ) ) { return baseName ; } var count = 0 ; while ( true ) { var name_18 = baseName + \"_\" + ( ++ count ) ; if ( ! ts . hasProperty ( currentSourceFile . identifiers , name_18 ) ) { return name_18 ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function writeDeclarationFile ( jsFilePath , sourceFile , host , resolver , diagnostics ) { var emitDeclarationResult = emitDeclarations ( host , resolver , diagnostics , jsFilePath , sourceFile ) ; // TODO(shkamat): Should we not write any declaration file if any of them can produce error, // or should we just not write this file like we are doing now if ( ! emitDeclarationResult . reportedDeclarationError ) { var declarationOutput = emitDeclarationResult . referencePathsOutput + getDeclarationOutput ( emitDeclarationResult . synchronousDeclarationOutput , emitDeclarationResult . moduleElementDeclarationEmitInfo ) ; ts . writeFile ( host , diagnostics , ts . removeFileExtension ( jsFilePath ) + \".d.ts\" , declarationOutput , host . getCompilerOptions ( ) . emitBOM ) ; } function getDeclarationOutput ( synchronousDeclarationOutput , moduleElementDeclarationEmitInfo ) { var appliedSyncOutputPos = 0 ; var declarationOutput = \"\" ; // apply asynchronous additions to the synchronous output ts . forEach ( moduleElementDeclarationEmitInfo , function ( aliasEmitInfo ) { if ( aliasEmitInfo . asynchronousOutput ) { declarationOutput += synchronousDeclarationOutput . substring ( appliedSyncOutputPos , aliasEmitInfo . outputPos ) ; declarationOutput += getDeclarationOutput ( aliasEmitInfo . asynchronousOutput , aliasEmitInfo . subModuleElementDeclarationEmitInfo ) ; appliedSyncOutputPos = aliasEmitInfo . outputPos ; } } ) ; declarationOutput += synchronousDeclarationOutput . substring ( appliedSyncOutputPos ) ; return declarationOutput ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "targetSourceFile is when users only want one file in entire project to be emitted . This is used in compileOnSave feature [CODESPLIT] function emitFiles ( resolver , host , targetSourceFile ) { // emit output for the __extends helper function var extendsHelper = \"\\nvar __extends = (this && this.__extends) || function (d, b) {\\n    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\\n    function __() { this.constructor = d; }\\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\\n};\" ; // emit output for the __decorate helper function var decorateHelper = \"\\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\\n    if (typeof Reflect === \\\"object\\\" && typeof Reflect.decorate === \\\"function\\\") r = Reflect.decorate(decorators, target, key, desc);\\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\\n};\" ; // emit output for the __metadata helper function var metadataHelper = \"\\nvar __metadata = (this && this.__metadata) || function (k, v) {\\n    if (typeof Reflect === \\\"object\\\" && typeof Reflect.metadata === \\\"function\\\") return Reflect.metadata(k, v);\\n};\" ; // emit output for the __param helper function var paramHelper = \"\\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\\n    return function (target, key) { decorator(target, key, paramIndex); }\\n};\" ; var awaiterHelper = \"\\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {\\n    return new Promise(function (resolve, reject) {\\n        generator = generator.call(thisArg, _arguments);\\n        function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }\\n        function onfulfill(value) { try { step(\\\"next\\\", value); } catch (e) { reject(e); } }\\n        function onreject(value) { try { step(\\\"throw\\\", value); } catch (e) { reject(e); } }\\n        function step(verb, value) {\\n            var result = generator[verb](value);\\n            result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);\\n        }\\n        step(\\\"next\\\", void 0);\\n    });\\n};\" ; var compilerOptions = host . getCompilerOptions ( ) ; var languageVersion = compilerOptions . target || 0 /* ES3 */ ; var modulekind = compilerOptions . module ? compilerOptions . module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */ ; var sourceMapDataList = compilerOptions . sourceMap || compilerOptions . inlineSourceMap ? [ ] : undefined ; var diagnostics = [ ] ; var newLine = host . getNewLine ( ) ; var jsxDesugaring = host . getCompilerOptions ( ) . jsx !== 1 /* Preserve */ ; var shouldEmitJsx = function ( s ) { return ( s . languageVariant === 1 /* JSX */ && ! jsxDesugaring ) ; } ; if ( targetSourceFile === undefined ) { ts . forEach ( host . getSourceFiles ( ) , function ( sourceFile ) { if ( ts . shouldEmitToOwnFile ( sourceFile , compilerOptions ) ) { var jsFilePath = ts . getOwnEmitOutputFilePath ( sourceFile , host , shouldEmitJsx ( sourceFile ) ? \".jsx\" : \".js\" ) ; emitFile ( jsFilePath , sourceFile ) ; } } ) ; if ( compilerOptions . outFile || compilerOptions . out ) { emitFile ( compilerOptions . outFile || compilerOptions . out ) ; } } else { // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service) if ( ts . shouldEmitToOwnFile ( targetSourceFile , compilerOptions ) ) { var jsFilePath = ts . getOwnEmitOutputFilePath ( targetSourceFile , host , shouldEmitJsx ( targetSourceFile ) ? \".jsx\" : \".js\" ) ; emitFile ( jsFilePath , targetSourceFile ) ; } else if ( ! ts . isDeclarationFile ( targetSourceFile ) && ( compilerOptions . outFile || compilerOptions . out ) ) { emitFile ( compilerOptions . outFile || compilerOptions . out ) ; } } // Sort and make the unique list of diagnostics diagnostics = ts . sortAndDeduplicateDiagnostics ( diagnostics ) ; return { emitSkipped : false , diagnostics : diagnostics , sourceMaps : sourceMapDataList } ; function isUniqueLocalName ( name , container ) { for ( var node = container ; ts . isNodeDescendentOf ( node , container ) ; node = node . nextContainer ) { if ( node . locals && ts . hasProperty ( node . locals , name ) ) { // We conservatively include alias symbols to cover cases where they're emitted as locals if ( node . locals [ name ] . flags & ( 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */ ) ) { return false ; } } } return true ; } function emitJavaScript ( jsFilePath , root ) { var writer = ts . createTextWriter ( newLine ) ; var write = writer . write , writeTextOfNode = writer . writeTextOfNode , writeLine = writer . writeLine , increaseIndent = writer . increaseIndent , decreaseIndent = writer . decreaseIndent ; var currentSourceFile ; // name of an exporter function if file is a System external module // System.register([...], function (<exporter>) {...}) // exporting in System modules looks like: // export var x; ... x = 1 // => // var x;... exporter(\"x\", x = 1) var exportFunctionForFile ; var generatedNameSet = { } ; var nodeToGeneratedName = [ ] ; var computedPropertyNamesToGeneratedNames ; var extendsEmitted = false ; var decorateEmitted = false ; var paramEmitted = false ; var awaiterEmitted = false ; var tempFlags = 0 ; var tempVariables ; var tempParameters ; var externalImports ; var exportSpecifiers ; var exportEquals ; var hasExportStars ; /** Write emitted output to disk */ var writeEmittedFiles = writeJavaScriptFile ; var detachedCommentsInfo ; var writeComment = ts . writeCommentRange ; /** Emit a node */ var emit = emitNodeWithCommentsAndWithoutSourcemap ; /** Called just before starting emit of a node */ var emitStart = function ( node ) { } ; /** Called once the emit of the node is done */ var emitEnd = function ( node ) { } ; /** Emit the text for the given token that comes after startPos\n             * This by default writes the text provided with the given tokenKind\n             * but if optional emitFn callback is provided the text is emitted using the callback instead of default text\n             * @param tokenKind the kind of the token to search and emit\n             * @param startPos the position in the source to start searching for the token\n             * @param emitFn if given will be invoked to emit the text instead of actual token emit */ var emitToken = emitTokenText ; /** Called to before starting the lexical scopes as in function/class in the emitted code because of node\n             * @param scopeDeclaration node that starts the lexical scope\n             * @param scopeName Optional name of this scope instead of deducing one from the declaration node */ var scopeEmitStart = function ( scopeDeclaration , scopeName ) { } ; /** Called after coming out of the scope */ var scopeEmitEnd = function ( ) { } ; /** Sourcemap data that will get encoded */ var sourceMapData ; /** If removeComments is true, no leading-comments needed to be emitted **/ var emitLeadingCommentsOfPosition = compilerOptions . removeComments ? function ( pos ) { } : emitLeadingCommentsOfPositionWorker ; var moduleEmitDelegates = ( _a = { } , _a [ 5 /* ES6 */ ] = emitES6Module , _a [ 2 /* AMD */ ] = emitAMDModule , _a [ 4 /* System */ ] = emitSystemModule , _a [ 3 /* UMD */ ] = emitUMDModule , _a [ 1 /* CommonJS */ ] = emitCommonJSModule , _a ) ; if ( compilerOptions . sourceMap || compilerOptions . inlineSourceMap ) { initializeEmitterWithSourceMaps ( ) ; } if ( root ) { // Do not call emit directly. It does not set the currentSourceFile. emitSourceFile ( root ) ; } else { ts . forEach ( host . getSourceFiles ( ) , function ( sourceFile ) { if ( ! isExternalModuleOrDeclarationFile ( sourceFile ) ) { emitSourceFile ( sourceFile ) ; } } ) ; } writeLine ( ) ; writeEmittedFiles ( writer . getText ( ) , /*writeByteOrderMark*/ compilerOptions . emitBOM ) ; return ; function emitSourceFile ( sourceFile ) { currentSourceFile = sourceFile ; exportFunctionForFile = undefined ; emit ( sourceFile ) ; } function isUniqueName ( name ) { return ! resolver . hasGlobalName ( name ) && ! ts . hasProperty ( currentSourceFile . identifiers , name ) && ! ts . hasProperty ( generatedNameSet , name ) ; } // Return the next available name in the pattern _a ... _z, _0, _1, ... // TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. // Note that names generated by makeTempVariableName and makeUniqueName will never conflict. function makeTempVariableName ( flags ) { if ( flags && ! ( tempFlags & flags ) ) { var name_19 = flags === 268435456 /* _i */ ? \"_i\" : \"_n\" ; if ( isUniqueName ( name_19 ) ) { tempFlags |= flags ; return name_19 ; } } while ( true ) { var count = tempFlags & 268435455 /* CountMask */ ; tempFlags ++ ; // Skip over 'i' and 'n' if ( count !== 8 && count !== 13 ) { var name_20 = count < 26 ? \"_\" + String . fromCharCode ( 97 /* a */ + count ) : \"_\" + ( count - 26 ) ; if ( isUniqueName ( name_20 ) ) { return name_20 ; } } } } // Generate a name that is unique within the current file and doesn't conflict with any names // in global scope. The name is formed by adding an '_n' suffix to the specified base name, // where n is a positive integer. Note that names generated by makeTempVariableName and // makeUniqueName are guaranteed to never conflict. function makeUniqueName ( baseName ) { // Find the first unique 'name_n', where n is a positive number if ( baseName . charCodeAt ( baseName . length - 1 ) !== 95 /* _ */ ) { baseName += \"_\" ; } var i = 1 ; while ( true ) { var generatedName = baseName + i ; if ( isUniqueName ( generatedName ) ) { return generatedNameSet [ generatedName ] = generatedName ; } i ++ ; } } function generateNameForModuleOrEnum ( node ) { var name = node . name . text ; // Use module/enum name itself if it is unique, otherwise make a unique variation return isUniqueLocalName ( name , node ) ? name : makeUniqueName ( name ) ; } function generateNameForImportOrExportDeclaration ( node ) { var expr = ts . getExternalModuleName ( node ) ; var baseName = expr . kind === 9 /* StringLiteral */ ? ts . escapeIdentifier ( ts . makeIdentifierFromModuleName ( expr . text ) ) : \"module\" ; return makeUniqueName ( baseName ) ; } function generateNameForExportDefault ( ) { return makeUniqueName ( \"default\" ) ; } function generateNameForClassExpression ( ) { return makeUniqueName ( \"class\" ) ; } function generateNameForNode ( node ) { switch ( node . kind ) { case 69 /* Identifier */ : return makeUniqueName ( node . text ) ; case 218 /* ModuleDeclaration */ : case 217 /* EnumDeclaration */ : return generateNameForModuleOrEnum ( node ) ; case 222 /* ImportDeclaration */ : case 228 /* ExportDeclaration */ : return generateNameForImportOrExportDeclaration ( node ) ; case 213 /* FunctionDeclaration */ : case 214 /* ClassDeclaration */ : case 227 /* ExportAssignment */ : return generateNameForExportDefault ( ) ; case 186 /* ClassExpression */ : return generateNameForClassExpression ( ) ; } } function getGeneratedNameForNode ( node ) { var id = ts . getNodeId ( node ) ; return nodeToGeneratedName [ id ] || ( nodeToGeneratedName [ id ] = ts . unescapeIdentifier ( generateNameForNode ( node ) ) ) ; } function initializeEmitterWithSourceMaps ( ) { var sourceMapDir ; // The directory in which sourcemap will be // Current source map file and its index in the sources list var sourceMapSourceIndex = - 1 ; // Names and its index map var sourceMapNameIndexMap = { } ; var sourceMapNameIndices = [ ] ; function getSourceMapNameIndex ( ) { return sourceMapNameIndices . length ? ts . lastOrUndefined ( sourceMapNameIndices ) : - 1 ; } // Last recorded and encoded spans var lastRecordedSourceMapSpan ; var lastEncodedSourceMapSpan = { emittedLine : 1 , emittedColumn : 1 , sourceLine : 1 , sourceColumn : 1 , sourceIndex : 0 } ; var lastEncodedNameIndex = 0 ; // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan ( ) { if ( ! lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan ) { return ; } var prevEncodedEmittedColumn = lastEncodedSourceMapSpan . emittedColumn ; // Line/Comma delimiters if ( lastEncodedSourceMapSpan . emittedLine === lastRecordedSourceMapSpan . emittedLine ) { // Emit comma to separate the entry if ( sourceMapData . sourceMapMappings ) { sourceMapData . sourceMapMappings += \",\" ; } } else { // Emit line delimiters for ( var encodedLine = lastEncodedSourceMapSpan . emittedLine ; encodedLine < lastRecordedSourceMapSpan . emittedLine ; encodedLine ++ ) { sourceMapData . sourceMapMappings += \";\" ; } prevEncodedEmittedColumn = 1 ; } // 1. Relative Column 0 based sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . emittedColumn - prevEncodedEmittedColumn ) ; // 2. Relative sourceIndex sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . sourceIndex - lastEncodedSourceMapSpan . sourceIndex ) ; // 3. Relative sourceLine 0 based sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . sourceLine - lastEncodedSourceMapSpan . sourceLine ) ; // 4. Relative sourceColumn 0 based sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . sourceColumn - lastEncodedSourceMapSpan . sourceColumn ) ; // 5. Relative namePosition 0 based if ( lastRecordedSourceMapSpan . nameIndex >= 0 ) { sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . nameIndex - lastEncodedNameIndex ) ; lastEncodedNameIndex = lastRecordedSourceMapSpan . nameIndex ; } lastEncodedSourceMapSpan = lastRecordedSourceMapSpan ; sourceMapData . sourceMapDecodedMappings . push ( lastEncodedSourceMapSpan ) ; function base64VLQFormatEncode ( inValue ) { function base64FormatEncode ( inValue ) { if ( inValue < 64 ) { return \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" . charAt ( inValue ) ; } throw TypeError ( inValue + \": not a 64 based value\" ) ; } // Add a new least significant bit that has the sign of the value. // if negative number the least significant bit that gets added to the number has value 1 // else least significant bit value that gets added is 0 // eg. -1 changes to binary : 01 [1] => 3 //     +1 changes to binary : 01 [0] => 2 if ( inValue < 0 ) { inValue = ( ( - inValue ) << 1 ) + 1 ; } else { inValue = inValue << 1 ; } // Encode 5 bits at a time starting from least significant bits var encodedStr = \"\" ; do { var currentDigit = inValue & 31 ; // 11111 inValue = inValue >> 5 ; if ( inValue > 0 ) { // There are still more digits to decode, set the msb (6th bit) currentDigit = currentDigit | 32 ; } encodedStr = encodedStr + base64FormatEncode ( currentDigit ) ; } while ( inValue > 0 ) ; return encodedStr ; } } function recordSourceMapSpan ( pos ) { var sourceLinePos = ts . getLineAndCharacterOfPosition ( currentSourceFile , pos ) ; // Convert the location to be one-based. sourceLinePos . line ++ ; sourceLinePos . character ++ ; var emittedLine = writer . getLine ( ) ; var emittedColumn = writer . getColumn ( ) ; // If this location wasn't recorded or the location in source is going backwards, record the span if ( ! lastRecordedSourceMapSpan || lastRecordedSourceMapSpan . emittedLine !== emittedLine || lastRecordedSourceMapSpan . emittedColumn !== emittedColumn || ( lastRecordedSourceMapSpan . sourceIndex === sourceMapSourceIndex && ( lastRecordedSourceMapSpan . sourceLine > sourceLinePos . line || ( lastRecordedSourceMapSpan . sourceLine === sourceLinePos . line && lastRecordedSourceMapSpan . sourceColumn > sourceLinePos . character ) ) ) ) { // Encode the last recordedSpan before assigning new encodeLastRecordedSourceMapSpan ( ) ; // New span lastRecordedSourceMapSpan = { emittedLine : emittedLine , emittedColumn : emittedColumn , sourceLine : sourceLinePos . line , sourceColumn : sourceLinePos . character , nameIndex : getSourceMapNameIndex ( ) , sourceIndex : sourceMapSourceIndex } ; } else { // Take the new pos instead since there is no change in emittedLine and column since last location lastRecordedSourceMapSpan . sourceLine = sourceLinePos . line ; lastRecordedSourceMapSpan . sourceColumn = sourceLinePos . character ; lastRecordedSourceMapSpan . sourceIndex = sourceMapSourceIndex ; } } function recordEmitNodeStartSpan ( node ) { // Get the token pos after skipping to the token (ignoring the leading trivia) recordSourceMapSpan ( ts . skipTrivia ( currentSourceFile . text , node . pos ) ) ; } function recordEmitNodeEndSpan ( node ) { recordSourceMapSpan ( node . end ) ; } function writeTextWithSpanRecord ( tokenKind , startPos , emitFn ) { var tokenStartPos = ts . skipTrivia ( currentSourceFile . text , startPos ) ; recordSourceMapSpan ( tokenStartPos ) ; var tokenEndPos = emitTokenText ( tokenKind , tokenStartPos , emitFn ) ; recordSourceMapSpan ( tokenEndPos ) ; return tokenEndPos ; } function recordNewSourceFileStart ( node ) { // Add the file to tsFilePaths // If sourceroot option: Use the relative path corresponding to the common directory path // otherwise source locations relative to map file location var sourcesDirectoryPath = compilerOptions . sourceRoot ? host . getCommonSourceDirectory ( ) : sourceMapDir ; sourceMapData . sourceMapSources . push ( ts . getRelativePathToDirectoryOrUrl ( sourcesDirectoryPath , node . fileName , host . getCurrentDirectory ( ) , host . getCanonicalFileName , /*isAbsolutePathAnUrl*/ true ) ) ; sourceMapSourceIndex = sourceMapData . sourceMapSources . length - 1 ; // The one that can be used from program to get the actual source file sourceMapData . inputSourceFileNames . push ( node . fileName ) ; if ( compilerOptions . inlineSources ) { if ( ! sourceMapData . sourceMapSourcesContent ) { sourceMapData . sourceMapSourcesContent = [ ] ; } sourceMapData . sourceMapSourcesContent . push ( node . text ) ; } } function recordScopeNameOfNode ( node , scopeName ) { function recordScopeNameIndex ( scopeNameIndex ) { sourceMapNameIndices . push ( scopeNameIndex ) ; } function recordScopeNameStart ( scopeName ) { var scopeNameIndex = - 1 ; if ( scopeName ) { var parentIndex = getSourceMapNameIndex ( ) ; if ( parentIndex !== - 1 ) { // Child scopes are always shown with a dot (even if they have no name), // unless it is a computed property. Then it is shown with brackets, // but the brackets are included in the name. var name_21 = node . name ; if ( ! name_21 || name_21 . kind !== 136 /* ComputedPropertyName */ ) { scopeName = \".\" + scopeName ; } scopeName = sourceMapData . sourceMapNames [ parentIndex ] + scopeName ; } scopeNameIndex = ts . getProperty ( sourceMapNameIndexMap , scopeName ) ; if ( scopeNameIndex === undefined ) { scopeNameIndex = sourceMapData . sourceMapNames . length ; sourceMapData . sourceMapNames . push ( scopeName ) ; sourceMapNameIndexMap [ scopeName ] = scopeNameIndex ; } } recordScopeNameIndex ( scopeNameIndex ) ; } if ( scopeName ) { // The scope was already given a name  use it recordScopeNameStart ( scopeName ) ; } else if ( node . kind === 213 /* FunctionDeclaration */ || node . kind === 173 /* FunctionExpression */ || node . kind === 143 /* MethodDeclaration */ || node . kind === 142 /* MethodSignature */ || node . kind === 145 /* GetAccessor */ || node . kind === 146 /* SetAccessor */ || node . kind === 218 /* ModuleDeclaration */ || node . kind === 214 /* ClassDeclaration */ || node . kind === 217 /* EnumDeclaration */ ) { // Declaration and has associated name use it if ( node . name ) { var name_22 = node . name ; // For computed property names, the text will include the brackets scopeName = name_22 . kind === 136 /* ComputedPropertyName */ ? ts . getTextOfNode ( name_22 ) : node . name . text ; } recordScopeNameStart ( scopeName ) ; } else { // Block just use the name from upper level scope recordScopeNameIndex ( getSourceMapNameIndex ( ) ) ; } } function recordScopeNameEnd ( ) { sourceMapNameIndices . pop ( ) ; } ; function writeCommentRangeWithMap ( curentSourceFile , writer , comment , newLine ) { recordSourceMapSpan ( comment . pos ) ; ts . writeCommentRange ( currentSourceFile , writer , comment , newLine ) ; recordSourceMapSpan ( comment . end ) ; } function serializeSourceMapContents ( version , file , sourceRoot , sources , names , mappings , sourcesContent ) { if ( typeof JSON !== \"undefined\" ) { var map_1 = { version : version , file : file , sourceRoot : sourceRoot , sources : sources , names : names , mappings : mappings } ; if ( sourcesContent !== undefined ) { map_1 . sourcesContent = sourcesContent ; } return JSON . stringify ( map_1 ) ; } return \"{\\\"version\\\":\" + version + \",\\\"file\\\":\\\"\" + ts . escapeString ( file ) + \"\\\",\\\"sourceRoot\\\":\\\"\" + ts . escapeString ( sourceRoot ) + \"\\\",\\\"sources\\\":[\" + serializeStringArray ( sources ) + \"],\\\"names\\\":[\" + serializeStringArray ( names ) + \"],\\\"mappings\\\":\\\"\" + ts . escapeString ( mappings ) + \"\\\" \" + ( sourcesContent !== undefined ? \",\\\"sourcesContent\\\":[\" + serializeStringArray ( sourcesContent ) + \"]\" : \"\" ) + \"}\" ; function serializeStringArray ( list ) { var output = \"\" ; for ( var i = 0 , n = list . length ; i < n ; i ++ ) { if ( i ) { output += \",\" ; } output += \"\\\"\" + ts . escapeString ( list [ i ] ) + \"\\\"\" ; } return output ; } } function writeJavaScriptAndSourceMapFile ( emitOutput , writeByteOrderMark ) { encodeLastRecordedSourceMapSpan ( ) ; var sourceMapText = serializeSourceMapContents ( 3 , sourceMapData . sourceMapFile , sourceMapData . sourceMapSourceRoot , sourceMapData . sourceMapSources , sourceMapData . sourceMapNames , sourceMapData . sourceMapMappings , sourceMapData . sourceMapSourcesContent ) ; sourceMapDataList . push ( sourceMapData ) ; var sourceMapUrl ; if ( compilerOptions . inlineSourceMap ) { // Encode the sourceMap into the sourceMap url var base64SourceMapText = ts . convertToBase64 ( sourceMapText ) ; sourceMapUrl = \"//# sourceMappingURL=data:application/json;base64,\" + base64SourceMapText ; } else { // Write source map file ts . writeFile ( host , diagnostics , sourceMapData . sourceMapFilePath , sourceMapText , /*writeByteOrderMark*/ false ) ; sourceMapUrl = \"//# sourceMappingURL=\" + sourceMapData . jsSourceMappingURL ; } // Write sourcemap url to the js file and write the js file writeJavaScriptFile ( emitOutput + sourceMapUrl , writeByteOrderMark ) ; } // Initialize source map data var sourceMapJsFile = ts . getBaseFileName ( ts . normalizeSlashes ( jsFilePath ) ) ; sourceMapData = { sourceMapFilePath : jsFilePath + \".map\" , jsSourceMappingURL : sourceMapJsFile + \".map\" , sourceMapFile : sourceMapJsFile , sourceMapSourceRoot : compilerOptions . sourceRoot || \"\" , sourceMapSources : [ ] , inputSourceFileNames : [ ] , sourceMapNames : [ ] , sourceMapMappings : \"\" , sourceMapSourcesContent : undefined , sourceMapDecodedMappings : [ ] } ; // Normalize source root and make sure it has trailing \"/\" so that it can be used to combine paths with the // relative paths of the sources list in the sourcemap sourceMapData . sourceMapSourceRoot = ts . normalizeSlashes ( sourceMapData . sourceMapSourceRoot ) ; if ( sourceMapData . sourceMapSourceRoot . length && sourceMapData . sourceMapSourceRoot . charCodeAt ( sourceMapData . sourceMapSourceRoot . length - 1 ) !== 47 /* slash */ ) { sourceMapData . sourceMapSourceRoot += ts . directorySeparator ; } if ( compilerOptions . mapRoot ) { sourceMapDir = ts . normalizeSlashes ( compilerOptions . mapRoot ) ; if ( root ) { // For modules or multiple emit files the mapRoot will have directory structure like the sources // So if src\\a.ts and src\\lib\\b.ts are compiled together user would be moving the maps into mapRoot\\a.js.map and mapRoot\\lib\\b.js.map sourceMapDir = ts . getDirectoryPath ( ts . getSourceFilePathInNewDir ( root , host , sourceMapDir ) ) ; } if ( ! ts . isRootedDiskPath ( sourceMapDir ) && ! ts . isUrl ( sourceMapDir ) ) { // The relative paths are relative to the common directory sourceMapDir = ts . combinePaths ( host . getCommonSourceDirectory ( ) , sourceMapDir ) ; sourceMapData . jsSourceMappingURL = ts . getRelativePathToDirectoryOrUrl ( ts . getDirectoryPath ( ts . normalizePath ( jsFilePath ) ) , // get the relative sourceMapDir path based on jsFilePath ts . combinePaths ( sourceMapDir , sourceMapData . jsSourceMappingURL ) , // this is where user expects to see sourceMap host . getCurrentDirectory ( ) , host . getCanonicalFileName , /*isAbsolutePathAnUrl*/ true ) ; } else { sourceMapData . jsSourceMappingURL = ts . combinePaths ( sourceMapDir , sourceMapData . jsSourceMappingURL ) ; } } else { sourceMapDir = ts . getDirectoryPath ( ts . normalizePath ( jsFilePath ) ) ; } function emitNodeWithSourceMap ( node ) { if ( node ) { if ( ts . nodeIsSynthesized ( node ) ) { return emitNodeWithoutSourceMap ( node ) ; } if ( node . kind !== 248 /* SourceFile */ ) { recordEmitNodeStartSpan ( node ) ; emitNodeWithoutSourceMap ( node ) ; recordEmitNodeEndSpan ( node ) ; } else { recordNewSourceFileStart ( node ) ; emitNodeWithoutSourceMap ( node ) ; } } } function emitNodeWithCommentsAndWithSourcemap ( node ) { emitNodeConsideringCommentsOption ( node , emitNodeWithSourceMap ) ; } writeEmittedFiles = writeJavaScriptAndSourceMapFile ; emit = emitNodeWithCommentsAndWithSourcemap ; emitStart = recordEmitNodeStartSpan ; emitEnd = recordEmitNodeEndSpan ; emitToken = writeTextWithSpanRecord ; scopeEmitStart = recordScopeNameOfNode ; scopeEmitEnd = recordScopeNameEnd ; writeComment = writeCommentRangeWithMap ; } function writeJavaScriptFile ( emitOutput , writeByteOrderMark ) { ts . writeFile ( host , diagnostics , jsFilePath , emitOutput , writeByteOrderMark ) ; } // Create a temporary variable with a unique unused name. function createTempVariable ( flags ) { var result = ts . createSynthesizedNode ( 69 /* Identifier */ ) ; result . text = makeTempVariableName ( flags ) ; return result ; } function recordTempDeclaration ( name ) { if ( ! tempVariables ) { tempVariables = [ ] ; } tempVariables . push ( name ) ; } function createAndRecordTempVariable ( flags ) { var temp = createTempVariable ( flags ) ; recordTempDeclaration ( temp ) ; return temp ; } function emitTempDeclarations ( newLine ) { if ( tempVariables ) { if ( newLine ) { writeLine ( ) ; } else { write ( \" \" ) ; } write ( \"var \" ) ; emitCommaList ( tempVariables ) ; write ( \";\" ) ; } } function emitTokenText ( tokenKind , startPos , emitFn ) { var tokenString = ts . tokenToString ( tokenKind ) ; if ( emitFn ) { emitFn ( ) ; } else { write ( tokenString ) ; } return startPos + tokenString . length ; } function emitOptional ( prefix , node ) { if ( node ) { write ( prefix ) ; emit ( node ) ; } } function emitParenthesizedIf ( node , parenthesized ) { if ( parenthesized ) { write ( \"(\" ) ; } emit ( node ) ; if ( parenthesized ) { write ( \")\" ) ; } } function emitTrailingCommaIfPresent ( nodeList ) { if ( nodeList . hasTrailingComma ) { write ( \",\" ) ; } } function emitLinePreservingList ( parent , nodes , allowTrailingComma , spacesBetweenBraces ) { ts . Debug . assert ( nodes . length > 0 ) ; increaseIndent ( ) ; if ( nodeStartPositionsAreOnSameLine ( parent , nodes [ 0 ] ) ) { if ( spacesBetweenBraces ) { write ( \" \" ) ; } } else { writeLine ( ) ; } for ( var i = 0 , n = nodes . length ; i < n ; i ++ ) { if ( i ) { if ( nodeEndIsOnSameLineAsNodeStart ( nodes [ i - 1 ] , nodes [ i ] ) ) { write ( \", \" ) ; } else { write ( \",\" ) ; writeLine ( ) ; } } emit ( nodes [ i ] ) ; } if ( nodes . hasTrailingComma && allowTrailingComma ) { write ( \",\" ) ; } decreaseIndent ( ) ; if ( nodeEndPositionsAreOnSameLine ( parent , ts . lastOrUndefined ( nodes ) ) ) { if ( spacesBetweenBraces ) { write ( \" \" ) ; } } else { writeLine ( ) ; } } function emitList ( nodes , start , count , multiLine , trailingComma , leadingComma , noTrailingNewLine , emitNode ) { if ( ! emitNode ) { emitNode = emit ; } for ( var i = 0 ; i < count ; i ++ ) { if ( multiLine ) { if ( i || leadingComma ) { write ( \",\" ) ; } writeLine ( ) ; } else { if ( i || leadingComma ) { write ( \", \" ) ; } } var node = nodes [ start + i ] ; // This emitting is to make sure we emit following comment properly //   ...(x, /*comment1*/ y)... //         ^ => node.pos // \"comment1\" is not considered leading comment for \"y\" but rather // considered as trailing comment of the previous node. emitTrailingCommentsOfPosition ( node . pos ) ; emitNode ( node ) ; leadingComma = true ; } if ( trailingComma ) { write ( \",\" ) ; } if ( multiLine && ! noTrailingNewLine ) { writeLine ( ) ; } return count ; } function emitCommaList ( nodes ) { if ( nodes ) { emitList ( nodes , 0 , nodes . length , /*multiline*/ false , /*trailingComma*/ false ) ; } } function emitLines ( nodes ) { emitLinesStartingAt ( nodes , /*startIndex*/ 0 ) ; } function emitLinesStartingAt ( nodes , startIndex ) { for ( var i = startIndex ; i < nodes . length ; i ++ ) { writeLine ( ) ; emit ( nodes [ i ] ) ; } } function isBinaryOrOctalIntegerLiteral ( node , text ) { if ( node . kind === 8 /* NumericLiteral */ && text . length > 1 ) { switch ( text . charCodeAt ( 1 ) ) { case 98 /* b */ : case 66 /* B */ : case 111 /* o */ : case 79 /* O */ : return true ; } } return false ; } function emitLiteral ( node ) { var text = getLiteralText ( node ) ; if ( ( compilerOptions . sourceMap || compilerOptions . inlineSourceMap ) && ( node . kind === 9 /* StringLiteral */ || ts . isTemplateLiteralKind ( node . kind ) ) ) { writer . writeLiteral ( text ) ; } else if ( languageVersion < 2 /* ES6 */ && isBinaryOrOctalIntegerLiteral ( node , text ) ) { write ( node . text ) ; } else { write ( text ) ; } } function getLiteralText ( node ) { // Any template literal or string literal with an extended escape // (e.g. \"\\u{0067}\") will need to be downleveled as a escaped string literal. if ( languageVersion < 2 /* ES6 */ && ( ts . isTemplateLiteralKind ( node . kind ) || node . hasExtendedUnicodeEscape ) ) { return getQuotedEscapedLiteralText ( \"\\\"\" , node . text , \"\\\"\" ) ; } // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if ( node . parent ) { return ts . getSourceTextOfNodeFromSourceFile ( currentSourceFile , node ) ; } // If we can't reach the original source text, use the canonical form if it's a number, // or an escaped quoted form of the original text if it's string-like. switch ( node . kind ) { case 9 /* StringLiteral */ : return getQuotedEscapedLiteralText ( \"\\\"\" , node . text , \"\\\"\" ) ; case 11 /* NoSubstitutionTemplateLiteral */ : return getQuotedEscapedLiteralText ( \"`\" , node . text , \"`\" ) ; case 12 /* TemplateHead */ : return getQuotedEscapedLiteralText ( \"`\" , node . text , \"${\" ) ; case 13 /* TemplateMiddle */ : return getQuotedEscapedLiteralText ( \"}\" , node . text , \"${\" ) ; case 14 /* TemplateTail */ : return getQuotedEscapedLiteralText ( \"}\" , node . text , \"`\" ) ; case 8 /* NumericLiteral */ : return node . text ; } ts . Debug . fail ( \"Literal kind '\" + node . kind + \"' not accounted for.\" ) ; } function getQuotedEscapedLiteralText ( leftQuote , text , rightQuote ) { return leftQuote + ts . escapeNonAsciiCharacters ( ts . escapeString ( text ) ) + rightQuote ; } function emitDownlevelRawTemplateLiteral ( node ) { // Find original source text, since we need to emit the raw strings of the tagged template. // The raw strings contain the (escaped) strings of what the user wrote. // Examples: `\\n` is converted to \"\\\\n\", a template string with a newline to \"\\n\". var text = ts . getSourceTextOfNodeFromSourceFile ( currentSourceFile , node ) ; // text contains the original source, it will also contain quotes (\"`\"), dolar signs and braces (\"${\" and \"}\"), // thus we need to remove those characters. // First template piece starts with \"`\", others with \"}\" // Last template piece ends with \"`\", others with \"${\" var isLast = node . kind === 11 /* NoSubstitutionTemplateLiteral */ || node . kind === 14 /* TemplateTail */ ; text = text . substring ( 1 , text . length - ( isLast ? 1 : 2 ) ) ; // Newline normalization: // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV. text = text . replace ( / \\r\\n? / g , \"\\n\" ) ; text = ts . escapeString ( text ) ; write ( \"\\\"\" + text + \"\\\"\" ) ; } function emitDownlevelTaggedTemplateArray ( node , literalEmitter ) { write ( \"[\" ) ; if ( node . template . kind === 11 /* NoSubstitutionTemplateLiteral */ ) { literalEmitter ( node . template ) ; } else { literalEmitter ( node . template . head ) ; ts . forEach ( node . template . templateSpans , function ( child ) { write ( \", \" ) ; literalEmitter ( child . literal ) ; } ) ; } write ( \"]\" ) ; } function emitDownlevelTaggedTemplate ( node ) { var tempVariable = createAndRecordTempVariable ( 0 /* Auto */ ) ; write ( \"(\" ) ; emit ( tempVariable ) ; write ( \" = \" ) ; emitDownlevelTaggedTemplateArray ( node , emit ) ; write ( \", \" ) ; emit ( tempVariable ) ; write ( \".raw = \" ) ; emitDownlevelTaggedTemplateArray ( node , emitDownlevelRawTemplateLiteral ) ; write ( \", \" ) ; emitParenthesizedIf ( node . tag , needsParenthesisForPropertyAccessOrInvocation ( node . tag ) ) ; write ( \"(\" ) ; emit ( tempVariable ) ; // Now we emit the expressions if ( node . template . kind === 183 /* TemplateExpression */ ) { ts . forEach ( node . template . templateSpans , function ( templateSpan ) { write ( \", \" ) ; var needsParens = templateSpan . expression . kind === 181 /* BinaryExpression */ && templateSpan . expression . operatorToken . kind === 24 /* CommaToken */ ; emitParenthesizedIf ( templateSpan . expression , needsParens ) ; } ) ; } write ( \"))\" ) ; } function emitTemplateExpression ( node ) { // In ES6 mode and above, we can simply emit each portion of a template in order, but in // ES3 & ES5 we must convert the template expression into a series of string concatenations. if ( languageVersion >= 2 /* ES6 */ ) { ts . forEachChild ( node , emit ) ; return ; } var emitOuterParens = ts . isExpression ( node . parent ) && templateNeedsParens ( node , node . parent ) ; if ( emitOuterParens ) { write ( \"(\" ) ; } var headEmitted = false ; if ( shouldEmitTemplateHead ( ) ) { emitLiteral ( node . head ) ; headEmitted = true ; } for ( var i = 0 , n = node . templateSpans . length ; i < n ; i ++ ) { var templateSpan = node . templateSpans [ i ] ; // Check if the expression has operands and binds its operands less closely than binary '+'. // If it does, we need to wrap the expression in parentheses. Otherwise, something like //    `abc${ 1 << 2 }` // becomes //    \"abc\" + 1 << 2 + \"\" // which is really //    (\"abc\" + 1) << (2 + \"\") // rather than //    \"abc\" + (1 << 2) + \"\" var needsParens = templateSpan . expression . kind !== 172 /* ParenthesizedExpression */ && comparePrecedenceToBinaryPlus ( templateSpan . expression ) !== 1 /* GreaterThan */ ; if ( i > 0 || headEmitted ) { // If this is the first span and the head was not emitted, then this templateSpan's // expression will be the first to be emitted. Don't emit the preceding ' + ' in that // case. write ( \" + \" ) ; } emitParenthesizedIf ( templateSpan . expression , needsParens ) ; // Only emit if the literal is non-empty. // The binary '+' operator is left-associative, so the first string concatenation // with the head will force the result up to this point to be a string. // Emitting a '+ \"\"' has no semantic effect for middles and tails. if ( templateSpan . literal . text . length !== 0 ) { write ( \" + \" ) ; emitLiteral ( templateSpan . literal ) ; } } if ( emitOuterParens ) { write ( \")\" ) ; } function shouldEmitTemplateHead ( ) { // If this expression has an empty head literal and the first template span has a non-empty // literal, then emitting the empty head literal is not necessary. //     `${ foo } and ${ bar }` // can be emitted as //     foo + \" and \" + bar // This is because it is only required that one of the first two operands in the emit // output must be a string literal, so that the other operand and all following operands // are forced into strings. // // If the first template span has an empty literal, then the head must still be emitted. //     `${ foo }${ bar }` // must still be emitted as //     \"\" + foo + bar // There is always atleast one templateSpan in this code path, since // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() ts . Debug . assert ( node . templateSpans . length !== 0 ) ; return node . head . text . length !== 0 || node . templateSpans [ 0 ] . literal . text . length === 0 ; } function templateNeedsParens ( template , parent ) { switch ( parent . kind ) { case 168 /* CallExpression */ : case 169 /* NewExpression */ : return parent . expression === template ; case 170 /* TaggedTemplateExpression */ : case 172 /* ParenthesizedExpression */ : return false ; default : return comparePrecedenceToBinaryPlus ( parent ) !== - 1 /* LessThan */ ; } } /**\n                 * Returns whether the expression has lesser, greater,\n                 * or equal precedence to the binary '+' operator\n                 */ function comparePrecedenceToBinaryPlus ( expression ) { // All binary expressions have lower precedence than '+' apart from '*', '/', and '%' // which have greater precedence and '-' which has equal precedence. // All unary operators have a higher precedence apart from yield. // Arrow functions and conditionals have a lower precedence, // although we convert the former into regular function expressions in ES5 mode, // and in ES6 mode this function won't get called anyway. // // TODO (drosen): Note that we need to account for the upcoming 'yield' and //                spread ('...') unary operators that are anticipated for ES6. switch ( expression . kind ) { case 181 /* BinaryExpression */ : switch ( expression . operatorToken . kind ) { case 37 /* AsteriskToken */ : case 39 /* SlashToken */ : case 40 /* PercentToken */ : return 1 /* GreaterThan */ ; case 35 /* PlusToken */ : case 36 /* MinusToken */ : return 0 /* EqualTo */ ; default : return - 1 /* LessThan */ ; } case 184 /* YieldExpression */ : case 182 /* ConditionalExpression */ : return - 1 /* LessThan */ ; default : return 1 /* GreaterThan */ ; } } } function emitTemplateSpan ( span ) { emit ( span . expression ) ; emit ( span . literal ) ; } function jsxEmitReact ( node ) { /// Emit a tag name, which is either '\"div\"' for lower-cased names, or /// 'Div' for upper-cased or dotted names function emitTagName ( name ) { if ( name . kind === 69 /* Identifier */ && ts . isIntrinsicJsxName ( name . text ) ) { write ( \"\\\"\" ) ; emit ( name ) ; write ( \"\\\"\" ) ; } else { emit ( name ) ; } } /// Emit an attribute name, which is quoted if it needs to be quoted. Because /// these emit into an object literal property name, we don't need to be worried /// about keywords, just non-identifier characters function emitAttributeName ( name ) { if ( / [A-Za-z_]+[\\w*] / . test ( name . text ) ) { write ( \"\\\"\" ) ; emit ( name ) ; write ( \"\\\"\" ) ; } else { emit ( name ) ; } } /// Emit an name/value pair for an attribute (e.g. \"x: 3\") function emitJsxAttribute ( node ) { emitAttributeName ( node . name ) ; write ( \": \" ) ; if ( node . initializer ) { emit ( node . initializer ) ; } else { write ( \"true\" ) ; } } function emitJsxElement ( openingNode , children ) { var syntheticReactRef = ts . createSynthesizedNode ( 69 /* Identifier */ ) ; syntheticReactRef . text = \"React\" ; syntheticReactRef . parent = openingNode ; // Call React.createElement(tag, ... emitLeadingComments ( openingNode ) ; emitExpressionIdentifier ( syntheticReactRef ) ; write ( \".createElement(\" ) ; emitTagName ( openingNode . tagName ) ; write ( \", \" ) ; // Attribute list if ( openingNode . attributes . length === 0 ) { // When there are no attributes, React wants \"null\" write ( \"null\" ) ; } else { // Either emit one big object literal (no spread attribs), or // a call to React.__spread var attrs = openingNode . attributes ; if ( ts . forEach ( attrs , function ( attr ) { return attr . kind === 239 /* JsxSpreadAttribute */ ; } ) ) { emitExpressionIdentifier ( syntheticReactRef ) ; write ( \".__spread(\" ) ; var haveOpenedObjectLiteral = false ; for ( var i_1 = 0 ; i_1 < attrs . length ; i_1 ++ ) { if ( attrs [ i_1 ] . kind === 239 /* JsxSpreadAttribute */ ) { // If this is the first argument, we need to emit a {} as the first argument if ( i_1 === 0 ) { write ( \"{}, \" ) ; } if ( haveOpenedObjectLiteral ) { write ( \"}\" ) ; haveOpenedObjectLiteral = false ; } if ( i_1 > 0 ) { write ( \", \" ) ; } emit ( attrs [ i_1 ] . expression ) ; } else { ts . Debug . assert ( attrs [ i_1 ] . kind === 238 /* JsxAttribute */ ) ; if ( haveOpenedObjectLiteral ) { write ( \", \" ) ; } else { haveOpenedObjectLiteral = true ; if ( i_1 > 0 ) { write ( \", \" ) ; } write ( \"{\" ) ; } emitJsxAttribute ( attrs [ i_1 ] ) ; } } if ( haveOpenedObjectLiteral ) write ( \"}\" ) ; write ( \")\" ) ; // closing paren to React.__spread( } else { // One object literal with all the attributes in them write ( \"{\" ) ; for ( var i = 0 ; i < attrs . length ; i ++ ) { if ( i > 0 ) { write ( \", \" ) ; } emitJsxAttribute ( attrs [ i ] ) ; } write ( \"}\" ) ; } } // Children if ( children ) { for ( var i = 0 ; i < children . length ; i ++ ) { // Don't emit empty expressions if ( children [ i ] . kind === 240 /* JsxExpression */ && ! ( children [ i ] . expression ) ) { continue ; } // Don't emit empty strings if ( children [ i ] . kind === 236 /* JsxText */ ) { var text = getTextToEmit ( children [ i ] ) ; if ( text !== undefined ) { write ( \", \\\"\" ) ; write ( text ) ; write ( \"\\\"\" ) ; } } else { write ( \", \" ) ; emit ( children [ i ] ) ; } } } // Closing paren write ( \")\" ) ; // closes \"React.createElement(\" emitTrailingComments ( openingNode ) ; } if ( node . kind === 233 /* JsxElement */ ) { emitJsxElement ( node . openingElement , node . children ) ; } else { ts . Debug . assert ( node . kind === 234 /* JsxSelfClosingElement */ ) ; emitJsxElement ( node ) ; } } function jsxEmitPreserve ( node ) { function emitJsxAttribute ( node ) { emit ( node . name ) ; if ( node . initializer ) { write ( \"=\" ) ; emit ( node . initializer ) ; } } function emitJsxSpreadAttribute ( node ) { write ( \"{...\" ) ; emit ( node . expression ) ; write ( \"}\" ) ; } function emitAttributes ( attribs ) { for ( var i = 0 , n = attribs . length ; i < n ; i ++ ) { if ( i > 0 ) { write ( \" \" ) ; } if ( attribs [ i ] . kind === 239 /* JsxSpreadAttribute */ ) { emitJsxSpreadAttribute ( attribs [ i ] ) ; } else { ts . Debug . assert ( attribs [ i ] . kind === 238 /* JsxAttribute */ ) ; emitJsxAttribute ( attribs [ i ] ) ; } } } function emitJsxOpeningOrSelfClosingElement ( node ) { write ( \"<\" ) ; emit ( node . tagName ) ; if ( node . attributes . length > 0 || ( node . kind === 234 /* JsxSelfClosingElement */ ) ) { write ( \" \" ) ; } emitAttributes ( node . attributes ) ; if ( node . kind === 234 /* JsxSelfClosingElement */ ) { write ( \"/>\" ) ; } else { write ( \">\" ) ; } } function emitJsxClosingElement ( node ) { write ( \"</\" ) ; emit ( node . tagName ) ; write ( \">\" ) ; } function emitJsxElement ( node ) { emitJsxOpeningOrSelfClosingElement ( node . openingElement ) ; for ( var i = 0 , n = node . children . length ; i < n ; i ++ ) { emit ( node . children [ i ] ) ; } emitJsxClosingElement ( node . closingElement ) ; } if ( node . kind === 233 /* JsxElement */ ) { emitJsxElement ( node ) ; } else { ts . Debug . assert ( node . kind === 234 /* JsxSelfClosingElement */ ) ; emitJsxOpeningOrSelfClosingElement ( node ) ; } } // This function specifically handles numeric/string literals for enum and accessor 'identifiers'. // In a sense, it does not actually emit identifiers as much as it declares a name for a specific property. // For example, this is utilized when feeding in a result to Object.defineProperty. function emitExpressionForPropertyName ( node ) { ts . Debug . assert ( node . kind !== 163 /* BindingElement */ ) ; if ( node . kind === 9 /* StringLiteral */ ) { emitLiteral ( node ) ; } else if ( node . kind === 136 /* ComputedPropertyName */ ) { // if this is a decorated computed property, we will need to capture the result // of the property expression so that we can apply decorators later. This is to ensure // we don't introduce unintended side effects: // //   class C { //     [_a = x]() { } //   } // // The emit for the decorated computed property decorator is: // //   __decorate([dec], C.prototype, _a, Object.getOwnPropertyDescriptor(C.prototype, _a)); // if ( ts . nodeIsDecorated ( node . parent ) ) { if ( ! computedPropertyNamesToGeneratedNames ) { computedPropertyNamesToGeneratedNames = [ ] ; } var generatedName = computedPropertyNamesToGeneratedNames [ ts . getNodeId ( node ) ] ; if ( generatedName ) { // we have already generated a variable for this node, write that value instead. write ( generatedName ) ; return ; } generatedName = createAndRecordTempVariable ( 0 /* Auto */ ) . text ; computedPropertyNamesToGeneratedNames [ ts . getNodeId ( node ) ] = generatedName ; write ( generatedName ) ; write ( \" = \" ) ; } emit ( node . expression ) ; } else { write ( \"\\\"\" ) ; if ( node . kind === 8 /* NumericLiteral */ ) { write ( node . text ) ; } else { writeTextOfNode ( currentSourceFile , node ) ; } write ( \"\\\"\" ) ; } } function isExpressionIdentifier ( node ) { var parent = node . parent ; switch ( parent . kind ) { case 164 /* ArrayLiteralExpression */ : case 189 /* AsExpression */ : case 181 /* BinaryExpression */ : case 168 /* CallExpression */ : case 241 /* CaseClause */ : case 136 /* ComputedPropertyName */ : case 182 /* ConditionalExpression */ : case 139 /* Decorator */ : case 175 /* DeleteExpression */ : case 197 /* DoStatement */ : case 167 /* ElementAccessExpression */ : case 227 /* ExportAssignment */ : case 195 /* ExpressionStatement */ : case 188 /* ExpressionWithTypeArguments */ : case 199 /* ForStatement */ : case 200 /* ForInStatement */ : case 201 /* ForOfStatement */ : case 196 /* IfStatement */ : case 234 /* JsxSelfClosingElement */ : case 235 /* JsxOpeningElement */ : case 239 /* JsxSpreadAttribute */ : case 240 /* JsxExpression */ : case 169 /* NewExpression */ : case 172 /* ParenthesizedExpression */ : case 180 /* PostfixUnaryExpression */ : case 179 /* PrefixUnaryExpression */ : case 204 /* ReturnStatement */ : case 246 /* ShorthandPropertyAssignment */ : case 185 /* SpreadElementExpression */ : case 206 /* SwitchStatement */ : case 170 /* TaggedTemplateExpression */ : case 190 /* TemplateSpan */ : case 208 /* ThrowStatement */ : case 171 /* TypeAssertionExpression */ : case 176 /* TypeOfExpression */ : case 177 /* VoidExpression */ : case 198 /* WhileStatement */ : case 205 /* WithStatement */ : case 184 /* YieldExpression */ : return true ; case 163 /* BindingElement */ : case 247 /* EnumMember */ : case 138 /* Parameter */ : case 245 /* PropertyAssignment */ : case 141 /* PropertyDeclaration */ : case 211 /* VariableDeclaration */ : return parent . initializer === node ; case 166 /* PropertyAccessExpression */ : return parent . expression === node ; case 174 /* ArrowFunction */ : case 173 /* FunctionExpression */ : return parent . body === node ; case 221 /* ImportEqualsDeclaration */ : return parent . moduleReference === node ; case 135 /* QualifiedName */ : return parent . left === node ; } return false ; } function emitExpressionIdentifier ( node ) { if ( resolver . getNodeCheckFlags ( node ) & 2048 /* LexicalArguments */ ) { write ( \"_arguments\" ) ; return ; } var container = resolver . getReferencedExportContainer ( node ) ; if ( container ) { if ( container . kind === 248 /* SourceFile */ ) { // Identifier references module export if ( modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */ ) { write ( \"exports.\" ) ; } } else { // Identifier references namespace export write ( getGeneratedNameForNode ( container ) ) ; write ( \".\" ) ; } } else { if ( modulekind !== 5 /* ES6 */ ) { var declaration = resolver . getReferencedImportDeclaration ( node ) ; if ( declaration ) { if ( declaration . kind === 223 /* ImportClause */ ) { // Identifier references default import write ( getGeneratedNameForNode ( declaration . parent ) ) ; write ( languageVersion === 0 /* ES3 */ ? \"[\\\"default\\\"]\" : \".default\" ) ; return ; } else if ( declaration . kind === 226 /* ImportSpecifier */ ) { // Identifier references named import write ( getGeneratedNameForNode ( declaration . parent . parent . parent ) ) ; var name_23 = declaration . propertyName || declaration . name ; var identifier = ts . getSourceTextOfNodeFromSourceFile ( currentSourceFile , name_23 ) ; if ( languageVersion === 0 /* ES3 */ && identifier === \"default\" ) { write ( \"[\\\"default\\\"]\" ) ; } else { write ( \".\" ) ; write ( identifier ) ; } return ; } } } if ( languageVersion !== 2 /* ES6 */ ) { var declaration = resolver . getReferencedNestedRedeclaration ( node ) ; if ( declaration ) { write ( getGeneratedNameForNode ( declaration . name ) ) ; return ; } } } if ( ts . nodeIsSynthesized ( node ) ) { write ( node . text ) ; } else { writeTextOfNode ( currentSourceFile , node ) ; } } function isNameOfNestedRedeclaration ( node ) { if ( languageVersion < 2 /* ES6 */ ) { var parent_6 = node . parent ; switch ( parent_6 . kind ) { case 163 /* BindingElement */ : case 214 /* ClassDeclaration */ : case 217 /* EnumDeclaration */ : case 211 /* VariableDeclaration */ : return parent_6 . name === node && resolver . isNestedRedeclaration ( parent_6 ) ; } } return false ; } function emitIdentifier ( node ) { if ( ! node . parent ) { write ( node . text ) ; } else if ( isExpressionIdentifier ( node ) ) { emitExpressionIdentifier ( node ) ; } else if ( isNameOfNestedRedeclaration ( node ) ) { write ( getGeneratedNameForNode ( node ) ) ; } else if ( ts . nodeIsSynthesized ( node ) ) { write ( node . text ) ; } else { writeTextOfNode ( currentSourceFile , node ) ; } } function emitThis ( node ) { if ( resolver . getNodeCheckFlags ( node ) & 2 /* LexicalThis */ ) { write ( \"_this\" ) ; } else { write ( \"this\" ) ; } } function emitSuper ( node ) { if ( languageVersion >= 2 /* ES6 */ ) { write ( \"super\" ) ; } else { var flags = resolver . getNodeCheckFlags ( node ) ; if ( flags & 256 /* SuperInstance */ ) { write ( \"_super.prototype\" ) ; } else { write ( \"_super\" ) ; } } } function emitObjectBindingPattern ( node ) { write ( \"{ \" ) ; var elements = node . elements ; emitList ( elements , 0 , elements . length , /*multiLine*/ false , /*trailingComma*/ elements . hasTrailingComma ) ; write ( \" }\" ) ; } function emitArrayBindingPattern ( node ) { write ( \"[\" ) ; var elements = node . elements ; emitList ( elements , 0 , elements . length , /*multiLine*/ false , /*trailingComma*/ elements . hasTrailingComma ) ; write ( \"]\" ) ; } function emitBindingElement ( node ) { if ( node . propertyName ) { emit ( node . propertyName ) ; write ( \": \" ) ; } if ( node . dotDotDotToken ) { write ( \"...\" ) ; } if ( ts . isBindingPattern ( node . name ) ) { emit ( node . name ) ; } else { emitModuleMemberName ( node ) ; } emitOptional ( \" = \" , node . initializer ) ; } function emitSpreadElementExpression ( node ) { write ( \"...\" ) ; emit ( node . expression ) ; } function emitYieldExpression ( node ) { write ( ts . tokenToString ( 114 /* YieldKeyword */ ) ) ; if ( node . asteriskToken ) { write ( \"*\" ) ; } if ( node . expression ) { write ( \" \" ) ; emit ( node . expression ) ; } } function emitAwaitExpression ( node ) { var needsParenthesis = needsParenthesisForAwaitExpressionAsYield ( node ) ; if ( needsParenthesis ) { write ( \"(\" ) ; } write ( ts . tokenToString ( 114 /* YieldKeyword */ ) ) ; write ( \" \" ) ; emit ( node . expression ) ; if ( needsParenthesis ) { write ( \")\" ) ; } } function needsParenthesisForAwaitExpressionAsYield ( node ) { if ( node . parent . kind === 181 /* BinaryExpression */ && ! ts . isAssignmentOperator ( node . parent . operatorToken . kind ) ) { return true ; } else if ( node . parent . kind === 182 /* ConditionalExpression */ && node . parent . condition === node ) { return true ; } return false ; } function needsParenthesisForPropertyAccessOrInvocation ( node ) { switch ( node . kind ) { case 69 /* Identifier */ : case 164 /* ArrayLiteralExpression */ : case 166 /* PropertyAccessExpression */ : case 167 /* ElementAccessExpression */ : case 168 /* CallExpression */ : case 172 /* ParenthesizedExpression */ : // This list is not exhaustive and only includes those cases that are relevant // to the check in emitArrayLiteral. More cases can be added as needed. return false ; } return true ; } function emitListWithSpread ( elements , needsUniqueCopy , multiLine , trailingComma , useConcat ) { var pos = 0 ; var group = 0 ; var length = elements . length ; while ( pos < length ) { // Emit using the pattern <group0>.concat(<group1>, <group2>, ...) if ( group === 1 && useConcat ) { write ( \".concat(\" ) ; } else if ( group > 0 ) { write ( \", \" ) ; } var e = elements [ pos ] ; if ( e . kind === 185 /* SpreadElementExpression */ ) { e = e . expression ; emitParenthesizedIf ( e , /*parenthesized*/ group === 0 && needsParenthesisForPropertyAccessOrInvocation ( e ) ) ; pos ++ ; if ( pos === length && group === 0 && needsUniqueCopy && e . kind !== 164 /* ArrayLiteralExpression */ ) { write ( \".slice()\" ) ; } } else { var i = pos ; while ( i < length && elements [ i ] . kind !== 185 /* SpreadElementExpression */ ) { i ++ ; } write ( \"[\" ) ; if ( multiLine ) { increaseIndent ( ) ; } emitList ( elements , pos , i - pos , multiLine , trailingComma && i === length ) ; if ( multiLine ) { decreaseIndent ( ) ; } write ( \"]\" ) ; pos = i ; } group ++ ; } if ( group > 1 ) { if ( useConcat ) { write ( \")\" ) ; } } } function isSpreadElementExpression ( node ) { return node . kind === 185 /* SpreadElementExpression */ ; } function emitArrayLiteral ( node ) { var elements = node . elements ; if ( elements . length === 0 ) { write ( \"[]\" ) ; } else if ( languageVersion >= 2 /* ES6 */ || ! ts . forEach ( elements , isSpreadElementExpression ) ) { write ( \"[\" ) ; emitLinePreservingList ( node , node . elements , elements . hasTrailingComma , /*spacesBetweenBraces:*/ false ) ; write ( \"]\" ) ; } else { emitListWithSpread ( elements , /*needsUniqueCopy*/ true , /*multiLine*/ ( node . flags & 2048 /* MultiLine */ ) !== 0 , /*trailingComma*/ elements . hasTrailingComma , /*useConcat*/ true ) ; } } function emitObjectLiteralBody ( node , numElements ) { if ( numElements === 0 ) { write ( \"{}\" ) ; return ; } write ( \"{\" ) ; if ( numElements > 0 ) { var properties = node . properties ; // If we are not doing a downlevel transformation for object literals, // then try to preserve the original shape of the object literal. // Otherwise just try to preserve the formatting. if ( numElements === properties . length ) { emitLinePreservingList ( node , properties , /* allowTrailingComma */ languageVersion >= 1 /* ES5 */ , /* spacesBetweenBraces */ true ) ; } else { var multiLine = ( node . flags & 2048 /* MultiLine */ ) !== 0 ; if ( ! multiLine ) { write ( \" \" ) ; } else { increaseIndent ( ) ; } emitList ( properties , 0 , numElements , /*multiLine*/ multiLine , /*trailingComma*/ false ) ; if ( ! multiLine ) { write ( \" \" ) ; } else { decreaseIndent ( ) ; } } } write ( \"}\" ) ; } function emitDownlevelObjectLiteralWithComputedProperties ( node , firstComputedPropertyIndex ) { var multiLine = ( node . flags & 2048 /* MultiLine */ ) !== 0 ; var properties = node . properties ; write ( \"(\" ) ; if ( multiLine ) { increaseIndent ( ) ; } // For computed properties, we need to create a unique handle to the object // literal so we can modify it without risking internal assignments tainting the object. var tempVar = createAndRecordTempVariable ( 0 /* Auto */ ) ; // Write out the first non-computed properties // (or all properties if none of them are computed), // then emit the rest through indexing on the temp variable. emit ( tempVar ) ; write ( \" = \" ) ; emitObjectLiteralBody ( node , firstComputedPropertyIndex ) ; for ( var i = firstComputedPropertyIndex , n = properties . length ; i < n ; i ++ ) { writeComma ( ) ; var property = properties [ i ] ; emitStart ( property ) ; if ( property . kind === 145 /* GetAccessor */ || property . kind === 146 /* SetAccessor */ ) { // TODO (drosen): Reconcile with 'emitMemberFunctions'. var accessors = ts . getAllAccessorDeclarations ( node . properties , property ) ; if ( property !== accessors . firstAccessor ) { continue ; } write ( \"Object.defineProperty(\" ) ; emit ( tempVar ) ; write ( \", \" ) ; emitStart ( node . name ) ; emitExpressionForPropertyName ( property . name ) ; emitEnd ( property . name ) ; write ( \", {\" ) ; increaseIndent ( ) ; if ( accessors . getAccessor ) { writeLine ( ) ; emitLeadingComments ( accessors . getAccessor ) ; write ( \"get: \" ) ; emitStart ( accessors . getAccessor ) ; write ( \"function \" ) ; emitSignatureAndBody ( accessors . getAccessor ) ; emitEnd ( accessors . getAccessor ) ; emitTrailingComments ( accessors . getAccessor ) ; write ( \",\" ) ; } if ( accessors . setAccessor ) { writeLine ( ) ; emitLeadingComments ( accessors . setAccessor ) ; write ( \"set: \" ) ; emitStart ( accessors . setAccessor ) ; write ( \"function \" ) ; emitSignatureAndBody ( accessors . setAccessor ) ; emitEnd ( accessors . setAccessor ) ; emitTrailingComments ( accessors . setAccessor ) ; write ( \",\" ) ; } writeLine ( ) ; write ( \"enumerable: true,\" ) ; writeLine ( ) ; write ( \"configurable: true\" ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"})\" ) ; emitEnd ( property ) ; } else { emitLeadingComments ( property ) ; emitStart ( property . name ) ; emit ( tempVar ) ; emitMemberAccessForPropertyName ( property . name ) ; emitEnd ( property . name ) ; write ( \" = \" ) ; if ( property . kind === 245 /* PropertyAssignment */ ) { emit ( property . initializer ) ; } else if ( property . kind === 246 /* ShorthandPropertyAssignment */ ) { emitExpressionIdentifier ( property . name ) ; } else if ( property . kind === 143 /* MethodDeclaration */ ) { emitFunctionDeclaration ( property ) ; } else { ts . Debug . fail ( \"ObjectLiteralElement type not accounted for: \" + property . kind ) ; } } emitEnd ( property ) ; } writeComma ( ) ; emit ( tempVar ) ; if ( multiLine ) { decreaseIndent ( ) ; writeLine ( ) ; } write ( \")\" ) ; function writeComma ( ) { if ( multiLine ) { write ( \",\" ) ; writeLine ( ) ; } else { write ( \", \" ) ; } } } function emitObjectLiteral ( node ) { var properties = node . properties ; if ( languageVersion < 2 /* ES6 */ ) { var numProperties = properties . length ; // Find the first computed property. // Everything until that point can be emitted as part of the initial object literal. var numInitialNonComputedProperties = numProperties ; for ( var i = 0 , n = properties . length ; i < n ; i ++ ) { if ( properties [ i ] . name . kind === 136 /* ComputedPropertyName */ ) { numInitialNonComputedProperties = i ; break ; } } var hasComputedProperty = numInitialNonComputedProperties !== properties . length ; if ( hasComputedProperty ) { emitDownlevelObjectLiteralWithComputedProperties ( node , numInitialNonComputedProperties ) ; return ; } } // Ordinary case: either the object has no computed properties // or we're compiling with an ES6+ target. emitObjectLiteralBody ( node , properties . length ) ; } function createBinaryExpression ( left , operator , right , startsOnNewLine ) { var result = ts . createSynthesizedNode ( 181 /* BinaryExpression */ , startsOnNewLine ) ; result . operatorToken = ts . createSynthesizedNode ( operator ) ; result . left = left ; result . right = right ; return result ; } function createPropertyAccessExpression ( expression , name ) { var result = ts . createSynthesizedNode ( 166 /* PropertyAccessExpression */ ) ; result . expression = parenthesizeForAccess ( expression ) ; result . dotToken = ts . createSynthesizedNode ( 21 /* DotToken */ ) ; result . name = name ; return result ; } function createElementAccessExpression ( expression , argumentExpression ) { var result = ts . createSynthesizedNode ( 167 /* ElementAccessExpression */ ) ; result . expression = parenthesizeForAccess ( expression ) ; result . argumentExpression = argumentExpression ; return result ; } function parenthesizeForAccess ( expr ) { // When diagnosing whether the expression needs parentheses, the decision should be based // on the innermost expression in a chain of nested type assertions. while ( expr . kind === 171 /* TypeAssertionExpression */ || expr . kind === 189 /* AsExpression */ ) { expr = expr . expression ; } // isLeftHandSideExpression is almost the correct criterion for when it is not necessary // to parenthesize the expression before a dot. The known exceptions are: // //    NewExpression: //       new C.x        -> not the same as (new C).x //    NumberLiteral //       1.x            -> not the same as (1).x // if ( ts . isLeftHandSideExpression ( expr ) && expr . kind !== 169 /* NewExpression */ && expr . kind !== 8 /* NumericLiteral */ ) { return expr ; } var node = ts . createSynthesizedNode ( 172 /* ParenthesizedExpression */ ) ; node . expression = expr ; return node ; } function emitComputedPropertyName ( node ) { write ( \"[\" ) ; emitExpressionForPropertyName ( node ) ; write ( \"]\" ) ; } function emitMethod ( node ) { if ( languageVersion >= 2 /* ES6 */ && node . asteriskToken ) { write ( \"*\" ) ; } emit ( node . name ) ; if ( languageVersion < 2 /* ES6 */ ) { write ( \": function \" ) ; } emitSignatureAndBody ( node ) ; } function emitPropertyAssignment ( node ) { emit ( node . name ) ; write ( \": \" ) ; // This is to ensure that we emit comment in the following case: //      For example: //          obj = { //              id: /*comment1*/ ()=>void //          } // \"comment1\" is not considered to be leading comment for node.initializer // but rather a trailing comment on the previous node. emitTrailingCommentsOfPosition ( node . initializer . pos ) ; emit ( node . initializer ) ; } // Return true if identifier resolves to an exported member of a namespace function isNamespaceExportReference ( node ) { var container = resolver . getReferencedExportContainer ( node ) ; return container && container . kind !== 248 /* SourceFile */ ; } function emitShorthandPropertyAssignment ( node ) { // The name property of a short-hand property assignment is considered an expression position, so here // we manually emit the identifier to avoid rewriting. writeTextOfNode ( currentSourceFile , node . name ) ; // If emitting pre-ES6 code, or if the name requires rewriting when resolved as an expression identifier, // we emit a normal property assignment. For example: //   module m { //       export let y; //   } //   module m { //       let obj = { y }; //   } // Here we need to emit obj = { y : m.y } regardless of the output target. if ( languageVersion < 2 /* ES6 */ || isNamespaceExportReference ( node . name ) ) { // Emit identifier as an identifier write ( \": \" ) ; emit ( node . name ) ; } if ( languageVersion >= 2 /* ES6 */ && node . objectAssignmentInitializer ) { write ( \" = \" ) ; emit ( node . objectAssignmentInitializer ) ; } } function tryEmitConstantValue ( node ) { var constantValue = tryGetConstEnumValue ( node ) ; if ( constantValue !== undefined ) { write ( constantValue . toString ( ) ) ; if ( ! compilerOptions . removeComments ) { var propertyName = node . kind === 166 /* PropertyAccessExpression */ ? ts . declarationNameToString ( node . name ) : ts . getTextOfNode ( node . argumentExpression ) ; write ( \" /* \" + propertyName + \" */\" ) ; } return true ; } return false ; } function tryGetConstEnumValue ( node ) { if ( compilerOptions . isolatedModules ) { return undefined ; } return node . kind === 166 /* PropertyAccessExpression */ || node . kind === 167 /* ElementAccessExpression */ ? resolver . getConstantValue ( node ) : undefined ; } // Returns 'true' if the code was actually indented, false otherwise. // If the code is not indented, an optional valueToWriteWhenNotIndenting will be // emitted instead. function indentIfOnDifferentLines ( parent , node1 , node2 , valueToWriteWhenNotIndenting ) { var realNodesAreOnDifferentLines = ! ts . nodeIsSynthesized ( parent ) && ! nodeEndIsOnSameLineAsNodeStart ( node1 , node2 ) ; // Always use a newline for synthesized code if the synthesizer desires it. var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine ( node2 ) ; if ( realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine ) { increaseIndent ( ) ; writeLine ( ) ; return true ; } else { if ( valueToWriteWhenNotIndenting ) { write ( valueToWriteWhenNotIndenting ) ; } return false ; } } function emitPropertyAccess ( node ) { if ( tryEmitConstantValue ( node ) ) { return ; } emit ( node . expression ) ; var indentedBeforeDot = indentIfOnDifferentLines ( node , node . expression , node . dotToken ) ; // 1 .toString is a valid property access, emit a space after the literal // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal var shouldEmitSpace ; if ( ! indentedBeforeDot ) { if ( node . expression . kind === 8 /* NumericLiteral */ ) { // check if numeric literal was originally written with a dot var text = ts . getSourceTextOfNodeFromSourceFile ( currentSourceFile , node . expression ) ; shouldEmitSpace = text . indexOf ( ts . tokenToString ( 21 /* DotToken */ ) ) < 0 ; } else { // check if constant enum value is integer var constantValue = tryGetConstEnumValue ( node . expression ) ; // isFinite handles cases when constantValue is undefined shouldEmitSpace = isFinite ( constantValue ) && Math . floor ( constantValue ) === constantValue ; } } if ( shouldEmitSpace ) { write ( \" .\" ) ; } else { write ( \".\" ) ; } var indentedAfterDot = indentIfOnDifferentLines ( node , node . dotToken , node . name ) ; emit ( node . name ) ; decreaseIndentIf ( indentedBeforeDot , indentedAfterDot ) ; } function emitQualifiedName ( node ) { emit ( node . left ) ; write ( \".\" ) ; emit ( node . right ) ; } function emitQualifiedNameAsExpression ( node , useFallback ) { if ( node . left . kind === 69 /* Identifier */ ) { emitEntityNameAsExpression ( node . left , useFallback ) ; } else if ( useFallback ) { var temp = createAndRecordTempVariable ( 0 /* Auto */ ) ; write ( \"(\" ) ; emitNodeWithoutSourceMap ( temp ) ; write ( \" = \" ) ; emitEntityNameAsExpression ( node . left , /*useFallback*/ true ) ; write ( \") && \" ) ; emitNodeWithoutSourceMap ( temp ) ; } else { emitEntityNameAsExpression ( node . left , /*useFallback*/ false ) ; } write ( \".\" ) ; emit ( node . right ) ; } function emitEntityNameAsExpression ( node , useFallback ) { switch ( node . kind ) { case 69 /* Identifier */ : if ( useFallback ) { write ( \"typeof \" ) ; emitExpressionIdentifier ( node ) ; write ( \" !== 'undefined' && \" ) ; } emitExpressionIdentifier ( node ) ; break ; case 135 /* QualifiedName */ : emitQualifiedNameAsExpression ( node , useFallback ) ; break ; } } function emitIndexedAccess ( node ) { if ( tryEmitConstantValue ( node ) ) { return ; } emit ( node . expression ) ; write ( \"[\" ) ; emit ( node . argumentExpression ) ; write ( \"]\" ) ; } function hasSpreadElement ( elements ) { return ts . forEach ( elements , function ( e ) { return e . kind === 185 /* SpreadElementExpression */ ; } ) ; } function skipParentheses ( node ) { while ( node . kind === 172 /* ParenthesizedExpression */ || node . kind === 171 /* TypeAssertionExpression */ || node . kind === 189 /* AsExpression */ ) { node = node . expression ; } return node ; } function emitCallTarget ( node ) { if ( node . kind === 69 /* Identifier */ || node . kind === 97 /* ThisKeyword */ || node . kind === 95 /* SuperKeyword */ ) { emit ( node ) ; return node ; } var temp = createAndRecordTempVariable ( 0 /* Auto */ ) ; write ( \"(\" ) ; emit ( temp ) ; write ( \" = \" ) ; emit ( node ) ; write ( \")\" ) ; return temp ; } function emitCallWithSpread ( node ) { var target ; var expr = skipParentheses ( node . expression ) ; if ( expr . kind === 166 /* PropertyAccessExpression */ ) { // Target will be emitted as \"this\" argument target = emitCallTarget ( expr . expression ) ; write ( \".\" ) ; emit ( expr . name ) ; } else if ( expr . kind === 167 /* ElementAccessExpression */ ) { // Target will be emitted as \"this\" argument target = emitCallTarget ( expr . expression ) ; write ( \"[\" ) ; emit ( expr . argumentExpression ) ; write ( \"]\" ) ; } else if ( expr . kind === 95 /* SuperKeyword */ ) { target = expr ; write ( \"_super\" ) ; } else { emit ( node . expression ) ; } write ( \".apply(\" ) ; if ( target ) { if ( target . kind === 95 /* SuperKeyword */ ) { // Calls of form super(...) and super.foo(...) emitThis ( target ) ; } else { // Calls of form obj.foo(...) emit ( target ) ; } } else { // Calls of form foo(...) write ( \"void 0\" ) ; } write ( \", \" ) ; emitListWithSpread ( node . arguments , /*needsUniqueCopy*/ false , /*multiLine*/ false , /*trailingComma*/ false , /*useConcat*/ true ) ; write ( \")\" ) ; } function emitCallExpression ( node ) { if ( languageVersion < 2 /* ES6 */ && hasSpreadElement ( node . arguments ) ) { emitCallWithSpread ( node ) ; return ; } var superCall = false ; if ( node . expression . kind === 95 /* SuperKeyword */ ) { emitSuper ( node . expression ) ; superCall = true ; } else { emit ( node . expression ) ; superCall = node . expression . kind === 166 /* PropertyAccessExpression */ && node . expression . expression . kind === 95 /* SuperKeyword */ ; } if ( superCall && languageVersion < 2 /* ES6 */ ) { write ( \".call(\" ) ; emitThis ( node . expression ) ; if ( node . arguments . length ) { write ( \", \" ) ; emitCommaList ( node . arguments ) ; } write ( \")\" ) ; } else { write ( \"(\" ) ; emitCommaList ( node . arguments ) ; write ( \")\" ) ; } } function emitNewExpression ( node ) { write ( \"new \" ) ; // Spread operator logic is supported in new expressions in ES5 using a combination // of Function.prototype.bind() and Function.prototype.apply(). // //     Example: // //         var args = [1, 2, 3, 4, 5]; //         new Array(...args); // //     is compiled into the following ES5: // //         var args = [1, 2, 3, 4, 5]; //         new (Array.bind.apply(Array, [void 0].concat(args))); // // The 'thisArg' to 'bind' is ignored when invoking the result of 'bind' with 'new', // Thus, we set it to undefined ('void 0'). if ( languageVersion === 1 /* ES5 */ && node . arguments && hasSpreadElement ( node . arguments ) ) { write ( \"(\" ) ; var target = emitCallTarget ( node . expression ) ; write ( \".bind.apply(\" ) ; emit ( target ) ; write ( \", [void 0].concat(\" ) ; emitListWithSpread ( node . arguments , /*needsUniqueCopy*/ false , /*multiline*/ false , /*trailingComma*/ false , /*useConcat*/ false ) ; write ( \")))\" ) ; write ( \"()\" ) ; } else { emit ( node . expression ) ; if ( node . arguments ) { write ( \"(\" ) ; emitCommaList ( node . arguments ) ; write ( \")\" ) ; } } } function emitTaggedTemplateExpression ( node ) { if ( languageVersion >= 2 /* ES6 */ ) { emit ( node . tag ) ; write ( \" \" ) ; emit ( node . template ) ; } else { emitDownlevelTaggedTemplate ( node ) ; } } function emitParenExpression ( node ) { // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. if ( ! ts . nodeIsSynthesized ( node ) && node . parent . kind !== 174 /* ArrowFunction */ ) { if ( node . expression . kind === 171 /* TypeAssertionExpression */ || node . expression . kind === 189 /* AsExpression */ ) { var operand = node . expression . expression ; // Make sure we consider all nested cast expressions, e.g.: // (<any><number><any>-A).x; while ( operand . kind === 171 /* TypeAssertionExpression */ || operand . kind === 189 /* AsExpression */ ) { operand = operand . expression ; } // We have an expression of the form: (<Type>SubExpr) // Emitting this as (SubExpr) is really not desirable. We would like to emit the subexpr as is. // Omitting the parentheses, however, could cause change in the semantics of the generated // code if the casted expression has a lower precedence than the rest of the expression, e.g.: //      (<any>new A).foo should be emitted as (new A).foo and not new A.foo //      (<any>typeof A).toString() should be emitted as (typeof A).toString() and not typeof A.toString() //      new (<any>A()) should be emitted as new (A()) and not new A() //      (<any>function foo() { })() should be emitted as an IIF (function foo(){})() and not declaration function foo(){} () if ( operand . kind !== 179 /* PrefixUnaryExpression */ && operand . kind !== 177 /* VoidExpression */ && operand . kind !== 176 /* TypeOfExpression */ && operand . kind !== 175 /* DeleteExpression */ && operand . kind !== 180 /* PostfixUnaryExpression */ && operand . kind !== 169 /* NewExpression */ && ! ( operand . kind === 168 /* CallExpression */ && node . parent . kind === 169 /* NewExpression */ ) && ! ( operand . kind === 173 /* FunctionExpression */ && node . parent . kind === 168 /* CallExpression */ ) && ! ( operand . kind === 8 /* NumericLiteral */ && node . parent . kind === 166 /* PropertyAccessExpression */ ) ) { emit ( operand ) ; return ; } } } write ( \"(\" ) ; emit ( node . expression ) ; write ( \")\" ) ; } function emitDeleteExpression ( node ) { write ( ts . tokenToString ( 78 /* DeleteKeyword */ ) ) ; write ( \" \" ) ; emit ( node . expression ) ; } function emitVoidExpression ( node ) { write ( ts . tokenToString ( 103 /* VoidKeyword */ ) ) ; write ( \" \" ) ; emit ( node . expression ) ; } function emitTypeOfExpression ( node ) { write ( ts . tokenToString ( 101 /* TypeOfKeyword */ ) ) ; write ( \" \" ) ; emit ( node . expression ) ; } function isNameOfExportedSourceLevelDeclarationInSystemExternalModule ( node ) { if ( ! isCurrentFileSystemExternalModule ( ) || node . kind !== 69 /* Identifier */ || ts . nodeIsSynthesized ( node ) ) { return false ; } var isVariableDeclarationOrBindingElement = node . parent && ( node . parent . kind === 211 /* VariableDeclaration */ || node . parent . kind === 163 /* BindingElement */ ) ; var targetDeclaration = isVariableDeclarationOrBindingElement ? node . parent : resolver . getReferencedValueDeclaration ( node ) ; return isSourceFileLevelDeclarationInSystemJsModule ( targetDeclaration , /*isExported*/ true ) ; } function emitPrefixUnaryExpression ( node ) { var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule ( node . operand ) ; if ( exportChanged ) { // emit // ++x // as // exports('x', ++x) write ( exportFunctionForFile + \"(\\\"\" ) ; emitNodeWithoutSourceMap ( node . operand ) ; write ( \"\\\", \" ) ; } write ( ts . tokenToString ( node . operator ) ) ; // In some cases, we need to emit a space between the operator and the operand. One obvious case // is when the operator is an identifier, like delete or typeof. We also need to do this for plus // and minus expressions in certain cases. Specifically, consider the following two cases (parens // are just for clarity of exposition, and not part of the source code): // //  (+(+1)) //  (+(++1)) // // We need to emit a space in both cases. In the first case, the absence of a space will make // the resulting expression a prefix increment operation. And in the second, it will make the resulting // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. if ( node . operand . kind === 179 /* PrefixUnaryExpression */ ) { var operand = node . operand ; if ( node . operator === 35 /* PlusToken */ && ( operand . operator === 35 /* PlusToken */ || operand . operator === 41 /* PlusPlusToken */ ) ) { write ( \" \" ) ; } else if ( node . operator === 36 /* MinusToken */ && ( operand . operator === 36 /* MinusToken */ || operand . operator === 42 /* MinusMinusToken */ ) ) { write ( \" \" ) ; } } emit ( node . operand ) ; if ( exportChanged ) { write ( \")\" ) ; } } function emitPostfixUnaryExpression ( node ) { var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule ( node . operand ) ; if ( exportChanged ) { // export function returns the value that was passes as the second argument // however for postfix unary expressions result value should be the value before modification. // emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)' write ( \"(\" + exportFunctionForFile + \"(\\\"\" ) ; emitNodeWithoutSourceMap ( node . operand ) ; write ( \"\\\", \" ) ; write ( ts . tokenToString ( node . operator ) ) ; emit ( node . operand ) ; if ( node . operator === 41 /* PlusPlusToken */ ) { write ( \") - 1)\" ) ; } else { write ( \") + 1)\" ) ; } } else { emit ( node . operand ) ; write ( ts . tokenToString ( node . operator ) ) ; } } function shouldHoistDeclarationInSystemJsModule ( node ) { return isSourceFileLevelDeclarationInSystemJsModule ( node , /*isExported*/ false ) ; } /*\n             * Checks if given node is a source file level declaration (not nested in module/function).\n             * If 'isExported' is true - then declaration must also be exported.\n             * This function is used in two cases:\n             * - check if node is a exported source file level value to determine\n             *   if we should also export the value after its it changed\n             * - check if node is a source level declaration to emit it differently,\n             *   i.e non-exported variable statement 'var x = 1' is hoisted so\n             *   we we emit variable statement 'var' should be dropped.\n             */ function isSourceFileLevelDeclarationInSystemJsModule ( node , isExported ) { if ( ! node || languageVersion >= 2 /* ES6 */ || ! isCurrentFileSystemExternalModule ( ) ) { return false ; } var current = node ; while ( current ) { if ( current . kind === 248 /* SourceFile */ ) { return ! isExported || ( ( ts . getCombinedNodeFlags ( node ) & 1 /* Export */ ) !== 0 ) ; } else if ( ts . isFunctionLike ( current ) || current . kind === 219 /* ModuleBlock */ ) { return false ; } else { current = current . parent ; } } } /**\n             * Emit ES7 exponentiation operator downlevel using Math.pow\n             * @param node a binary expression node containing exponentiationOperator (**, **=)\n             */ function emitExponentiationOperator ( node ) { var leftHandSideExpression = node . left ; if ( node . operatorToken . kind === 60 /* AsteriskAsteriskEqualsToken */ ) { var synthesizedLHS ; var shouldEmitParentheses = false ; if ( ts . isElementAccessExpression ( leftHandSideExpression ) ) { shouldEmitParentheses = true ; write ( \"(\" ) ; synthesizedLHS = ts . createSynthesizedNode ( 167 /* ElementAccessExpression */ , /*startsOnNewLine*/ false ) ; var identifier = emitTempVariableAssignment ( leftHandSideExpression . expression , /*canDefinedTempVariablesInPlaces*/ false , /*shouldEmitCommaBeforeAssignment*/ false ) ; synthesizedLHS . expression = identifier ; if ( leftHandSideExpression . argumentExpression . kind !== 8 /* NumericLiteral */ && leftHandSideExpression . argumentExpression . kind !== 9 /* StringLiteral */ ) { var tempArgumentExpression = createAndRecordTempVariable ( 268435456 /* _i */ ) ; synthesizedLHS . argumentExpression = tempArgumentExpression ; emitAssignment ( tempArgumentExpression , leftHandSideExpression . argumentExpression , /*shouldEmitCommaBeforeAssignment*/ true ) ; } else { synthesizedLHS . argumentExpression = leftHandSideExpression . argumentExpression ; } write ( \", \" ) ; } else if ( ts . isPropertyAccessExpression ( leftHandSideExpression ) ) { shouldEmitParentheses = true ; write ( \"(\" ) ; synthesizedLHS = ts . createSynthesizedNode ( 166 /* PropertyAccessExpression */ , /*startsOnNewLine*/ false ) ; var identifier = emitTempVariableAssignment ( leftHandSideExpression . expression , /*canDefinedTempVariablesInPlaces*/ false , /*shouldemitCommaBeforeAssignment*/ false ) ; synthesizedLHS . expression = identifier ; synthesizedLHS . dotToken = leftHandSideExpression . dotToken ; synthesizedLHS . name = leftHandSideExpression . name ; write ( \", \" ) ; } emit ( synthesizedLHS || leftHandSideExpression ) ; write ( \" = \" ) ; write ( \"Math.pow(\" ) ; emit ( synthesizedLHS || leftHandSideExpression ) ; write ( \", \" ) ; emit ( node . right ) ; write ( \")\" ) ; if ( shouldEmitParentheses ) { write ( \")\" ) ; } } else { write ( \"Math.pow(\" ) ; emit ( leftHandSideExpression ) ; write ( \", \" ) ; emit ( node . right ) ; write ( \")\" ) ; } } function emitBinaryExpression ( node ) { if ( languageVersion < 2 /* ES6 */ && node . operatorToken . kind === 56 /* EqualsToken */ && ( node . left . kind === 165 /* ObjectLiteralExpression */ || node . left . kind === 164 /* ArrayLiteralExpression */ ) ) { emitDestructuring ( node , node . parent . kind === 195 /* ExpressionStatement */ ) ; } else { var exportChanged = node . operatorToken . kind >= 56 /* FirstAssignment */ && node . operatorToken . kind <= 68 /* LastAssignment */ && isNameOfExportedSourceLevelDeclarationInSystemExternalModule ( node . left ) ; if ( exportChanged ) { // emit assignment 'x <op> y' as 'exports(\"x\", x <op> y)' write ( exportFunctionForFile + \"(\\\"\" ) ; emitNodeWithoutSourceMap ( node . left ) ; write ( \"\\\", \" ) ; } if ( node . operatorToken . kind === 38 /* AsteriskAsteriskToken */ || node . operatorToken . kind === 60 /* AsteriskAsteriskEqualsToken */ ) { // Downleveled emit exponentiation operator using Math.pow emitExponentiationOperator ( node ) ; } else { emit ( node . left ) ; // Add indentation before emit the operator if the operator is on different line // For example: //      3 //      + 2; //   emitted as //      3 //          + 2; var indentedBeforeOperator = indentIfOnDifferentLines ( node , node . left , node . operatorToken , node . operatorToken . kind !== 24 /* CommaToken */ ? \" \" : undefined ) ; write ( ts . tokenToString ( node . operatorToken . kind ) ) ; var indentedAfterOperator = indentIfOnDifferentLines ( node , node . operatorToken , node . right , \" \" ) ; emit ( node . right ) ; decreaseIndentIf ( indentedBeforeOperator , indentedAfterOperator ) ; } if ( exportChanged ) { write ( \")\" ) ; } } } function synthesizedNodeStartsOnNewLine ( node ) { return ts . nodeIsSynthesized ( node ) && node . startsOnNewLine ; } function emitConditionalExpression ( node ) { emit ( node . condition ) ; var indentedBeforeQuestion = indentIfOnDifferentLines ( node , node . condition , node . questionToken , \" \" ) ; write ( \"?\" ) ; var indentedAfterQuestion = indentIfOnDifferentLines ( node , node . questionToken , node . whenTrue , \" \" ) ; emit ( node . whenTrue ) ; decreaseIndentIf ( indentedBeforeQuestion , indentedAfterQuestion ) ; var indentedBeforeColon = indentIfOnDifferentLines ( node , node . whenTrue , node . colonToken , \" \" ) ; write ( \":\" ) ; var indentedAfterColon = indentIfOnDifferentLines ( node , node . colonToken , node . whenFalse , \" \" ) ; emit ( node . whenFalse ) ; decreaseIndentIf ( indentedBeforeColon , indentedAfterColon ) ; } // Helper function to decrease the indent if we previously indented.  Allows multiple // previous indent values to be considered at a time.  This also allows caller to just // call this once, passing in all their appropriate indent values, instead of needing // to call this helper function multiple times. function decreaseIndentIf ( value1 , value2 ) { if ( value1 ) { decreaseIndent ( ) ; } if ( value2 ) { decreaseIndent ( ) ; } } function isSingleLineEmptyBlock ( node ) { if ( node && node . kind === 192 /* Block */ ) { var block = node ; return block . statements . length === 0 && nodeEndIsOnSameLineAsNodeStart ( block , block ) ; } } function emitBlock ( node ) { if ( isSingleLineEmptyBlock ( node ) ) { emitToken ( 15 /* OpenBraceToken */ , node . pos ) ; write ( \" \" ) ; emitToken ( 16 /* CloseBraceToken */ , node . statements . end ) ; return ; } emitToken ( 15 /* OpenBraceToken */ , node . pos ) ; increaseIndent ( ) ; scopeEmitStart ( node . parent ) ; if ( node . kind === 219 /* ModuleBlock */ ) { ts . Debug . assert ( node . parent . kind === 218 /* ModuleDeclaration */ ) ; emitCaptureThisForNodeIfNecessary ( node . parent ) ; } emitLines ( node . statements ) ; if ( node . kind === 219 /* ModuleBlock */ ) { emitTempDeclarations ( /*newLine*/ true ) ; } decreaseIndent ( ) ; writeLine ( ) ; emitToken ( 16 /* CloseBraceToken */ , node . statements . end ) ; scopeEmitEnd ( ) ; } function emitEmbeddedStatement ( node ) { if ( node . kind === 192 /* Block */ ) { write ( \" \" ) ; emit ( node ) ; } else { increaseIndent ( ) ; writeLine ( ) ; emit ( node ) ; decreaseIndent ( ) ; } } function emitExpressionStatement ( node ) { emitParenthesizedIf ( node . expression , /*parenthesized*/ node . expression . kind === 174 /* ArrowFunction */ ) ; write ( \";\" ) ; } function emitIfStatement ( node ) { var endPos = emitToken ( 88 /* IfKeyword */ , node . pos ) ; write ( \" \" ) ; endPos = emitToken ( 17 /* OpenParenToken */ , endPos ) ; emit ( node . expression ) ; emitToken ( 18 /* CloseParenToken */ , node . expression . end ) ; emitEmbeddedStatement ( node . thenStatement ) ; if ( node . elseStatement ) { writeLine ( ) ; emitToken ( 80 /* ElseKeyword */ , node . thenStatement . end ) ; if ( node . elseStatement . kind === 196 /* IfStatement */ ) { write ( \" \" ) ; emit ( node . elseStatement ) ; } else { emitEmbeddedStatement ( node . elseStatement ) ; } } } function emitDoStatement ( node ) { write ( \"do\" ) ; emitEmbeddedStatement ( node . statement ) ; if ( node . statement . kind === 192 /* Block */ ) { write ( \" \" ) ; } else { writeLine ( ) ; } write ( \"while (\" ) ; emit ( node . expression ) ; write ( \");\" ) ; } function emitWhileStatement ( node ) { write ( \"while (\" ) ; emit ( node . expression ) ; write ( \")\" ) ; emitEmbeddedStatement ( node . statement ) ; } /**\n             * Returns true if start of variable declaration list was emitted.\n             * Returns false if nothing was written - this can happen for source file level variable declarations\n             *     in system modules where such variable declarations are hoisted.\n             */ function tryEmitStartOfVariableDeclarationList ( decl , startPos ) { if ( shouldHoistVariable ( decl , /*checkIfSourceFileLevelDecl*/ true ) ) { // variables in variable declaration list were already hoisted return false ; } var tokenKind = 102 /* VarKeyword */ ; if ( decl && languageVersion >= 2 /* ES6 */ ) { if ( ts . isLet ( decl ) ) { tokenKind = 108 /* LetKeyword */ ; } else if ( ts . isConst ( decl ) ) { tokenKind = 74 /* ConstKeyword */ ; } } if ( startPos !== undefined ) { emitToken ( tokenKind , startPos ) ; write ( \" \" ) ; } else { switch ( tokenKind ) { case 102 /* VarKeyword */ : write ( \"var \" ) ; break ; case 108 /* LetKeyword */ : write ( \"let \" ) ; break ; case 74 /* ConstKeyword */ : write ( \"const \" ) ; break ; } } return true ; } function emitVariableDeclarationListSkippingUninitializedEntries ( list ) { var started = false ; for ( var _a = 0 , _b = list . declarations ; _a < _b . length ; _a ++ ) { var decl = _b [ _a ] ; if ( ! decl . initializer ) { continue ; } if ( ! started ) { started = true ; } else { write ( \", \" ) ; } emit ( decl ) ; } return started ; } function emitForStatement ( node ) { var endPos = emitToken ( 86 /* ForKeyword */ , node . pos ) ; write ( \" \" ) ; endPos = emitToken ( 17 /* OpenParenToken */ , endPos ) ; if ( node . initializer && node . initializer . kind === 212 /* VariableDeclarationList */ ) { var variableDeclarationList = node . initializer ; var startIsEmitted = tryEmitStartOfVariableDeclarationList ( variableDeclarationList , endPos ) ; if ( startIsEmitted ) { emitCommaList ( variableDeclarationList . declarations ) ; } else { emitVariableDeclarationListSkippingUninitializedEntries ( variableDeclarationList ) ; } } else if ( node . initializer ) { emit ( node . initializer ) ; } write ( \";\" ) ; emitOptional ( \" \" , node . condition ) ; write ( \";\" ) ; emitOptional ( \" \" , node . incrementor ) ; write ( \")\" ) ; emitEmbeddedStatement ( node . statement ) ; } function emitForInOrForOfStatement ( node ) { if ( languageVersion < 2 /* ES6 */ && node . kind === 201 /* ForOfStatement */ ) { return emitDownLevelForOfStatement ( node ) ; } var endPos = emitToken ( 86 /* ForKeyword */ , node . pos ) ; write ( \" \" ) ; endPos = emitToken ( 17 /* OpenParenToken */ , endPos ) ; if ( node . initializer . kind === 212 /* VariableDeclarationList */ ) { var variableDeclarationList = node . initializer ; if ( variableDeclarationList . declarations . length >= 1 ) { tryEmitStartOfVariableDeclarationList ( variableDeclarationList , endPos ) ; emit ( variableDeclarationList . declarations [ 0 ] ) ; } } else { emit ( node . initializer ) ; } if ( node . kind === 200 /* ForInStatement */ ) { write ( \" in \" ) ; } else { write ( \" of \" ) ; } emit ( node . expression ) ; emitToken ( 18 /* CloseParenToken */ , node . expression . end ) ; emitEmbeddedStatement ( node . statement ) ; } function emitDownLevelForOfStatement ( node ) { // The following ES6 code: // //    for (let v of expr) { } // // should be emitted as // //    for (let _i = 0, _a = expr; _i < _a.length; _i++) { //        let v = _a[_i]; //    } // // where _a and _i are temps emitted to capture the RHS and the counter, // respectively. // When the left hand side is an expression instead of a let declaration, // the \"let v\" is not emitted. // When the left hand side is a let/const, the v is renamed if there is // another v in scope. // Note that all assignments to the LHS are emitted in the body, including // all destructuring. // Note also that because an extra statement is needed to assign to the LHS, // for-of bodies are always emitted as blocks. var endPos = emitToken ( 86 /* ForKeyword */ , node . pos ) ; write ( \" \" ) ; endPos = emitToken ( 17 /* OpenParenToken */ , endPos ) ; // Do not emit the LHS let declaration yet, because it might contain destructuring. // Do not call recordTempDeclaration because we are declaring the temps // right here. Recording means they will be declared later. // In the case where the user wrote an identifier as the RHS, like this: // //     for (let v of arr) { } // // we don't want to emit a temporary variable for the RHS, just use it directly. var rhsIsIdentifier = node . expression . kind === 69 /* Identifier */ ; var counter = createTempVariable ( 268435456 /* _i */ ) ; var rhsReference = rhsIsIdentifier ? node . expression : createTempVariable ( 0 /* Auto */ ) ; // This is the let keyword for the counter and rhsReference. The let keyword for // the LHS will be emitted inside the body. emitStart ( node . expression ) ; write ( \"var \" ) ; // _i = 0 emitNodeWithoutSourceMap ( counter ) ; write ( \" = 0\" ) ; emitEnd ( node . expression ) ; if ( ! rhsIsIdentifier ) { // , _a = expr write ( \", \" ) ; emitStart ( node . expression ) ; emitNodeWithoutSourceMap ( rhsReference ) ; write ( \" = \" ) ; emitNodeWithoutSourceMap ( node . expression ) ; emitEnd ( node . expression ) ; } write ( \"; \" ) ; // _i < _a.length; emitStart ( node . initializer ) ; emitNodeWithoutSourceMap ( counter ) ; write ( \" < \" ) ; emitNodeWithCommentsAndWithoutSourcemap ( rhsReference ) ; write ( \".length\" ) ; emitEnd ( node . initializer ) ; write ( \"; \" ) ; // _i++) emitStart ( node . initializer ) ; emitNodeWithoutSourceMap ( counter ) ; write ( \"++\" ) ; emitEnd ( node . initializer ) ; emitToken ( 18 /* CloseParenToken */ , node . expression . end ) ; // Body write ( \" {\" ) ; writeLine ( ) ; increaseIndent ( ) ; // Initialize LHS // let v = _a[_i]; var rhsIterationValue = createElementAccessExpression ( rhsReference , counter ) ; emitStart ( node . initializer ) ; if ( node . initializer . kind === 212 /* VariableDeclarationList */ ) { write ( \"var \" ) ; var variableDeclarationList = node . initializer ; if ( variableDeclarationList . declarations . length > 0 ) { var declaration = variableDeclarationList . declarations [ 0 ] ; if ( ts . isBindingPattern ( declaration . name ) ) { // This works whether the declaration is a var, let, or const. // It will use rhsIterationValue _a[_i] as the initializer. emitDestructuring ( declaration , /*isAssignmentExpressionStatement*/ false , rhsIterationValue ) ; } else { // The following call does not include the initializer, so we have // to emit it separately. emitNodeWithCommentsAndWithoutSourcemap ( declaration ) ; write ( \" = \" ) ; emitNodeWithoutSourceMap ( rhsIterationValue ) ; } } else { // It's an empty declaration list. This can only happen in an error case, if the user wrote //     for (let of []) {} emitNodeWithoutSourceMap ( createTempVariable ( 0 /* Auto */ ) ) ; write ( \" = \" ) ; emitNodeWithoutSourceMap ( rhsIterationValue ) ; } } else { // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. var assignmentExpression = createBinaryExpression ( node . initializer , 56 /* EqualsToken */ , rhsIterationValue , /*startsOnNewLine*/ false ) ; if ( node . initializer . kind === 164 /* ArrayLiteralExpression */ || node . initializer . kind === 165 /* ObjectLiteralExpression */ ) { // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash. emitDestructuring ( assignmentExpression , /*isAssignmentExpressionStatement*/ true , /*value*/ undefined ) ; } else { emitNodeWithCommentsAndWithoutSourcemap ( assignmentExpression ) ; } } emitEnd ( node . initializer ) ; write ( \";\" ) ; if ( node . statement . kind === 192 /* Block */ ) { emitLines ( node . statement . statements ) ; } else { writeLine ( ) ; emit ( node . statement ) ; } writeLine ( ) ; decreaseIndent ( ) ; write ( \"}\" ) ; } function emitBreakOrContinueStatement ( node ) { emitToken ( node . kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */ , node . pos ) ; emitOptional ( \" \" , node . label ) ; write ( \";\" ) ; } function emitReturnStatement ( node ) { emitToken ( 94 /* ReturnKeyword */ , node . pos ) ; emitOptional ( \" \" , node . expression ) ; write ( \";\" ) ; } function emitWithStatement ( node ) { write ( \"with (\" ) ; emit ( node . expression ) ; write ( \")\" ) ; emitEmbeddedStatement ( node . statement ) ; } function emitSwitchStatement ( node ) { var endPos = emitToken ( 96 /* SwitchKeyword */ , node . pos ) ; write ( \" \" ) ; emitToken ( 17 /* OpenParenToken */ , endPos ) ; emit ( node . expression ) ; endPos = emitToken ( 18 /* CloseParenToken */ , node . expression . end ) ; write ( \" \" ) ; emitCaseBlock ( node . caseBlock , endPos ) ; } function emitCaseBlock ( node , startPos ) { emitToken ( 15 /* OpenBraceToken */ , startPos ) ; increaseIndent ( ) ; emitLines ( node . clauses ) ; decreaseIndent ( ) ; writeLine ( ) ; emitToken ( 16 /* CloseBraceToken */ , node . clauses . end ) ; } function nodeStartPositionsAreOnSameLine ( node1 , node2 ) { return ts . getLineOfLocalPosition ( currentSourceFile , ts . skipTrivia ( currentSourceFile . text , node1 . pos ) ) === ts . getLineOfLocalPosition ( currentSourceFile , ts . skipTrivia ( currentSourceFile . text , node2 . pos ) ) ; } function nodeEndPositionsAreOnSameLine ( node1 , node2 ) { return ts . getLineOfLocalPosition ( currentSourceFile , node1 . end ) === ts . getLineOfLocalPosition ( currentSourceFile , node2 . end ) ; } function nodeEndIsOnSameLineAsNodeStart ( node1 , node2 ) { return ts . getLineOfLocalPosition ( currentSourceFile , node1 . end ) === ts . getLineOfLocalPosition ( currentSourceFile , ts . skipTrivia ( currentSourceFile . text , node2 . pos ) ) ; } function emitCaseOrDefaultClause ( node ) { if ( node . kind === 241 /* CaseClause */ ) { write ( \"case \" ) ; emit ( node . expression ) ; write ( \":\" ) ; } else { write ( \"default:\" ) ; } if ( node . statements . length === 1 && nodeStartPositionsAreOnSameLine ( node , node . statements [ 0 ] ) ) { write ( \" \" ) ; emit ( node . statements [ 0 ] ) ; } else { increaseIndent ( ) ; emitLines ( node . statements ) ; decreaseIndent ( ) ; } } function emitThrowStatement ( node ) { write ( \"throw \" ) ; emit ( node . expression ) ; write ( \";\" ) ; } function emitTryStatement ( node ) { write ( \"try \" ) ; emit ( node . tryBlock ) ; emit ( node . catchClause ) ; if ( node . finallyBlock ) { writeLine ( ) ; write ( \"finally \" ) ; emit ( node . finallyBlock ) ; } } function emitCatchClause ( node ) { writeLine ( ) ; var endPos = emitToken ( 72 /* CatchKeyword */ , node . pos ) ; write ( \" \" ) ; emitToken ( 17 /* OpenParenToken */ , endPos ) ; emit ( node . variableDeclaration ) ; emitToken ( 18 /* CloseParenToken */ , node . variableDeclaration ? node . variableDeclaration . end : endPos ) ; write ( \" \" ) ; emitBlock ( node . block ) ; } function emitDebuggerStatement ( node ) { emitToken ( 76 /* DebuggerKeyword */ , node . pos ) ; write ( \";\" ) ; } function emitLabelledStatement ( node ) { emit ( node . label ) ; write ( \": \" ) ; emit ( node . statement ) ; } function getContainingModule ( node ) { do { node = node . parent ; } while ( node && node . kind !== 218 /* ModuleDeclaration */ ) ; return node ; } function emitContainingModuleName ( node ) { var container = getContainingModule ( node ) ; write ( container ? getGeneratedNameForNode ( container ) : \"exports\" ) ; } function emitModuleMemberName ( node ) { emitStart ( node . name ) ; if ( ts . getCombinedNodeFlags ( node ) & 1 /* Export */ ) { var container = getContainingModule ( node ) ; if ( container ) { write ( getGeneratedNameForNode ( container ) ) ; write ( \".\" ) ; } else if ( modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */ ) { write ( \"exports.\" ) ; } } emitNodeWithCommentsAndWithoutSourcemap ( node . name ) ; emitEnd ( node . name ) ; } function createVoidZero ( ) { var zero = ts . createSynthesizedNode ( 8 /* NumericLiteral */ ) ; zero . text = \"0\" ; var result = ts . createSynthesizedNode ( 177 /* VoidExpression */ ) ; result . expression = zero ; return result ; } function emitEs6ExportDefaultCompat ( node ) { if ( node . parent . kind === 248 /* SourceFile */ ) { ts . Debug . assert ( ! ! ( node . flags & 1024 /* Default */ ) || node . kind === 227 /* ExportAssignment */ ) ; // only allow export default at a source file level if ( modulekind === 1 /* CommonJS */ || modulekind === 2 /* AMD */ || modulekind === 3 /* UMD */ ) { if ( ! currentSourceFile . symbol . exports [ \"___esModule\" ] ) { if ( languageVersion === 1 /* ES5 */ ) { // default value of configurable, enumerable, writable are `false`. write ( \"Object.defineProperty(exports, \\\"__esModule\\\", { value: true });\" ) ; writeLine ( ) ; } else if ( languageVersion === 0 /* ES3 */ ) { write ( \"exports.__esModule = true;\" ) ; writeLine ( ) ; } } } } } function emitExportMemberAssignment ( node ) { if ( node . flags & 1 /* Export */ ) { writeLine ( ) ; emitStart ( node ) ; // emit call to exporter only for top level nodes if ( modulekind === 4 /* System */ && node . parent === currentSourceFile ) { // emit export default <smth> as // export(\"default\", <smth>) write ( exportFunctionForFile + \"(\\\"\" ) ; if ( node . flags & 1024 /* Default */ ) { write ( \"default\" ) ; } else { emitNodeWithCommentsAndWithoutSourcemap ( node . name ) ; } write ( \"\\\", \" ) ; emitDeclarationName ( node ) ; write ( \")\" ) ; } else { if ( node . flags & 1024 /* Default */ ) { emitEs6ExportDefaultCompat ( node ) ; if ( languageVersion === 0 /* ES3 */ ) { write ( \"exports[\\\"default\\\"]\" ) ; } else { write ( \"exports.default\" ) ; } } else { emitModuleMemberName ( node ) ; } write ( \" = \" ) ; emitDeclarationName ( node ) ; } emitEnd ( node ) ; write ( \";\" ) ; } } function emitExportMemberAssignments ( name ) { if ( modulekind === 4 /* System */ ) { return ; } if ( ! exportEquals && exportSpecifiers && ts . hasProperty ( exportSpecifiers , name . text ) ) { for ( var _a = 0 , _b = exportSpecifiers [ name . text ] ; _a < _b . length ; _a ++ ) { var specifier = _b [ _a ] ; writeLine ( ) ; emitStart ( specifier . name ) ; emitContainingModuleName ( specifier ) ; write ( \".\" ) ; emitNodeWithCommentsAndWithoutSourcemap ( specifier . name ) ; emitEnd ( specifier . name ) ; write ( \" = \" ) ; emitExpressionIdentifier ( name ) ; write ( \";\" ) ; } } } function emitExportSpecifierInSystemModule ( specifier ) { ts . Debug . assert ( modulekind === 4 /* System */ ) ; if ( ! resolver . getReferencedValueDeclaration ( specifier . propertyName || specifier . name ) && ! resolver . isValueAliasDeclaration ( specifier ) ) { return ; } writeLine ( ) ; emitStart ( specifier . name ) ; write ( exportFunctionForFile + \"(\\\"\" ) ; emitNodeWithCommentsAndWithoutSourcemap ( specifier . name ) ; write ( \"\\\", \" ) ; emitExpressionIdentifier ( specifier . propertyName || specifier . name ) ; write ( \")\" ) ; emitEnd ( specifier . name ) ; write ( \";\" ) ; } /**\n             * Emit an assignment to a given identifier, 'name', with a given expression, 'value'.\n             * @param name an identifier as a left-hand-side operand of the assignment\n             * @param value an expression as a right-hand-side operand of the assignment\n             * @param shouldEmitCommaBeforeAssignment a boolean indicating whether to prefix an assignment with comma\n             */ function emitAssignment ( name , value , shouldEmitCommaBeforeAssignment ) { if ( shouldEmitCommaBeforeAssignment ) { write ( \", \" ) ; } var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule ( name ) ; if ( exportChanged ) { write ( exportFunctionForFile + \"(\\\"\" ) ; emitNodeWithCommentsAndWithoutSourcemap ( name ) ; write ( \"\\\", \" ) ; } var isVariableDeclarationOrBindingElement = name . parent && ( name . parent . kind === 211 /* VariableDeclaration */ || name . parent . kind === 163 /* BindingElement */ ) ; if ( isVariableDeclarationOrBindingElement ) { emitModuleMemberName ( name . parent ) ; } else { emit ( name ) ; } write ( \" = \" ) ; emit ( value ) ; if ( exportChanged ) { write ( \")\" ) ; } } /**\n             * Create temporary variable, emit an assignment of the variable the given expression\n             * @param expression an expression to assign to the newly created temporary variable\n             * @param canDefineTempVariablesInPlace a boolean indicating whether you can define the temporary variable at an assignment location\n             * @param shouldEmitCommaBeforeAssignment a boolean indicating whether an assignment should prefix with comma\n             */ function emitTempVariableAssignment ( expression , canDefineTempVariablesInPlace , shouldEmitCommaBeforeAssignment ) { var identifier = createTempVariable ( 0 /* Auto */ ) ; if ( ! canDefineTempVariablesInPlace ) { recordTempDeclaration ( identifier ) ; } emitAssignment ( identifier , expression , shouldEmitCommaBeforeAssignment ) ; return identifier ; } function emitDestructuring ( root , isAssignmentExpressionStatement , value ) { var emitCount = 0 ; // An exported declaration is actually emitted as an assignment (to a property on the module object), so // temporary variables in an exported declaration need to have real declarations elsewhere // Also temporary variables should be explicitly allocated for source level declarations when module target is system // because actual variable declarations are hoisted var canDefineTempVariablesInPlace = false ; if ( root . kind === 211 /* VariableDeclaration */ ) { var isExported = ts . getCombinedNodeFlags ( root ) & 1 /* Export */ ; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule ( root ) ; canDefineTempVariablesInPlace = ! isExported && ! isSourceLevelForSystemModuleKind ; } else if ( root . kind === 138 /* Parameter */ ) { canDefineTempVariablesInPlace = true ; } if ( root . kind === 181 /* BinaryExpression */ ) { emitAssignmentExpression ( root ) ; } else { ts . Debug . assert ( ! isAssignmentExpressionStatement ) ; emitBindingElement ( root , value ) ; } /**\n                 * Ensures that there exists a declared identifier whose value holds the given expression.\n                 * This function is useful to ensure that the expression's value can be read from in subsequent expressions.\n                 * Unless 'reuseIdentifierExpressions' is false, 'expr' will be returned if it is just an identifier.\n                 *\n                 * @param expr the expression whose value needs to be bound.\n                 * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;\n                 *                                   false if it is necessary to always emit an identifier.\n                 */ function ensureIdentifier ( expr , reuseIdentifierExpressions ) { if ( expr . kind === 69 /* Identifier */ && reuseIdentifierExpressions ) { return expr ; } var identifier = emitTempVariableAssignment ( expr , canDefineTempVariablesInPlace , emitCount > 0 ) ; emitCount ++ ; return identifier ; } function createDefaultValueCheck ( value , defaultValue ) { // The value expression will be evaluated twice, so for anything but a simple identifier // we need to generate a temporary variable value = ensureIdentifier ( value , /*reuseIdentifierExpressions*/ true ) ; // Return the expression 'value === void 0 ? defaultValue : value' var equals = ts . createSynthesizedNode ( 181 /* BinaryExpression */ ) ; equals . left = value ; equals . operatorToken = ts . createSynthesizedNode ( 32 /* EqualsEqualsEqualsToken */ ) ; equals . right = createVoidZero ( ) ; return createConditionalExpression ( equals , defaultValue , value ) ; } function createConditionalExpression ( condition , whenTrue , whenFalse ) { var cond = ts . createSynthesizedNode ( 182 /* ConditionalExpression */ ) ; cond . condition = condition ; cond . questionToken = ts . createSynthesizedNode ( 53 /* QuestionToken */ ) ; cond . whenTrue = whenTrue ; cond . colonToken = ts . createSynthesizedNode ( 54 /* ColonToken */ ) ; cond . whenFalse = whenFalse ; return cond ; } function createNumericLiteral ( value ) { var node = ts . createSynthesizedNode ( 8 /* NumericLiteral */ ) ; node . text = \"\" + value ; return node ; } function createPropertyAccessForDestructuringProperty ( object , propName ) { // We create a synthetic copy of the identifier in order to avoid the rewriting that might // otherwise occur when the identifier is emitted. var syntheticName = ts . createSynthesizedNode ( propName . kind ) ; syntheticName . text = propName . text ; if ( syntheticName . kind !== 69 /* Identifier */ ) { return createElementAccessExpression ( object , syntheticName ) ; } return createPropertyAccessExpression ( object , syntheticName ) ; } function createSliceCall ( value , sliceIndex ) { var call = ts . createSynthesizedNode ( 168 /* CallExpression */ ) ; var sliceIdentifier = ts . createSynthesizedNode ( 69 /* Identifier */ ) ; sliceIdentifier . text = \"slice\" ; call . expression = createPropertyAccessExpression ( value , sliceIdentifier ) ; call . arguments = ts . createSynthesizedNodeArray ( ) ; call . arguments [ 0 ] = createNumericLiteral ( sliceIndex ) ; return call ; } function emitObjectLiteralAssignment ( target , value ) { var properties = target . properties ; if ( properties . length !== 1 ) { // For anything but a single element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. value = ensureIdentifier ( value , /*reuseIdentifierExpressions*/ true ) ; } for ( var _a = 0 ; _a < properties . length ; _a ++ ) { var p = properties [ _a ] ; if ( p . kind === 245 /* PropertyAssignment */ || p . kind === 246 /* ShorthandPropertyAssignment */ ) { var propName = p . name ; var target_1 = p . kind === 246 /* ShorthandPropertyAssignment */ ? p : p . initializer || propName ; emitDestructuringAssignment ( target_1 , createPropertyAccessForDestructuringProperty ( value , propName ) ) ; } } } function emitArrayLiteralAssignment ( target , value ) { var elements = target . elements ; if ( elements . length !== 1 ) { // For anything but a single element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. value = ensureIdentifier ( value , /*reuseIdentifierExpressions*/ true ) ; } for ( var i = 0 ; i < elements . length ; i ++ ) { var e = elements [ i ] ; if ( e . kind !== 187 /* OmittedExpression */ ) { if ( e . kind !== 185 /* SpreadElementExpression */ ) { emitDestructuringAssignment ( e , createElementAccessExpression ( value , createNumericLiteral ( i ) ) ) ; } else if ( i === elements . length - 1 ) { emitDestructuringAssignment ( e . expression , createSliceCall ( value , i ) ) ; } } } } function emitDestructuringAssignment ( target , value ) { if ( target . kind === 246 /* ShorthandPropertyAssignment */ ) { if ( target . objectAssignmentInitializer ) { value = createDefaultValueCheck ( value , target . objectAssignmentInitializer ) ; } target = target . name ; } else if ( target . kind === 181 /* BinaryExpression */ && target . operatorToken . kind === 56 /* EqualsToken */ ) { value = createDefaultValueCheck ( value , target . right ) ; target = target . left ; } if ( target . kind === 165 /* ObjectLiteralExpression */ ) { emitObjectLiteralAssignment ( target , value ) ; } else if ( target . kind === 164 /* ArrayLiteralExpression */ ) { emitArrayLiteralAssignment ( target , value ) ; } else { emitAssignment ( target , value , /*shouldEmitCommaBeforeAssignment*/ emitCount > 0 ) ; emitCount ++ ; } } function emitAssignmentExpression ( root ) { var target = root . left ; var value = root . right ; if ( ts . isEmptyObjectLiteralOrArrayLiteral ( target ) ) { emit ( value ) ; } else if ( isAssignmentExpressionStatement ) { emitDestructuringAssignment ( target , value ) ; } else { if ( root . parent . kind !== 172 /* ParenthesizedExpression */ ) { write ( \"(\" ) ; } value = ensureIdentifier ( value , /*reuseIdentifierExpressions*/ true ) ; emitDestructuringAssignment ( target , value ) ; write ( \", \" ) ; emit ( value ) ; if ( root . parent . kind !== 172 /* ParenthesizedExpression */ ) { write ( \")\" ) ; } } } function emitBindingElement ( target , value ) { if ( target . initializer ) { // Combine value and initializer value = value ? createDefaultValueCheck ( value , target . initializer ) : target . initializer ; } else if ( ! value ) { // Use 'void 0' in absence of value and initializer value = createVoidZero ( ) ; } if ( ts . isBindingPattern ( target . name ) ) { var pattern = target . name ; var elements = pattern . elements ; var numElements = elements . length ; if ( numElements !== 1 ) { // For anything other than a single-element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. Additionally, if we have zero elements // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, // so in that case, we'll intentionally create that temporary. value = ensureIdentifier ( value , /*reuseIdentifierExpressions*/ numElements !== 0 ) ; } for ( var i = 0 ; i < numElements ; i ++ ) { var element = elements [ i ] ; if ( pattern . kind === 161 /* ObjectBindingPattern */ ) { // Rewrite element to a declaration with an initializer that fetches property var propName = element . propertyName || element . name ; emitBindingElement ( element , createPropertyAccessForDestructuringProperty ( value , propName ) ) ; } else if ( element . kind !== 187 /* OmittedExpression */ ) { if ( ! element . dotDotDotToken ) { // Rewrite element to a declaration that accesses array element at index i emitBindingElement ( element , createElementAccessExpression ( value , createNumericLiteral ( i ) ) ) ; } else if ( i === numElements - 1 ) { emitBindingElement ( element , createSliceCall ( value , i ) ) ; } } } } else { emitAssignment ( target . name , value , /*shouldEmitCommaBeforeAssignment*/ emitCount > 0 ) ; emitCount ++ ; } } } function emitVariableDeclaration ( node ) { if ( ts . isBindingPattern ( node . name ) ) { if ( languageVersion < 2 /* ES6 */ ) { emitDestructuring ( node , /*isAssignmentExpressionStatement*/ false ) ; } else { emit ( node . name ) ; emitOptional ( \" = \" , node . initializer ) ; } } else { var initializer = node . initializer ; if ( ! initializer && languageVersion < 2 /* ES6 */ ) { // downlevel emit for non-initialized let bindings defined in loops // for (...) {  let x; } // should be // for (...) { var <some-uniqie-name> = void 0; } // this is necessary to preserve ES6 semantic in scenarios like // for (...) { let x; console.log(x); x = 1 } // assignment on one iteration should not affect other iterations var isUninitializedLet = ( resolver . getNodeCheckFlags ( node ) & 16384 /* BlockScopedBindingInLoop */ ) && ( getCombinedFlagsForIdentifier ( node . name ) & 16384 /* Let */ ) ; // NOTE: default initialization should not be added to let bindings in for-in\\for-of statements if ( isUninitializedLet && node . parent . parent . kind !== 200 /* ForInStatement */ && node . parent . parent . kind !== 201 /* ForOfStatement */ ) { initializer = createVoidZero ( ) ; } } var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule ( node . name ) ; if ( exportChanged ) { write ( exportFunctionForFile + \"(\\\"\" ) ; emitNodeWithCommentsAndWithoutSourcemap ( node . name ) ; write ( \"\\\", \" ) ; } emitModuleMemberName ( node ) ; emitOptional ( \" = \" , initializer ) ; if ( exportChanged ) { write ( \")\" ) ; } } } function emitExportVariableAssignments ( node ) { if ( node . kind === 187 /* OmittedExpression */ ) { return ; } var name = node . name ; if ( name . kind === 69 /* Identifier */ ) { emitExportMemberAssignments ( name ) ; } else if ( ts . isBindingPattern ( name ) ) { ts . forEach ( name . elements , emitExportVariableAssignments ) ; } } function getCombinedFlagsForIdentifier ( node ) { if ( ! node . parent || ( node . parent . kind !== 211 /* VariableDeclaration */ && node . parent . kind !== 163 /* BindingElement */ ) ) { return 0 ; } return ts . getCombinedNodeFlags ( node . parent ) ; } function isES6ExportedDeclaration ( node ) { return ! ! ( node . flags & 1 /* Export */ ) && modulekind === 5 /* ES6 */ && node . parent . kind === 248 /* SourceFile */ ; } function emitVariableStatement ( node ) { var startIsEmitted = false ; if ( node . flags & 1 /* Export */ ) { if ( isES6ExportedDeclaration ( node ) ) { // Exported ES6 module member write ( \"export \" ) ; startIsEmitted = tryEmitStartOfVariableDeclarationList ( node . declarationList ) ; } } else { startIsEmitted = tryEmitStartOfVariableDeclarationList ( node . declarationList ) ; } if ( startIsEmitted ) { emitCommaList ( node . declarationList . declarations ) ; write ( \";\" ) ; } else { var atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries ( node . declarationList ) ; if ( atLeastOneItem ) { write ( \";\" ) ; } } if ( modulekind !== 5 /* ES6 */ && node . parent === currentSourceFile ) { ts . forEach ( node . declarationList . declarations , emitExportVariableAssignments ) ; } } function shouldEmitLeadingAndTrailingCommentsForVariableStatement ( node ) { // If we're not exporting the variables, there's nothing special here. // Always emit comments for these nodes. if ( ! ( node . flags & 1 /* Export */ ) ) { return true ; } // If we are exporting, but it's a top-level ES6 module exports, // we'll emit the declaration list verbatim, so emit comments too. if ( isES6ExportedDeclaration ( node ) ) { return true ; } // Otherwise, only emit if we have at least one initializer present. for ( var _a = 0 , _b = node . declarationList . declarations ; _a < _b . length ; _a ++ ) { var declaration = _b [ _a ] ; if ( declaration . initializer ) { return true ; } } return false ; } function emitParameter ( node ) { if ( languageVersion < 2 /* ES6 */ ) { if ( ts . isBindingPattern ( node . name ) ) { var name_24 = createTempVariable ( 0 /* Auto */ ) ; if ( ! tempParameters ) { tempParameters = [ ] ; } tempParameters . push ( name_24 ) ; emit ( name_24 ) ; } else { emit ( node . name ) ; } } else { if ( node . dotDotDotToken ) { write ( \"...\" ) ; } emit ( node . name ) ; emitOptional ( \" = \" , node . initializer ) ; } } function emitDefaultValueAssignments ( node ) { if ( languageVersion < 2 /* ES6 */ ) { var tempIndex = 0 ; ts . forEach ( node . parameters , function ( parameter ) { // A rest parameter cannot have a binding pattern or an initializer, // so let's just ignore it. if ( parameter . dotDotDotToken ) { return ; } var paramName = parameter . name , initializer = parameter . initializer ; if ( ts . isBindingPattern ( paramName ) ) { // In cases where a binding pattern is simply '[]' or '{}', // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. var hasBindingElements = paramName . elements . length > 0 ; if ( hasBindingElements || initializer ) { writeLine ( ) ; write ( \"var \" ) ; if ( hasBindingElements ) { emitDestructuring ( parameter , /*isAssignmentExpressionStatement*/ false , tempParameters [ tempIndex ] ) ; } else { emit ( tempParameters [ tempIndex ] ) ; write ( \" = \" ) ; emit ( initializer ) ; } write ( \";\" ) ; tempIndex ++ ; } } else if ( initializer ) { writeLine ( ) ; emitStart ( parameter ) ; write ( \"if (\" ) ; emitNodeWithoutSourceMap ( paramName ) ; write ( \" === void 0)\" ) ; emitEnd ( parameter ) ; write ( \" { \" ) ; emitStart ( parameter ) ; emitNodeWithCommentsAndWithoutSourcemap ( paramName ) ; write ( \" = \" ) ; emitNodeWithCommentsAndWithoutSourcemap ( initializer ) ; emitEnd ( parameter ) ; write ( \"; }\" ) ; } } ) ; } } function emitRestParameter ( node ) { if ( languageVersion < 2 /* ES6 */ && ts . hasRestParameter ( node ) ) { var restIndex = node . parameters . length - 1 ; var restParam = node . parameters [ restIndex ] ; // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. if ( ts . isBindingPattern ( restParam . name ) ) { return ; } var tempName = createTempVariable ( 268435456 /* _i */ ) . text ; writeLine ( ) ; emitLeadingComments ( restParam ) ; emitStart ( restParam ) ; write ( \"var \" ) ; emitNodeWithCommentsAndWithoutSourcemap ( restParam . name ) ; write ( \" = [];\" ) ; emitEnd ( restParam ) ; emitTrailingComments ( restParam ) ; writeLine ( ) ; write ( \"for (\" ) ; emitStart ( restParam ) ; write ( \"var \" + tempName + \" = \" + restIndex + \";\" ) ; emitEnd ( restParam ) ; write ( \" \" ) ; emitStart ( restParam ) ; write ( tempName + \" < arguments.length;\" ) ; emitEnd ( restParam ) ; write ( \" \" ) ; emitStart ( restParam ) ; write ( tempName + \"++\" ) ; emitEnd ( restParam ) ; write ( \") {\" ) ; increaseIndent ( ) ; writeLine ( ) ; emitStart ( restParam ) ; emitNodeWithCommentsAndWithoutSourcemap ( restParam . name ) ; write ( \"[\" + tempName + \" - \" + restIndex + \"] = arguments[\" + tempName + \"];\" ) ; emitEnd ( restParam ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"}\" ) ; } } function emitAccessor ( node ) { write ( node . kind === 145 /* GetAccessor */ ? \"get \" : \"set \" ) ; emit ( node . name ) ; emitSignatureAndBody ( node ) ; } function shouldEmitAsArrowFunction ( node ) { return node . kind === 174 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */ ; } function emitDeclarationName ( node ) { if ( node . name ) { emitNodeWithCommentsAndWithoutSourcemap ( node . name ) ; } else { write ( getGeneratedNameForNode ( node ) ) ; } } function shouldEmitFunctionName ( node ) { if ( node . kind === 173 /* FunctionExpression */ ) { // Emit name if one is present return ! ! node . name ; } if ( node . kind === 213 /* FunctionDeclaration */ ) { // Emit name if one is present, or emit generated name in down-level case (for export default case) return ! ! node . name || languageVersion < 2 /* ES6 */ ; } } function emitFunctionDeclaration ( node ) { if ( ts . nodeIsMissing ( node . body ) ) { return emitCommentsOnNotEmittedNode ( node ) ; } // TODO (yuisu) : we should not have special cases to condition emitting comments // but have one place to fix check for these conditions. if ( node . kind !== 143 /* MethodDeclaration */ && node . kind !== 142 /* MethodSignature */ && node . parent && node . parent . kind !== 245 /* PropertyAssignment */ && node . parent . kind !== 168 /* CallExpression */ ) { // 1. Methods will emit the comments as part of emitting method declaration // 2. If the function is a property of object literal, emitting leading-comments // is done by emitNodeWithoutSourceMap which then call this function. // In particular, we would like to avoid emit comments twice in following case: //      For example: //          var obj = { //              id: //                  /*comment*/ () => void //          } // 3. If the function is an argument in call expression, emitting of comments will be // taken care of in emit list of arguments inside of emitCallexpression emitLeadingComments ( node ) ; } emitStart ( node ) ; // For targeting below es6, emit functions-like declaration including arrow function using function keyword. // When targeting ES6, emit arrow function natively in ES6 by omitting function keyword and using fat arrow instead if ( ! shouldEmitAsArrowFunction ( node ) ) { if ( isES6ExportedDeclaration ( node ) ) { write ( \"export \" ) ; if ( node . flags & 1024 /* Default */ ) { write ( \"default \" ) ; } } write ( \"function\" ) ; if ( languageVersion >= 2 /* ES6 */ && node . asteriskToken ) { write ( \"*\" ) ; } write ( \" \" ) ; } if ( shouldEmitFunctionName ( node ) ) { emitDeclarationName ( node ) ; } emitSignatureAndBody ( node ) ; if ( modulekind !== 5 /* ES6 */ && node . kind === 213 /* FunctionDeclaration */ && node . parent === currentSourceFile && node . name ) { emitExportMemberAssignments ( node . name ) ; } emitEnd ( node ) ; if ( node . kind !== 143 /* MethodDeclaration */ && node . kind !== 142 /* MethodSignature */ ) { emitTrailingComments ( node ) ; } } function emitCaptureThisForNodeIfNecessary ( node ) { if ( resolver . getNodeCheckFlags ( node ) & 4 /* CaptureThis */ ) { writeLine ( ) ; emitStart ( node ) ; write ( \"var _this = this;\" ) ; emitEnd ( node ) ; } } function emitSignatureParameters ( node ) { increaseIndent ( ) ; write ( \"(\" ) ; if ( node ) { var parameters = node . parameters ; var omitCount = languageVersion < 2 /* ES6 */ && ts . hasRestParameter ( node ) ? 1 : 0 ; emitList ( parameters , 0 , parameters . length - omitCount , /*multiLine*/ false , /*trailingComma*/ false ) ; } write ( \")\" ) ; decreaseIndent ( ) ; } function emitSignatureParametersForArrow ( node ) { // Check whether the parameter list needs parentheses and preserve no-parenthesis if ( node . parameters . length === 1 && node . pos === node . parameters [ 0 ] . pos ) { emit ( node . parameters [ 0 ] ) ; return ; } emitSignatureParameters ( node ) ; } function emitAsyncFunctionBodyForES6 ( node ) { var promiseConstructor = ts . getEntityNameFromTypeNode ( node . type ) ; var isArrowFunction = node . kind === 174 /* ArrowFunction */ ; var hasLexicalArguments = ( resolver . getNodeCheckFlags ( node ) & 4096 /* CaptureArguments */ ) !== 0 ; var args ; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current // `this` and `arguments` objects to `__awaiter`. The generator function // passed to `__awaiter` is executed inside of the callback to the // promise constructor. // // The emit for an async arrow without a lexical `arguments` binding might be: // //  // input //  let a = async (b) => { await b; } // //  // output //  let a = (b) => __awaiter(this, void 0, void 0, function* () { //      yield b; //  }); // // The emit for an async arrow with a lexical `arguments` binding might be: // //  // input //  let a = async (b) => { await arguments[0]; } // //  // output //  let a = (b) => __awaiter(this, arguments, void 0, function* (arguments) { //      yield arguments[0]; //  }); // // The emit for an async function expression without a lexical `arguments` binding // might be: // //  // input //  let a = async function (b) { //      await b; //  } // //  // output //  let a = function (b) { //      return __awaiter(this, void 0, void 0, function* () { //          yield b; //      }); //  } // // The emit for an async function expression with a lexical `arguments` binding // might be: // //  // input //  let a = async function (b) { //      await arguments[0]; //  } // //  // output //  let a = function (b) { //      return __awaiter(this, arguments, void 0, function* (_arguments) { //          yield _arguments[0]; //      }); //  } // // The emit for an async function expression with a lexical `arguments` binding // and a return type annotation might be: // //  // input //  let a = async function (b): MyPromise<any> { //      await arguments[0]; //  } // //  // output //  let a = function (b) { //      return __awaiter(this, arguments, MyPromise, function* (_arguments) { //          yield _arguments[0]; //      }); //  } // // If this is not an async arrow, emit the opening brace of the function body // and the start of the return statement. if ( ! isArrowFunction ) { write ( \" {\" ) ; increaseIndent ( ) ; writeLine ( ) ; write ( \"return\" ) ; } write ( \" __awaiter(this\" ) ; if ( hasLexicalArguments ) { write ( \", arguments\" ) ; } else { write ( \", void 0\" ) ; } if ( promiseConstructor ) { write ( \", \" ) ; emitNodeWithoutSourceMap ( promiseConstructor ) ; } else { write ( \", Promise\" ) ; } // Emit the call to __awaiter. if ( hasLexicalArguments ) { write ( \", function* (_arguments)\" ) ; } else { write ( \", function* ()\" ) ; } // Emit the signature and body for the inner generator function. emitFunctionBody ( node ) ; write ( \")\" ) ; // If this is not an async arrow, emit the closing brace of the outer function body. if ( ! isArrowFunction ) { write ( \";\" ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"}\" ) ; } } function emitFunctionBody ( node ) { if ( ! node . body ) { // There can be no body when there are parse errors.  Just emit an empty block // in that case. write ( \" { }\" ) ; } else { if ( node . body . kind === 192 /* Block */ ) { emitBlockFunctionBody ( node , node . body ) ; } else { emitExpressionFunctionBody ( node , node . body ) ; } } } function emitSignatureAndBody ( node ) { var saveTempFlags = tempFlags ; var saveTempVariables = tempVariables ; var saveTempParameters = tempParameters ; tempFlags = 0 ; tempVariables = undefined ; tempParameters = undefined ; // When targeting ES6, emit arrow function natively in ES6 if ( shouldEmitAsArrowFunction ( node ) ) { emitSignatureParametersForArrow ( node ) ; write ( \" =>\" ) ; } else { emitSignatureParameters ( node ) ; } var isAsync = ts . isAsyncFunctionLike ( node ) ; if ( isAsync && languageVersion === 2 /* ES6 */ ) { emitAsyncFunctionBodyForES6 ( node ) ; } else { emitFunctionBody ( node ) ; } if ( ! isES6ExportedDeclaration ( node ) ) { emitExportMemberAssignment ( node ) ; } tempFlags = saveTempFlags ; tempVariables = saveTempVariables ; tempParameters = saveTempParameters ; } // Returns true if any preamble code was emitted. function emitFunctionBodyPreamble ( node ) { emitCaptureThisForNodeIfNecessary ( node ) ; emitDefaultValueAssignments ( node ) ; emitRestParameter ( node ) ; } function emitExpressionFunctionBody ( node , body ) { if ( languageVersion < 2 /* ES6 */ || node . flags & 512 /* Async */ ) { emitDownLevelExpressionFunctionBody ( node , body ) ; return ; } // For es6 and higher we can emit the expression as is.  However, in the case // where the expression might end up looking like a block when emitted, we'll // also wrap it in parentheses first.  For example if you have: a => <foo>{} // then we need to generate: a => ({}) write ( \" \" ) ; // Unwrap all type assertions. var current = body ; while ( current . kind === 171 /* TypeAssertionExpression */ ) { current = current . expression ; } emitParenthesizedIf ( body , current . kind === 165 /* ObjectLiteralExpression */ ) ; } function emitDownLevelExpressionFunctionBody ( node , body ) { write ( \" {\" ) ; scopeEmitStart ( node ) ; increaseIndent ( ) ; var outPos = writer . getTextPos ( ) ; emitDetachedComments ( node . body ) ; emitFunctionBodyPreamble ( node ) ; var preambleEmitted = writer . getTextPos ( ) !== outPos ; decreaseIndent ( ) ; // If we didn't have to emit any preamble code, then attempt to keep the arrow // function on one line. if ( ! preambleEmitted && nodeStartPositionsAreOnSameLine ( node , body ) ) { write ( \" \" ) ; emitStart ( body ) ; write ( \"return \" ) ; emit ( body ) ; emitEnd ( body ) ; write ( \";\" ) ; emitTempDeclarations ( /*newLine*/ false ) ; write ( \" \" ) ; } else { increaseIndent ( ) ; writeLine ( ) ; emitLeadingComments ( node . body ) ; write ( \"return \" ) ; emit ( body ) ; write ( \";\" ) ; emitTrailingComments ( node . body ) ; emitTempDeclarations ( /*newLine*/ true ) ; decreaseIndent ( ) ; writeLine ( ) ; } emitStart ( node . body ) ; write ( \"}\" ) ; emitEnd ( node . body ) ; scopeEmitEnd ( ) ; } function emitBlockFunctionBody ( node , body ) { write ( \" {\" ) ; scopeEmitStart ( node ) ; var initialTextPos = writer . getTextPos ( ) ; increaseIndent ( ) ; emitDetachedComments ( body . statements ) ; // Emit all the directive prologues (like \"use strict\").  These have to come before // any other preamble code we write (like parameter initializers). var startIndex = emitDirectivePrologues ( body . statements , /*startWithNewLine*/ true ) ; emitFunctionBodyPreamble ( node ) ; decreaseIndent ( ) ; var preambleEmitted = writer . getTextPos ( ) !== initialTextPos ; if ( ! preambleEmitted && nodeEndIsOnSameLineAsNodeStart ( body , body ) ) { for ( var _a = 0 , _b = body . statements ; _a < _b . length ; _a ++ ) { var statement = _b [ _a ] ; write ( \" \" ) ; emit ( statement ) ; } emitTempDeclarations ( /*newLine*/ false ) ; write ( \" \" ) ; emitLeadingCommentsOfPosition ( body . statements . end ) ; } else { increaseIndent ( ) ; emitLinesStartingAt ( body . statements , startIndex ) ; emitTempDeclarations ( /*newLine*/ true ) ; writeLine ( ) ; emitLeadingCommentsOfPosition ( body . statements . end ) ; decreaseIndent ( ) ; } emitToken ( 16 /* CloseBraceToken */ , body . statements . end ) ; scopeEmitEnd ( ) ; } function findInitialSuperCall ( ctor ) { if ( ctor . body ) { var statement = ctor . body . statements [ 0 ] ; if ( statement && statement . kind === 195 /* ExpressionStatement */ ) { var expr = statement . expression ; if ( expr && expr . kind === 168 /* CallExpression */ ) { var func = expr . expression ; if ( func && func . kind === 95 /* SuperKeyword */ ) { return statement ; } } } } } function emitParameterPropertyAssignments ( node ) { ts . forEach ( node . parameters , function ( param ) { if ( param . flags & 112 /* AccessibilityModifier */ ) { writeLine ( ) ; emitStart ( param ) ; emitStart ( param . name ) ; write ( \"this.\" ) ; emitNodeWithoutSourceMap ( param . name ) ; emitEnd ( param . name ) ; write ( \" = \" ) ; emit ( param . name ) ; write ( \";\" ) ; emitEnd ( param ) ; } } ) ; } function emitMemberAccessForPropertyName ( memberName ) { // This does not emit source map because it is emitted by caller as caller // is aware how the property name changes to the property access // eg. public x = 10; becomes this.x and static x = 10 becomes className.x if ( memberName . kind === 9 /* StringLiteral */ || memberName . kind === 8 /* NumericLiteral */ ) { write ( \"[\" ) ; emitNodeWithCommentsAndWithoutSourcemap ( memberName ) ; write ( \"]\" ) ; } else if ( memberName . kind === 136 /* ComputedPropertyName */ ) { emitComputedPropertyName ( memberName ) ; } else { write ( \".\" ) ; emitNodeWithCommentsAndWithoutSourcemap ( memberName ) ; } } function getInitializedProperties ( node , isStatic ) { var properties = [ ] ; for ( var _a = 0 , _b = node . members ; _a < _b . length ; _a ++ ) { var member = _b [ _a ] ; if ( member . kind === 141 /* PropertyDeclaration */ && isStatic === ( ( member . flags & 128 /* Static */ ) !== 0 ) && member . initializer ) { properties . push ( member ) ; } } return properties ; } function emitPropertyDeclarations ( node , properties ) { for ( var _a = 0 ; _a < properties . length ; _a ++ ) { var property = properties [ _a ] ; emitPropertyDeclaration ( node , property ) ; } } function emitPropertyDeclaration ( node , property , receiver , isExpression ) { writeLine ( ) ; emitLeadingComments ( property ) ; emitStart ( property ) ; emitStart ( property . name ) ; if ( receiver ) { emit ( receiver ) ; } else { if ( property . flags & 128 /* Static */ ) { emitDeclarationName ( node ) ; } else { write ( \"this\" ) ; } } emitMemberAccessForPropertyName ( property . name ) ; emitEnd ( property . name ) ; write ( \" = \" ) ; emit ( property . initializer ) ; if ( ! isExpression ) { write ( \";\" ) ; } emitEnd ( property ) ; emitTrailingComments ( property ) ; } function emitMemberFunctionsForES5AndLower ( node ) { ts . forEach ( node . members , function ( member ) { if ( member . kind === 191 /* SemicolonClassElement */ ) { writeLine ( ) ; write ( \";\" ) ; } else if ( member . kind === 143 /* MethodDeclaration */ || node . kind === 142 /* MethodSignature */ ) { if ( ! member . body ) { return emitCommentsOnNotEmittedNode ( member ) ; } writeLine ( ) ; emitLeadingComments ( member ) ; emitStart ( member ) ; emitStart ( member . name ) ; emitClassMemberPrefix ( node , member ) ; emitMemberAccessForPropertyName ( member . name ) ; emitEnd ( member . name ) ; write ( \" = \" ) ; emitFunctionDeclaration ( member ) ; emitEnd ( member ) ; write ( \";\" ) ; emitTrailingComments ( member ) ; } else if ( member . kind === 145 /* GetAccessor */ || member . kind === 146 /* SetAccessor */ ) { var accessors = ts . getAllAccessorDeclarations ( node . members , member ) ; if ( member === accessors . firstAccessor ) { writeLine ( ) ; emitStart ( member ) ; write ( \"Object.defineProperty(\" ) ; emitStart ( member . name ) ; emitClassMemberPrefix ( node , member ) ; write ( \", \" ) ; emitExpressionForPropertyName ( member . name ) ; emitEnd ( member . name ) ; write ( \", {\" ) ; increaseIndent ( ) ; if ( accessors . getAccessor ) { writeLine ( ) ; emitLeadingComments ( accessors . getAccessor ) ; write ( \"get: \" ) ; emitStart ( accessors . getAccessor ) ; write ( \"function \" ) ; emitSignatureAndBody ( accessors . getAccessor ) ; emitEnd ( accessors . getAccessor ) ; emitTrailingComments ( accessors . getAccessor ) ; write ( \",\" ) ; } if ( accessors . setAccessor ) { writeLine ( ) ; emitLeadingComments ( accessors . setAccessor ) ; write ( \"set: \" ) ; emitStart ( accessors . setAccessor ) ; write ( \"function \" ) ; emitSignatureAndBody ( accessors . setAccessor ) ; emitEnd ( accessors . setAccessor ) ; emitTrailingComments ( accessors . setAccessor ) ; write ( \",\" ) ; } writeLine ( ) ; write ( \"enumerable: true,\" ) ; writeLine ( ) ; write ( \"configurable: true\" ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"});\" ) ; emitEnd ( member ) ; } } } ) ; } function emitMemberFunctionsForES6AndHigher ( node ) { for ( var _a = 0 , _b = node . members ; _a < _b . length ; _a ++ ) { var member = _b [ _a ] ; if ( ( member . kind === 143 /* MethodDeclaration */ || node . kind === 142 /* MethodSignature */ ) && ! member . body ) { emitCommentsOnNotEmittedNode ( member ) ; } else if ( member . kind === 143 /* MethodDeclaration */ || member . kind === 145 /* GetAccessor */ || member . kind === 146 /* SetAccessor */ ) { writeLine ( ) ; emitLeadingComments ( member ) ; emitStart ( member ) ; if ( member . flags & 128 /* Static */ ) { write ( \"static \" ) ; } if ( member . kind === 145 /* GetAccessor */ ) { write ( \"get \" ) ; } else if ( member . kind === 146 /* SetAccessor */ ) { write ( \"set \" ) ; } if ( member . asteriskToken ) { write ( \"*\" ) ; } emit ( member . name ) ; emitSignatureAndBody ( member ) ; emitEnd ( member ) ; emitTrailingComments ( member ) ; } else if ( member . kind === 191 /* SemicolonClassElement */ ) { writeLine ( ) ; write ( \";\" ) ; } } } function emitConstructor ( node , baseTypeElement ) { var saveTempFlags = tempFlags ; var saveTempVariables = tempVariables ; var saveTempParameters = tempParameters ; tempFlags = 0 ; tempVariables = undefined ; tempParameters = undefined ; emitConstructorWorker ( node , baseTypeElement ) ; tempFlags = saveTempFlags ; tempVariables = saveTempVariables ; tempParameters = saveTempParameters ; } function emitConstructorWorker ( node , baseTypeElement ) { // Check if we have property assignment inside class declaration. // If there is property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it var hasInstancePropertyWithInitializer = false ; // Emit the constructor overload pinned comments ts . forEach ( node . members , function ( member ) { if ( member . kind === 144 /* Constructor */ && ! member . body ) { emitCommentsOnNotEmittedNode ( member ) ; } // Check if there is any non-static property assignment if ( member . kind === 141 /* PropertyDeclaration */ && member . initializer && ( member . flags & 128 /* Static */ ) === 0 ) { hasInstancePropertyWithInitializer = true ; } } ) ; var ctor = ts . getFirstConstructorWithBody ( node ) ; // For target ES6 and above, if there is no user-defined constructor and there is no property assignment // do not emit constructor in class declaration. if ( languageVersion >= 2 /* ES6 */ && ! ctor && ! hasInstancePropertyWithInitializer ) { return ; } if ( ctor ) { emitLeadingComments ( ctor ) ; } emitStart ( ctor || node ) ; if ( languageVersion < 2 /* ES6 */ ) { write ( \"function \" ) ; emitDeclarationName ( node ) ; emitSignatureParameters ( ctor ) ; } else { write ( \"constructor\" ) ; if ( ctor ) { emitSignatureParameters ( ctor ) ; } else { // Based on EcmaScript6 section 14.5.14: Runtime Semantics: ClassDefinitionEvaluation. // If constructor is empty, then, //      If ClassHeritageopt is present, then //          Let constructor be the result of parsing the String \"constructor(... args){ super (...args);}\" using the syntactic grammar with the goal symbol MethodDefinition. //      Else, //          Let constructor be the result of parsing the String \"constructor( ){ }\" using the syntactic grammar with the goal symbol MethodDefinition if ( baseTypeElement ) { write ( \"(...args)\" ) ; } else { write ( \"()\" ) ; } } } var startIndex = 0 ; write ( \" {\" ) ; scopeEmitStart ( node , \"constructor\" ) ; increaseIndent ( ) ; if ( ctor ) { // Emit all the directive prologues (like \"use strict\").  These have to come before // any other preamble code we write (like parameter initializers). startIndex = emitDirectivePrologues ( ctor . body . statements , /*startWithNewLine*/ true ) ; emitDetachedComments ( ctor . body . statements ) ; } emitCaptureThisForNodeIfNecessary ( node ) ; var superCall ; if ( ctor ) { emitDefaultValueAssignments ( ctor ) ; emitRestParameter ( ctor ) ; if ( baseTypeElement ) { superCall = findInitialSuperCall ( ctor ) ; if ( superCall ) { writeLine ( ) ; emit ( superCall ) ; } } emitParameterPropertyAssignments ( ctor ) ; } else { if ( baseTypeElement ) { writeLine ( ) ; emitStart ( baseTypeElement ) ; if ( languageVersion < 2 /* ES6 */ ) { write ( \"_super.apply(this, arguments);\" ) ; } else { write ( \"super(...args);\" ) ; } emitEnd ( baseTypeElement ) ; } } emitPropertyDeclarations ( node , getInitializedProperties ( node , /*static:*/ false ) ) ; if ( ctor ) { var statements = ctor . body . statements ; if ( superCall ) { statements = statements . slice ( 1 ) ; } emitLinesStartingAt ( statements , startIndex ) ; } emitTempDeclarations ( /*newLine*/ true ) ; writeLine ( ) ; if ( ctor ) { emitLeadingCommentsOfPosition ( ctor . body . statements . end ) ; } decreaseIndent ( ) ; emitToken ( 16 /* CloseBraceToken */ , ctor ? ctor . body . statements . end : node . members . end ) ; scopeEmitEnd ( ) ; emitEnd ( ctor || node ) ; if ( ctor ) { emitTrailingComments ( ctor ) ; } } function emitClassExpression ( node ) { return emitClassLikeDeclaration ( node ) ; } function emitClassDeclaration ( node ) { return emitClassLikeDeclaration ( node ) ; } function emitClassLikeDeclaration ( node ) { if ( languageVersion < 2 /* ES6 */ ) { emitClassLikeDeclarationBelowES6 ( node ) ; } else { emitClassLikeDeclarationForES6AndHigher ( node ) ; } if ( modulekind !== 5 /* ES6 */ && node . parent === currentSourceFile && node . name ) { emitExportMemberAssignments ( node . name ) ; } } function emitClassLikeDeclarationForES6AndHigher ( node ) { var thisNodeIsDecorated = ts . nodeIsDecorated ( node ) ; if ( node . kind === 214 /* ClassDeclaration */ ) { if ( thisNodeIsDecorated ) { // To preserve the correct runtime semantics when decorators are applied to the class, // the emit needs to follow one of the following rules: // // * For a local class declaration: // //     @dec class C { //     } // //   The emit should be: // //     let C = class { //     }; //     C = __decorate([dec], C); // // * For an exported class declaration: // //     @dec export class C { //     } // //   The emit should be: // //     export let C = class { //     }; //     C = __decorate([dec], C); // // * For a default export of a class declaration with a name: // //     @dec default export class C { //     } // //   The emit should be: // //     let C = class { //     } //     C = __decorate([dec], C); //     export default C; // // * For a default export of a class declaration without a name: // //     @dec default export class { //     } // //   The emit should be: // //     let _default = class { //     } //     _default = __decorate([dec], _default); //     export default _default; // if ( isES6ExportedDeclaration ( node ) && ! ( node . flags & 1024 /* Default */ ) ) { write ( \"export \" ) ; } write ( \"let \" ) ; emitDeclarationName ( node ) ; write ( \" = \" ) ; } else if ( isES6ExportedDeclaration ( node ) ) { write ( \"export \" ) ; if ( node . flags & 1024 /* Default */ ) { write ( \"default \" ) ; } } } // If the class has static properties, and it's a class expression, then we'll need // to specialize the emit a bit.  for a class expression of the form: // //      class C { static a = 1; static b = 2; ... } // // We'll emit: // //      (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp) // // This keeps the expression as an expression, while ensuring that the static parts // of it have been initialized by the time it is used. var staticProperties = getInitializedProperties ( node , /*static:*/ true ) ; var isClassExpressionWithStaticProperties = staticProperties . length > 0 && node . kind === 186 /* ClassExpression */ ; var tempVariable ; if ( isClassExpressionWithStaticProperties ) { tempVariable = createAndRecordTempVariable ( 0 /* Auto */ ) ; write ( \"(\" ) ; increaseIndent ( ) ; emit ( tempVariable ) ; write ( \" = \" ) ; } write ( \"class\" ) ; // emit name if // - node has a name // - this is default export with static initializers if ( ( node . name || ( node . flags & 1024 /* Default */ && staticProperties . length > 0 ) ) && ! thisNodeIsDecorated ) { write ( \" \" ) ; emitDeclarationName ( node ) ; } var baseTypeNode = ts . getClassExtendsHeritageClauseElement ( node ) ; if ( baseTypeNode ) { write ( \" extends \" ) ; emit ( baseTypeNode . expression ) ; } write ( \" {\" ) ; increaseIndent ( ) ; scopeEmitStart ( node ) ; writeLine ( ) ; emitConstructor ( node , baseTypeNode ) ; emitMemberFunctionsForES6AndHigher ( node ) ; decreaseIndent ( ) ; writeLine ( ) ; emitToken ( 16 /* CloseBraceToken */ , node . members . end ) ; scopeEmitEnd ( ) ; // TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now. // For a decorated class, we need to assign its name (if it has one). This is because we emit // the class as a class expression to avoid the double-binding of the identifier: // //   let C = class { //   } //   Object.defineProperty(C, \"name\", { value: \"C\", configurable: true }); // if ( thisNodeIsDecorated ) { write ( \";\" ) ; } // Emit static property assignment. Because classDeclaration is lexically evaluated, // it is safe to emit static property assignment after classDeclaration // From ES6 specification: //      HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using //                                  a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. if ( isClassExpressionWithStaticProperties ) { for ( var _a = 0 ; _a < staticProperties . length ; _a ++ ) { var property = staticProperties [ _a ] ; write ( \",\" ) ; writeLine ( ) ; emitPropertyDeclaration ( node , property , /*receiver:*/ tempVariable , /*isExpression:*/ true ) ; } write ( \",\" ) ; writeLine ( ) ; emit ( tempVariable ) ; decreaseIndent ( ) ; write ( \")\" ) ; } else { writeLine ( ) ; emitPropertyDeclarations ( node , staticProperties ) ; emitDecoratorsOfClass ( node ) ; } // If this is an exported class, but not on the top level (i.e. on an internal // module), export it if ( ! isES6ExportedDeclaration ( node ) && ( node . flags & 1 /* Export */ ) ) { writeLine ( ) ; emitStart ( node ) ; emitModuleMemberName ( node ) ; write ( \" = \" ) ; emitDeclarationName ( node ) ; emitEnd ( node ) ; write ( \";\" ) ; } else if ( isES6ExportedDeclaration ( node ) && ( node . flags & 1024 /* Default */ ) && thisNodeIsDecorated ) { // if this is a top level default export of decorated class, write the export after the declaration. writeLine ( ) ; write ( \"export default \" ) ; emitDeclarationName ( node ) ; write ( \";\" ) ; } } function emitClassLikeDeclarationBelowES6 ( node ) { if ( node . kind === 214 /* ClassDeclaration */ ) { // source file level classes in system modules are hoisted so 'var's for them are already defined if ( ! shouldHoistDeclarationInSystemJsModule ( node ) ) { write ( \"var \" ) ; } emitDeclarationName ( node ) ; write ( \" = \" ) ; } write ( \"(function (\" ) ; var baseTypeNode = ts . getClassExtendsHeritageClauseElement ( node ) ; if ( baseTypeNode ) { write ( \"_super\" ) ; } write ( \") {\" ) ; var saveTempFlags = tempFlags ; var saveTempVariables = tempVariables ; var saveTempParameters = tempParameters ; var saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames ; tempFlags = 0 ; tempVariables = undefined ; tempParameters = undefined ; computedPropertyNamesToGeneratedNames = undefined ; increaseIndent ( ) ; scopeEmitStart ( node ) ; if ( baseTypeNode ) { writeLine ( ) ; emitStart ( baseTypeNode ) ; write ( \"__extends(\" ) ; emitDeclarationName ( node ) ; write ( \", _super);\" ) ; emitEnd ( baseTypeNode ) ; } writeLine ( ) ; emitConstructor ( node , baseTypeNode ) ; emitMemberFunctionsForES5AndLower ( node ) ; emitPropertyDeclarations ( node , getInitializedProperties ( node , /*static:*/ true ) ) ; writeLine ( ) ; emitDecoratorsOfClass ( node ) ; writeLine ( ) ; emitToken ( 16 /* CloseBraceToken */ , node . members . end , function ( ) { write ( \"return \" ) ; emitDeclarationName ( node ) ; } ) ; write ( \";\" ) ; emitTempDeclarations ( /*newLine*/ true ) ; tempFlags = saveTempFlags ; tempVariables = saveTempVariables ; tempParameters = saveTempParameters ; computedPropertyNamesToGeneratedNames = saveComputedPropertyNamesToGeneratedNames ; decreaseIndent ( ) ; writeLine ( ) ; emitToken ( 16 /* CloseBraceToken */ , node . members . end ) ; scopeEmitEnd ( ) ; emitStart ( node ) ; write ( \")(\" ) ; if ( baseTypeNode ) { emit ( baseTypeNode . expression ) ; } write ( \")\" ) ; if ( node . kind === 214 /* ClassDeclaration */ ) { write ( \";\" ) ; } emitEnd ( node ) ; if ( node . kind === 214 /* ClassDeclaration */ ) { emitExportMemberAssignment ( node ) ; } } function emitClassMemberPrefix ( node , member ) { emitDeclarationName ( node ) ; if ( ! ( member . flags & 128 /* Static */ ) ) { write ( \".prototype\" ) ; } } function emitDecoratorsOfClass ( node ) { emitDecoratorsOfMembers ( node , /*staticFlag*/ 0 ) ; emitDecoratorsOfMembers ( node , 128 /* Static */ ) ; emitDecoratorsOfConstructor ( node ) ; } function emitDecoratorsOfConstructor ( node ) { var decorators = node . decorators ; var constructor = ts . getFirstConstructorWithBody ( node ) ; var hasDecoratedParameters = constructor && ts . forEach ( constructor . parameters , ts . nodeIsDecorated ) ; // skip decoration of the constructor if neither it nor its parameters are decorated if ( ! decorators && ! hasDecoratedParameters ) { return ; } // Emit the call to __decorate. Given the class: // //   @dec //   class C { //   } // // The emit for the class is: // //   C = __decorate([dec], C); // writeLine ( ) ; emitStart ( node ) ; emitDeclarationName ( node ) ; write ( \" = __decorate([\" ) ; increaseIndent ( ) ; writeLine ( ) ; var decoratorCount = decorators ? decorators . length : 0 ; var argumentsWritten = emitList ( decorators , 0 , decoratorCount , /*multiLine*/ true , /*trailingComma*/ false , /*leadingComma*/ false , /*noTrailingNewLine*/ true , function ( decorator ) { emitStart ( decorator ) ; emit ( decorator . expression ) ; emitEnd ( decorator ) ; } ) ; argumentsWritten += emitDecoratorsOfParameters ( constructor , /*leadingComma*/ argumentsWritten > 0 ) ; emitSerializedTypeMetadata ( node , /*leadingComma*/ argumentsWritten >= 0 ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"], \" ) ; emitDeclarationName ( node ) ; write ( \");\" ) ; emitEnd ( node ) ; writeLine ( ) ; } function emitDecoratorsOfMembers ( node , staticFlag ) { for ( var _a = 0 , _b = node . members ; _a < _b . length ; _a ++ ) { var member = _b [ _a ] ; // only emit members in the correct group if ( ( member . flags & 128 /* Static */ ) !== staticFlag ) { continue ; } // skip members that cannot be decorated (such as the constructor) if ( ! ts . nodeCanBeDecorated ( member ) ) { continue ; } // skip a member if it or any of its parameters are not decorated if ( ! ts . nodeOrChildIsDecorated ( member ) ) { continue ; } // skip an accessor declaration if it is not the first accessor var decorators = void 0 ; var functionLikeMember = void 0 ; if ( ts . isAccessor ( member ) ) { var accessors = ts . getAllAccessorDeclarations ( node . members , member ) ; if ( member !== accessors . firstAccessor ) { continue ; } // get the decorators from the first accessor with decorators decorators = accessors . firstAccessor . decorators ; if ( ! decorators && accessors . secondAccessor ) { decorators = accessors . secondAccessor . decorators ; } // we only decorate parameters of the set accessor functionLikeMember = accessors . setAccessor ; } else { decorators = member . decorators ; // we only decorate the parameters here if this is a method if ( member . kind === 143 /* MethodDeclaration */ ) { functionLikeMember = member ; } } // Emit the call to __decorate. Given the following: // //   class C { //     @dec method(@dec2 x) {} //     @dec get accessor() {} //     @dec prop; //   } // // The emit for a method is: // //   __decorate([ //       dec, //       __param(0, dec2), //       __metadata(\"design:type\", Function), //       __metadata(\"design:paramtypes\", [Object]), //       __metadata(\"design:returntype\", void 0) //   ], C.prototype, \"method\", undefined); // // The emit for an accessor is: // //   __decorate([ //       dec //   ], C.prototype, \"accessor\", undefined); // // The emit for a property is: // //   __decorate([ //       dec //   ], C.prototype, \"prop\"); // writeLine ( ) ; emitStart ( member ) ; write ( \"__decorate([\" ) ; increaseIndent ( ) ; writeLine ( ) ; var decoratorCount = decorators ? decorators . length : 0 ; var argumentsWritten = emitList ( decorators , 0 , decoratorCount , /*multiLine*/ true , /*trailingComma*/ false , /*leadingComma*/ false , /*noTrailingNewLine*/ true , function ( decorator ) { emitStart ( decorator ) ; emit ( decorator . expression ) ; emitEnd ( decorator ) ; } ) ; argumentsWritten += emitDecoratorsOfParameters ( functionLikeMember , argumentsWritten > 0 ) ; emitSerializedTypeMetadata ( member , argumentsWritten > 0 ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"], \" ) ; emitStart ( member . name ) ; emitClassMemberPrefix ( node , member ) ; write ( \", \" ) ; emitExpressionForPropertyName ( member . name ) ; emitEnd ( member . name ) ; if ( languageVersion > 0 /* ES3 */ ) { if ( member . kind !== 141 /* PropertyDeclaration */ ) { // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. // We have this extra argument here so that we can inject an explicit property descriptor at a later date. write ( \", null\" ) ; } else { // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. write ( \", void 0\" ) ; } } write ( \");\" ) ; emitEnd ( member ) ; writeLine ( ) ; } } function emitDecoratorsOfParameters ( node , leadingComma ) { var argumentsWritten = 0 ; if ( node ) { var parameterIndex = 0 ; for ( var _a = 0 , _b = node . parameters ; _a < _b . length ; _a ++ ) { var parameter = _b [ _a ] ; if ( ts . nodeIsDecorated ( parameter ) ) { var decorators = parameter . decorators ; argumentsWritten += emitList ( decorators , 0 , decorators . length , /*multiLine*/ true , /*trailingComma*/ false , /*leadingComma*/ leadingComma , /*noTrailingNewLine*/ true , function ( decorator ) { emitStart ( decorator ) ; write ( \"__param(\" + parameterIndex + \", \" ) ; emit ( decorator . expression ) ; write ( \")\" ) ; emitEnd ( decorator ) ; } ) ; leadingComma = true ; } ++ parameterIndex ; } } return argumentsWritten ; } function shouldEmitTypeMetadata ( node ) { // This method determines whether to emit the \"design:type\" metadata based on the node's kind. // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch ( node . kind ) { case 143 /* MethodDeclaration */ : case 145 /* GetAccessor */ : case 146 /* SetAccessor */ : case 141 /* PropertyDeclaration */ : return true ; } return false ; } function shouldEmitReturnTypeMetadata ( node ) { // This method determines whether to emit the \"design:returntype\" metadata based on the node's kind. // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch ( node . kind ) { case 143 /* MethodDeclaration */ : return true ; } return false ; } function shouldEmitParamTypesMetadata ( node ) { // This method determines whether to emit the \"design:paramtypes\" metadata based on the node's kind. // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch ( node . kind ) { case 214 /* ClassDeclaration */ : case 143 /* MethodDeclaration */ : case 146 /* SetAccessor */ : return true ; } return false ; } /** Serializes the type of a declaration to an appropriate JS constructor value. Used by the __metadata decorator for a class member. */ function emitSerializedTypeOfNode ( node ) { // serialization of the type of a declaration uses the following rules: // // * The serialized type of a ClassDeclaration is \"Function\" // * The serialized type of a ParameterDeclaration is the serialized type of its type annotation. // * The serialized type of a PropertyDeclaration is the serialized type of its type annotation. // * The serialized type of an AccessorDeclaration is the serialized type of the return type annotation of its getter or parameter type annotation of its setter. // * The serialized type of any other FunctionLikeDeclaration is \"Function\". // * The serialized type of any other node is \"void 0\". // // For rules on serializing type annotations, see `serializeTypeNode`. switch ( node . kind ) { case 214 /* ClassDeclaration */ : write ( \"Function\" ) ; return ; case 141 /* PropertyDeclaration */ : emitSerializedTypeNode ( node . type ) ; return ; case 138 /* Parameter */ : emitSerializedTypeNode ( node . type ) ; return ; case 145 /* GetAccessor */ : emitSerializedTypeNode ( node . type ) ; return ; case 146 /* SetAccessor */ : emitSerializedTypeNode ( ts . getSetAccessorTypeAnnotationNode ( node ) ) ; return ; } if ( ts . isFunctionLike ( node ) ) { write ( \"Function\" ) ; return ; } write ( \"void 0\" ) ; } function emitSerializedTypeNode ( node ) { if ( node ) { switch ( node . kind ) { case 103 /* VoidKeyword */ : write ( \"void 0\" ) ; return ; case 160 /* ParenthesizedType */ : emitSerializedTypeNode ( node . type ) ; return ; case 152 /* FunctionType */ : case 153 /* ConstructorType */ : write ( \"Function\" ) ; return ; case 156 /* ArrayType */ : case 157 /* TupleType */ : write ( \"Array\" ) ; return ; case 150 /* TypePredicate */ : case 120 /* BooleanKeyword */ : write ( \"Boolean\" ) ; return ; case 130 /* StringKeyword */ : case 9 /* StringLiteral */ : write ( \"String\" ) ; return ; case 128 /* NumberKeyword */ : write ( \"Number\" ) ; return ; case 131 /* SymbolKeyword */ : write ( \"Symbol\" ) ; return ; case 151 /* TypeReference */ : emitSerializedTypeReferenceNode ( node ) ; return ; case 154 /* TypeQuery */ : case 155 /* TypeLiteral */ : case 158 /* UnionType */ : case 159 /* IntersectionType */ : case 117 /* AnyKeyword */ : break ; default : ts . Debug . fail ( \"Cannot serialize unexpected type node.\" ) ; break ; } } write ( \"Object\" ) ; } /** Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator. */ function emitSerializedTypeReferenceNode ( node ) { var location = node . parent ; while ( ts . isDeclaration ( location ) || ts . isTypeNode ( location ) ) { location = location . parent ; } // Clone the type name and parent it to a location outside of the current declaration. var typeName = ts . cloneEntityName ( node . typeName ) ; typeName . parent = location ; var result = resolver . getTypeReferenceSerializationKind ( typeName ) ; switch ( result ) { case ts . TypeReferenceSerializationKind . Unknown : var temp = createAndRecordTempVariable ( 0 /* Auto */ ) ; write ( \"(typeof (\" ) ; emitNodeWithoutSourceMap ( temp ) ; write ( \" = \" ) ; emitEntityNameAsExpression ( typeName , /*useFallback*/ true ) ; write ( \") === 'function' && \" ) ; emitNodeWithoutSourceMap ( temp ) ; write ( \") || Object\" ) ; break ; case ts . TypeReferenceSerializationKind . TypeWithConstructSignatureAndValue : emitEntityNameAsExpression ( typeName , /*useFallback*/ false ) ; break ; case ts . TypeReferenceSerializationKind . VoidType : write ( \"void 0\" ) ; break ; case ts . TypeReferenceSerializationKind . BooleanType : write ( \"Boolean\" ) ; break ; case ts . TypeReferenceSerializationKind . NumberLikeType : write ( \"Number\" ) ; break ; case ts . TypeReferenceSerializationKind . StringLikeType : write ( \"String\" ) ; break ; case ts . TypeReferenceSerializationKind . ArrayLikeType : write ( \"Array\" ) ; break ; case ts . TypeReferenceSerializationKind . ESSymbolType : if ( languageVersion < 2 /* ES6 */ ) { write ( \"typeof Symbol === 'function' ? Symbol : Object\" ) ; } else { write ( \"Symbol\" ) ; } break ; case ts . TypeReferenceSerializationKind . TypeWithCallSignature : write ( \"Function\" ) ; break ; case ts . TypeReferenceSerializationKind . ObjectType : write ( \"Object\" ) ; break ; } } /** Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor. */ function emitSerializedParameterTypesOfNode ( node ) { // serialization of parameter types uses the following rules: // // * If the declaration is a class, the parameters of the first constructor with a body are used. // * If the declaration is function-like and has a body, the parameters of the function are used. // // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`. if ( node ) { var valueDeclaration ; if ( node . kind === 214 /* ClassDeclaration */ ) { valueDeclaration = ts . getFirstConstructorWithBody ( node ) ; } else if ( ts . isFunctionLike ( node ) && ts . nodeIsPresent ( node . body ) ) { valueDeclaration = node ; } if ( valueDeclaration ) { var parameters = valueDeclaration . parameters ; var parameterCount = parameters . length ; if ( parameterCount > 0 ) { for ( var i = 0 ; i < parameterCount ; i ++ ) { if ( i > 0 ) { write ( \", \" ) ; } if ( parameters [ i ] . dotDotDotToken ) { var parameterType = parameters [ i ] . type ; if ( parameterType . kind === 156 /* ArrayType */ ) { parameterType = parameterType . elementType ; } else if ( parameterType . kind === 151 /* TypeReference */ && parameterType . typeArguments && parameterType . typeArguments . length === 1 ) { parameterType = parameterType . typeArguments [ 0 ] ; } else { parameterType = undefined ; } emitSerializedTypeNode ( parameterType ) ; } else { emitSerializedTypeOfNode ( parameters [ i ] ) ; } } } } } } /** Serializes the return type of function. Used by the __metadata decorator for a method. */ function emitSerializedReturnTypeOfNode ( node ) { if ( node && ts . isFunctionLike ( node ) && node . type ) { emitSerializedTypeNode ( node . type ) ; return ; } write ( \"void 0\" ) ; } function emitSerializedTypeMetadata ( node , writeComma ) { // This method emits the serialized type metadata for a decorator target. // The caller should have already tested whether the node has decorators. var argumentsWritten = 0 ; if ( compilerOptions . emitDecoratorMetadata ) { if ( shouldEmitTypeMetadata ( node ) ) { if ( writeComma ) { write ( \", \" ) ; } writeLine ( ) ; write ( \"__metadata('design:type', \" ) ; emitSerializedTypeOfNode ( node ) ; write ( \")\" ) ; argumentsWritten ++ ; } if ( shouldEmitParamTypesMetadata ( node ) ) { if ( writeComma || argumentsWritten ) { write ( \", \" ) ; } writeLine ( ) ; write ( \"__metadata('design:paramtypes', [\" ) ; emitSerializedParameterTypesOfNode ( node ) ; write ( \"])\" ) ; argumentsWritten ++ ; } if ( shouldEmitReturnTypeMetadata ( node ) ) { if ( writeComma || argumentsWritten ) { write ( \", \" ) ; } writeLine ( ) ; write ( \"__metadata('design:returntype', \" ) ; emitSerializedReturnTypeOfNode ( node ) ; write ( \")\" ) ; argumentsWritten ++ ; } } return argumentsWritten ; } function emitInterfaceDeclaration ( node ) { emitCommentsOnNotEmittedNode ( node ) ; } function shouldEmitEnumDeclaration ( node ) { var isConstEnum = ts . isConst ( node ) ; return ! isConstEnum || compilerOptions . preserveConstEnums || compilerOptions . isolatedModules ; } function emitEnumDeclaration ( node ) { // const enums are completely erased during compilation. if ( ! shouldEmitEnumDeclaration ( node ) ) { return ; } if ( ! shouldHoistDeclarationInSystemJsModule ( node ) ) { // do not emit var if variable was already hoisted if ( ! ( node . flags & 1 /* Export */ ) || isES6ExportedDeclaration ( node ) ) { emitStart ( node ) ; if ( isES6ExportedDeclaration ( node ) ) { write ( \"export \" ) ; } write ( \"var \" ) ; emit ( node . name ) ; emitEnd ( node ) ; write ( \";\" ) ; } } writeLine ( ) ; emitStart ( node ) ; write ( \"(function (\" ) ; emitStart ( node . name ) ; write ( getGeneratedNameForNode ( node ) ) ; emitEnd ( node . name ) ; write ( \") {\" ) ; increaseIndent ( ) ; scopeEmitStart ( node ) ; emitLines ( node . members ) ; decreaseIndent ( ) ; writeLine ( ) ; emitToken ( 16 /* CloseBraceToken */ , node . members . end ) ; scopeEmitEnd ( ) ; write ( \")(\" ) ; emitModuleMemberName ( node ) ; write ( \" || (\" ) ; emitModuleMemberName ( node ) ; write ( \" = {}));\" ) ; emitEnd ( node ) ; if ( ! isES6ExportedDeclaration ( node ) && node . flags & 1 /* Export */ && ! shouldHoistDeclarationInSystemJsModule ( node ) ) { // do not emit var if variable was already hoisted writeLine ( ) ; emitStart ( node ) ; write ( \"var \" ) ; emit ( node . name ) ; write ( \" = \" ) ; emitModuleMemberName ( node ) ; emitEnd ( node ) ; write ( \";\" ) ; } if ( modulekind !== 5 /* ES6 */ && node . parent === currentSourceFile ) { if ( modulekind === 4 /* System */ && ( node . flags & 1 /* Export */ ) ) { // write the call to exporter for enum writeLine ( ) ; write ( exportFunctionForFile + \"(\\\"\" ) ; emitDeclarationName ( node ) ; write ( \"\\\", \" ) ; emitDeclarationName ( node ) ; write ( \");\" ) ; } emitExportMemberAssignments ( node . name ) ; } } function emitEnumMember ( node ) { var enumParent = node . parent ; emitStart ( node ) ; write ( getGeneratedNameForNode ( enumParent ) ) ; write ( \"[\" ) ; write ( getGeneratedNameForNode ( enumParent ) ) ; write ( \"[\" ) ; emitExpressionForPropertyName ( node . name ) ; write ( \"] = \" ) ; writeEnumMemberDeclarationValue ( node ) ; write ( \"] = \" ) ; emitExpressionForPropertyName ( node . name ) ; emitEnd ( node ) ; write ( \";\" ) ; } function writeEnumMemberDeclarationValue ( member ) { var value = resolver . getConstantValue ( member ) ; if ( value !== undefined ) { write ( value . toString ( ) ) ; return ; } else if ( member . initializer ) { emit ( member . initializer ) ; } else { write ( \"undefined\" ) ; } } function getInnerMostModuleDeclarationFromDottedModule ( moduleDeclaration ) { if ( moduleDeclaration . body . kind === 218 /* ModuleDeclaration */ ) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule ( moduleDeclaration . body ) ; return recursiveInnerModule || moduleDeclaration . body ; } } function shouldEmitModuleDeclaration ( node ) { return ts . isInstantiatedModule ( node , compilerOptions . preserveConstEnums || compilerOptions . isolatedModules ) ; } function isModuleMergedWithES6Class ( node ) { return languageVersion === 2 /* ES6 */ && ! ! ( resolver . getNodeCheckFlags ( node ) & 32768 /* LexicalModuleMergesWithClass */ ) ; } function emitModuleDeclaration ( node ) { // Emit only if this module is non-ambient. var shouldEmit = shouldEmitModuleDeclaration ( node ) ; if ( ! shouldEmit ) { return emitCommentsOnNotEmittedNode ( node ) ; } var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule ( node ) ; var emitVarForModule = ! hoistedInDeclarationScope && ! isModuleMergedWithES6Class ( node ) ; if ( emitVarForModule ) { emitStart ( node ) ; if ( isES6ExportedDeclaration ( node ) ) { write ( \"export \" ) ; } write ( \"var \" ) ; emit ( node . name ) ; write ( \";\" ) ; emitEnd ( node ) ; writeLine ( ) ; } emitStart ( node ) ; write ( \"(function (\" ) ; emitStart ( node . name ) ; write ( getGeneratedNameForNode ( node ) ) ; emitEnd ( node . name ) ; write ( \") \" ) ; if ( node . body . kind === 219 /* ModuleBlock */ ) { var saveTempFlags = tempFlags ; var saveTempVariables = tempVariables ; tempFlags = 0 ; tempVariables = undefined ; emit ( node . body ) ; tempFlags = saveTempFlags ; tempVariables = saveTempVariables ; } else { write ( \"{\" ) ; increaseIndent ( ) ; scopeEmitStart ( node ) ; emitCaptureThisForNodeIfNecessary ( node ) ; writeLine ( ) ; emit ( node . body ) ; decreaseIndent ( ) ; writeLine ( ) ; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule ( node ) . body ; emitToken ( 16 /* CloseBraceToken */ , moduleBlock . statements . end ) ; scopeEmitEnd ( ) ; } write ( \")(\" ) ; // write moduleDecl = containingModule.m only if it is not exported es6 module member if ( ( node . flags & 1 /* Export */ ) && ! isES6ExportedDeclaration ( node ) ) { emit ( node . name ) ; write ( \" = \" ) ; } emitModuleMemberName ( node ) ; write ( \" || (\" ) ; emitModuleMemberName ( node ) ; write ( \" = {}));\" ) ; emitEnd ( node ) ; if ( ! isES6ExportedDeclaration ( node ) && node . name . kind === 69 /* Identifier */ && node . parent === currentSourceFile ) { if ( modulekind === 4 /* System */ && ( node . flags & 1 /* Export */ ) ) { writeLine ( ) ; write ( exportFunctionForFile + \"(\\\"\" ) ; emitDeclarationName ( node ) ; write ( \"\\\", \" ) ; emitDeclarationName ( node ) ; write ( \");\" ) ; } emitExportMemberAssignments ( node . name ) ; } } /*\n             * Some bundlers (SystemJS builder) sometimes want to rename dependencies.\n             * Here we check if alternative name was provided for a given moduleName and return it if possible.\n             */ function tryRenameExternalModule ( moduleName ) { if ( currentSourceFile . renamedDependencies && ts . hasProperty ( currentSourceFile . renamedDependencies , moduleName . text ) ) { return \"\\\"\" + currentSourceFile . renamedDependencies [ moduleName . text ] + \"\\\"\" ; } return undefined ; } function emitRequire ( moduleName ) { if ( moduleName . kind === 9 /* StringLiteral */ ) { write ( \"require(\" ) ; var text = tryRenameExternalModule ( moduleName ) ; if ( text ) { write ( text ) ; } else { emitStart ( moduleName ) ; emitLiteral ( moduleName ) ; emitEnd ( moduleName ) ; } emitToken ( 18 /* CloseParenToken */ , moduleName . end ) ; } else { write ( \"require()\" ) ; } } function getNamespaceDeclarationNode ( node ) { if ( node . kind === 221 /* ImportEqualsDeclaration */ ) { return node ; } var importClause = node . importClause ; if ( importClause && importClause . namedBindings && importClause . namedBindings . kind === 224 /* NamespaceImport */ ) { return importClause . namedBindings ; } } function isDefaultImport ( node ) { return node . kind === 222 /* ImportDeclaration */ && node . importClause && ! ! node . importClause . name ; } function emitExportImportAssignments ( node ) { if ( ts . isAliasSymbolDeclaration ( node ) && resolver . isValueAliasDeclaration ( node ) ) { emitExportMemberAssignments ( node . name ) ; } ts . forEachChild ( node , emitExportImportAssignments ) ; } function emitImportDeclaration ( node ) { if ( modulekind !== 5 /* ES6 */ ) { return emitExternalImportDeclaration ( node ) ; } // ES6 import if ( node . importClause ) { var shouldEmitDefaultBindings = resolver . isReferencedAliasDeclaration ( node . importClause ) ; var shouldEmitNamedBindings = node . importClause . namedBindings && resolver . isReferencedAliasDeclaration ( node . importClause . namedBindings , /* checkChildren */ true ) ; if ( shouldEmitDefaultBindings || shouldEmitNamedBindings ) { write ( \"import \" ) ; emitStart ( node . importClause ) ; if ( shouldEmitDefaultBindings ) { emit ( node . importClause . name ) ; if ( shouldEmitNamedBindings ) { write ( \", \" ) ; } } if ( shouldEmitNamedBindings ) { emitLeadingComments ( node . importClause . namedBindings ) ; emitStart ( node . importClause . namedBindings ) ; if ( node . importClause . namedBindings . kind === 224 /* NamespaceImport */ ) { write ( \"* as \" ) ; emit ( node . importClause . namedBindings . name ) ; } else { write ( \"{ \" ) ; emitExportOrImportSpecifierList ( node . importClause . namedBindings . elements , resolver . isReferencedAliasDeclaration ) ; write ( \" }\" ) ; } emitEnd ( node . importClause . namedBindings ) ; emitTrailingComments ( node . importClause . namedBindings ) ; } emitEnd ( node . importClause ) ; write ( \" from \" ) ; emit ( node . moduleSpecifier ) ; write ( \";\" ) ; } } else { write ( \"import \" ) ; emit ( node . moduleSpecifier ) ; write ( \";\" ) ; } } function emitExternalImportDeclaration ( node ) { if ( ts . contains ( externalImports , node ) ) { var isExportedImport = node . kind === 221 /* ImportEqualsDeclaration */ && ( node . flags & 1 /* Export */ ) !== 0 ; var namespaceDeclaration = getNamespaceDeclarationNode ( node ) ; if ( modulekind !== 2 /* AMD */ ) { emitLeadingComments ( node ) ; emitStart ( node ) ; if ( namespaceDeclaration && ! isDefaultImport ( node ) ) { // import x = require(\"foo\") // import * as x from \"foo\" if ( ! isExportedImport ) write ( \"var \" ) ; emitModuleMemberName ( namespaceDeclaration ) ; write ( \" = \" ) ; } else { // import \"foo\" // import x from \"foo\" // import { x, y } from \"foo\" // import d, * as x from \"foo\" // import d, { x, y } from \"foo\" var isNakedImport = 222 /* ImportDeclaration */ && ! node . importClause ; if ( ! isNakedImport ) { write ( \"var \" ) ; write ( getGeneratedNameForNode ( node ) ) ; write ( \" = \" ) ; } } emitRequire ( ts . getExternalModuleName ( node ) ) ; if ( namespaceDeclaration && isDefaultImport ( node ) ) { // import d, * as x from \"foo\" write ( \", \" ) ; emitModuleMemberName ( namespaceDeclaration ) ; write ( \" = \" ) ; write ( getGeneratedNameForNode ( node ) ) ; } write ( \";\" ) ; emitEnd ( node ) ; emitExportImportAssignments ( node ) ; emitTrailingComments ( node ) ; } else { if ( isExportedImport ) { emitModuleMemberName ( namespaceDeclaration ) ; write ( \" = \" ) ; emit ( namespaceDeclaration . name ) ; write ( \";\" ) ; } else if ( namespaceDeclaration && isDefaultImport ( node ) ) { // import d, * as x from \"foo\" write ( \"var \" ) ; emitModuleMemberName ( namespaceDeclaration ) ; write ( \" = \" ) ; write ( getGeneratedNameForNode ( node ) ) ; write ( \";\" ) ; } emitExportImportAssignments ( node ) ; } } } function emitImportEqualsDeclaration ( node ) { if ( ts . isExternalModuleImportEqualsDeclaration ( node ) ) { emitExternalImportDeclaration ( node ) ; return ; } // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when // - current file is not external module // - import declaration is top level and target is value imported by entity name if ( resolver . isReferencedAliasDeclaration ( node ) || ( ! ts . isExternalModule ( currentSourceFile ) && resolver . isTopLevelValueImportEqualsWithEntityName ( node ) ) ) { emitLeadingComments ( node ) ; emitStart ( node ) ; // variable declaration for import-equals declaration can be hoisted in system modules // in this case 'var' should be omitted and emit should contain only initialization var variableDeclarationIsHoisted = shouldHoistVariable ( node , /*checkIfSourceFileLevelDecl*/ true ) ; // is it top level export import v = a.b.c in system module? // if yes - it needs to be rewritten as exporter('v', v = a.b.c) var isExported = isSourceFileLevelDeclarationInSystemJsModule ( node , /*isExported*/ true ) ; if ( ! variableDeclarationIsHoisted ) { ts . Debug . assert ( ! isExported ) ; if ( isES6ExportedDeclaration ( node ) ) { write ( \"export \" ) ; write ( \"var \" ) ; } else if ( ! ( node . flags & 1 /* Export */ ) ) { write ( \"var \" ) ; } } if ( isExported ) { write ( exportFunctionForFile + \"(\\\"\" ) ; emitNodeWithoutSourceMap ( node . name ) ; write ( \"\\\", \" ) ; } emitModuleMemberName ( node ) ; write ( \" = \" ) ; emit ( node . moduleReference ) ; if ( isExported ) { write ( \")\" ) ; } write ( \";\" ) ; emitEnd ( node ) ; emitExportImportAssignments ( node ) ; emitTrailingComments ( node ) ; } } function emitExportDeclaration ( node ) { ts . Debug . assert ( modulekind !== 4 /* System */ ) ; if ( modulekind !== 5 /* ES6 */ ) { if ( node . moduleSpecifier && ( ! node . exportClause || resolver . isValueAliasDeclaration ( node ) ) ) { emitStart ( node ) ; var generatedName = getGeneratedNameForNode ( node ) ; if ( node . exportClause ) { // export { x, y, ... } from \"foo\" if ( modulekind !== 2 /* AMD */ ) { write ( \"var \" ) ; write ( generatedName ) ; write ( \" = \" ) ; emitRequire ( ts . getExternalModuleName ( node ) ) ; write ( \";\" ) ; } for ( var _a = 0 , _b = node . exportClause . elements ; _a < _b . length ; _a ++ ) { var specifier = _b [ _a ] ; if ( resolver . isValueAliasDeclaration ( specifier ) ) { writeLine ( ) ; emitStart ( specifier ) ; emitContainingModuleName ( specifier ) ; write ( \".\" ) ; emitNodeWithCommentsAndWithoutSourcemap ( specifier . name ) ; write ( \" = \" ) ; write ( generatedName ) ; write ( \".\" ) ; emitNodeWithCommentsAndWithoutSourcemap ( specifier . propertyName || specifier . name ) ; write ( \";\" ) ; emitEnd ( specifier ) ; } } } else { // export * from \"foo\" writeLine ( ) ; write ( \"__export(\" ) ; if ( modulekind !== 2 /* AMD */ ) { emitRequire ( ts . getExternalModuleName ( node ) ) ; } else { write ( generatedName ) ; } write ( \");\" ) ; } emitEnd ( node ) ; } } else { if ( ! node . exportClause || resolver . isValueAliasDeclaration ( node ) ) { write ( \"export \" ) ; if ( node . exportClause ) { // export { x, y, ... } write ( \"{ \" ) ; emitExportOrImportSpecifierList ( node . exportClause . elements , resolver . isValueAliasDeclaration ) ; write ( \" }\" ) ; } else { write ( \"*\" ) ; } if ( node . moduleSpecifier ) { write ( \" from \" ) ; emit ( node . moduleSpecifier ) ; } write ( \";\" ) ; } } } function emitExportOrImportSpecifierList ( specifiers , shouldEmit ) { ts . Debug . assert ( modulekind === 5 /* ES6 */ ) ; var needsComma = false ; for ( var _a = 0 ; _a < specifiers . length ; _a ++ ) { var specifier = specifiers [ _a ] ; if ( shouldEmit ( specifier ) ) { if ( needsComma ) { write ( \", \" ) ; } if ( specifier . propertyName ) { emit ( specifier . propertyName ) ; write ( \" as \" ) ; } emit ( specifier . name ) ; needsComma = true ; } } } function emitExportAssignment ( node ) { if ( ! node . isExportEquals && resolver . isValueAliasDeclaration ( node ) ) { if ( modulekind === 5 /* ES6 */ ) { writeLine ( ) ; emitStart ( node ) ; write ( \"export default \" ) ; var expression = node . expression ; emit ( expression ) ; if ( expression . kind !== 213 /* FunctionDeclaration */ && expression . kind !== 214 /* ClassDeclaration */ ) { write ( \";\" ) ; } emitEnd ( node ) ; } else { writeLine ( ) ; emitStart ( node ) ; if ( modulekind === 4 /* System */ ) { write ( exportFunctionForFile + \"(\\\"default\\\",\" ) ; emit ( node . expression ) ; write ( \")\" ) ; } else { emitEs6ExportDefaultCompat ( node ) ; emitContainingModuleName ( node ) ; if ( languageVersion === 0 /* ES3 */ ) { write ( \"[\\\"default\\\"] = \" ) ; } else { write ( \".default = \" ) ; } emit ( node . expression ) ; } write ( \";\" ) ; emitEnd ( node ) ; } } } function collectExternalModuleInfo ( sourceFile ) { externalImports = [ ] ; exportSpecifiers = { } ; exportEquals = undefined ; hasExportStars = false ; for ( var _a = 0 , _b = sourceFile . statements ; _a < _b . length ; _a ++ ) { var node = _b [ _a ] ; switch ( node . kind ) { case 222 /* ImportDeclaration */ : if ( ! node . importClause || resolver . isReferencedAliasDeclaration ( node . importClause , /*checkChildren*/ true ) ) { // import \"mod\" // import x from \"mod\" where x is referenced // import * as x from \"mod\" where x is referenced // import { x, y } from \"mod\" where at least one import is referenced externalImports . push ( node ) ; } break ; case 221 /* ImportEqualsDeclaration */ : if ( node . moduleReference . kind === 232 /* ExternalModuleReference */ && resolver . isReferencedAliasDeclaration ( node ) ) { // import x = require(\"mod\") where x is referenced externalImports . push ( node ) ; } break ; case 228 /* ExportDeclaration */ : if ( node . moduleSpecifier ) { if ( ! node . exportClause ) { // export * from \"mod\" externalImports . push ( node ) ; hasExportStars = true ; } else if ( resolver . isValueAliasDeclaration ( node ) ) { // export { x, y } from \"mod\" where at least one export is a value symbol externalImports . push ( node ) ; } } else { // export { x, y } for ( var _c = 0 , _d = node . exportClause . elements ; _c < _d . length ; _c ++ ) { var specifier = _d [ _c ] ; var name_25 = ( specifier . propertyName || specifier . name ) . text ; ( exportSpecifiers [ name_25 ] || ( exportSpecifiers [ name_25 ] = [ ] ) ) . push ( specifier ) ; } } break ; case 227 /* ExportAssignment */ : if ( node . isExportEquals && ! exportEquals ) { // export = x exportEquals = node ; } break ; } } } function emitExportStarHelper ( ) { if ( hasExportStars ) { writeLine ( ) ; write ( \"function __export(m) {\" ) ; increaseIndent ( ) ; writeLine ( ) ; write ( \"for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\" ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"}\" ) ; } } function getLocalNameForExternalImport ( node ) { var namespaceDeclaration = getNamespaceDeclarationNode ( node ) ; if ( namespaceDeclaration && ! isDefaultImport ( node ) ) { return ts . getSourceTextOfNodeFromSourceFile ( currentSourceFile , namespaceDeclaration . name ) ; } if ( node . kind === 222 /* ImportDeclaration */ && node . importClause ) { return getGeneratedNameForNode ( node ) ; } if ( node . kind === 228 /* ExportDeclaration */ && node . moduleSpecifier ) { return getGeneratedNameForNode ( node ) ; } } function getExternalModuleNameText ( importNode ) { var moduleName = ts . getExternalModuleName ( importNode ) ; if ( moduleName . kind === 9 /* StringLiteral */ ) { return tryRenameExternalModule ( moduleName ) || getLiteralText ( moduleName ) ; } return undefined ; } function emitVariableDeclarationsForImports ( ) { if ( externalImports . length === 0 ) { return ; } writeLine ( ) ; var started = false ; for ( var _a = 0 ; _a < externalImports . length ; _a ++ ) { var importNode = externalImports [ _a ] ; // do not create variable declaration for exports and imports that lack import clause var skipNode = importNode . kind === 228 /* ExportDeclaration */ || ( importNode . kind === 222 /* ImportDeclaration */ && ! importNode . importClause ) ; if ( skipNode ) { continue ; } if ( ! started ) { write ( \"var \" ) ; started = true ; } else { write ( \", \" ) ; } write ( getLocalNameForExternalImport ( importNode ) ) ; } if ( started ) { write ( \";\" ) ; } } function emitLocalStorageForExportedNamesIfNecessary ( exportedDeclarations ) { // when resolving exports local exported entries/indirect exported entries in the module // should always win over entries with similar names that were added via star exports // to support this we store names of local/indirect exported entries in a set. // this set is used to filter names brought by star expors. if ( ! hasExportStars ) { // local names set is needed only in presence of star exports return undefined ; } // local names set should only be added if we have anything exported if ( ! exportedDeclarations && ts . isEmpty ( exportSpecifiers ) ) { // no exported declarations (export var ...) or export specifiers (export {x}) // check if we have any non star export declarations. var hasExportDeclarationWithExportClause = false ; for ( var _a = 0 ; _a < externalImports . length ; _a ++ ) { var externalImport = externalImports [ _a ] ; if ( externalImport . kind === 228 /* ExportDeclaration */ && externalImport . exportClause ) { hasExportDeclarationWithExportClause = true ; break ; } } if ( ! hasExportDeclarationWithExportClause ) { // we still need to emit exportStar helper return emitExportStarFunction ( /*localNames*/ undefined ) ; } } var exportedNamesStorageRef = makeUniqueName ( \"exportedNames\" ) ; writeLine ( ) ; write ( \"var \" + exportedNamesStorageRef + \" = {\" ) ; increaseIndent ( ) ; var started = false ; if ( exportedDeclarations ) { for ( var i = 0 ; i < exportedDeclarations . length ; ++ i ) { // write name of exported declaration, i.e 'export var x...' writeExportedName ( exportedDeclarations [ i ] ) ; } } if ( exportSpecifiers ) { for ( var n in exportSpecifiers ) { for ( var _b = 0 , _c = exportSpecifiers [ n ] ; _b < _c . length ; _b ++ ) { var specifier = _c [ _b ] ; // write name of export specified, i.e. 'export {x}' writeExportedName ( specifier . name ) ; } } } for ( var _d = 0 ; _d < externalImports . length ; _d ++ ) { var externalImport = externalImports [ _d ] ; if ( externalImport . kind !== 228 /* ExportDeclaration */ ) { continue ; } var exportDecl = externalImport ; if ( ! exportDecl . exportClause ) { // export * from ... continue ; } for ( var _e = 0 , _f = exportDecl . exportClause . elements ; _e < _f . length ; _e ++ ) { var element = _f [ _e ] ; // write name of indirectly exported entry, i.e. 'export {x} from ...' writeExportedName ( element . name || element . propertyName ) ; } } decreaseIndent ( ) ; writeLine ( ) ; write ( \"};\" ) ; return emitExportStarFunction ( exportedNamesStorageRef ) ; function emitExportStarFunction ( localNames ) { var exportStarFunction = makeUniqueName ( \"exportStar\" ) ; writeLine ( ) ; // define an export star helper function write ( \"function \" + exportStarFunction + \"(m) {\" ) ; increaseIndent ( ) ; writeLine ( ) ; write ( \"var exports = {};\" ) ; writeLine ( ) ; write ( \"for(var n in m) {\" ) ; increaseIndent ( ) ; writeLine ( ) ; write ( \"if (n !== \\\"default\\\"\" ) ; if ( localNames ) { write ( \"&& !\" + localNames + \".hasOwnProperty(n)\" ) ; } write ( \") exports[n] = m[n];\" ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"}\" ) ; writeLine ( ) ; write ( exportFunctionForFile + \"(exports);\" ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"}\" ) ; return exportStarFunction ; } function writeExportedName ( node ) { // do not record default exports // they are local to module and never overwritten (explicitly skipped) by star export if ( node . kind !== 69 /* Identifier */ && node . flags & 1024 /* Default */ ) { return ; } if ( started ) { write ( \",\" ) ; } else { started = true ; } writeLine ( ) ; write ( \"'\" ) ; if ( node . kind === 69 /* Identifier */ ) { emitNodeWithCommentsAndWithoutSourcemap ( node ) ; } else { emitDeclarationName ( node ) ; } write ( \"': true\" ) ; } } function processTopLevelVariableAndFunctionDeclarations ( node ) { // per ES6 spec: // 15.2.1.16.4 ModuleDeclarationInstantiation() Concrete Method // - var declarations are initialized to undefined - 14.a.ii // - function/generator declarations are instantiated - 16.a.iv // this means that after module is instantiated but before its evaluation // exported functions are already accessible at import sites // in theory we should hoist only exported functions and its dependencies // in practice to simplify things we'll hoist all source level functions and variable declaration // including variables declarations for module and class declarations var hoistedVars ; var hoistedFunctionDeclarations ; var exportedDeclarations ; visit ( node ) ; if ( hoistedVars ) { writeLine ( ) ; write ( \"var \" ) ; var seen = { } ; for ( var i = 0 ; i < hoistedVars . length ; ++ i ) { var local = hoistedVars [ i ] ; var name_26 = local . kind === 69 /* Identifier */ ? local : local . name ; if ( name_26 ) { // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables var text = ts . unescapeIdentifier ( name_26 . text ) ; if ( ts . hasProperty ( seen , text ) ) { continue ; } else { seen [ text ] = text ; } } if ( i !== 0 ) { write ( \", \" ) ; } if ( local . kind === 214 /* ClassDeclaration */ || local . kind === 218 /* ModuleDeclaration */ || local . kind === 217 /* EnumDeclaration */ ) { emitDeclarationName ( local ) ; } else { emit ( local ) ; } var flags = ts . getCombinedNodeFlags ( local . kind === 69 /* Identifier */ ? local . parent : local ) ; if ( flags & 1 /* Export */ ) { if ( ! exportedDeclarations ) { exportedDeclarations = [ ] ; } exportedDeclarations . push ( local ) ; } } write ( \";\" ) ; } if ( hoistedFunctionDeclarations ) { for ( var _a = 0 ; _a < hoistedFunctionDeclarations . length ; _a ++ ) { var f = hoistedFunctionDeclarations [ _a ] ; writeLine ( ) ; emit ( f ) ; if ( f . flags & 1 /* Export */ ) { if ( ! exportedDeclarations ) { exportedDeclarations = [ ] ; } exportedDeclarations . push ( f ) ; } } } return exportedDeclarations ; function visit ( node ) { if ( node . flags & 2 /* Ambient */ ) { return ; } if ( node . kind === 213 /* FunctionDeclaration */ ) { if ( ! hoistedFunctionDeclarations ) { hoistedFunctionDeclarations = [ ] ; } hoistedFunctionDeclarations . push ( node ) ; return ; } if ( node . kind === 214 /* ClassDeclaration */ ) { if ( ! hoistedVars ) { hoistedVars = [ ] ; } hoistedVars . push ( node ) ; return ; } if ( node . kind === 217 /* EnumDeclaration */ ) { if ( shouldEmitEnumDeclaration ( node ) ) { if ( ! hoistedVars ) { hoistedVars = [ ] ; } hoistedVars . push ( node ) ; } return ; } if ( node . kind === 218 /* ModuleDeclaration */ ) { if ( shouldEmitModuleDeclaration ( node ) ) { if ( ! hoistedVars ) { hoistedVars = [ ] ; } hoistedVars . push ( node ) ; } return ; } if ( node . kind === 211 /* VariableDeclaration */ || node . kind === 163 /* BindingElement */ ) { if ( shouldHoistVariable ( node , /*checkIfSourceFileLevelDecl*/ false ) ) { var name_27 = node . name ; if ( name_27 . kind === 69 /* Identifier */ ) { if ( ! hoistedVars ) { hoistedVars = [ ] ; } hoistedVars . push ( name_27 ) ; } else { ts . forEachChild ( name_27 , visit ) ; } } return ; } if ( ts . isInternalModuleImportEqualsDeclaration ( node ) && resolver . isValueAliasDeclaration ( node ) ) { if ( ! hoistedVars ) { hoistedVars = [ ] ; } hoistedVars . push ( node . name ) ; return ; } if ( ts . isBindingPattern ( node ) ) { ts . forEach ( node . elements , visit ) ; return ; } if ( ! ts . isDeclaration ( node ) ) { ts . forEachChild ( node , visit ) ; } } } function shouldHoistVariable ( node , checkIfSourceFileLevelDecl ) { if ( checkIfSourceFileLevelDecl && ! shouldHoistDeclarationInSystemJsModule ( node ) ) { return false ; } // hoist variable if // - it is not block scoped // - it is top level block scoped // if block scoped variables are nested in some another block then // no other functions can use them except ones that are defined at least in the same block return ( ts . getCombinedNodeFlags ( node ) & 49152 /* BlockScoped */ ) === 0 || ts . getEnclosingBlockScopeContainer ( node ) . kind === 248 /* SourceFile */ ; } function isCurrentFileSystemExternalModule ( ) { return modulekind === 4 /* System */ && ts . isExternalModule ( currentSourceFile ) ; } function emitSystemModuleBody ( node , dependencyGroups , startIndex ) { // shape of the body in system modules: // function (exports) { //     <list of local aliases for imports> //     <hoisted function declarations> //     <hoisted variable declarations> //     return { //         setters: [ //             <list of setter function for imports> //         ], //         execute: function() { //             <module statements> //         } //     } //     <temp declarations> // } // I.e: // import {x} from 'file1' // var y = 1; // export function foo() { return y + x(); } // console.log(y); // will be transformed to // function(exports) { //     var file1; // local alias //     var y; //     function foo() { return y + file1.x(); } //     exports(\"foo\", foo); //     return { //         setters: [ //             function(v) { file1 = v } //         ], //         execute(): function() { //             y = 1; //             console.log(y); //         } //     }; // } emitVariableDeclarationsForImports ( ) ; writeLine ( ) ; var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations ( node ) ; var exportStarFunction = emitLocalStorageForExportedNamesIfNecessary ( exportedDeclarations ) ; writeLine ( ) ; write ( \"return {\" ) ; increaseIndent ( ) ; writeLine ( ) ; emitSetters ( exportStarFunction , dependencyGroups ) ; writeLine ( ) ; emitExecute ( node , startIndex ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"}\" ) ; // return emitTempDeclarations ( /*newLine*/ true ) ; } function emitSetters ( exportStarFunction , dependencyGroups ) { write ( \"setters:[\" ) ; for ( var i = 0 ; i < dependencyGroups . length ; ++ i ) { if ( i !== 0 ) { write ( \",\" ) ; } writeLine ( ) ; increaseIndent ( ) ; var group = dependencyGroups [ i ] ; // derive a unique name for parameter from the first named entry in the group var parameterName = makeUniqueName ( ts . forEach ( group , getLocalNameForExternalImport ) || \"\" ) ; write ( \"function (\" + parameterName + \") {\" ) ; increaseIndent ( ) ; for ( var _a = 0 ; _a < group . length ; _a ++ ) { var entry = group [ _a ] ; var importVariableName = getLocalNameForExternalImport ( entry ) || \"\" ; switch ( entry . kind ) { case 222 /* ImportDeclaration */ : if ( ! entry . importClause ) { // 'import \"...\"' case // module is imported only for side-effects, no emit required break ; } // fall-through case 221 /* ImportEqualsDeclaration */ : ts . Debug . assert ( importVariableName !== \"\" ) ; writeLine ( ) ; // save import into the local write ( importVariableName + \" = \" + parameterName + \";\" ) ; writeLine ( ) ; break ; case 228 /* ExportDeclaration */ : ts . Debug . assert ( importVariableName !== \"\" ) ; if ( entry . exportClause ) { // export {a, b as c} from 'foo' // emit as: // exports_({ //    \"a\": _[\"a\"], //    \"c\": _[\"b\"] // }); writeLine ( ) ; write ( exportFunctionForFile + \"({\" ) ; writeLine ( ) ; increaseIndent ( ) ; for ( var i_2 = 0 , len = entry . exportClause . elements . length ; i_2 < len ; ++ i_2 ) { if ( i_2 !== 0 ) { write ( \",\" ) ; writeLine ( ) ; } var e = entry . exportClause . elements [ i_2 ] ; write ( \"\\\"\" ) ; emitNodeWithCommentsAndWithoutSourcemap ( e . name ) ; write ( \"\\\": \" + parameterName + \"[\\\"\" ) ; emitNodeWithCommentsAndWithoutSourcemap ( e . propertyName || e . name ) ; write ( \"\\\"]\" ) ; } decreaseIndent ( ) ; writeLine ( ) ; write ( \"});\" ) ; } else { writeLine ( ) ; // export * from 'foo' // emit as: // exportStar(_foo); write ( exportStarFunction + \"(\" + parameterName + \");\" ) ; } writeLine ( ) ; break ; } } decreaseIndent ( ) ; write ( \"}\" ) ; decreaseIndent ( ) ; } write ( \"],\" ) ; } function emitExecute ( node , startIndex ) { write ( \"execute: function() {\" ) ; increaseIndent ( ) ; writeLine ( ) ; for ( var i = startIndex ; i < node . statements . length ; ++ i ) { var statement = node . statements [ i ] ; switch ( statement . kind ) { // - function declarations are not emitted because they were already hoisted // - import declarations are not emitted since they are already handled in setters // - export declarations with module specifiers are not emitted since they were already written in setters // - export declarations without module specifiers are emitted preserving the order case 213 /* FunctionDeclaration */ : case 222 /* ImportDeclaration */ : continue ; case 228 /* ExportDeclaration */ : if ( ! statement . moduleSpecifier ) { for ( var _a = 0 , _b = statement . exportClause . elements ; _a < _b . length ; _a ++ ) { var element = _b [ _a ] ; // write call to exporter function for every export specifier in exports list emitExportSpecifierInSystemModule ( element ) ; } } continue ; case 221 /* ImportEqualsDeclaration */ : if ( ! ts . isInternalModuleImportEqualsDeclaration ( statement ) ) { // - import equals declarations that import external modules are not emitted continue ; } // fall-though for import declarations that import internal modules default : writeLine ( ) ; emit ( statement ) ; } } decreaseIndent ( ) ; writeLine ( ) ; write ( \"}\" ) ; // execute } function emitSystemModule ( node ) { collectExternalModuleInfo ( node ) ; // System modules has the following shape // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) // 'exports' here is a function 'exports<T>(name: string, value: T): T' that is used to publish exported values. // 'exports' returns its 'value' argument so in most cases expressions // that mutate exported values can be rewritten as: // expr -> exports('name', expr). // The only exception in this rule is postfix unary operators, // see comment to 'emitPostfixUnaryExpression' for more details ts . Debug . assert ( ! exportFunctionForFile ) ; // make sure that  name of 'exports' function does not conflict with existing identifiers exportFunctionForFile = makeUniqueName ( \"exports\" ) ; writeLine ( ) ; write ( \"System.register(\" ) ; if ( node . moduleName ) { write ( \"\\\"\" + node . moduleName + \"\\\", \" ) ; } write ( \"[\" ) ; var groupIndices = { } ; var dependencyGroups = [ ] ; for ( var i = 0 ; i < externalImports . length ; ++ i ) { var text = getExternalModuleNameText ( externalImports [ i ] ) ; if ( ts . hasProperty ( groupIndices , text ) ) { // deduplicate/group entries in dependency list by the dependency name var groupIndex = groupIndices [ text ] ; dependencyGroups [ groupIndex ] . push ( externalImports [ i ] ) ; continue ; } else { groupIndices [ text ] = dependencyGroups . length ; dependencyGroups . push ( [ externalImports [ i ] ] ) ; } if ( i !== 0 ) { write ( \", \" ) ; } write ( text ) ; } write ( \"], function(\" + exportFunctionForFile + \") {\" ) ; writeLine ( ) ; increaseIndent ( ) ; var startIndex = emitDirectivePrologues ( node . statements , /*startWithNewLine*/ true ) ; emitEmitHelpers ( node ) ; emitCaptureThisForNodeIfNecessary ( node ) ; emitSystemModuleBody ( node , dependencyGroups , startIndex ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"});\" ) ; } function getAMDDependencyNames ( node , includeNonAmdDependencies ) { // names of modules with corresponding parameter in the factory function var aliasedModuleNames = [ ] ; // names of modules with no corresponding parameters in factory function var unaliasedModuleNames = [ ] ; var importAliasNames = [ ] ; // names of the parameters in the factory function; these // parameters need to match the indexes of the corresponding // module names in aliasedModuleNames. // Fill in amd-dependency tags for ( var _a = 0 , _b = node . amdDependencies ; _a < _b . length ; _a ++ ) { var amdDependency = _b [ _a ] ; if ( amdDependency . name ) { aliasedModuleNames . push ( \"\\\"\" + amdDependency . path + \"\\\"\" ) ; importAliasNames . push ( amdDependency . name ) ; } else { unaliasedModuleNames . push ( \"\\\"\" + amdDependency . path + \"\\\"\" ) ; } } for ( var _c = 0 ; _c < externalImports . length ; _c ++ ) { var importNode = externalImports [ _c ] ; // Find the name of the external module var externalModuleName = getExternalModuleNameText ( importNode ) ; // Find the name of the module alias, if there is one var importAliasName = getLocalNameForExternalImport ( importNode ) ; if ( includeNonAmdDependencies && importAliasName ) { aliasedModuleNames . push ( externalModuleName ) ; importAliasNames . push ( importAliasName ) ; } else { unaliasedModuleNames . push ( externalModuleName ) ; } } return { aliasedModuleNames : aliasedModuleNames , unaliasedModuleNames : unaliasedModuleNames , importAliasNames : importAliasNames } ; } function emitAMDDependencies ( node , includeNonAmdDependencies ) { // An AMD define function has the following shape: //     define(id?, dependencies?, factory); // // This has the shape of //     define(name, [\"module1\", \"module2\"], function (module1Alias) { // The location of the alias in the parameter list in the factory function needs to // match the position of the module name in the dependency list. // // To ensure this is true in cases of modules with no aliases, e.g.: // `import \"module\"` or `<amd-dependency path= \"a.css\" />` // we need to add modules without alias names to the end of the dependencies list var dependencyNames = getAMDDependencyNames ( node , includeNonAmdDependencies ) ; emitAMDDependencyList ( dependencyNames ) ; write ( \", \" ) ; emitAMDFactoryHeader ( dependencyNames ) ; } function emitAMDDependencyList ( _a ) { var aliasedModuleNames = _a . aliasedModuleNames , unaliasedModuleNames = _a . unaliasedModuleNames ; write ( \"[\\\"require\\\", \\\"exports\\\"\" ) ; if ( aliasedModuleNames . length ) { write ( \", \" ) ; write ( aliasedModuleNames . join ( \", \" ) ) ; } if ( unaliasedModuleNames . length ) { write ( \", \" ) ; write ( unaliasedModuleNames . join ( \", \" ) ) ; } write ( \"]\" ) ; } function emitAMDFactoryHeader ( _a ) { var importAliasNames = _a . importAliasNames ; write ( \"function (require, exports\" ) ; if ( importAliasNames . length ) { write ( \", \" ) ; write ( importAliasNames . join ( \", \" ) ) ; } write ( \") {\" ) ; } function emitAMDModule ( node ) { emitEmitHelpers ( node ) ; collectExternalModuleInfo ( node ) ; writeLine ( ) ; write ( \"define(\" ) ; if ( node . moduleName ) { write ( \"\\\"\" + node . moduleName + \"\\\", \" ) ; } emitAMDDependencies ( node , /*includeNonAmdDependencies*/ true ) ; increaseIndent ( ) ; var startIndex = emitDirectivePrologues ( node . statements , /*startWithNewLine*/ true ) ; emitExportStarHelper ( ) ; emitCaptureThisForNodeIfNecessary ( node ) ; emitLinesStartingAt ( node . statements , startIndex ) ; emitTempDeclarations ( /*newLine*/ true ) ; emitExportEquals ( /*emitAsReturn*/ true ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"});\" ) ; } function emitCommonJSModule ( node ) { var startIndex = emitDirectivePrologues ( node . statements , /*startWithNewLine*/ false ) ; emitEmitHelpers ( node ) ; collectExternalModuleInfo ( node ) ; emitExportStarHelper ( ) ; emitCaptureThisForNodeIfNecessary ( node ) ; emitLinesStartingAt ( node . statements , startIndex ) ; emitTempDeclarations ( /*newLine*/ true ) ; emitExportEquals ( /*emitAsReturn*/ false ) ; } function emitUMDModule ( node ) { emitEmitHelpers ( node ) ; collectExternalModuleInfo ( node ) ; var dependencyNames = getAMDDependencyNames ( node , /*includeNonAmdDependencies*/ false ) ; // Module is detected first to support Browserify users that load into a browser with an AMD loader writeLines ( \"(function (factory) {\\n    if (typeof module === 'object' && typeof module.exports === 'object') {\\n        var v = factory(require, exports); if (v !== undefined) module.exports = v;\\n    }\\n    else if (typeof define === 'function' && define.amd) {\\n        define(\" ) ; emitAMDDependencyList ( dependencyNames ) ; write ( \", factory);\" ) ; writeLines ( \"    }\\n})(\" ) ; emitAMDFactoryHeader ( dependencyNames ) ; increaseIndent ( ) ; var startIndex = emitDirectivePrologues ( node . statements , /*startWithNewLine*/ true ) ; emitExportStarHelper ( ) ; emitCaptureThisForNodeIfNecessary ( node ) ; emitLinesStartingAt ( node . statements , startIndex ) ; emitTempDeclarations ( /*newLine*/ true ) ; emitExportEquals ( /*emitAsReturn*/ true ) ; decreaseIndent ( ) ; writeLine ( ) ; write ( \"});\" ) ; } function emitES6Module ( node ) { externalImports = undefined ; exportSpecifiers = undefined ; exportEquals = undefined ; hasExportStars = false ; var startIndex = emitDirectivePrologues ( node . statements , /*startWithNewLine*/ false ) ; emitEmitHelpers ( node ) ; emitCaptureThisForNodeIfNecessary ( node ) ; emitLinesStartingAt ( node . statements , startIndex ) ; emitTempDeclarations ( /*newLine*/ true ) ; // Emit exportDefault if it exists will happen as part // or normal statement emit. } function emitExportEquals ( emitAsReturn ) { if ( exportEquals && resolver . isValueAliasDeclaration ( exportEquals ) ) { writeLine ( ) ; emitStart ( exportEquals ) ; write ( emitAsReturn ? \"return \" : \"module.exports = \" ) ; emit ( exportEquals . expression ) ; write ( \";\" ) ; emitEnd ( exportEquals ) ; } } function emitJsxElement ( node ) { switch ( compilerOptions . jsx ) { case 2 /* React */ : jsxEmitReact ( node ) ; break ; case 1 /* Preserve */ : // Fall back to preserve if None was specified (we'll error earlier) default : jsxEmitPreserve ( node ) ; break ; } } function trimReactWhitespaceAndApplyEntities ( node ) { var result = undefined ; var text = ts . getTextOfNode ( node , /*includeTrivia*/ true ) ; var firstNonWhitespace = 0 ; var lastNonWhitespace = - 1 ; // JSX trims whitespace at the end and beginning of lines, except that the // start/end of a tag is considered a start/end of a line only if that line is // on the same line as the closing tag. See examples in tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx for ( var i = 0 ; i < text . length ; i ++ ) { var c = text . charCodeAt ( i ) ; if ( ts . isLineBreak ( c ) ) { if ( firstNonWhitespace !== - 1 && ( lastNonWhitespace - firstNonWhitespace + 1 > 0 ) ) { var part = text . substr ( firstNonWhitespace , lastNonWhitespace - firstNonWhitespace + 1 ) ; result = ( result ? result + \"\\\" + ' ' + \\\"\" : \"\" ) + ts . escapeString ( part ) ; } firstNonWhitespace = - 1 ; } else if ( ! ts . isWhiteSpace ( c ) ) { lastNonWhitespace = i ; if ( firstNonWhitespace === - 1 ) { firstNonWhitespace = i ; } } } if ( firstNonWhitespace !== - 1 ) { var part = text . substr ( firstNonWhitespace ) ; result = ( result ? result + \"\\\" + ' ' + \\\"\" : \"\" ) + ts . escapeString ( part ) ; } if ( result ) { // Replace entities like &nbsp; result = result . replace ( / &(\\w+); / g , function ( s , m ) { if ( entities [ m ] !== undefined ) { return String . fromCharCode ( entities [ m ] ) ; } else { return s ; } } ) ; } return result ; } function getTextToEmit ( node ) { switch ( compilerOptions . jsx ) { case 2 /* React */ : var text = trimReactWhitespaceAndApplyEntities ( node ) ; if ( text === undefined || text . length === 0 ) { return undefined ; } else { return text ; } case 1 /* Preserve */ : default : return ts . getTextOfNode ( node , /*includeTrivia*/ true ) ; } } function emitJsxText ( node ) { switch ( compilerOptions . jsx ) { case 2 /* React */ : write ( \"\\\"\" ) ; write ( trimReactWhitespaceAndApplyEntities ( node ) ) ; write ( \"\\\"\" ) ; break ; case 1 /* Preserve */ : default : writer . writeLiteral ( ts . getTextOfNode ( node , /*includeTrivia*/ true ) ) ; break ; } } function emitJsxExpression ( node ) { if ( node . expression ) { switch ( compilerOptions . jsx ) { case 1 /* Preserve */ : default : write ( \"{\" ) ; emit ( node . expression ) ; write ( \"}\" ) ; break ; case 2 /* React */ : emit ( node . expression ) ; break ; } } } function emitDirectivePrologues ( statements , startWithNewLine ) { for ( var i = 0 ; i < statements . length ; ++ i ) { if ( ts . isPrologueDirective ( statements [ i ] ) ) { if ( startWithNewLine || i > 0 ) { writeLine ( ) ; } emit ( statements [ i ] ) ; } else { // return index of the first non prologue directive return i ; } } return statements . length ; } function writeLines ( text ) { var lines = text . split ( / \\r\\n|\\r|\\n / g ) ; for ( var i = 0 ; i < lines . length ; ++ i ) { var line = lines [ i ] ; if ( line . length ) { writeLine ( ) ; write ( line ) ; } } } function emitEmitHelpers ( node ) { // Only emit helpers if the user did not say otherwise. if ( ! compilerOptions . noEmitHelpers ) { // Only Emit __extends function when target ES5. // For target ES6 and above, we can emit classDeclaration as is. if ( ( languageVersion < 2 /* ES6 */ ) && ( ! extendsEmitted && resolver . getNodeCheckFlags ( node ) & 8 /* EmitExtends */ ) ) { writeLines ( extendsHelper ) ; extendsEmitted = true ; } if ( ! decorateEmitted && resolver . getNodeCheckFlags ( node ) & 16 /* EmitDecorate */ ) { writeLines ( decorateHelper ) ; if ( compilerOptions . emitDecoratorMetadata ) { writeLines ( metadataHelper ) ; } decorateEmitted = true ; } if ( ! paramEmitted && resolver . getNodeCheckFlags ( node ) & 32 /* EmitParam */ ) { writeLines ( paramHelper ) ; paramEmitted = true ; } if ( ! awaiterEmitted && resolver . getNodeCheckFlags ( node ) & 64 /* EmitAwaiter */ ) { writeLines ( awaiterHelper ) ; awaiterEmitted = true ; } } } function emitSourceFileNode ( node ) { // Start new file on new line writeLine ( ) ; emitShebang ( ) ; emitDetachedComments ( node ) ; if ( ts . isExternalModule ( node ) || compilerOptions . isolatedModules ) { var emitModule = moduleEmitDelegates [ modulekind ] || moduleEmitDelegates [ 1 /* CommonJS */ ] ; emitModule ( node ) ; } else { // emit prologue directives prior to __extends var startIndex = emitDirectivePrologues ( node . statements , /*startWithNewLine*/ false ) ; externalImports = undefined ; exportSpecifiers = undefined ; exportEquals = undefined ; hasExportStars = false ; emitEmitHelpers ( node ) ; emitCaptureThisForNodeIfNecessary ( node ) ; emitLinesStartingAt ( node . statements , startIndex ) ; emitTempDeclarations ( /*newLine*/ true ) ; } emitLeadingComments ( node . endOfFileToken ) ; } function emitNodeWithCommentsAndWithoutSourcemap ( node ) { emitNodeConsideringCommentsOption ( node , emitNodeWithoutSourceMap ) ; } function emitNodeConsideringCommentsOption ( node , emitNodeConsideringSourcemap ) { if ( node ) { if ( node . flags & 2 /* Ambient */ ) { return emitCommentsOnNotEmittedNode ( node ) ; } if ( isSpecializedCommentHandling ( node ) ) { // This is the node that will handle its own comments and sourcemap return emitNodeWithoutSourceMap ( node ) ; } var emitComments_1 = shouldEmitLeadingAndTrailingComments ( node ) ; if ( emitComments_1 ) { emitLeadingComments ( node ) ; } emitNodeConsideringSourcemap ( node ) ; if ( emitComments_1 ) { emitTrailingComments ( node ) ; } } } function emitNodeWithoutSourceMap ( node ) { if ( node ) { emitJavaScriptWorker ( node ) ; } } function isSpecializedCommentHandling ( node ) { switch ( node . kind ) { // All of these entities are emitted in a specialized fashion.  As such, we allow // the specialized methods for each to handle the comments on the nodes. case 215 /* InterfaceDeclaration */ : case 213 /* FunctionDeclaration */ : case 222 /* ImportDeclaration */ : case 221 /* ImportEqualsDeclaration */ : case 216 /* TypeAliasDeclaration */ : case 227 /* ExportAssignment */ : return true ; } } function shouldEmitLeadingAndTrailingComments ( node ) { switch ( node . kind ) { case 193 /* VariableStatement */ : return shouldEmitLeadingAndTrailingCommentsForVariableStatement ( node ) ; case 218 /* ModuleDeclaration */ : // Only emit the leading/trailing comments for a module if we're actually // emitting the module as well. return shouldEmitModuleDeclaration ( node ) ; case 217 /* EnumDeclaration */ : // Only emit the leading/trailing comments for an enum if we're actually // emitting the module as well. return shouldEmitEnumDeclaration ( node ) ; } // If the node is emitted in specialized fashion, dont emit comments as this node will handle // emitting comments when emitting itself ts . Debug . assert ( ! isSpecializedCommentHandling ( node ) ) ; // If this is the expression body of an arrow function that we're down-leveling, // then we don't want to emit comments when we emit the body.  It will have already // been taken care of when we emitted the 'return' statement for the function // expression body. if ( node . kind !== 192 /* Block */ && node . parent && node . parent . kind === 174 /* ArrowFunction */ && node . parent . body === node && compilerOptions . target <= 1 /* ES5 */ ) { return false ; } // Emit comments for everything else. return true ; } function emitJavaScriptWorker ( node ) { // Check if the node can be emitted regardless of the ScriptTarget switch ( node . kind ) { case 69 /* Identifier */ : return emitIdentifier ( node ) ; case 138 /* Parameter */ : return emitParameter ( node ) ; case 143 /* MethodDeclaration */ : case 142 /* MethodSignature */ : return emitMethod ( node ) ; case 145 /* GetAccessor */ : case 146 /* SetAccessor */ : return emitAccessor ( node ) ; case 97 /* ThisKeyword */ : return emitThis ( node ) ; case 95 /* SuperKeyword */ : return emitSuper ( node ) ; case 93 /* NullKeyword */ : return write ( \"null\" ) ; case 99 /* TrueKeyword */ : return write ( \"true\" ) ; case 84 /* FalseKeyword */ : return write ( \"false\" ) ; case 8 /* NumericLiteral */ : case 9 /* StringLiteral */ : case 10 /* RegularExpressionLiteral */ : case 11 /* NoSubstitutionTemplateLiteral */ : case 12 /* TemplateHead */ : case 13 /* TemplateMiddle */ : case 14 /* TemplateTail */ : return emitLiteral ( node ) ; case 183 /* TemplateExpression */ : return emitTemplateExpression ( node ) ; case 190 /* TemplateSpan */ : return emitTemplateSpan ( node ) ; case 233 /* JsxElement */ : case 234 /* JsxSelfClosingElement */ : return emitJsxElement ( node ) ; case 236 /* JsxText */ : return emitJsxText ( node ) ; case 240 /* JsxExpression */ : return emitJsxExpression ( node ) ; case 135 /* QualifiedName */ : return emitQualifiedName ( node ) ; case 161 /* ObjectBindingPattern */ : return emitObjectBindingPattern ( node ) ; case 162 /* ArrayBindingPattern */ : return emitArrayBindingPattern ( node ) ; case 163 /* BindingElement */ : return emitBindingElement ( node ) ; case 164 /* ArrayLiteralExpression */ : return emitArrayLiteral ( node ) ; case 165 /* ObjectLiteralExpression */ : return emitObjectLiteral ( node ) ; case 245 /* PropertyAssignment */ : return emitPropertyAssignment ( node ) ; case 246 /* ShorthandPropertyAssignment */ : return emitShorthandPropertyAssignment ( node ) ; case 136 /* ComputedPropertyName */ : return emitComputedPropertyName ( node ) ; case 166 /* PropertyAccessExpression */ : return emitPropertyAccess ( node ) ; case 167 /* ElementAccessExpression */ : return emitIndexedAccess ( node ) ; case 168 /* CallExpression */ : return emitCallExpression ( node ) ; case 169 /* NewExpression */ : return emitNewExpression ( node ) ; case 170 /* TaggedTemplateExpression */ : return emitTaggedTemplateExpression ( node ) ; case 171 /* TypeAssertionExpression */ : return emit ( node . expression ) ; case 189 /* AsExpression */ : return emit ( node . expression ) ; case 172 /* ParenthesizedExpression */ : return emitParenExpression ( node ) ; case 213 /* FunctionDeclaration */ : case 173 /* FunctionExpression */ : case 174 /* ArrowFunction */ : return emitFunctionDeclaration ( node ) ; case 175 /* DeleteExpression */ : return emitDeleteExpression ( node ) ; case 176 /* TypeOfExpression */ : return emitTypeOfExpression ( node ) ; case 177 /* VoidExpression */ : return emitVoidExpression ( node ) ; case 178 /* AwaitExpression */ : return emitAwaitExpression ( node ) ; case 179 /* PrefixUnaryExpression */ : return emitPrefixUnaryExpression ( node ) ; case 180 /* PostfixUnaryExpression */ : return emitPostfixUnaryExpression ( node ) ; case 181 /* BinaryExpression */ : return emitBinaryExpression ( node ) ; case 182 /* ConditionalExpression */ : return emitConditionalExpression ( node ) ; case 185 /* SpreadElementExpression */ : return emitSpreadElementExpression ( node ) ; case 184 /* YieldExpression */ : return emitYieldExpression ( node ) ; case 187 /* OmittedExpression */ : return ; case 192 /* Block */ : case 219 /* ModuleBlock */ : return emitBlock ( node ) ; case 193 /* VariableStatement */ : return emitVariableStatement ( node ) ; case 194 /* EmptyStatement */ : return write ( \";\" ) ; case 195 /* ExpressionStatement */ : return emitExpressionStatement ( node ) ; case 196 /* IfStatement */ : return emitIfStatement ( node ) ; case 197 /* DoStatement */ : return emitDoStatement ( node ) ; case 198 /* WhileStatement */ : return emitWhileStatement ( node ) ; case 199 /* ForStatement */ : return emitForStatement ( node ) ; case 201 /* ForOfStatement */ : case 200 /* ForInStatement */ : return emitForInOrForOfStatement ( node ) ; case 202 /* ContinueStatement */ : case 203 /* BreakStatement */ : return emitBreakOrContinueStatement ( node ) ; case 204 /* ReturnStatement */ : return emitReturnStatement ( node ) ; case 205 /* WithStatement */ : return emitWithStatement ( node ) ; case 206 /* SwitchStatement */ : return emitSwitchStatement ( node ) ; case 241 /* CaseClause */ : case 242 /* DefaultClause */ : return emitCaseOrDefaultClause ( node ) ; case 207 /* LabeledStatement */ : return emitLabelledStatement ( node ) ; case 208 /* ThrowStatement */ : return emitThrowStatement ( node ) ; case 209 /* TryStatement */ : return emitTryStatement ( node ) ; case 244 /* CatchClause */ : return emitCatchClause ( node ) ; case 210 /* DebuggerStatement */ : return emitDebuggerStatement ( node ) ; case 211 /* VariableDeclaration */ : return emitVariableDeclaration ( node ) ; case 186 /* ClassExpression */ : return emitClassExpression ( node ) ; case 214 /* ClassDeclaration */ : return emitClassDeclaration ( node ) ; case 215 /* InterfaceDeclaration */ : return emitInterfaceDeclaration ( node ) ; case 217 /* EnumDeclaration */ : return emitEnumDeclaration ( node ) ; case 247 /* EnumMember */ : return emitEnumMember ( node ) ; case 218 /* ModuleDeclaration */ : return emitModuleDeclaration ( node ) ; case 222 /* ImportDeclaration */ : return emitImportDeclaration ( node ) ; case 221 /* ImportEqualsDeclaration */ : return emitImportEqualsDeclaration ( node ) ; case 228 /* ExportDeclaration */ : return emitExportDeclaration ( node ) ; case 227 /* ExportAssignment */ : return emitExportAssignment ( node ) ; case 248 /* SourceFile */ : return emitSourceFileNode ( node ) ; } } function hasDetachedComments ( pos ) { return detachedCommentsInfo !== undefined && ts . lastOrUndefined ( detachedCommentsInfo ) . nodePos === pos ; } function getLeadingCommentsWithoutDetachedComments ( ) { // get the leading comments from detachedPos var leadingComments = ts . getLeadingCommentRanges ( currentSourceFile . text , ts . lastOrUndefined ( detachedCommentsInfo ) . detachedCommentEndPos ) ; if ( detachedCommentsInfo . length - 1 ) { detachedCommentsInfo . pop ( ) ; } else { detachedCommentsInfo = undefined ; } return leadingComments ; } function isPinnedComments ( comment ) { return currentSourceFile . text . charCodeAt ( comment . pos + 1 ) === 42 /* asterisk */ && currentSourceFile . text . charCodeAt ( comment . pos + 2 ) === 33 /* exclamation */ ; } /**\n             * Determine if the given comment is a triple-slash\n             *\n             * @return true if the comment is a triple-slash comment else false\n             **/ function isTripleSlashComment ( comment ) { // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text // so that we don't end up computing comment string and doing match for all // comments if ( currentSourceFile . text . charCodeAt ( comment . pos + 1 ) === 47 /* slash */ && comment . pos + 2 < comment . end && currentSourceFile . text . charCodeAt ( comment . pos + 2 ) === 47 /* slash */ ) { var textSubStr = currentSourceFile . text . substring ( comment . pos , comment . end ) ; return textSubStr . match ( ts . fullTripleSlashReferencePathRegEx ) || textSubStr . match ( ts . fullTripleSlashAMDReferencePathRegEx ) ? true : false ; } return false ; } function getLeadingCommentsToEmit ( node ) { // Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments if ( node . parent ) { if ( node . parent . kind === 248 /* SourceFile */ || node . pos !== node . parent . pos ) { if ( hasDetachedComments ( node . pos ) ) { // get comments without detached comments return getLeadingCommentsWithoutDetachedComments ( ) ; } else { // get the leading comments from the node return ts . getLeadingCommentRangesOfNode ( node , currentSourceFile ) ; } } } } function getTrailingCommentsToEmit ( node ) { // Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments if ( node . parent ) { if ( node . parent . kind === 248 /* SourceFile */ || node . end !== node . parent . end ) { return ts . getTrailingCommentRanges ( currentSourceFile . text , node . end ) ; } } } /**\n             * Emit comments associated with node that will not be emitted into JS file\n             */ function emitCommentsOnNotEmittedNode ( node ) { emitLeadingCommentsWorker ( node , /*isEmittedNode:*/ false ) ; } function emitLeadingComments ( node ) { return emitLeadingCommentsWorker ( node , /*isEmittedNode:*/ true ) ; } function emitLeadingCommentsWorker ( node , isEmittedNode ) { if ( compilerOptions . removeComments ) { return ; } var leadingComments ; if ( isEmittedNode ) { leadingComments = getLeadingCommentsToEmit ( node ) ; } else { // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, // unless it is a triple slash comment at the top of the file. // For Example: //      /// <reference-path ...> //      declare var x; //      /// <reference-path ...> //      interface F {} //  The first /// will NOT be removed while the second one will be removed eventhough both node will not be emitted if ( node . pos === 0 ) { leadingComments = ts . filter ( getLeadingCommentsToEmit ( node ) , isTripleSlashComment ) ; } } ts . emitNewLineBeforeLeadingComments ( currentSourceFile , writer , node , leadingComments ) ; // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space ts . emitComments ( currentSourceFile , writer , leadingComments , /*trailingSeparator:*/ true , newLine , writeComment ) ; } function emitTrailingComments ( node ) { if ( compilerOptions . removeComments ) { return ; } // Emit the trailing comments only if the parent's end doesn't match var trailingComments = getTrailingCommentsToEmit ( node ) ; // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ ts . emitComments ( currentSourceFile , writer , trailingComments , /*trailingSeparator*/ false , newLine , writeComment ) ; } /**\n             * Emit trailing comments at the position. The term trailing comment is used here to describe following comment:\n             *      x, /comment1/ y\n             *        ^ => pos; the function will emit \"comment1\" in the emitJS\n             */ function emitTrailingCommentsOfPosition ( pos ) { if ( compilerOptions . removeComments ) { return ; } var trailingComments = ts . getTrailingCommentRanges ( currentSourceFile . text , pos ) ; // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ ts . emitComments ( currentSourceFile , writer , trailingComments , /*trailingSeparator*/ true , newLine , writeComment ) ; } function emitLeadingCommentsOfPositionWorker ( pos ) { if ( compilerOptions . removeComments ) { return ; } var leadingComments ; if ( hasDetachedComments ( pos ) ) { // get comments without detached comments leadingComments = getLeadingCommentsWithoutDetachedComments ( ) ; } else { // get the leading comments from the node leadingComments = ts . getLeadingCommentRanges ( currentSourceFile . text , pos ) ; } ts . emitNewLineBeforeLeadingComments ( currentSourceFile , writer , { pos : pos , end : pos } , leadingComments ) ; // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space ts . emitComments ( currentSourceFile , writer , leadingComments , /*trailingSeparator*/ true , newLine , writeComment ) ; } function emitDetachedComments ( node ) { var leadingComments ; if ( compilerOptions . removeComments ) { // removeComments is true, only reserve pinned comment at the top of file // For example: //      /*! Pinned Comment */ // //      var x = 10; if ( node . pos === 0 ) { leadingComments = ts . filter ( ts . getLeadingCommentRanges ( currentSourceFile . text , node . pos ) , isPinnedComments ) ; } } else { // removeComments is false, just get detached as normal and bypass the process to filter comment leadingComments = ts . getLeadingCommentRanges ( currentSourceFile . text , node . pos ) ; } if ( leadingComments ) { var detachedComments = [ ] ; var lastComment ; ts . forEach ( leadingComments , function ( comment ) { if ( lastComment ) { var lastCommentLine = ts . getLineOfLocalPosition ( currentSourceFile , lastComment . end ) ; var commentLine = ts . getLineOfLocalPosition ( currentSourceFile , comment . pos ) ; if ( commentLine >= lastCommentLine + 2 ) { // There was a blank line between the last comment and this comment.  This // comment is not part of the copyright comments.  Return what we have so // far. return detachedComments ; } } detachedComments . push ( comment ) ; lastComment = comment ; } ) ; if ( detachedComments . length ) { // All comments look like they could have been part of the copyright header.  Make // sure there is at least one blank line between it and the node.  If not, it's not // a copyright header. var lastCommentLine = ts . getLineOfLocalPosition ( currentSourceFile , ts . lastOrUndefined ( detachedComments ) . end ) ; var nodeLine = ts . getLineOfLocalPosition ( currentSourceFile , ts . skipTrivia ( currentSourceFile . text , node . pos ) ) ; if ( nodeLine >= lastCommentLine + 2 ) { // Valid detachedComments ts . emitNewLineBeforeLeadingComments ( currentSourceFile , writer , node , leadingComments ) ; ts . emitComments ( currentSourceFile , writer , detachedComments , /*trailingSeparator*/ true , newLine , writeComment ) ; var currentDetachedCommentInfo = { nodePos : node . pos , detachedCommentEndPos : ts . lastOrUndefined ( detachedComments ) . end } ; if ( detachedCommentsInfo ) { detachedCommentsInfo . push ( currentDetachedCommentInfo ) ; } else { detachedCommentsInfo = [ currentDetachedCommentInfo ] ; } } } } } function emitShebang ( ) { var shebang = ts . getShebang ( currentSourceFile . text ) ; if ( shebang ) { write ( shebang ) ; } } var _a ; } function emitFile ( jsFilePath , sourceFile ) { emitJavaScript ( jsFilePath , sourceFile ) ; if ( compilerOptions . declaration ) { ts . writeDeclarationFile ( jsFilePath , sourceFile , host , resolver , diagnostics ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the next available name in the pattern _a ... _z _0 _1 ... TempFlags . _i or TempFlags . _n may be used to express a preference for that dedicated name . Note that names generated by makeTempVariableName and makeUniqueName will never conflict . [CODESPLIT] function makeTempVariableName ( flags ) { if ( flags && ! ( tempFlags & flags ) ) { var name_19 = flags === 268435456 /* _i */ ? \"_i\" : \"_n\" ; if ( isUniqueName ( name_19 ) ) { tempFlags |= flags ; return name_19 ; } } while ( true ) { var count = tempFlags & 268435455 /* CountMask */ ; tempFlags ++ ; // Skip over 'i' and 'n' if ( count !== 8 && count !== 13 ) { var name_20 = count < 26 ? \"_\" + String . fromCharCode ( 97 /* a */ + count ) : \"_\" + ( count - 26 ) ; if ( isUniqueName ( name_20 ) ) { return name_20 ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a name that is unique within the current file and doesn t conflict with any names in global scope . The name is formed by adding an _n suffix to the specified base name where n is a positive integer . Note that names generated by makeTempVariableName and makeUniqueName are guaranteed to never conflict . [CODESPLIT] function makeUniqueName ( baseName ) { // Find the first unique 'name_n', where n is a positive number if ( baseName . charCodeAt ( baseName . length - 1 ) !== 95 /* _ */ ) { baseName += \"_\" ; } var i = 1 ; while ( true ) { var generatedName = baseName + i ; if ( isUniqueName ( generatedName ) ) { return generatedNameSet [ generatedName ] = generatedName ; } i ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encoding for sourcemap span [CODESPLIT] function encodeLastRecordedSourceMapSpan ( ) { if ( ! lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan ) { return ; } var prevEncodedEmittedColumn = lastEncodedSourceMapSpan . emittedColumn ; // Line/Comma delimiters if ( lastEncodedSourceMapSpan . emittedLine === lastRecordedSourceMapSpan . emittedLine ) { // Emit comma to separate the entry if ( sourceMapData . sourceMapMappings ) { sourceMapData . sourceMapMappings += \",\" ; } } else { // Emit line delimiters for ( var encodedLine = lastEncodedSourceMapSpan . emittedLine ; encodedLine < lastRecordedSourceMapSpan . emittedLine ; encodedLine ++ ) { sourceMapData . sourceMapMappings += \";\" ; } prevEncodedEmittedColumn = 1 ; } // 1. Relative Column 0 based sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . emittedColumn - prevEncodedEmittedColumn ) ; // 2. Relative sourceIndex sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . sourceIndex - lastEncodedSourceMapSpan . sourceIndex ) ; // 3. Relative sourceLine 0 based sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . sourceLine - lastEncodedSourceMapSpan . sourceLine ) ; // 4. Relative sourceColumn 0 based sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . sourceColumn - lastEncodedSourceMapSpan . sourceColumn ) ; // 5. Relative namePosition 0 based if ( lastRecordedSourceMapSpan . nameIndex >= 0 ) { sourceMapData . sourceMapMappings += base64VLQFormatEncode ( lastRecordedSourceMapSpan . nameIndex - lastEncodedNameIndex ) ; lastEncodedNameIndex = lastRecordedSourceMapSpan . nameIndex ; } lastEncodedSourceMapSpan = lastRecordedSourceMapSpan ; sourceMapData . sourceMapDecodedMappings . push ( lastEncodedSourceMapSpan ) ; function base64VLQFormatEncode ( inValue ) { function base64FormatEncode ( inValue ) { if ( inValue < 64 ) { return \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" . charAt ( inValue ) ; } throw TypeError ( inValue + \": not a 64 based value\" ) ; } // Add a new least significant bit that has the sign of the value. // if negative number the least significant bit that gets added to the number has value 1 // else least significant bit value that gets added is 0 // eg. -1 changes to binary : 01 [1] => 3 //     +1 changes to binary : 01 [0] => 2 if ( inValue < 0 ) { inValue = ( ( - inValue ) << 1 ) + 1 ; } else { inValue = inValue << 1 ; } // Encode 5 bits at a time starting from least significant bits var encodedStr = \"\" ; do { var currentDigit = inValue & 31 ; // 11111 inValue = inValue >> 5 ; if ( inValue > 0 ) { // There are still more digits to decode, set the msb (6th bit) currentDigit = currentDigit | 32 ; } encodedStr = encodedStr + base64FormatEncode ( currentDigit ) ; } while ( inValue > 0 ) ; return encodedStr ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a temporary variable with a unique unused name . [CODESPLIT] function createTempVariable ( flags ) { var result = ts . createSynthesizedNode ( 69 /* Identifier */ ) ; result . text = makeTempVariableName ( flags ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ Emit a tag name which is either div for lower - cased names or / Div for upper - cased or dotted names [CODESPLIT] function emitTagName ( name ) { if ( name . kind === 69 /* Identifier */ && ts . isIntrinsicJsxName ( name . text ) ) { write ( \"\\\"\" ) ; emit ( name ) ; write ( \"\\\"\" ) ; } else { emit ( name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function specifically handles numeric / string literals for enum and accessor identifiers . In a sense it does not actually emit identifiers as much as it declares a name for a specific property . For example this is utilized when feeding in a result to Object . defineProperty . [CODESPLIT] function emitExpressionForPropertyName ( node ) { ts . Debug . assert ( node . kind !== 163 /* BindingElement */ ) ; if ( node . kind === 9 /* StringLiteral */ ) { emitLiteral ( node ) ; } else if ( node . kind === 136 /* ComputedPropertyName */ ) { // if this is a decorated computed property, we will need to capture the result // of the property expression so that we can apply decorators later. This is to ensure // we don't introduce unintended side effects: // //   class C { //     [_a = x]() { } //   } // // The emit for the decorated computed property decorator is: // //   __decorate([dec], C.prototype, _a, Object.getOwnPropertyDescriptor(C.prototype, _a)); // if ( ts . nodeIsDecorated ( node . parent ) ) { if ( ! computedPropertyNamesToGeneratedNames ) { computedPropertyNamesToGeneratedNames = [ ] ; } var generatedName = computedPropertyNamesToGeneratedNames [ ts . getNodeId ( node ) ] ; if ( generatedName ) { // we have already generated a variable for this node, write that value instead. write ( generatedName ) ; return ; } generatedName = createAndRecordTempVariable ( 0 /* Auto */ ) . text ; computedPropertyNamesToGeneratedNames [ ts . getNodeId ( node ) ] = generatedName ; write ( generatedName ) ; write ( \" = \" ) ; } emit ( node . expression ) ; } else { write ( \"\\\"\" ) ; if ( node . kind === 8 /* NumericLiteral */ ) { write ( node . text ) ; } else { writeTextOfNode ( currentSourceFile , node ) ; } write ( \"\\\"\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the code was actually indented false otherwise . If the code is not indented an optional valueToWriteWhenNotIndenting will be emitted instead . [CODESPLIT] function indentIfOnDifferentLines ( parent , node1 , node2 , valueToWriteWhenNotIndenting ) { var realNodesAreOnDifferentLines = ! ts . nodeIsSynthesized ( parent ) && ! nodeEndIsOnSameLineAsNodeStart ( node1 , node2 ) ; // Always use a newline for synthesized code if the synthesizer desires it. var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine ( node2 ) ; if ( realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine ) { increaseIndent ( ) ; writeLine ( ) ; return true ; } else { if ( valueToWriteWhenNotIndenting ) { write ( valueToWriteWhenNotIndenting ) ; } return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Checks if given node is a source file level declaration ( not nested in module / function ) . If isExported is true - then declaration must also be exported . This function is used in two cases : - check if node is a exported source file level value to determine if we should also export the value after its it changed - check if node is a source level declaration to emit it differently i . e non - exported variable statement var x = 1 is hoisted so we we emit variable statement var should be dropped . [CODESPLIT] function isSourceFileLevelDeclarationInSystemJsModule ( node , isExported ) { if ( ! node || languageVersion >= 2 /* ES6 */ || ! isCurrentFileSystemExternalModule ( ) ) { return false ; } var current = node ; while ( current ) { if ( current . kind === 248 /* SourceFile */ ) { return ! isExported || ( ( ts . getCombinedNodeFlags ( node ) & 1 /* Export */ ) !== 0 ) ; } else if ( ts . isFunctionLike ( current ) || current . kind === 219 /* ModuleBlock */ ) { return false ; } else { current = current . parent ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Emit ES7 exponentiation operator downlevel using Math . pow [CODESPLIT] function emitExponentiationOperator ( node ) { var leftHandSideExpression = node . left ; if ( node . operatorToken . kind === 60 /* AsteriskAsteriskEqualsToken */ ) { var synthesizedLHS ; var shouldEmitParentheses = false ; if ( ts . isElementAccessExpression ( leftHandSideExpression ) ) { shouldEmitParentheses = true ; write ( \"(\" ) ; synthesizedLHS = ts . createSynthesizedNode ( 167 /* ElementAccessExpression */ , /*startsOnNewLine*/ false ) ; var identifier = emitTempVariableAssignment ( leftHandSideExpression . expression , /*canDefinedTempVariablesInPlaces*/ false , /*shouldEmitCommaBeforeAssignment*/ false ) ; synthesizedLHS . expression = identifier ; if ( leftHandSideExpression . argumentExpression . kind !== 8 /* NumericLiteral */ && leftHandSideExpression . argumentExpression . kind !== 9 /* StringLiteral */ ) { var tempArgumentExpression = createAndRecordTempVariable ( 268435456 /* _i */ ) ; synthesizedLHS . argumentExpression = tempArgumentExpression ; emitAssignment ( tempArgumentExpression , leftHandSideExpression . argumentExpression , /*shouldEmitCommaBeforeAssignment*/ true ) ; } else { synthesizedLHS . argumentExpression = leftHandSideExpression . argumentExpression ; } write ( \", \" ) ; } else if ( ts . isPropertyAccessExpression ( leftHandSideExpression ) ) { shouldEmitParentheses = true ; write ( \"(\" ) ; synthesizedLHS = ts . createSynthesizedNode ( 166 /* PropertyAccessExpression */ , /*startsOnNewLine*/ false ) ; var identifier = emitTempVariableAssignment ( leftHandSideExpression . expression , /*canDefinedTempVariablesInPlaces*/ false , /*shouldemitCommaBeforeAssignment*/ false ) ; synthesizedLHS . expression = identifier ; synthesizedLHS . dotToken = leftHandSideExpression . dotToken ; synthesizedLHS . name = leftHandSideExpression . name ; write ( \", \" ) ; } emit ( synthesizedLHS || leftHandSideExpression ) ; write ( \" = \" ) ; write ( \"Math.pow(\" ) ; emit ( synthesizedLHS || leftHandSideExpression ) ; write ( \", \" ) ; emit ( node . right ) ; write ( \")\" ) ; if ( shouldEmitParentheses ) { write ( \")\" ) ; } } else { write ( \"Math.pow(\" ) ; emit ( leftHandSideExpression ) ; write ( \", \" ) ; emit ( node . right ) ; write ( \")\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if start of variable declaration list was emitted . Returns false if nothing was written - this can happen for source file level variable declarations in system modules where such variable declarations are hoisted . [CODESPLIT] function tryEmitStartOfVariableDeclarationList ( decl , startPos ) { if ( shouldHoistVariable ( decl , /*checkIfSourceFileLevelDecl*/ true ) ) { // variables in variable declaration list were already hoisted return false ; } var tokenKind = 102 /* VarKeyword */ ; if ( decl && languageVersion >= 2 /* ES6 */ ) { if ( ts . isLet ( decl ) ) { tokenKind = 108 /* LetKeyword */ ; } else if ( ts . isConst ( decl ) ) { tokenKind = 74 /* ConstKeyword */ ; } } if ( startPos !== undefined ) { emitToken ( tokenKind , startPos ) ; write ( \" \" ) ; } else { switch ( tokenKind ) { case 102 /* VarKeyword */ : write ( \"var \" ) ; break ; case 108 /* LetKeyword */ : write ( \"let \" ) ; break ; case 74 /* ConstKeyword */ : write ( \"const \" ) ; break ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Emit an assignment to a given identifier name with a given expression value . [CODESPLIT] function emitAssignment ( name , value , shouldEmitCommaBeforeAssignment ) { if ( shouldEmitCommaBeforeAssignment ) { write ( \", \" ) ; } var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule ( name ) ; if ( exportChanged ) { write ( exportFunctionForFile + \"(\\\"\" ) ; emitNodeWithCommentsAndWithoutSourcemap ( name ) ; write ( \"\\\", \" ) ; } var isVariableDeclarationOrBindingElement = name . parent && ( name . parent . kind === 211 /* VariableDeclaration */ || name . parent . kind === 163 /* BindingElement */ ) ; if ( isVariableDeclarationOrBindingElement ) { emitModuleMemberName ( name . parent ) ; } else { emit ( name ) ; } write ( \" = \" ) ; emit ( value ) ; if ( exportChanged ) { write ( \")\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create temporary variable emit an assignment of the variable the given expression [CODESPLIT] function emitTempVariableAssignment ( expression , canDefineTempVariablesInPlace , shouldEmitCommaBeforeAssignment ) { var identifier = createTempVariable ( 0 /* Auto */ ) ; if ( ! canDefineTempVariablesInPlace ) { recordTempDeclaration ( identifier ) ; } emitAssignment ( identifier , expression , shouldEmitCommaBeforeAssignment ) ; return identifier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that there exists a declared identifier whose value holds the given expression . This function is useful to ensure that the expression s value can be read from in subsequent expressions . Unless reuseIdentifierExpressions is false expr will be returned if it is just an identifier . [CODESPLIT] function ensureIdentifier ( expr , reuseIdentifierExpressions ) { if ( expr . kind === 69 /* Identifier */ && reuseIdentifierExpressions ) { return expr ; } var identifier = emitTempVariableAssignment ( expr , canDefineTempVariablesInPlace , emitCount > 0 ) ; emitCount ++ ; return identifier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes the type of a declaration to an appropriate JS constructor value . Used by the __metadata decorator for a class member . [CODESPLIT] function emitSerializedTypeOfNode ( node ) { // serialization of the type of a declaration uses the following rules: // // * The serialized type of a ClassDeclaration is \"Function\" // * The serialized type of a ParameterDeclaration is the serialized type of its type annotation. // * The serialized type of a PropertyDeclaration is the serialized type of its type annotation. // * The serialized type of an AccessorDeclaration is the serialized type of the return type annotation of its getter or parameter type annotation of its setter. // * The serialized type of any other FunctionLikeDeclaration is \"Function\". // * The serialized type of any other node is \"void 0\". // // For rules on serializing type annotations, see `serializeTypeNode`. switch ( node . kind ) { case 214 /* ClassDeclaration */ : write ( \"Function\" ) ; return ; case 141 /* PropertyDeclaration */ : emitSerializedTypeNode ( node . type ) ; return ; case 138 /* Parameter */ : emitSerializedTypeNode ( node . type ) ; return ; case 145 /* GetAccessor */ : emitSerializedTypeNode ( node . type ) ; return ; case 146 /* SetAccessor */ : emitSerializedTypeNode ( ts . getSetAccessorTypeAnnotationNode ( node ) ) ; return ; } if ( ts . isFunctionLike ( node ) ) { write ( \"Function\" ) ; return ; } write ( \"void 0\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes the return type of function . Used by the __metadata decorator for a method . [CODESPLIT] function emitSerializedReturnTypeOfNode ( node ) { if ( node && ts . isFunctionLike ( node ) && node . type ) { emitSerializedTypeNode ( node . type ) ; return ; } write ( \"void 0\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Some bundlers ( SystemJS builder ) sometimes want to rename dependencies . Here we check if alternative name was provided for a given moduleName and return it if possible . [CODESPLIT] function tryRenameExternalModule ( moduleName ) { if ( currentSourceFile . renamedDependencies && ts . hasProperty ( currentSourceFile . renamedDependencies , moduleName . text ) ) { return \"\\\"\" + currentSourceFile . renamedDependencies [ moduleName . text ] + \"\\\"\" ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Emit trailing comments at the position . The term trailing comment is used here to describe following comment : x / comment1 / y ^ = > pos ; the function will emit comment1 in the emitJS [CODESPLIT] function emitTrailingCommentsOfPosition ( pos ) { if ( compilerOptions . removeComments ) { return ; } var trailingComments = ts . getTrailingCommentRanges ( currentSourceFile . text , pos ) ; // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ ts . emitComments ( currentSourceFile , writer , trailingComments , /*trailingSeparator*/ true , newLine , writeComment ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get source file from normalized fileName [CODESPLIT] function findSourceFile ( fileName , isDefaultLib , refFile , refPos , refEnd ) { if ( filesByName . contains ( fileName ) ) { // We've already looked for this file, use cached result return getSourceFileFromCache ( fileName , /*useAbsolutePath*/ false ) ; } var normalizedAbsolutePath = ts . getNormalizedAbsolutePath ( fileName , host . getCurrentDirectory ( ) ) ; if ( filesByName . contains ( normalizedAbsolutePath ) ) { var file_1 = getSourceFileFromCache ( normalizedAbsolutePath , /*useAbsolutePath*/ true ) ; // we don't have resolution for this relative file name but the match was found by absolute file name // store resolution for relative name as well filesByName . set ( fileName , file_1 ) ; return file_1 ; } // We haven't looked for this file, do so now and cache result var file = host . getSourceFile ( fileName , options . target , function ( hostErrorMessage ) { if ( refFile !== undefined && refPos !== undefined && refEnd !== undefined ) { fileProcessingDiagnostics . add ( ts . createFileDiagnostic ( refFile , refPos , refEnd - refPos , ts . Diagnostics . Cannot_read_file_0_Colon_1 , fileName , hostErrorMessage ) ) ; } else { fileProcessingDiagnostics . add ( ts . createCompilerDiagnostic ( ts . Diagnostics . Cannot_read_file_0_Colon_1 , fileName , hostErrorMessage ) ) ; } } ) ; filesByName . set ( fileName , file ) ; if ( file ) { skipDefaultLib = skipDefaultLib || file . hasNoDefaultLib ; // Set the source file for normalized absolute path filesByName . set ( normalizedAbsolutePath , file ) ; var basePath = ts . getDirectoryPath ( fileName ) ; if ( ! options . noResolve ) { processReferencedFiles ( file , basePath ) ; } // always process imported modules to record module name resolutions processImportedModules ( file , basePath ) ; if ( isDefaultLib ) { file . isDefaultLib = true ; files . unshift ( file ) ; } else { files . push ( file ) ; } } return file ; function getSourceFileFromCache ( fileName , useAbsolutePath ) { var file = filesByName . get ( fileName ) ; if ( file && host . useCaseSensitiveFileNames ( ) ) { var sourceFileName = useAbsolutePath ? ts . getNormalizedAbsolutePath ( file . fileName , host . getCurrentDirectory ( ) ) : file . fileName ; if ( ts . normalizeSlashes ( fileName ) !== ts . normalizeSlashes ( sourceFileName ) ) { if ( refFile !== undefined && refPos !== undefined && refEnd !== undefined ) { fileProcessingDiagnostics . add ( ts . createFileDiagnostic ( refFile , refPos , refEnd - refPos , ts . Diagnostics . File_name_0_differs_from_already_included_file_name_1_only_in_casing , fileName , sourceFileName ) ) ; } else { fileProcessingDiagnostics . add ( ts . createCompilerDiagnostic ( ts . Diagnostics . File_name_0_differs_from_already_included_file_name_1_only_in_casing , fileName , sourceFileName ) ) ; } } } return file ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function getOptionNameMap ( ) { if ( optionNameMapCache ) { return optionNameMapCache ; } var optionNameMap = { } ; var shortOptionNames = { } ; ts . forEach ( ts . optionDeclarations , function ( option ) { optionNameMap [ option . name . toLowerCase ( ) ] = option ; if ( option . shortName ) { shortOptionNames [ option . shortName ] = option . name ; } } ) ; optionNameMapCache = { optionNameMap : optionNameMap , shortOptionNames : shortOptionNames } ; return optionNameMapCache ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read tsconfig . json file [CODESPLIT] function readConfigFile ( fileName , readFile ) { var text = \"\" ; try { text = readFile ( fileName ) ; } catch ( e ) { return { error : ts . createCompilerDiagnostic ( ts . Diagnostics . Cannot_read_file_0_Colon_1 , fileName , e . message ) } ; } return parseConfigFileTextToJson ( fileName , text ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the text of the tsconfig . json file [CODESPLIT] function parseConfigFileTextToJson ( fileName , jsonText ) { try { return { config : / \\S / . test ( jsonText ) ? JSON . parse ( jsonText ) : { } } ; } catch ( e ) { return { error : ts . createCompilerDiagnostic ( ts . Diagnostics . Failed_to_parse_file_0_Colon_1 , fileName , e . message ) } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the contents of a config file ( tsconfig . json ) . [CODESPLIT] function parseJsonConfigFileContent ( json , host , basePath ) { var errors = [ ] ; return { options : getCompilerOptions ( ) , fileNames : getFileNames ( ) , errors : errors } ; function getCompilerOptions ( ) { var options = { } ; var optionNameMap = { } ; ts . forEach ( ts . optionDeclarations , function ( option ) { optionNameMap [ option . name ] = option ; } ) ; var jsonOptions = json [ \"compilerOptions\" ] ; if ( jsonOptions ) { for ( var id in jsonOptions ) { if ( ts . hasProperty ( optionNameMap , id ) ) { var opt = optionNameMap [ id ] ; var optType = opt . type ; var value = jsonOptions [ id ] ; var expectedType = typeof optType === \"string\" ? optType : \"string\" ; if ( typeof value === expectedType ) { if ( typeof optType !== \"string\" ) { var key = value . toLowerCase ( ) ; if ( ts . hasProperty ( optType , key ) ) { value = optType [ key ] ; } else { errors . push ( ts . createCompilerDiagnostic ( opt . error ) ) ; value = 0 ; } } if ( opt . isFilePath ) { value = ts . normalizePath ( ts . combinePaths ( basePath , value ) ) ; if ( value === \"\" ) { value = \".\" ; } } options [ opt . name ] = value ; } else { errors . push ( ts . createCompilerDiagnostic ( ts . Diagnostics . Compiler_option_0_requires_a_value_of_type_1 , id , expectedType ) ) ; } } else { errors . push ( ts . createCompilerDiagnostic ( ts . Diagnostics . Unknown_compiler_option_0 , id ) ) ; } } } return options ; } function getFileNames ( ) { var fileNames = [ ] ; if ( ts . hasProperty ( json , \"files\" ) ) { if ( json [ \"files\" ] instanceof Array ) { fileNames = ts . map ( json [ \"files\" ] , function ( s ) { return ts . combinePaths ( basePath , s ) ; } ) ; } else { errors . push ( ts . createCompilerDiagnostic ( ts . Diagnostics . Compiler_option_0_requires_a_value_of_type_1 , \"files\" , \"Array\" ) ) ; } } else { var exclude = json [ \"exclude\" ] instanceof Array ? ts . map ( json [ \"exclude\" ] , ts . normalizeSlashes ) : undefined ; var sysFiles = host . readDirectory ( basePath , \".ts\" , exclude ) . concat ( host . readDirectory ( basePath , \".tsx\" , exclude ) ) ; for ( var i = 0 ; i < sysFiles . length ; i ++ ) { var name_28 = sysFiles [ i ] ; if ( ts . fileExtensionIs ( name_28 , \".d.ts\" ) ) { var baseName = name_28 . substr ( 0 , name_28 . length - \".d.ts\" . length ) ; if ( ! ts . contains ( sysFiles , baseName + \".tsx\" ) && ! ts . contains ( sysFiles , baseName + \".ts\" ) ) { fileNames . push ( name_28 ) ; } } else if ( ts . fileExtensionIs ( name_28 , \".ts\" ) ) { if ( ! ts . contains ( sysFiles , name_28 + \"x\" ) ) { fileNames . push ( name_28 ) ; } } else { fileNames . push ( name_28 ) ; } } } return fileNames ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like removeComputedProperties but retains the properties with well known symbol names [CODESPLIT] function removeDynamicallyNamedProperties ( node ) { return ts . filter ( node . members , function ( member ) { return ! ts . hasDynamicName ( member ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper function to compare two matches to determine which is better . Matches are first ordered by kind ( so all prefix matches always beat all substring matches ) . Then if the match is a camel case match the relative weights of the match are used to determine which is better ( with a greater weight being better ) . Then if the match is of the same type then a case sensitive match is considered better than an insensitive one . [CODESPLIT] function patternMatchCompareTo ( match1 , match2 ) { return compareType ( match1 , match2 ) || compareCamelCase ( match1 , match2 ) || compareCase ( match1 , match2 ) || comparePunctuation ( match1 , match2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assumes value is already lowercase . [CODESPLIT] function indexOfIgnoringCase ( string , value ) { for ( var i = 0 , n = string . length - value . length ; i <= n ; i ++ ) { if ( startsWithIgnoringCase ( string , value , i ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assumes value is already lowercase . [CODESPLIT] function startsWithIgnoringCase ( string , value , start ) { for ( var i = 0 , n = value . length ; i < n ; i ++ ) { var ch1 = toLowerCase ( string . charCodeAt ( i + start ) ) ; var ch2 = value . charCodeAt ( i ) ; if ( ch1 !== ch2 ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns relevant information for the argument list and the current argument if we are in the argument of an invocation ; returns undefined otherwise . [CODESPLIT] function getImmediatelyContainingArgumentInfo ( node ) { if ( node . parent . kind === 168 /* CallExpression */ || node . parent . kind === 169 /* NewExpression */ ) { var callExpression = node . parent ; // There are 3 cases to handle: //   1. The token introduces a list, and should begin a sig help session //   2. The token is either not associated with a list, or ends a list, so the session should end //   3. The token is buried inside a list, and should give sig help // // The following are examples of each: // //    Case 1: //          foo<#T, U>(#a, b)    -> The token introduces a list, and should begin a sig help session //    Case 2: //          fo#o<T, U>#(a, b)#   -> The token is either not associated with a list, or ends a list, so the session should end //    Case 3: //          foo<T#, U#>(a#, #b#) -> The token is buried inside a list, and should give sig help // Find out if 'node' is an argument, a type argument, or neither if ( node . kind === 25 /* LessThanToken */ || node . kind === 17 /* OpenParenToken */ ) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. var list = getChildListThatStartsWithOpenerToken ( callExpression , node , sourceFile ) ; var isTypeArgList = callExpression . typeArguments && callExpression . typeArguments . pos === list . pos ; ts . Debug . assert ( list !== undefined ) ; return { kind : isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */ , invocation : callExpression , argumentsSpan : getApplicableSpanForArguments ( list ) , argumentIndex : 0 , argumentCount : getArgumentCount ( list ) } ; } // findListItemInfo can return undefined if we are not in parent's argument list // or type argument list. This includes cases where the cursor is: //   - To the right of the closing paren, non-substitution template, or template tail. //   - Between the type arguments and the arguments (greater than token) //   - On the target of the call (parent.func) //   - On the 'new' keyword in a 'new' expression var listItemInfo = ts . findListItemInfo ( node ) ; if ( listItemInfo ) { var list = listItemInfo . list ; var isTypeArgList = callExpression . typeArguments && callExpression . typeArguments . pos === list . pos ; var argumentIndex = getArgumentIndex ( list , node ) ; var argumentCount = getArgumentCount ( list ) ; ts . Debug . assert ( argumentIndex === 0 || argumentIndex < argumentCount , \"argumentCount < argumentIndex, \" + argumentCount + \" < \" + argumentIndex ) ; return { kind : isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */ , invocation : callExpression , argumentsSpan : getApplicableSpanForArguments ( list ) , argumentIndex : argumentIndex , argumentCount : argumentCount } ; } } else if ( node . kind === 11 /* NoSubstitutionTemplateLiteral */ && node . parent . kind === 170 /* TaggedTemplateExpression */ ) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if ( ts . isInsideTemplateLiteral ( node , position ) ) { return getArgumentListInfoForTemplate ( node . parent , /*argumentIndex*/ 0 ) ; } } else if ( node . kind === 12 /* TemplateHead */ && node . parent . parent . kind === 170 /* TaggedTemplateExpression */ ) { var templateExpression = node . parent ; var tagExpression = templateExpression . parent ; ts . Debug . assert ( templateExpression . kind === 183 /* TemplateExpression */ ) ; var argumentIndex = ts . isInsideTemplateLiteral ( node , position ) ? 0 : 1 ; return getArgumentListInfoForTemplate ( tagExpression , argumentIndex ) ; } else if ( node . parent . kind === 190 /* TemplateSpan */ && node . parent . parent . parent . kind === 170 /* TaggedTemplateExpression */ ) { var templateSpan = node . parent ; var templateExpression = templateSpan . parent ; var tagExpression = templateExpression . parent ; ts . Debug . assert ( templateExpression . kind === 183 /* TemplateExpression */ ) ; // If we're just after a template tail, don't show signature help. if ( node . kind === 14 /* TemplateTail */ && ! ts . isInsideTemplateLiteral ( node , position ) ) { return undefined ; } var spanIndex = templateExpression . templateSpans . indexOf ( templateSpan ) ; var argumentIndex = getArgumentIndexForTemplatePiece ( spanIndex , node ) ; return getArgumentListInfoForTemplate ( tagExpression , argumentIndex ) ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The selectedItemIndex could be negative for several reasons . 1 . There are too many arguments for all of the overloads 2 . None of the overloads were type compatible The solution here is to try to pick the best overload by picking either the first one that has an appropriate number of parameters or the one with the most parameters . [CODESPLIT] function selectBestInvalidOverloadIndex ( candidates , argumentCount ) { var maxParamsSignatureIndex = - 1 ; var maxParams = - 1 ; for ( var i = 0 ; i < candidates . length ; i ++ ) { var candidate = candidates [ i ] ; if ( candidate . hasRestParameter || candidate . parameters . length >= argumentCount ) { return i ; } if ( candidate . parameters . length > maxParams ) { maxParams = candidate . parameters . length ; maxParamsSignatureIndex = i ; } } return maxParamsSignatureIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Checks if node ends with expectedLastToken . If child at position length - 1 is SemicolonToken it is skipped and expectedLastToken is compared with child at position length - 2 . [CODESPLIT] function nodeEndsWith ( n , expectedLastToken , sourceFile ) { var children = n . getChildren ( sourceFile ) ; if ( children . length ) { var last = ts . lastOrUndefined ( children ) ; if ( last . kind === expectedLastToken ) { return true ; } else if ( last . kind === 23 /* SemicolonToken */ && children . length !== 1 ) { return children [ children . length - 2 ] . kind === expectedLastToken ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Gets the token whose text has range [ start end ) and position > = start and ( position < end or ( position === end && token is keyword or identifier )) [CODESPLIT] function getTouchingWord ( sourceFile , position ) { return getTouchingToken ( sourceFile , position , function ( n ) { return isWord ( n . kind ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Gets the token whose text has range [ start end ) and position > = start and ( position < end or ( position === end && token is keyword or identifier or numeric \\ string litera )) [CODESPLIT] function getTouchingPropertyName ( sourceFile , position ) { return getTouchingToken ( sourceFile , position , function ( n ) { return isPropertyName ( n . kind ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the token whose text contains the position [CODESPLIT] function getTokenAtPositionWorker ( sourceFile , position , allowPositionInLeadingTrivia , includeItemAtEndPosition ) { var current = sourceFile ; outer : while ( true ) { if ( isToken ( current ) ) { // exit early return current ; } // find the child that contains 'position' for ( var i = 0 , n = current . getChildCount ( sourceFile ) ; i < n ; i ++ ) { var child = current . getChildAt ( i ) ; var start = allowPositionInLeadingTrivia ? child . getFullStart ( ) : child . getStart ( sourceFile ) ; if ( start <= position ) { var end = child . getEnd ( ) ; if ( position < end || ( position === end && child . kind === 1 /* EndOfFileToken */ ) ) { current = child ; continue outer ; } else if ( includeItemAtEndPosition && end === position ) { var previousToken = findPrecedingToken ( position , sourceFile , child ) ; if ( previousToken && includeItemAtEndPosition ( previousToken ) ) { return previousToken ; } } } } return current ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The token on the left of the position is the token that strictly includes the position or sits to the left of the cursor if it is on a boundary . For example [CODESPLIT] function findTokenOnLeftOfPosition ( file , position ) { // Ideally, getTokenAtPosition should return a token. However, it is currently // broken, so we do a check to make sure the result was indeed a token. var tokenAtPosition = getTokenAtPosition ( file , position ) ; if ( isToken ( tokenAtPosition ) && position > tokenAtPosition . getStart ( file ) && position < tokenAtPosition . getEnd ( ) ) { return tokenAtPosition ; } return findPrecedingToken ( position , file ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ finds last node that is considered as candidate for search ( isCandidate ( node ) === true ) starting from exclusiveStartPosition [CODESPLIT] function findRightmostChildNodeWithTokens ( children , exclusiveStartPosition ) { for ( var i = exclusiveStartPosition - 1 ; i >= 0 ; -- i ) { if ( nodeHasTokens ( children [ i ] ) ) { return children [ i ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the corresponding JSDocTag node if the position is in a jsDoc comment [CODESPLIT] function getJsDocTagAtPosition ( sourceFile , position ) { var node = ts . getTokenAtPosition ( sourceFile , position ) ; if ( isToken ( node ) ) { switch ( node . kind ) { case 102 /* VarKeyword */ : case 108 /* LetKeyword */ : case 74 /* ConstKeyword */ : // if the current token is var, let or const, skip the VariableDeclarationList node = node . parent === undefined ? undefined : node . parent . parent ; break ; default : node = node . parent ; break ; } } if ( node ) { var jsDocComment = node . jsDocComment ; if ( jsDocComment ) { for ( var _i = 0 , _a = jsDocComment . tags ; _i < _a . length ; _i ++ ) { var tag = _a [ _i ] ; if ( tag . pos <= position && position <= tag . end ) { return tag ; } } } } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strip off existed single quotes or double quotes from a given string [CODESPLIT] function stripQuotes ( name ) { var length = name . length ; if ( length >= 2 && name . charCodeAt ( 0 ) === name . charCodeAt ( length - 1 ) && ( name . charCodeAt ( 0 ) === 34 /* doubleQuote */ || name . charCodeAt ( 0 ) === 39 /* singleQuote */ ) ) { return name . substring ( 1 , length - 1 ) ; } ; return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "when containing node in the tree is token but its kind differs from the kind that was returned by the scanner then kind needs to be fixed . This might happen in cases when parser interprets token differently i . e keyword treated as identifier [CODESPLIT] function fixTokenKind ( tokenInfo , container ) { if ( ts . isToken ( container ) && tokenInfo . token . kind !== container . kind ) { tokenInfo . token . kind = container . kind ; } return tokenInfo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if node is a element in some list in parent i . e . parent is class declaration with the list of members and node is one of members . [CODESPLIT] function isListElement ( parent , node ) { switch ( parent . kind ) { case 214 /* ClassDeclaration */ : case 215 /* InterfaceDeclaration */ : return ts . rangeContainsRange ( parent . members , node ) ; case 218 /* ModuleDeclaration */ : var body = parent . body ; return body && body . kind === 192 /* Block */ && ts . rangeContainsRange ( body . statements , node ) ; case 248 /* SourceFile */ : case 192 /* Block */ : case 219 /* ModuleBlock */ : return ts . rangeContainsRange ( parent . statements , node ) ; case 244 /* CatchClause */ : return ts . rangeContainsRange ( parent . block . statements , node ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find node that fully contains given text range [CODESPLIT] function findEnclosingNode ( range , sourceFile ) { return find ( sourceFile ) ; function find ( n ) { var candidate = ts . forEachChild ( n , function ( c ) { return ts . startEndContainsRange ( c . getStart ( sourceFile ) , c . end , range ) && c ; } ) ; if ( candidate ) { var result = find ( candidate ) ; if ( result ) { return result ; } } return n ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "formatting is not applied to ranges that contain parse errors . This function will return a predicate that for a given text range will tell if there are any parse errors that overlap with the range . [CODESPLIT] function prepareRangeContainsErrorFunction ( errors , originalRange ) { if ( ! errors . length ) { return rangeHasNoErrors ; } // pick only errors that fall in range var sorted = errors . filter ( function ( d ) { return ts . rangeOverlapsWithStartEnd ( originalRange , d . start , d . start + d . length ) ; } ) . sort ( function ( e1 , e2 ) { return e1 . start - e2 . start ; } ) ; if ( ! sorted . length ) { return rangeHasNoErrors ; } var index = 0 ; return function ( r ) { // in current implementation sequence of arguments [r1, r2...] is monotonically increasing. // 'index' tracks the index of the most recent error that was checked. while ( true ) { if ( index >= sorted . length ) { // all errors in the range were already checked -> no error in specified range return false ; } var error = sorted [ index ] ; if ( r . end <= error . start ) { // specified range ends before the error refered by 'index' - no error in range return false ; } if ( ts . startEndOverlapsWithStartEnd ( r . pos , r . end , error . start , error . start + error . length ) ) { // specified range overlaps with error range return true ; } index ++ ; } } ; function rangeHasNoErrors ( r ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * For cases like if ( a || b ||$ c ) { ... } If we hit Enter at $ we want line b || to be indented . Formatting will be applied to the last two lines . Node that fully encloses these lines is binary expression a || ... . Initial indentation for this node will be 0 . Binary expressions don t introduce new indentation scopes however it is possible that some parent node on the same line does - like if statement in this case . Note that we are considering parents only from the same line with initial node - if parent is on the different line - its delta was already contributed to the initial indentation . [CODESPLIT] function getOwnOrInheritedDelta ( n , options , sourceFile ) { var previousLine = - 1 /* Unknown */ ; var childKind = 0 /* Unknown */ ; while ( n ) { var line = sourceFile . getLineAndCharacterOfPosition ( n . getStart ( sourceFile ) ) . line ; if ( previousLine !== - 1 /* Unknown */ && line !== previousLine ) { break ; } if ( formatting . SmartIndenter . shouldIndentChildNode ( n . kind , childKind ) ) { return options . IndentSize ; } previousLine = line ; childKind = n . kind ; n = n . parent ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Function returns Value . Unknown if indentation cannot be determined [CODESPLIT] function getActualIndentationForListItemBeforeComma ( commaToken , sourceFile , options ) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var commaItemInfo = ts . findListItemInfo ( commaToken ) ; if ( commaItemInfo && commaItemInfo . listItemIndex > 0 ) { return deriveActualIndentationFromList ( commaItemInfo . list . getChildren ( ) , commaItemInfo . listItemIndex - 1 , sourceFile , options ) ; } else { // handle broken code gracefully return - 1 /* Unknown */ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Function returns Value . Unknown if actual indentation for node should not be used ( i . e because node is nested expression ) [CODESPLIT] function getActualIndentationForNode ( current , parent , currentLineAndChar , parentAndChildShareLine , sourceFile , options ) { // actual indentation is used for statements\\declarations if one of cases below is true: // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = ( ts . isDeclaration ( current ) || ts . isStatement ( current ) ) && ( parent . kind === 248 /* SourceFile */ || ! parentAndChildShareLine ) ; if ( ! useActualIndentation ) { return - 1 /* Unknown */ ; } return findColumnForFirstNonWhitespaceCharacterInLine ( currentLineAndChar , sourceFile , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Character is the actual index of the character since the beginning of the line . Column - position of the character after expanding tabs to spaces 0 \\ t2$ value of character for $ is 3 value of column for $ is 6 ( assuming that tab size is 4 ) [CODESPLIT] function findFirstNonWhitespaceCharacterAndColumn ( startPos , endPos , sourceFile , options ) { var character = 0 ; var column = 0 ; for ( var pos = startPos ; pos < endPos ; ++ pos ) { var ch = sourceFile . text . charCodeAt ( pos ) ; if ( ! ts . isWhiteSpace ( ch ) ) { break ; } if ( ch === 9 /* tab */ ) { column += options . TabSize + ( column % options . TabSize ) ; } else { column ++ ; } character ++ ; } return { column : column , character : character } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This function will compile source text from input argument using specified compiler options . If not options are provided - it will use a set of default compiler options . Extra compiler options that will unconditionally be used by this function are : - isolatedModules = true - allowNonTsExtensions = true - noLib = true - noResolve = true [CODESPLIT] function transpileModule ( input , transpileOptions ) { var options = transpileOptions . compilerOptions ? ts . clone ( transpileOptions . compilerOptions ) : getDefaultCompilerOptions ( ) ; options . isolatedModules = true ; // Filename can be non-ts file. options . allowNonTsExtensions = true ; // We are not returning a sourceFile for lib file when asked by the program, // so pass --noLib to avoid reporting a file not found error. options . noLib = true ; // We are not doing a full typecheck, we are not resolving the whole context, // so pass --noResolve to avoid reporting missing file errors. options . noResolve = true ; // if jsx is specified then treat file as .tsx var inputFileName = transpileOptions . fileName || ( options . jsx ? \"module.tsx\" : \"module.ts\" ) ; var sourceFile = ts . createSourceFile ( inputFileName , input , options . target ) ; if ( transpileOptions . moduleName ) { sourceFile . moduleName = transpileOptions . moduleName ; } sourceFile . renamedDependencies = transpileOptions . renamedDependencies ; var newLine = ts . getNewLineCharacter ( options ) ; // Output var outputText ; var sourceMapText ; // Create a compilerHost object to allow the compiler to read and write files var compilerHost = { getSourceFile : function ( fileName , target ) { return fileName === ts . normalizeSlashes ( inputFileName ) ? sourceFile : undefined ; } , writeFile : function ( name , text , writeByteOrderMark ) { if ( ts . fileExtensionIs ( name , \".map\" ) ) { ts . Debug . assert ( sourceMapText === undefined , \"Unexpected multiple source map outputs for the file '\" + name + \"'\" ) ; sourceMapText = text ; } else { ts . Debug . assert ( outputText === undefined , \"Unexpected multiple outputs for the file: \" + name ) ; outputText = text ; } } , getDefaultLibFileName : function ( ) { return \"lib.d.ts\" ; } , useCaseSensitiveFileNames : function ( ) { return false ; } , getCanonicalFileName : function ( fileName ) { return fileName ; } , getCurrentDirectory : function ( ) { return \"\" ; } , getNewLine : function ( ) { return newLine ; } , fileExists : function ( fileName ) { return fileName === inputFileName ; } , readFile : function ( fileName ) { return \"\" ; } } ; var program = ts . createProgram ( [ inputFileName ] , options , compilerHost ) ; var diagnostics ; if ( transpileOptions . reportDiagnostics ) { diagnostics = [ ] ; ts . addRange ( /*to*/ diagnostics , /*from*/ program . getSyntacticDiagnostics ( sourceFile ) ) ; ts . addRange ( /*to*/ diagnostics , /*from*/ program . getOptionsDiagnostics ( ) ) ; } // Emit program . emit ( ) ; ts . Debug . assert ( outputText !== undefined , \"Output generation failed\" ) ; return { outputText : outputText , diagnostics : diagnostics , sourceMapText : sourceMapText } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result . [CODESPLIT] function transpile ( input , compilerOptions , fileName , diagnostics , moduleName ) { var output = transpileModule ( input , { compilerOptions : compilerOptions , fileName : fileName , reportDiagnostics : ! ! diagnostics , moduleName : moduleName } ) ; // addRange correctly handles cases when wither 'from' or 'to' argument is missing ts . addRange ( diagnostics , output . diagnostics ) ; return output . outputText ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ Helpers [CODESPLIT] function getTargetLabel ( referenceNode , labelName ) { while ( referenceNode ) { if ( referenceNode . kind === 207 /* LabeledStatement */ && referenceNode . label . text === labelName ) { return referenceNode . label ; } referenceNode = referenceNode . parent ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if node is a name of an object literal property e . g . a in x = { a : 1 } [CODESPLIT] function isNameOfPropertyAssignment ( node ) { return ( node . kind === 69 /* Identifier */ || node . kind === 9 /* StringLiteral */ || node . kind === 8 /* NumericLiteral */ ) && ( node . parent . kind === 245 /* PropertyAssignment */ || node . parent . kind === 246 /* ShorthandPropertyAssignment */ ) && node . parent . name === node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the position is within a comment [CODESPLIT] function isInsideComment ( sourceFile , token , position ) { // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment return position <= token . getStart ( sourceFile ) && ( isInsideCommentRange ( ts . getTrailingCommentRanges ( sourceFile . text , token . getFullStart ( ) ) ) || isInsideCommentRange ( ts . getLeadingCommentRanges ( sourceFile . text , token . getFullStart ( ) ) ) ) ; function isInsideCommentRange ( comments ) { return ts . forEach ( comments , function ( comment ) { // either we are 1. completely inside the comment, or 2. at the end of the comment if ( comment . pos < position && position < comment . end ) { return true ; } else if ( position === comment . end ) { var text = sourceFile . text ; var width = comment . end - comment . pos ; // is single line comment or just /* if ( width <= 2 || text . charCodeAt ( comment . pos + 1 ) === 47 /* slash */ ) { return true ; } else { // is unterminated multi-line comment return ! ( text . charCodeAt ( comment . end - 1 ) === 47 /* slash */ && text . charCodeAt ( comment . end - 2 ) === 42 /* asterisk */ ) ; } } return false ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getSemanticDiagnostiscs return array of Diagnostics . If - d is not enabled only report semantic errors If - d enabled report both semantic and emitter errors [CODESPLIT] function getSemanticDiagnostics ( fileName ) { synchronizeHostData ( ) ; var targetSourceFile = getValidSourceFile ( fileName ) ; // For JavaScript files, we don't want to report the normal typescript semantic errors. // Instead, we just report errors for using TypeScript-only constructs from within a // JavaScript file. if ( ts . isJavaScript ( fileName ) ) { return getJavaScriptSemanticDiagnostics ( targetSourceFile ) ; } // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program . getSemanticDiagnostics ( targetSourceFile , cancellationToken ) ; if ( ! program . getCompilerOptions ( ) . declaration ) { return semanticDiagnostics ; } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface var declarationDiagnostics = program . getDeclarationDiagnostics ( targetSourceFile , cancellationToken ) ; return ts . concatenate ( semanticDiagnostics , declarationDiagnostics ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a displayName from a given for completion list performing any necessary quotes stripping and checking whether the name is valid identifier name . [CODESPLIT] function getCompletionEntryDisplayName ( name , target , performCharacterChecks ) { if ( ! name ) { return undefined ; } name = ts . stripQuotes ( name ) ; if ( ! name ) { return undefined ; } // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. // e.g \"b a\" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if ( performCharacterChecks ) { if ( ! ts . isIdentifierStart ( name . charCodeAt ( 0 ) , target ) ) { return undefined ; } for ( var i = 1 , n = name . length ; i < n ; i ++ ) { if ( ! ts . isIdentifierPart ( name . charCodeAt ( i ) , target ) ) { return undefined ; } } } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first node that embraces the position so that one may accurately aggregate locals from the closest containing scope . [CODESPLIT] function getScopeNode ( initialToken , position , sourceFile ) { var scope = initialToken ; while ( scope && ! ts . positionBelongsToNode ( scope , position , sourceFile ) ) { scope = scope . parent ; } return scope ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Aggregates relevant symbols for completion in object literals and object binding patterns . Relevant symbols are stored in the captured symbols variable . [CODESPLIT] function tryGetObjectLikeCompletionSymbols ( objectLikeContainer ) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true ; var typeForObject ; var existingMembers ; if ( objectLikeContainer . kind === 165 /* ObjectLiteralExpression */ ) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true ; typeForObject = typeChecker . getContextualType ( objectLikeContainer ) ; existingMembers = objectLikeContainer . properties ; } else if ( objectLikeContainer . kind === 161 /* ObjectBindingPattern */ ) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false ; var rootDeclaration = ts . getRootDeclaration ( objectLikeContainer . parent ) ; if ( ts . isVariableLike ( rootDeclaration ) ) { // We don't want to complete using the type acquired by the shape // of the binding pattern; we are only interested in types acquired // through type declaration or inference. if ( rootDeclaration . initializer || rootDeclaration . type ) { typeForObject = typeChecker . getTypeAtLocation ( objectLikeContainer ) ; existingMembers = objectLikeContainer . elements ; } } else { ts . Debug . fail ( \"Root declaration is not variable-like.\" ) ; } } else { ts . Debug . fail ( \"Expected object literal or binding pattern, got \" + objectLikeContainer . kind ) ; } if ( ! typeForObject ) { return false ; } var typeMembers = typeChecker . getPropertiesOfType ( typeForObject ) ; if ( typeMembers && typeMembers . length > 0 ) { // Add filtered items to the completion list symbols = filterObjectMembersList ( typeMembers , existingMembers ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Aggregates relevant symbols for completion in import clauses and export clauses whose declarations have a module specifier ; for instance symbols will be aggregated for [CODESPLIT] function tryGetImportOrExportClauseCompletionSymbols ( namedImportsOrExports ) { var declarationKind = namedImportsOrExports . kind === 225 /* NamedImports */ ? 222 /* ImportDeclaration */ : 228 /* ExportDeclaration */ ; var importOrExportDeclaration = ts . getAncestor ( namedImportsOrExports , declarationKind ) ; var moduleSpecifier = importOrExportDeclaration . moduleSpecifier ; if ( ! moduleSpecifier ) { return false ; } isMemberCompletion = true ; isNewIdentifierLocation = false ; var exports ; var moduleSpecifierSymbol = typeChecker . getSymbolAtLocation ( importOrExportDeclaration . moduleSpecifier ) ; if ( moduleSpecifierSymbol ) { exports = typeChecker . getExportsOfModule ( moduleSpecifierSymbol ) ; } symbols = exports ? filterNamedImportOrExportCompletionItems ( exports , namedImportsOrExports . elements ) : emptyArray ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the immediate owning object literal or binding pattern of a context token on the condition that one exists and that the context implies completion should be given . [CODESPLIT] function tryGetObjectLikeCompletionContainer ( contextToken ) { if ( contextToken ) { switch ( contextToken . kind ) { case 15 /* OpenBraceToken */ : // let x = { | case 24 /* CommaToken */ : var parent_10 = contextToken . parent ; if ( parent_10 && ( parent_10 . kind === 165 /* ObjectLiteralExpression */ || parent_10 . kind === 161 /* ObjectBindingPattern */ ) ) { return parent_10 ; } break ; } } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters out completion suggestions for named imports or exports . [CODESPLIT] function filterNamedImportOrExportCompletionItems ( exportsOfModule , namedImportsOrExports ) { var exisingImportsOrExports = { } ; for ( var _i = 0 ; _i < namedImportsOrExports . length ; _i ++ ) { var element = namedImportsOrExports [ _i ] ; // If this is the current item we are editing right now, do not filter it out if ( element . getStart ( ) <= position && position <= element . getEnd ( ) ) { continue ; } var name_32 = element . propertyName || element . name ; exisingImportsOrExports [ name_32 . text ] = true ; } if ( ts . isEmpty ( exisingImportsOrExports ) ) { return exportsOfModule ; } return ts . filter ( exportsOfModule , function ( e ) { return ! ts . lookUp ( exisingImportsOrExports , e . name ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters out completion suggestions for named imports or exports . [CODESPLIT] function filterObjectMembersList ( contextualMemberSymbols , existingMembers ) { if ( ! existingMembers || existingMembers . length === 0 ) { return contextualMemberSymbols ; } var existingMemberNames = { } ; for ( var _i = 0 ; _i < existingMembers . length ; _i ++ ) { var m = existingMembers [ _i ] ; // Ignore omitted expressions for missing members if ( m . kind !== 245 /* PropertyAssignment */ && m . kind !== 246 /* ShorthandPropertyAssignment */ && m . kind !== 163 /* BindingElement */ ) { continue ; } // If this is the current item we are editing right now, do not filter it out if ( m . getStart ( ) <= position && position <= m . getEnd ( ) ) { continue ; } var existingName = void 0 ; if ( m . kind === 163 /* BindingElement */ && m . propertyName ) { existingName = m . propertyName . text ; } else { // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. existingName = m . name . text ; } existingMemberNames [ existingName ] = true ; } return ts . filter ( contextualMemberSymbols , function ( m ) { return ! ts . lookUp ( existingMemberNames , m . name ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters out completion suggestions from symbols according to existing JSX attributes . [CODESPLIT] function filterJsxAttributes ( symbols , attributes ) { var seenNames = { } ; for ( var _i = 0 ; _i < attributes . length ; _i ++ ) { var attr = attributes [ _i ] ; // If this is the current item we are editing right now, do not filter it out if ( attr . getStart ( ) <= position && position <= attr . getEnd ( ) ) { continue ; } if ( attr . kind === 238 /* JsxAttribute */ ) { seenNames [ attr . name . text ] = true ; } } return ts . filter ( symbols , function ( a ) { return ! ts . lookUp ( seenNames , a . name ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO ( drosen ) : use contextual SemanticMeaning . [CODESPLIT] function getSymbolKind ( symbol , location ) { var flags = symbol . getFlags ( ) ; if ( flags & 32 /* Class */ ) return ts . getDeclarationOfKind ( symbol , 186 /* ClassExpression */ ) ? ScriptElementKind . localClassElement : ScriptElementKind . classElement ; if ( flags & 384 /* Enum */ ) return ScriptElementKind . enumElement ; if ( flags & 524288 /* TypeAlias */ ) return ScriptElementKind . typeElement ; if ( flags & 64 /* Interface */ ) return ScriptElementKind . interfaceElement ; if ( flags & 262144 /* TypeParameter */ ) return ScriptElementKind . typeParameterElement ; var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar ( symbol , flags , location ) ; if ( result === ScriptElementKind . unknown ) { if ( flags & 262144 /* TypeParameter */ ) return ScriptElementKind . typeParameterElement ; if ( flags & 8 /* EnumMember */ ) return ScriptElementKind . variableElement ; if ( flags & 8388608 /* Alias */ ) return ScriptElementKind . alias ; if ( flags & 1536 /* Module */ ) return ScriptElementKind . moduleElement ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ Goto definition [CODESPLIT] function getDefinitionAtPosition ( fileName , position ) { synchronizeHostData ( ) ; var sourceFile = getValidSourceFile ( fileName ) ; var node = ts . getTouchingPropertyName ( sourceFile , position ) ; if ( ! node ) { return undefined ; } // Labels if ( isJumpStatementTarget ( node ) ) { var labelName = node . text ; var label = getTargetLabel ( node . parent , node . text ) ; return label ? [ createDefinitionInfo ( label , ScriptElementKind . label , labelName , /*containerName*/ undefined ) ] : undefined ; } /// Triple slash reference comments var comment = ts . forEach ( sourceFile . referencedFiles , function ( r ) { return ( r . pos <= position && position < r . end ) ? r : undefined ; } ) ; if ( comment ) { var referenceFile = ts . tryResolveScriptReference ( program , sourceFile , comment ) ; if ( referenceFile ) { return [ { fileName : referenceFile . fileName , textSpan : ts . createTextSpanFromBounds ( 0 , 0 ) , kind : ScriptElementKind . scriptElement , name : comment . fileName , containerName : undefined , containerKind : undefined } ] ; } return undefined ; } var typeChecker = program . getTypeChecker ( ) ; var symbol = typeChecker . getSymbolAtLocation ( node ) ; // Could not find a symbol e.g. node is string or number keyword, // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol if ( ! symbol ) { return undefined ; } // If this is an alias, and the request came at the declaration location // get the aliased symbol instead. This allows for goto def on an import e.g. //   import {A, B} from \"mod\"; // to jump to the implementation directly. if ( symbol . flags & 8388608 /* Alias */ ) { var declaration = symbol . declarations [ 0 ] ; if ( node . kind === 69 /* Identifier */ && node . parent === declaration ) { symbol = typeChecker . getAliasedSymbol ( symbol ) ; } } // Because name in short-hand property assignment has two different meanings: property name and property value, // using go-to-definition at such position should go to the variable declaration of the property value rather than // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. if ( node . parent . kind === 246 /* ShorthandPropertyAssignment */ ) { var shorthandSymbol = typeChecker . getShorthandAssignmentValueSymbol ( symbol . valueDeclaration ) ; if ( ! shorthandSymbol ) { return [ ] ; } var shorthandDeclarations = shorthandSymbol . getDeclarations ( ) ; var shorthandSymbolKind = getSymbolKind ( shorthandSymbol , node ) ; var shorthandSymbolName = typeChecker . symbolToString ( shorthandSymbol ) ; var shorthandContainerName = typeChecker . symbolToString ( symbol . parent , node ) ; return ts . map ( shorthandDeclarations , function ( declaration ) { return createDefinitionInfo ( declaration , shorthandSymbolKind , shorthandSymbolName , shorthandContainerName ) ; } ) ; } return getDefinitionFromSymbol ( symbol , node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Aggregates all throw - statements within this node * without * crossing into function boundaries and try - blocks with catch - clauses . [CODESPLIT] function aggregateOwnedThrowStatements ( node ) { var statementAccumulator = [ ] ; aggregate ( node ) ; return statementAccumulator ; function aggregate ( node ) { if ( node . kind === 208 /* ThrowStatement */ ) { statementAccumulator . push ( node ) ; } else if ( node . kind === 209 /* TryStatement */ ) { var tryStatement = node ; if ( tryStatement . catchClause ) { aggregate ( tryStatement . catchClause ) ; } else { // Exceptions thrown within a try block lacking a catch clause // are \"owned\" in the current context. aggregate ( tryStatement . tryBlock ) ; } if ( tryStatement . finallyBlock ) { aggregate ( tryStatement . finallyBlock ) ; } } else if ( ! ts . isFunctionLike ( node ) ) { ts . forEachChild ( node , aggregate ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For lack of a better name this function takes a throw statement and returns the nearest ancestor that is a try - block ( whose try statement has a catch clause ) function - block or source file . [CODESPLIT] function getThrowStatementOwner ( throwStatement ) { var child = throwStatement ; while ( child . parent ) { var parent_12 = child . parent ; if ( ts . isFunctionBlock ( parent_12 ) || parent_12 . kind === 248 /* SourceFile */ ) { return parent_12 ; } // A throw-statement is only owned by a try-statement if the try-statement has // a catch clause, and if the throw-statement occurs within the try block. if ( parent_12 . kind === 209 /* TryStatement */ ) { var tryStatement = parent_12 ; if ( tryStatement . tryBlock === child && tryStatement . catchClause ) { return child ; } } child = parent_12 ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search within node container for references for a search value where the search value is defined as a tuple of ( searchSymbol searchText searchLocation and searchMeaning ) . searchLocation : a node where the search value [CODESPLIT] function getReferencesInNode ( container , searchSymbol , searchText , searchLocation , searchMeaning , findInStrings , findInComments , result , symbolToIndex ) { var sourceFile = container . getSourceFile ( ) ; var tripleSlashDirectivePrefixRegex = / ^\\/\\/\\/\\s*< / ; var possiblePositions = getPossibleSymbolReferencePositions ( sourceFile , searchText , container . getStart ( ) , container . getEnd ( ) ) ; if ( possiblePositions . length ) { // Build the set of symbols to search for, initially it has only the current symbol var searchSymbols = populateSearchSymbolSet ( searchSymbol , searchLocation ) ; ts . forEach ( possiblePositions , function ( position ) { cancellationToken . throwIfCancellationRequested ( ) ; var referenceLocation = ts . getTouchingPropertyName ( sourceFile , position ) ; if ( ! isValidReferencePosition ( referenceLocation , searchText ) ) { // This wasn't the start of a token.  Check to see if it might be a // match in a comment or string if that's what the caller is asking // for. if ( ( findInStrings && ts . isInString ( sourceFile , position ) ) || ( findInComments && isInNonReferenceComment ( sourceFile , position ) ) ) { // In the case where we're looking inside comments/strings, we don't have // an actual definition.  So just use 'undefined' here.  Features like // 'Rename' won't care (as they ignore the definitions), and features like // 'FindReferences' will just filter out these results. result . push ( { definition : undefined , references : [ { fileName : sourceFile . fileName , textSpan : ts . createTextSpan ( position , searchText . length ) , isWriteAccess : false } ] } ) ; } return ; } if ( ! ( getMeaningFromLocation ( referenceLocation ) & searchMeaning ) ) { return ; } var referenceSymbol = typeChecker . getSymbolAtLocation ( referenceLocation ) ; if ( referenceSymbol ) { var referenceSymbolDeclaration = referenceSymbol . valueDeclaration ; var shorthandValueSymbol = typeChecker . getShorthandAssignmentValueSymbol ( referenceSymbolDeclaration ) ; var relatedSymbol = getRelatedSymbol ( searchSymbols , referenceSymbol , referenceLocation ) ; if ( relatedSymbol ) { var referencedSymbol = getReferencedSymbol ( relatedSymbol ) ; referencedSymbol . references . push ( getReferenceEntryFromNode ( referenceLocation ) ) ; } else if ( ! ( referenceSymbol . flags & 67108864 /* Transient */ ) && searchSymbols . indexOf ( shorthandValueSymbol ) >= 0 ) { var referencedSymbol = getReferencedSymbol ( shorthandValueSymbol ) ; referencedSymbol . references . push ( getReferenceEntryFromNode ( referenceSymbolDeclaration . name ) ) ; } } } ) ; } return ; function getReferencedSymbol ( symbol ) { var symbolId = ts . getSymbolId ( symbol ) ; var index = symbolToIndex [ symbolId ] ; if ( index === undefined ) { index = result . length ; symbolToIndex [ symbolId ] = index ; result . push ( { definition : getDefinition ( symbol ) , references : [ ] } ) ; } return result [ index ] ; } function isInNonReferenceComment ( sourceFile , position ) { return ts . isInCommentHelper ( sourceFile , position , isNonReferenceComment ) ; function isNonReferenceComment ( c ) { var commentText = sourceFile . text . substring ( c . pos , c . end ) ; return ! tripleSlashDirectivePrefixRegex . test ( commentText ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given an initial searchMeaning extracted from a location widen the search scope based on the declarations of the corresponding symbol . e . g . if we are searching for Foo in value position but Foo references a class then we need to widen the search to include type positions as well . On the contrary if we are searching for Bar in type position and we trace bar to an interface and an uninstantiated module we want to keep the search limited to only types as the two declarations ( interface and uninstantiated module ) do not intersect in any of the three spaces . [CODESPLIT] function getIntersectingMeaningFromDeclarations ( meaning , declarations ) { if ( declarations ) { var lastIterationMeaning ; do { // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module // intersects with the class in the value space. // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning ; for ( var _i = 0 ; _i < declarations . length ; _i ++ ) { var declaration = declarations [ _i ] ; var declarationMeaning = getMeaningFromDeclaration ( declaration ) ; if ( declarationMeaning & meaning ) { meaning |= declarationMeaning ; } } } while ( meaning !== lastIterationMeaning ) ; } return meaning ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment [CODESPLIT] function isWriteAccess ( node ) { if ( node . kind === 69 /* Identifier */ && ts . isDeclarationName ( node ) ) { return true ; } var parent = node . parent ; if ( parent ) { if ( parent . kind === 180 /* PostfixUnaryExpression */ || parent . kind === 179 /* PrefixUnaryExpression */ ) { return true ; } else if ( parent . kind === 181 /* BinaryExpression */ && parent . left === node ) { var operator = parent . operatorToken . kind ; return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */ ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ NavigateTo [CODESPLIT] function getNavigateToItems ( searchValue , maxResultCount ) { synchronizeHostData ( ) ; return ts . NavigateTo . getNavigateToItems ( program , cancellationToken , searchValue , maxResultCount ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signature help This is a semantic operation . [CODESPLIT] function getSignatureHelpItems ( fileName , position ) { synchronizeHostData ( ) ; var sourceFile = getValidSourceFile ( fileName ) ; return ts . SignatureHelp . getSignatureHelpItems ( program , sourceFile , position , cancellationToken ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if there exists a module that introduces entities on the value side . [CODESPLIT] function hasValueSideModule ( symbol ) { return ts . forEach ( symbol . declarations , function ( declaration ) { return declaration . kind === 218 /* ModuleDeclaration */ && ts . getModuleInstanceState ( declaration ) === 1 /* Instantiated */ ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for accurate classification the actual token should be passed in . however for cases like disabled merge code classification we just get the token kind and classify based on that instead . [CODESPLIT] function classifyTokenType ( tokenKind , token ) { if ( ts . isKeyword ( tokenKind ) ) { return 3 /* keyword */ ; } // Special case < and >  If they appear in a generic context they are punctuation, // not operators. if ( tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */ ) { // If the node owning the token has a type argument list or type parameter list, then // we can effectively assume that a '<' and '>' belong to those lists. if ( token && ts . getTypeArgumentOrTypeParameterList ( token . parent ) ) { return 10 /* punctuation */ ; } } if ( ts . isPunctuation ( tokenKind ) ) { if ( token ) { if ( tokenKind === 56 /* EqualsToken */ ) { // the '=' in a variable declaration is special cased here. if ( token . parent . kind === 211 /* VariableDeclaration */ || token . parent . kind === 141 /* PropertyDeclaration */ || token . parent . kind === 138 /* Parameter */ ) { return 5 /* operator */ ; } } if ( token . parent . kind === 181 /* BinaryExpression */ || token . parent . kind === 179 /* PrefixUnaryExpression */ || token . parent . kind === 180 /* PostfixUnaryExpression */ || token . parent . kind === 182 /* ConditionalExpression */ ) { return 5 /* operator */ ; } } return 10 /* punctuation */ ; } else if ( tokenKind === 8 /* NumericLiteral */ ) { return 4 /* numericLiteral */ ; } else if ( tokenKind === 9 /* StringLiteral */ ) { return 6 /* stringLiteral */ ; } else if ( tokenKind === 10 /* RegularExpressionLiteral */ ) { // TODO: we should get another classification type for these literals. return 6 /* stringLiteral */ ; } else if ( ts . isTemplateLiteralKind ( tokenKind ) ) { // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */ ; } else if ( tokenKind === 69 /* Identifier */ ) { if ( token ) { switch ( token . parent . kind ) { case 214 /* ClassDeclaration */ : if ( token . parent . name === token ) { return 11 /* className */ ; } return ; case 137 /* TypeParameter */ : if ( token . parent . name === token ) { return 15 /* typeParameterName */ ; } return ; case 215 /* InterfaceDeclaration */ : if ( token . parent . name === token ) { return 13 /* interfaceName */ ; } return ; case 217 /* EnumDeclaration */ : if ( token . parent . name === token ) { return 12 /* enumName */ ; } return ; case 218 /* ModuleDeclaration */ : if ( token . parent . name === token ) { return 14 /* moduleName */ ; } return ; case 138 /* Parameter */ : if ( token . parent . name === token ) { return 17 /* parameterName */ ; } return ; } } return 2 /* identifier */ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Digs into an an initializer or RHS operand of an assignment operation to get the parameters of an apt signature corresponding to a function expression or a class expression . [CODESPLIT] function getParametersFromRightHandSideOfAssignment ( rightHandSide ) { while ( rightHandSide . kind === 172 /* ParenthesizedExpression */ ) { rightHandSide = rightHandSide . expression ; } switch ( rightHandSide . kind ) { case 173 /* FunctionExpression */ : case 174 /* ArrowFunction */ : return rightHandSide . parameters ; case 186 /* ClassExpression */ : for ( var _i = 0 , _a = rightHandSide . members ; _i < _a . length ; _i ++ ) { var member = _a [ _i ] ; if ( member . kind === 144 /* Constructor */ ) { return member . parameters ; } } break ; } return emptyArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the path of the default library files ( lib . d . ts ) as distributed with the typescript node package . The functionality is not supported if the ts module is consumed outside of a node module . [CODESPLIT] function getDefaultLibFilePath ( options ) { // Check __dirname is defined and that we are on a node.js system. if ( typeof __dirname !== \"undefined\" ) { return __dirname + ts . directorySeparator + ts . getDefaultLibFileName ( options ) ; } throw new Error ( \"getDefaultLibFilePath is only supported when consumed as a node module. \" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tokens : [CODESPLIT] function spanInOpenBraceToken ( node ) { switch ( node . parent . kind ) { case 217 /* EnumDeclaration */ : var enumDeclaration = node . parent ; return spanInNodeIfStartsOnSameLine ( ts . findPrecedingToken ( node . pos , sourceFile , node . parent ) , enumDeclaration . members . length ? enumDeclaration . members [ 0 ] : enumDeclaration . getLastToken ( sourceFile ) ) ; case 214 /* ClassDeclaration */ : var classDeclaration = node . parent ; return spanInNodeIfStartsOnSameLine ( ts . findPrecedingToken ( node . pos , sourceFile , node . parent ) , classDeclaration . members . length ? classDeclaration . members [ 0 ] : classDeclaration . getLastToken ( sourceFile ) ) ; case 220 /* CaseBlock */ : return spanInNodeIfStartsOnSameLine ( node . parent . parent , node . parent . clauses [ 0 ] ) ; } // Default to parent node return spanInNode ( node . parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "** send html css and js for gui [CODESPLIT] async function serveGUI ( url ) { let res , fileType ; const headerContentTypes = { 'html' : 'text/html' , 'js' : 'application/javascript' , 'css' : 'text/css' } const pathname = ( url . pathname === '/' ) ? '/index.html' : url . pathname ; res = await fetch ( 'file://build' + pathname ) ; fileType = pathname . split ( '.' ) . pop ( ) ; if ( res . status === 200 && Object . keys ( headerContentTypes ) . includes ( fileType ) ) { let fileText = await res . text ( ) ; return { data : fileText , status : 200 , contentType : headerContentTypes [ fileType ] } ; } return { data : \"<p>Not found.</p>\" , status : 404 , contentType : \"text/html\" } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "** serve api data ; we only validate fields if query is not coming from the gui [CODESPLIT] async function getGitHubData ( req , url ) { let cacheKey = \"\" , queryString = \"\" ; let reqString = await req . text ( ) ; const client = new GraphQLClient ( 'https://api.github.com/graphql' , { headers : { 'User-Agent' : req . headers . get ( 'User-Agent' ) || app . config . userAgent , 'Authorization' : req . headers . get ( 'Authorization' ) || 'Bearer ' + app . config . userToken } } ) ; //only requests from gui are json; non-gui requests use graphql syntax if ( url . pathname === '/standard' ) { let reqStringJSON = await JSON . parse ( reqString ) ; cacheKey = reqStringJSON . org + \"-\" + reqStringJSON . repo ; queryString = reqStringJSON . query ; } else { queryString = addRequiredQueryFields ( reqString ) ; } const { dataString , status } = await getIssues ( queryString , client , cacheKey ) ; return { data : dataString , status : status , contentType : \"application/json\" } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "** add missing query fields ( if any ) for custom queries ; we need id number title and bodyText to deliver sentiment [CODESPLIT] function addRequiredQueryFields ( query ) { let stringCondensed = query . replace ( / \\s+ / g , \" \" ) ; let starti = stringCondensed . indexOf ( 'node {' ) + 6 ; let endi = stringCondensed . indexOf ( '}' , starti ) ; let currentParams = ( stringCondensed . substring ( starti , endi ) ) . split ( \" \" ) ; const requiredParams = [ \"id\" , \"number\" , \"title\" , \"bodyText\" ] ; requiredParams . forEach ( function ( p ) { if ( ! currentParams . includes ( p ) ) { currentParams . push ( p ) } } ) ; currentParams = currentParams . join ( \" \" ) ; return stringCondensed . substr ( 0 , starti ) + currentParams + stringCondensed . substr ( endi ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "** send user s request to github OR retrieve from cache if possible [CODESPLIT] async function getIssues ( query , client , cacheKey ) { let data , dataString , dataJson , status , cachedResponse = null ; if ( cacheKey ) { cachedResponse = await cache . getString ( cacheKey ) ; } if ( cachedResponse !== null ) { status = 200 ; dataString = cachedResponse ; return { dataString , status } ; } else { //get issue details try { data = await client . request ( query ) ; //query github dataString = await JSON . stringify ( data ) ; dataJson = await JSON . parse ( dataString ) ; dataJson = getSentiment ( dataJson ) ; status = 200 ; } catch ( err ) { //remove github status before returning because it seems to return 200 no matter what dataString = await JSON . stringify ( err ) ; dataJson = await JSON . parse ( dataString ) ; delete dataJson . response . status ; status = 500 ; } dataString = await JSON . stringify ( dataJson ) ; if ( cacheKey && ( status !== 500 ) ) { cache . set ( cacheKey , dataString , 172800 ) ; //cache for 2 days (only non-custom requests) } return { dataString , status } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "** analyze issue ( s ) and stitch sentiment into github response ; return updated response [CODESPLIT] function getSentiment ( response ) { const issuesToEvaluate = response . repository . issues . edges ; for ( let i = issuesToEvaluate . length - 1 ; i >= 0 ; i -- ) { let sent = polarity ( ( issuesToEvaluate [ i ] . node . title + \" \" + issuesToEvaluate [ i ] . node . bodyText ) . split ( \" \" ) ) ; issuesToEvaluate [ i ] . node . sentiment = sent ; } ; return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A fetch function load balancer . Distributes requests to a set of backends ; attempts to send requests to most recently healthy backends using a 2 random ( pick two healthiest randomize which gets requests ) . [CODESPLIT] function balancer ( backends ) { const tracked = backends . map ( ( h ) => { if ( typeof h !== \"function\" ) { throw Error ( \"Backend must be a fetch like function\" ) ; } return { proxy : h , requestCount : 0 , scoredRequestCount : 0 , statuses : Array ( 10 ) , lastError : 0 , healthScore : 1 , errorCount : 0 } ; } ) ; const fn = async function fetchBalancer ( req , init ) { if ( typeof req === \"string\" ) { req = new Request ( req ) ; } const attempted = new Set ( ) ; while ( attempted . size < tracked . length ) { let backend = null ; const [ backendA , backendB ] = chooseBackends ( tracked , attempted ) ; if ( ! backendA ) { return new Response ( \"No backend available\" , { status : 502 } ) ; } if ( ! backendB ) { backend = backendA ; } else { // randomize between 2 good candidates backend = ( Math . floor ( Math . random ( ) * 2 ) == 0 ) ? backendA : backendB ; } const promise = backend . proxy ( req , init ) ; if ( backend . scoredRequestCount != backend . requestCount ) { // fixup score // this should be relatively concurrent with the fetch promise score ( backend ) ; } backend . requestCount += 1 ; attempted . add ( backend ) ; let resp ; try { resp = await promise ; } catch ( e ) { resp = proxyError ; } if ( backend . statuses . length < 10 ) { backend . statuses . push ( resp . status ) ; } else { backend . statuses [ ( backend . requestCount - 1 ) % backend . statuses . length ] = resp . status ; } if ( resp . status >= 500 && resp . status < 600 ) { backend . lastError = Date . now ( ) ; // always recompute score on errors score ( backend ) ; // clear out response to trigger retry if ( canRetry ( req , resp ) ) { continue ; } } return resp ; } return proxyError ; } ; return Object . assign ( fn , { backends : tracked } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compute a backend health score with time + status codes [CODESPLIT] function score ( backend , errorBasis ) { if ( typeof errorBasis !== \"number\" && ! errorBasis ) errorBasis = Date . now ( ) ; const timeSinceError = ( errorBasis - backend . lastError ) ; const statuses = backend . statuses ; const timeWeight = ( backend . lastError === 0 && 0 ) || ( ( timeSinceError < 1000 ) && 1 ) || ( ( timeSinceError < 3000 ) && 0.8 ) || ( ( timeSinceError < 5000 ) && 0.3 ) || ( ( timeSinceError < 10000 ) && 0.1 ) || 0 ; if ( statuses . length == 0 ) return 0 ; let requests = 0 ; let errors = 0 ; for ( let i = 0 ; i < statuses . length ; i ++ ) { const status = statuses [ i ] ; if ( status && ! isNaN ( status ) ) { requests += 1 ; if ( status >= 500 && status < 600 ) { errors += 1 ; } } } const score = ( 1 - ( timeWeight * ( errors / requests ) ) ) ; backend . healthScore = score ; backend . scoredRequestCount = backend . requestCount ; return score ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is just a basic origin http server that lets us control status codes . [CODESPLIT] async function origin ( req , init ) { const url = new URL ( req . url ) const status = parseInt ( url . searchParams . get ( 'status' ) || '200' ) if ( status === 200 ) { return new Response ( ` ${ req . url } ${ new Date ( ) } ` ) } else { return new Response ( ` ${ status } ` , { status : status } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is just a basic origin http server that response to two paths : [CODESPLIT] async function origin ( req , init ) { const url = new URL ( req . url ) switch ( url . pathname ) { case \"/\" : return new Response ( ` ${ new Date ( ) } ` , { headers : { \"Cache-Control\" : \"max-age=600\" } } ) case \"/never-cache\" : return new Response ( ` ${ new Date ( ) } ` ) } return new Response ( \"not found\" , { status : 404 } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ==================================================================== = Compile and minify js generating source maps = ==================================================================== [CODESPLIT] function ( dest , src ) { return gulp . src ( src ) . pipe ( sourcemaps . init ( ) ) . pipe ( concat ( dest ) ) . pipe ( gulp . dest ( path . join ( 'dist' , 'js' ) ) ) . pipe ( uglify ( ) ) . pipe ( rename ( { suffix : '.min' } ) ) . pipe ( sourcemaps . write ( '.' ) ) . pipe ( gulp . dest ( path . join ( 'dist' , 'js' ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is an example of custom transform function [CODESPLIT] function ( element , transform , touch ) { // // use translate both as basis for the new transform: // var t = $drag . TRANSLATE_BOTH ( element , transform , touch ) ; // // Add rotation: // var Dx = touch . distanceX ; var t0 = touch . startTransform ; var sign = Dx < 0 ? - 1 : 1 ; var angle = sign * Math . min ( ( Math . abs ( Dx ) / 700 ) * 30 , 30 ) ; t . rotateZ = angle + ( Math . round ( t0 . rotateZ ) ) ; return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@function initialize @memberOf mobile - angular - ui . core . sharedState~SharedState @description [CODESPLIT] function ( scope , id , options ) { options = options || { } ; var isNewScope = scopes [ scope ] === undefined ; var defaultValue = options . defaultValue ; var exclusionGroup = options . exclusionGroup ; scopes [ scope . $id ] = scopes [ scope . $id ] || [ ] ; scopes [ scope . $id ] . push ( id ) ; if ( ! statusesMeta [ id ] ) { // is a brand new state // not referenced by any // scope currently statusesMeta [ id ] = angular . extend ( { } , options , { references : 1 } ) ; $rootScope . $broadcast ( 'mobile-angular-ui.state.initialized.' + id , defaultValue ) ; if ( defaultValue !== undefined ) { this . setOne ( id , defaultValue ) ; } if ( exclusionGroup ) { // Exclusion groups are sets of statuses references exclusionGroups [ exclusionGroup ] = exclusionGroups [ exclusionGroup ] || { } ; exclusionGroups [ exclusionGroup ] [ id ] = true ; } } else if ( isNewScope ) { // is a new reference from // a different scope statusesMeta [ id ] . references ++ ; } scope . $on ( '$destroy' , function ( ) { var ids = scopes [ scope . $id ] || [ ] ; for ( var i = 0 ; i < ids . length ; i ++ ) { var status = statusesMeta [ ids [ i ] ] ; if ( status . exclusionGroup ) { delete exclusionGroups [ status . exclusionGroup ] [ ids [ i ] ] ; if ( Object . keys ( exclusionGroups [ status . exclusionGroup ] ) . length === 0 ) { delete exclusionGroups [ status . exclusionGroup ] ; } } status . references -- ; if ( status . references <= 0 ) { delete statusesMeta [ ids [ i ] ] ; delete values [ ids [ i ] ] ; $rootScope . $broadcast ( 'mobile-angular-ui.state.destroyed.' + id ) ; } } delete scopes [ scope . $id ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@function setOne @memberOf mobile - angular - ui . core . sharedState~SharedState @description [CODESPLIT] function ( id , value ) { if ( statusesMeta [ id ] !== undefined ) { var prev = values [ id ] ; values [ id ] = value ; if ( prev !== value ) { $rootScope . $broadcast ( 'mobile-angular-ui.state.changed.' + id , value , prev ) ; } return value ; } $log . warn ( 'Warning: Attempt to set uninitialized shared state: ' + id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@function set @memberOf mobile - angular - ui . core . sharedState~SharedState @description [CODESPLIT] function ( idOrMap , value ) { if ( ! idOrMap ) { return ; } else if ( angular . isObject ( idOrMap ) ) { this . setMany ( idOrMap ) ; } else { this . setOne ( idOrMap , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@function turnOn @memberOf mobile - angular - ui . core . sharedState~SharedState @description [CODESPLIT] function ( id ) { // Turns off other statuses belonging to the same exclusion group. var eg = statusesMeta [ id ] && statusesMeta [ id ] . exclusionGroup ; if ( eg ) { var egStatuses = Object . keys ( exclusionGroups [ eg ] ) ; for ( var i = 0 ; i < egStatuses . length ; i ++ ) { var item = egStatuses [ i ] ; if ( item !== id ) { this . turnOff ( item ) ; } } } return this . setOne ( id , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This would make postLink calls happen after ngClick ( and similar ) ones thus intercepting events after them . This will prevent eventual ng - if to detach elements before ng - click fires . [CODESPLIT] function ( elem , attrs ) { var attr = attrs [ directiveName ] ; var needsInterpolation = attr . match ( / \\{\\{ / ) ; var exprFn = function ( $scope ) { var res = attr ; if ( needsInterpolation ) { var interpolateFn = $interpolate ( res ) ; res = interpolateFn ( $scope ) ; } if ( methodName === 'set' ) { res = ( $parse ( res ) ) ( $scope ) ; } return res ; } ; return function ( scope , elem , attrs ) { var callback = function ( ) { var arg = exprFn ( scope ) ; return method . call ( SharedState , arg ) ; } ; uiBindEvent ( scope , elem , attrs . uiTriggers , callback ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@name uiScopeContext @inner @description [CODESPLIT] function ( attr ) { if ( ! attr || attr === '' ) { return [ ] ; } var vars = attr ? attr . trim ( ) . split ( /  *, * / ) : [ ] ; var res = [ ] ; for ( var i = 0 ; i < vars . length ; i ++ ) { var item = vars [ i ] . split ( /  *as * / ) ; if ( item . length > 2 || item . length < 1 ) { throw new Error ( 'Error parsing uiScopeContext=\"' + attr + '\"' ) ; } res . push ( item ) ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill er up! From here down all logic is associated with touch scroll handling elem references the overthrow element in use [CODESPLIT] function ( val ) { inputs = elem . querySelectorAll ( \"textarea, input\" ) ; for ( var i = 0 , il = inputs . length ; i < il ; i ++ ) { inputs [ i ] . style . pointerEvents = val ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill er up! From here down all logic is associated with touch scroll handling elem references the overthrow element in use [CODESPLIT] function ( startEvent , ascend ) { if ( doc . createEvent ) { var newTarget = ( ! ascend || ascend === undefined ) && elem . parentNode || elem . touchchild || elem , tEnd ; if ( newTarget !== elem ) { tEnd = doc . createEvent ( \"HTMLEvents\" ) ; tEnd . initEvent ( \"touchend\" , true , true ) ; elem . dispatchEvent ( tEnd ) ; newTarget . touchchild = elem ; elem = newTarget ; newTarget . dispatchEvent ( startEvent ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill er up! From here down all logic is associated with touch scroll handling elem references the overthrow element in use [CODESPLIT] function ( e ) { // Stop any throw in progress if ( o . intercept ) { o . intercept ( ) ; } // Reset the distance and direction tracking resetVertTracking ( ) ; resetHorTracking ( ) ; elem = o . closest ( e . target ) ; if ( ! elem || elem === docElem || e . touches . length > 1 ) { return ; } setPointers ( \"none\" ) ; var touchStartE = e , scrollT = elem . scrollTop , scrollL = elem . scrollLeft , height = elem . offsetHeight , width = elem . offsetWidth , startY = e . touches [ 0 ] . pageY , startX = e . touches [ 0 ] . pageX , scrollHeight = elem . scrollHeight , scrollWidth = elem . scrollWidth , // Touchmove handler move = function ( e ) { var ty = scrollT + startY - e . touches [ 0 ] . pageY , tx = scrollL + startX - e . touches [ 0 ] . pageX , down = ty >= ( lastTops . length ? lastTops [ 0 ] : 0 ) , right = tx >= ( lastLefts . length ? lastLefts [ 0 ] : 0 ) ; // If there's room to scroll the current container, prevent the default window scroll if ( ( ty > 0 && ty < scrollHeight - height ) || ( tx > 0 && tx < scrollWidth - width ) ) { e . preventDefault ( ) ; } // This bubbling is dumb. Needs a rethink. else { changeScrollTarget ( touchStartE ) ; } // If down and lastDown are inequal, the y scroll has changed direction. Reset tracking. if ( lastDown && down !== lastDown ) { resetVertTracking ( ) ; } // If right and lastRight are inequal, the x scroll has changed direction. Reset tracking. if ( lastRight && right !== lastRight ) { resetHorTracking ( ) ; } // remember the last direction in which we were headed lastDown = down ; lastRight = right ; // set the container's scroll elem . scrollTop = ty ; elem . scrollLeft = tx ; lastTops . unshift ( ty ) ; lastLefts . unshift ( tx ) ; if ( lastTops . length > 3 ) { lastTops . pop ( ) ; } if ( lastLefts . length > 3 ) { lastLefts . pop ( ) ; } } , // Touchend handler end = function ( e ) { // Bring the pointers back setPointers ( \"auto\" ) ; setTimeout ( function ( ) { setPointers ( \"none\" ) ; } , 450 ) ; elem . removeEventListener ( \"touchmove\" , move , false ) ; elem . removeEventListener ( \"touchend\" , end , false ) ; } ; elem . addEventListener ( \"touchmove\" , move , false ) ; elem . addEventListener ( \"touchend\" , end , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "bind function [CODESPLIT] function ( $element , dragOptions , touchOptions ) { $element = angular . element ( $element ) ; dragOptions = dragOptions || { } ; touchOptions = touchOptions || { } ; var startEventHandler = dragOptions . start ; var endEventHandler = dragOptions . end ; var moveEventHandler = dragOptions . move ; var cancelEventHandler = dragOptions . cancel ; var transformEventHandler = dragOptions . transform || this . TRANSLATE_BOTH ; var domElement = $element [ 0 ] ; var tO = $transform . get ( $element ) ; // original transform var rO = domElement . getBoundingClientRect ( ) ; // original bounding rect var tS ; // transform at start var rS ; var moving = false ; var isMoving = function ( ) { return moving ; } ; var cleanup = function ( ) { moving = false ; tS = rS = null ; $element . removeClass ( 'ui-drag-move' ) ; } ; var reset = function ( ) { $transform . set ( domElement , tO ) ; } ; var undo = function ( ) { $transform . set ( domElement , tS || tO ) ; } ; var setup = function ( ) { moving = true ; rS = domElement . getBoundingClientRect ( ) ; tS = $transform . get ( domElement ) ; $element . addClass ( 'ui-drag-move' ) ; } ; var createDragInfo = function ( touch ) { touch = angular . extend ( { } , touch ) ; touch . originalTransform = tO ; touch . originalRect = rO ; touch . startRect = rS ; touch . rect = domElement . getBoundingClientRect ( ) ; touch . startTransform = tS ; touch . transform = $transform . get ( domElement ) ; touch . reset = reset ; touch . undo = undo ; return touch ; } ; var onTouchMove = function ( touch , event ) { // preventDefault no matter what // it is (ie. maybe html5 drag for images or scroll) event . preventDefault ( ) ; // $touch calls start on the first touch // to ensure $drag.start is called only while actually // dragging and not for touches we will bind $drag.start // to the first time move is called if ( isMoving ( ) ) { // drag move touch = createDragInfo ( touch ) ; var transform = transformEventHandler ( $element , angular . extend ( { } , touch . transform ) , touch , event ) ; $transform . set ( domElement , transform ) ; if ( moveEventHandler ) { moveEventHandler ( touch , event ) ; } } else { // drag start setup ( ) ; if ( startEventHandler ) { startEventHandler ( createDragInfo ( touch ) , event ) ; } } } ; var onTouchEnd = function ( touch , event ) { if ( ! isMoving ( ) ) { return ; } // prevents outer swipes event . __UiSwipeHandled__ = true ; touch = createDragInfo ( touch ) ; cleanup ( ) ; if ( endEventHandler ) { endEventHandler ( touch , event ) ; } } ; var onTouchCancel = function ( touch , event ) { if ( ! isMoving ( ) ) { return ; } touch = createDragInfo ( touch ) ; undo ( ) ; // on cancel movement is undoed automatically; cleanup ( ) ; if ( cancelEventHandler ) { cancelEventHandler ( touch , event ) ; } } ; return $touch . bind ( $element , { move : onTouchMove , end : onTouchEnd , cancel : onTouchCancel } , touchOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start to consider only if movement exceeded MOVEMENT_THRESHOLD [CODESPLIT] function ( t ) { var absAngle = abs ( t . angle ) ; absAngle = absAngle >= 90 ? absAngle - 90 : absAngle ; var validDistance = t . total - t . distance <= TURNAROUND_MAX ; var validAngle = absAngle <= ANGLE_THRESHOLD || absAngle >= 90 - ANGLE_THRESHOLD ; var validVelocity = t . averageVelocity >= VELOCITY_THRESHOLD ; return validDistance && validAngle && validVelocity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind swipe gesture handlers for an element . [CODESPLIT] function ( element , eventHandlers , options ) { options = angular . extend ( { } , defaultOptions , options || { } ) ; return $touch . bind ( element , eventHandlers , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TouchInfo is an object containing the following extended informations about any touch event . [CODESPLIT] function ( type , c , t0 , tl ) { // Compute values for new TouchInfo based on coordinates and previus touches. // - c is coords of new touch // - t0 is first touch: useful to compute duration and distance (how far pointer //                    got from first touch) // - tl is last touch: useful to compute velocity and length (total length of the movement) t0 = t0 || { } ; tl = tl || { } ; // timestamps var ts = now ( ) ; var ts0 = t0 . timestamp || ts ; var tsl = tl . timestamp || ts0 ; // coords var x = c . x ; var y = c . y ; var x0 = t0 . x || x ; var y0 = t0 . y || y ; var xl = tl . x || x0 ; var yl = tl . y || y0 ; // total movement var totalXl = tl . totalX || 0 ; var totalYl = tl . totalY || 0 ; var totalX = totalXl + abs ( x - xl ) ; var totalY = totalYl + abs ( y - yl ) ; var total = len ( totalX , totalY ) ; // duration var duration = timediff ( ts , ts0 ) ; var durationl = timediff ( ts , tsl ) ; // distance var dxl = x - xl ; var dyl = y - yl ; var dl = len ( dxl , dyl ) ; var dx = x - x0 ; var dy = y - y0 ; var d = len ( dx , dy ) ; // velocity (px per second) var v = durationl > 0 ? abs ( dl / ( durationl / 1000 ) ) : 0 ; var tv = duration > 0 ? abs ( total / ( duration / 1000 ) ) : 0 ; // main direction: 'LEFT', 'RIGHT', 'TOP', 'BOTTOM' var dir = abs ( dx ) > abs ( dy ) ? ( dx < 0 ? 'LEFT' : 'RIGHT' ) : ( dy < 0 ? 'TOP' : 'BOTTOM' ) ; // angle (angle between distance vector and x axis) // angle will be: //   0 for x > 0 and y = 0 //   90 for y < 0 and x = 0 //   180 for x < 0 and y = 0 //   -90 for y > 0 and x = 0 // //               -90° //                | //                | //                | //   180° --------|-------- 0° //                | //                | //                | //               90° // var angle = dx !== 0 || dy !== 0 ? atan2 ( dy , dx ) * ( 180 / Math . PI ) : null ; angle = angle === - 180 ? 180 : angle ; return { type : type , timestamp : ts , duration : duration , startX : x0 , startY : y0 , prevX : xl , prevY : yl , x : c . x , y : c . y , step : dl , // distance from prev stepX : dxl , stepY : dyl , velocity : v , averageVelocity : tv , distance : d , // distance from start distanceX : dx , distanceY : dy , total : total , // total length of momement, // considering turnaround totalX : totalX , totalY : totalY , direction : dir , angle : angle } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callbacks on touchstart [CODESPLIT] function ( event ) { // don't handle multi-touch if ( event . touches && event . touches . length > 1 ) { return ; } tl = t0 = buildTouchInfo ( 'touchstart' , getCoordinates ( event ) ) ; $movementTarget . on ( moveEvents , onTouchMove ) ; $movementTarget . on ( endEvents , onTouchEnd ) ; if ( cancelEvents ) { $movementTarget . on ( cancelEvents , onTouchCancel ) ; } if ( startEventHandler ) { startEventHandler ( t0 , event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return current element transform matrix in a cross - browser way [CODESPLIT] function ( e ) { e = e . length ? e [ 0 ] : e ; var tr = window . getComputedStyle ( e , null ) . getPropertyValue ( transformProperty ) ; return tr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set current element transform matrix in a cross - browser way [CODESPLIT] function ( elem , value ) { elem = elem . length ? elem [ 0 ] : elem ; elem . style [ styleProperty ] = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recompose a transform from decomposition t and apply it to element e [CODESPLIT] function ( e , t ) { var str = ( typeof t === 'string' ) ? t : this . toCss ( t ) ; setElementTransformProperty ( e , str ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "loader . vue = > module . loaders . vue [CODESPLIT] function ( _path ) { if ( / ^((pre|post)?loader)s? / ig . test ( _path ) ) { return _path . replace ( / ^((pre|post)?loader)s? / ig , 'module.$1s' ) } if ( / ^(plugin)s? / g . test ( _path ) ) { return _path . replace ( / ^(plugin)s? / g , '$1s' ) } return _path }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * istanbul ignore next [CODESPLIT] function ( extend , cooking , options ) { require ( ` ${ extend } ` ) ( cooking , options ) logger . success ( ` ${ extend } ` ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the payload from a JWT [CODESPLIT] function getPayload ( token ) { const payloadBase64 = token . split ( \".\" ) [ 1 ] . replace ( \"-\" , \"+\" ) . replace ( \"_\" , \"/\" ) ; const payloadDecoded = base64 . decode ( payloadBase64 ) ; const payloadObject = JSON . parse ( payloadDecoded ) ; if ( AV . isNumber ( payloadObject . exp ) ) { payloadObject . exp = new Date ( payloadObject . exp * 1000 ) ; } return payloadObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new SDK instance [CODESPLIT] function SDK ( options = { } ) { let token ; let url ; let project = \"_\" ; let localExp ; let tokenExpiryTime = 5 ; if ( options . storage ) { let storedInfo = options . storage . getItem ( \"directus-sdk-js\" ) ; if ( storedInfo ) { storedInfo = JSON . parse ( storedInfo ) ; token = storedInfo . token ; url = storedInfo . url ; project = storedInfo . project ; localExp = storedInfo . localExp ; } } if ( options . token ) { token = options . token ; } if ( options . url ) { url = options . url ; } if ( options . project ) { project = options . project ; } if ( options . localExp ) { localExp = options . localExp ; } if ( options . tokenExpiryTime ) { tokenExpiryTime = options . tokenExpiryTime ; } const SDK = { url : url , token : token , project : project , // The token will contain an expiry time based on the server time // In order to make sure we check the right expiry date, we need to // keep a version that's based on the browser time localExp : localExp , axios : axios . create ( { paramsSerializer : qs . stringify , timeout : 10 * 60 * 1000 // 10 min } ) , refreshInterval : null , onAutoRefreshError : null , onAutoRefreshSuccess : null , // The storage method to use. Has to support getItem and setItem to store and // retrieve the token storage : options . storage || null , // Defaults to 5 minutes. Once the API supports a custom, this option can be used to reflect that tokenExpiryTime : tokenExpiryTime , get payload ( ) { if ( ! AV . isString ( this . token ) ) return null ; return getPayload ( this . token ) ; } , get loggedIn ( ) { if ( AV . isString ( this . token ) && AV . isString ( this . url ) && AV . isString ( this . project ) && AV . isObject ( this . payload ) ) { if ( this . localExp > Date . now ( ) ) { return true ; } } return false ; } , // REQUEST METHODS // ------------------------------------------------------------------------- /**\n     * Directus API request promise\n     * @promise RequestPromise\n     * @fulfill {object} Directus data\n     * @reject {Error} Network error (if no connection to API)\n     * @reject {Error} Directus error (eg not logged in or 404)\n     */ /**\n     * Perform an API request to the Directus API\n     * @param  {string} method      The HTTP method to use\n     * @param  {string} endpoint    The API endpoint to request\n     * @param  {Object} [params={}] The HTTP query parameters (GET only)\n     * @param  {Object} [data={}]   The HTTP request body (non-GET only)\n     * @param  {Boolean} noEnv      Don't use the project in the path\n     * @param  {Boolean} ignoreJson Don't parse the API result into JSON\n     * @return {RequestPromise}\n     */ request ( method , endpoint , params = { } , data = { } , noEnv = false , headers = { } , ignoreJson = false ) { AV . string ( method , \"method\" ) ; AV . string ( endpoint , \"endpoint\" ) ; AV . objectOrEmpty ( params , \"params\" ) ; Array . isArray ( data ) ? AV . arrayOrEmpty ( data , \"data\" ) : AV . objectOrEmpty ( data , \"data\" ) ; AV . string ( this . url , \"this.url\" ) ; let baseURL = ` ${ this . url } ` ; if ( noEnv === false ) { baseURL += ` ${ this . project } ` ; } const requestOptions = { url : endpoint , method , baseURL , params , data } ; if ( this . token && typeof this . token === \"string\" && this . token . length > 0 ) { requestOptions . headers = headers ; requestOptions . headers . Authorization = ` ${ this . token } ` ; } return this . axios . request ( requestOptions ) . then ( res => res . data ) . then ( data => { if ( ! data || data . length === 0 ) return data ; if ( ignoreJson ) return data ; if ( typeof data !== \"object\" ) { try { return JSON . parse ( data ) ; } catch ( error ) { throw { json : true , error , data } ; } } return data ; } ) . catch ( error => { if ( error . response ) { throw error . response . data . error ; } else if ( error . json === true ) { throw { // eslint-disable-line code : - 2 , message : \"API returned invalid JSON\" , error : error . error , data : error . data } ; } else { throw { // eslint-disable-line code : - 1 , message : \"Network Error\" , error } ; } } ) ; } , /**\n     * GET convenience method. Calls the request method for you\n     * @param  {string} endpoint    The endpoint to get\n     * @param  {Object} [params={}] The HTTP query parameters (GET only)\n     * @return {RequestPromise}\n     */ get ( endpoint , params = { } ) { AV . string ( endpoint , \"endpoint\" ) ; AV . objectOrEmpty ( params , \"params\" ) ; return this . request ( \"get\" , endpoint , params ) ; } , /**\n     * POST convenience method. Calls the request method for you\n     * @param  {string} endpoint  The endpoint to get\n     * @param  {Object} [body={}] The HTTP request body\n     * @return {RequestPromise}\n     */ post ( endpoint , body = { } , params = { } ) { AV . string ( endpoint , \"endpoint\" ) ; Array . isArray ( body ) ? AV . arrayOrEmpty ( body , \"body\" ) : AV . objectOrEmpty ( body , \"body\" ) ; return this . request ( \"post\" , endpoint , params , body ) ; } , /**\n     * PATCH convenience method. Calls the request method for you\n     * @param  {string} endpoint  The endpoint to get\n     * @param  {Object} [body={}] The HTTP request body\n     * @return {RequestPromise}\n     */ patch ( endpoint , body = { } , params = { } ) { AV . string ( endpoint , \"endpoint\" ) ; Array . isArray ( body ) ? AV . arrayOrEmpty ( body , \"body\" ) : AV . objectOrEmpty ( body , \"body\" ) ; return this . request ( \"patch\" , endpoint , params , body ) ; } , /**\n     * PATCH convenience method. Calls the request method for you\n     * @param  {string} endpoint  The endpoint to get\n     * @param  {Object} [body={}] The HTTP request body\n     * @return {RequestPromise}\n     */ put ( endpoint , body = { } , params = { } ) { AV . string ( endpoint , \"endpoint\" ) ; Array . isArray ( body ) ? AV . arrayOrEmpty ( body , \"body\" ) : AV . objectOrEmpty ( body , \"body\" ) ; return this . request ( \"put\" , endpoint , params , body ) ; } , /**\n     * PATCH convenience method. Calls the request method for you\n     * @param  {string} endpoint  The endpoint to get\n     * @return {RequestPromise}\n     */ delete ( endpoint ) { AV . string ( endpoint , \"endpoint\" ) ; return this . request ( \"delete\" , endpoint ) ; } , // AUTHENTICATION // ------------------------------------------------------------------------- /**\n     * Logging in promise\n     * @promise LoginPromise\n     * @fulfill {Object} Object containing URL, ENV, and TOKEN\n     * @reject {Error}   Network error (if no connection to API)\n     * @reject {Error}   Directus error (eg not logged in or 404)\n     */ /**\n     * Login to the API.\n     *\n     * Gets a new token from the API and stores it in this.token\n     * @param  {Object} credentials\n     * @param  {String} credentials.email     The user's email address\n     * @param  {String} credentials.password  The user's password\n     * @param  {String} [credentials.url]     The API to login to (overwrites this.url)\n     * @param  {String} [credentials.project] The API project to login to (overwrites this.project)\n     * @param  {String} [options.persist]     Auto-fetch a new token when it's about to expire\n     * @param  {Boolean} [options.storage]    Where to store the token (survive refreshes)\n     * @return {LoginPromise}\n     */ login ( credentials , options = { persist : true } ) { AV . object ( credentials , \"credentials\" ) ; AV . keysWithString ( credentials , [ \"email\" , \"password\" ] , \"credentials\" ) ; this . token = null ; if ( AV . hasKeysWithString ( credentials , [ \"url\" ] ) ) { this . url = credentials . url ; } if ( AV . hasKeysWithString ( credentials , [ \"project\" ] ) ) { this . project = credentials . project ; } if ( credentials . persist || options . persist ) { this . startInterval ( ) ; } return new Promise ( ( resolve , reject ) => { this . post ( \"/auth/authenticate\" , { email : credentials . email , password : credentials . password } ) . then ( res => res . data . token ) . then ( token => { this . token = token ; // Expiry date is the moment we got the token + 5 minutes this . localExp = new Date ( Date . now ( ) + this . tokenExpiryTime * 60000 ) . getTime ( ) ; if ( this . storage ) { this . storage . setItem ( \"directus-sdk-js\" , JSON . stringify ( { token : this . token , url : this . url , project : this . project , localExp : this . localExp } ) ) ; } resolve ( { url : this . url , project : this . project , token : this . token , localExp : this . localExp } ) ; } ) . catch ( reject ) ; } ) ; } , /**\n     * Logs the user out by \"forgetting\" the token, and clearing the refresh interval\n     */ logout ( ) { this . token = null ; if ( this . refreshInterval ) { this . stopInterval ( ) ; } if ( this . storage ) { this . storage . removeItem ( \"directus-sdk-js\" ) ; } } , /**\n     * Resets the client instance by logging out and removing the URL and project\n     */ reset ( ) { this . logout ( ) ; this . url = null ; this . project = null ; } , /**\n     * Starts an interval of 10 seconds that will check if the token needs refreshing\n     * @param {Boolean} fireImmediately Fire the refreshIfNeeded method directly\n     */ startInterval ( fireImmediately ) { if ( fireImmediately ) this . refreshIfNeeded ( ) ; this . refreshInterval = setInterval ( this . refreshIfNeeded . bind ( this ) , 10000 ) ; } , /**\n     * Clears and nullifies the token refreshing interval\n     */ stopInterval ( ) { clearInterval ( this . refreshInterval ) ; this . refreshInterval = null ; } , /**\n     * Refresh the token if it is about to expire (within 30 seconds of expiry date)\n     *\n     * Calls onAutoRefreshSuccess with the new token if the refreshing is successful\n     * Calls onAutoRefreshError if refreshing the token fails for some reason\n     */ refreshIfNeeded ( ) { if ( ! AV . hasStringKeys ( this , [ \"token\" , \"url\" , \"project\" ] ) ) return ; if ( ! this . payload || ! this . payload . exp ) return ; const timeDiff = this . localExp - Date . now ( ) ; if ( timeDiff <= 0 ) { if ( AV . isFunction ( this . onAutoRefreshError ) ) { this . onAutoRefreshError ( { message : \"auth_expired_token\" , code : 102 } ) ; } return ; } if ( timeDiff < 30000 ) { this . refresh ( this . token ) . then ( res => { this . token = res . data . token ; this . localExp = new Date ( Date . now ( ) + this . tokenExpiryTime * 60000 ) . getTime ( ) ; if ( AV . isFunction ( this . onAutoRefreshSuccess ) ) { this . onAutoRefreshSuccess ( { url : this . url , project : this . project , token : this . token , localExp : this . localExp } ) ; } if ( this . storage ) { this . storage . setItem ( \"directus-sdk-js\" , JSON . stringify ( { token : this . token , url : this . url , project : this . project , localExp : this . localExp } ) ) ; } } ) . catch ( error => { if ( AV . isFunction ( this . onAutoRefreshError ) ) { this . onAutoRefreshError ( error ) ; } } ) ; } } , /**\n     * Use the passed token to request a new one\n     * @param  {String} token Active & Valid token\n     * @return {RequestPromise}\n     */ refresh ( token ) { AV . string ( token , \"token\" ) ; return this . post ( \"/auth/refresh\" , { token } ) ; } , /**\n     * Request to reset the password of the user with the given email address\n     *\n     * The API will send an email to the given email address with a link to generate a new\n     * temporary password.\n     * @param {String} email The user's email\n     */ requestPasswordReset ( email ) { AV . string ( email , \"email\" ) ; return this . post ( \"/auth/password/request\" , { email : email } ) ; } , // ACTIVITY // ------------------------------------------------------------------------- /**\n     * Get activity\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getActivity ( params = { } ) { AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( \"/activity\" , params ) ; } , // BOOKMARKS // ------------------------------------------------------------------------- /**\n     * Get the bookmarks of the current user\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getMyBookmarks ( params = { } ) { AV . string ( this . token , \"this.token\" ) ; AV . objectOrEmpty ( params ) ; return Promise . all ( [ this . get ( \"/collection_presets\" , { \"filter[title][nnull]\" : 1 , \"filter[user][eq]\" : this . payload . id } ) , this . get ( \"/collection_presets\" , { \"filter[title][nnull]\" : 1 , \"filter[role][eq]\" : this . payload . role , \"filter[user][null]\" : 1 } ) ] ) . then ( values => { const [ user , role ] = values ; // eslint-disable-line no-shadow return [ ... user . data , ... role . data ] ; } ) ; } , // COLLECTIONS // ------------------------------------------------------------------------- /**\n     * Get all available collections\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getCollections ( params = { } ) { AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( \"/collections\" , params ) ; } , /**\n     * Get collection info by name\n     * @param  {String} collection  Collection name\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getCollection ( collection , params = { } ) { AV . string ( collection , \"collection\" ) ; AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( ` ${ collection } ` , params ) ; } , /**\n     * Create a collection\n     * @param {Object} data Collection information\n     * @return {RequestPromise}\n     */ createCollection ( data ) { AV . object ( data , \"data\" ) ; return this . post ( \"/collections\" , data ) ; } , /**\n     * @param  {String} The collection to update\n     * @param  {Object} The fields to update\n     * @return {RequestPromise}\n     */ updateCollection ( collection , data ) { AV . string ( collection , \"collection\" ) ; AV . object ( data , \"data\" ) ; return this . patch ( ` ${ collection } ` , data ) ; } , /**\n     * @param  {String} collection The primary key of the collection to remove\n     * @return {RequestPromise}\n     */ deleteCollection ( collection ) { AV . string ( collection , \"collection\" ) ; return this . delete ( ` ${ collection } ` ) ; } , // COLLECTION PRESETS // ------------------------------------------------------------------------- /**\n     * Create a new collection preset (bookmark / listing preferences)\n     * @param  {Object} data The bookmark info\n     * @return {RequestPromise}\n     */ createCollectionPreset ( data ) { AV . object ( data ) ; return this . post ( \"/collection_presets\" , data ) ; } , /**\n     * Update collection preset (bookmark / listing preference)\n     * @param {String|Number} primaryKey\n     * @param {RequestPromise} data\n     */ updateCollectionPreset ( primaryKey , data ) { AV . notNull ( primaryKey , \"primaryKey\" ) ; AV . object ( data , \"data\" ) ; return this . patch ( ` ${ primaryKey } ` , data ) ; } , /**\n     * Delete collection preset by primarykey\n     * @param {String|Number} primaryKey The primaryKey of the preset to delete\n     */ deleteCollectionPreset ( primaryKey ) { AV . notNull ( primaryKey , \"primaryKey\" ) ; return this . delete ( ` ${ primaryKey } ` ) ; } , // DATABASE // ------------------------------------------------------------------------ /**\n     * This will update the database of the API instance to the latest version\n     * using the migrations in the API\n     * @return {RequestPromise}\n     */ updateDatabase ( ) { return this . post ( \"/update\" ) ; } , // EXTENSIONS // ------------------------------------------------------------------------- /**\n     * Get the meta information of all installed interfaces\n     * @return {RequestPromise}\n     */ getInterfaces ( ) { return this . request ( \"get\" , \"/interfaces\" , { } , { } , true ) ; } , /**\n     * Get the meta information of all installed layouts\n     * @return {RequestPromise}\n     */ getLayouts ( ) { return this . request ( \"get\" , \"/layouts\" , { } , { } , true ) ; } , /**\n     * Get the meta information of all installed pages\n     * @return {RequestPromise}\n     */ getPages ( ) { return this . request ( \"get\" , \"/pages\" , { } , { } , true ) ; } , // FIELDS // ------------------------------------------------------------------------ /**\n     * Get all fields that are in Directus\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getAllFields ( params = { } ) { AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( \"/fields\" , params ) ; } , /**\n     * Get the fields that have been setup for a given collection\n     * @param  {String} collection  Collection name\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getFields ( collection , params = { } ) { AV . string ( collection , \"collection\" ) ; AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( ` ${ collection } ` , params ) ; } , /**\n     * Get the field information for a single given field\n     * @param  {String} collection  Collection name\n     * @param  {String} fieldName   Field name\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getField ( collection , fieldName , params = { } ) { AV . string ( collection , \"collection\" ) ; AV . string ( fieldName , \"fieldName\" ) ; AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( ` ${ collection } ${ fieldName } ` , params ) ; } , /**\n     * Create a field in the given collection\n     * @param  {String} collection Collection to add the field in\n     * @param  {Object} fieldInfo  The fields info to save\n     * @return {RequestPromise}\n     */ createField ( collection , fieldInfo ) { AV . string ( collection , \"collection\" ) ; AV . object ( fieldInfo , \"fieldInfo\" ) ; return this . post ( ` ${ collection } ` , fieldInfo ) ; } , /**\n     * Update a given field in a given collection\n     * @param  {String} collection Field's parent collection\n     * @param  {String} fieldName  Name of the field to update\n     * @param  {Object} fieldInfo  Fields to update\n     * @return {RequestPromise}\n     */ updateField ( collection , fieldName , fieldInfo ) { AV . string ( collection , \"collection\" ) ; AV . string ( fieldName , \"fieldName\" ) ; AV . object ( fieldInfo , \"fieldInfo\" ) ; return this . patch ( ` ${ collection } ${ fieldName } ` , fieldInfo ) ; } , /**\n     * Update multiple fields at once\n     * @param  {String} collection             Fields' parent collection\n     * @param  {Array} fieldsInfoOrFieldNames  Array of field objects or array of field names\n     * @param  {Object} [fieldInfo]            In case fieldsInfoOrFieldNames is an array of fieldNames, you need to provide the fields to update\n     * @return {RequestPromise}\n     *\n     * @example\n     *\n     * // Set multiple fields to the same value\n     * updateFields(\"projects\", [\"first_name\", \"last_name\", \"email\"], {\n     *   default_value: \"\"\n     * })\n     *\n     * // Set multiple fields to different values\n     * updateFields(\"projects\", [\n     *   {\n     *     id: 14,\n     *     sort: 1\n     *   },\n     *   {\n     *     id: 17,\n     *     sort: 2\n     *   },\n     *   {\n     *     id: 912,\n     *     sort: 3\n     *   }\n     * ])\n     */ updateFields ( collection , fieldsInfoOrFieldNames , fieldInfo = null ) { AV . string ( collection , \"collection\" ) ; AV . array ( fieldsInfoOrFieldNames , \"fieldsInfoOrFieldNames\" ) ; if ( fieldInfo ) { AV . object ( fieldInfo ) ; } if ( fieldInfo ) { return this . patch ( ` ${ collection } ${ fieldsInfoOrFieldNames . join ( \",\" ) } ` , fieldInfo ) ; } return this . patch ( ` ${ collection } ` , fieldsInfoOrFieldNames ) ; } , /**\n     * Delete a field from a collection\n     * @param  {String} collection Name of the collection\n     * @param  {String} fieldName  The name of the field to delete\n     * @return {RequestPromise}\n     */ deleteField ( collection , fieldName ) { AV . string ( collection , \"collection\" ) ; AV . string ( fieldName , \"fieldName\" ) ; return this . delete ( ` ${ collection } ${ fieldName } ` ) ; } , // FILES // ------------------------------------------------------------------------ /**\n     * Upload multipart files in multipart/form-data\n     * @param  {Object} data FormData object containing files\n     * @return {RequestPromise}\n     */ uploadFiles ( data , onUploadProgress = ( ) => { } ) { const headers = { \"Content-Type\" : \"multipart/form-data\" , Authorization : ` ${ this . token } ` } ; return this . axios . post ( ` ${ this . url } ${ this . project } ` , data , { headers , onUploadProgress } ) . then ( res => res . data ) . catch ( error => { if ( error . response ) { throw error . response . data . error ; } else { throw { // eslint-disable-line code : - 1 , message : \"Network Error\" , error } ; } } ) ; } , // ITEMS // ------------------------------------------------------------------------- /**\n     * Update an existing item\n     * @param  {String} collection The collection to add the item to\n     * @param  {String|Number} primaryKey Primary key of the item\n     * @param  {Object} body       The item's field values\n     * @param  {Object} params     Query parameters\n     * @return {RequestPromise}\n     */ updateItem ( collection , primaryKey , body , params = { } ) { AV . string ( collection , \"collection\" ) ; AV . notNull ( primaryKey , \"primaryKey\" ) ; AV . object ( body , \"body\" ) ; if ( collection . startsWith ( \"directus_\" ) ) { return this . patch ( ` ${ collection . substring ( 9 ) } ${ primaryKey } ` , body , params ) ; } return this . patch ( ` ${ collection } ${ primaryKey } ` , body , params ) ; } , /**\n     * Update multiple items\n     * @param  {String} collection The collection to add the item to\n     * @param  {Array} body        The item's field values\n     * @param  {Object} params     Query Parameters\n     * @return {RequestPromise}\n     */ updateItems ( collection , body , params = { } ) { AV . string ( collection , \"collection\" ) ; AV . array ( body , \"body\" ) ; if ( collection . startsWith ( \"directus_\" ) ) { return this . patch ( ` ${ collection . substring ( 9 ) } ` , body , params ) ; } return this . patch ( ` ${ collection } ` , body , params ) ; } , /**\n     * Create a new item\n     * @param  {String} collection The collection to add the item to\n     * @param  {Object} body       The item's field values\n     * @return {RequestPromise}\n     */ createItem ( collection , body ) { AV . string ( collection , \"collection\" ) ; AV . object ( body , \"body\" ) ; if ( collection . startsWith ( \"directus_\" ) ) { return this . post ( ` ${ collection . substring ( 9 ) } ` , body ) ; } return this . post ( ` ${ collection } ` , body ) ; } , /**\n     * Create multiple items\n     * @param  {String} collection The collection to add the item to\n     * @param  {Array} body        The item's field values\n     * @return {RequestPromise}\n     */ createItems ( collection , body ) { AV . string ( collection , \"collection\" ) ; AV . array ( body , \"body\" ) ; if ( collection . startsWith ( \"directus_\" ) ) { return this . post ( ` ${ collection . substring ( 9 ) } ` , body ) ; } return this . post ( ` ${ collection } ` , body ) ; } , /**\n     * Get items from a given collection\n     * @param  {String} collection The collection to add the item to\n     * @param  {Object} [params={}]   Query parameters\n     * @return {RequestPromise}\n     */ getItems ( collection , params = { } ) { AV . string ( collection , \"collection\" ) ; AV . objectOrEmpty ( params , \"params\" ) ; if ( collection . startsWith ( \"directus_\" ) ) { return this . get ( ` ${ collection . substring ( 9 ) } ` , params ) ; } return this . get ( ` ${ collection } ` , params ) ; } , /**\n     * Get a single item by primary key\n     * @param  {String} collection  The collection to add the item to\n     * @param  {String|Number} primaryKey Primary key of the item\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getItem ( collection , primaryKey , params = { } ) { AV . string ( collection , \"collection\" ) ; AV . notNull ( primaryKey , \"primaryKey\" ) ; AV . objectOrEmpty ( params , \"params\" ) ; if ( collection . startsWith ( \"directus_\" ) ) { return this . get ( ` ${ collection . substring ( 9 ) } ${ primaryKey } ` , params ) ; } return this . get ( ` ${ collection } ${ primaryKey } ` , params ) ; } , /**\n     * Delete a single item by primary key\n     * @param  {String} collection  The collection to delete the item from\n     * @param  {String|Number} primaryKey Primary key of the item\n     * @return {RequestPromise}\n     */ deleteItem ( collection , primaryKey ) { AV . string ( collection , \"collection\" ) ; AV . notNull ( primaryKey , \"primaryKey\" ) ; if ( collection . startsWith ( \"directus_\" ) ) { return this . delete ( ` ${ collection . substring ( 9 ) } ${ primaryKey } ` ) ; } return this . delete ( ` ${ collection } ${ primaryKey } ` ) ; } , /**\n     * Delete multiple items by primary key\n     * @param  {String} collection  The collection to delete the item from\n     * @param  {Array} primaryKey Primary key of the item\n     * @return {RequestPromise}\n     */ deleteItems ( collection , primaryKeys ) { AV . string ( collection , \"collection\" ) ; AV . array ( primaryKeys , \"primaryKeys\" ) ; if ( collection . startsWith ( \"directus_\" ) ) { return this . delete ( ` ${ collection . substring ( 9 ) } ${ primaryKeys . join ( ) } ` ) ; } return this . delete ( ` ${ collection } ${ primaryKeys . join ( ) } ` ) ; } , // LISTING PREFERENCES // ------------------------------------------------------------------------- /**\n     * Get the collection presets of the current user for a single collection\n     * @param  {String} collection  Collection to fetch the preferences for\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getMyListingPreferences ( collection , params = { } ) { AV . string ( this . token , \"this.token\" ) ; AV . objectOrEmpty ( params , \"params\" ) ; return Promise . all ( [ this . get ( \"/collection_presets\" , { limit : 1 , \"filter[title][null]\" : 1 , \"filter[collection][eq]\" : collection , \"filter[role][null]\" : 1 , \"filter[user][null]\" : 1 , sort : \"-id\" } ) , this . get ( \"/collection_presets\" , { limit : 1 , \"filter[title][null]\" : 1 , \"filter[collection][eq]\" : collection , \"filter[role][eq]\" : this . payload . role , \"filter[user][null]\" : 1 , sort : \"-id\" } ) , this . get ( \"/collection_presets\" , { limit : 1 , \"filter[title][null]\" : 1 , \"filter[collection][eq]\" : collection , \"filter[role][eq]\" : this . payload . role , \"filter[user][eq]\" : this . payload . id , sort : \"-id\" } ) ] ) . then ( values => { const [ collection , role , user ] = values ; // eslint-disable-line no-shadow if ( user . data && user . data . length > 0 ) { return user . data [ 0 ] ; } if ( role . data && role . data . length > 0 ) { return role . data [ 0 ] ; } if ( collection . data && collection . data . length > 0 ) { return collection . data [ 0 ] ; } return { } ; } ) ; } , // PERMISSIONS // ------------------------------------------------------------------------- /**\n     * Get permissions\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getPermissions ( params = { } ) { AV . objectOrEmpty ( params , \"params\" ) ; return this . getItems ( \"directus_permissions\" , params ) ; } , /**\n     * Get the currently logged in user's permissions\n     * @param  {Object} params Query parameters\n     * @return {RequestPromise}\n     */ getMyPermissions ( params = { } ) { AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( \"/permissions/me\" , params ) ; } , /**\n     * Create multiple new permissions\n     * @param  {Array} data  Permission records to save\n     * @return {RequestPromise}\n     */ createPermissions ( data ) { AV . array ( data ) ; return this . post ( \"/permissions\" , data ) ; } , /**\n     * Update multiple permission records\n     * @param  {Array} data  Permission records to update\n     * @return {RequestPromise}\n     */ updatePermissions ( data ) { AV . array ( data ) ; return this . patch ( \"/permissions\" , data ) ; } , // RELATIONS // ------------------------------------------------------------------------- /**\n     * Get all relationships\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getRelations ( params = { } ) { AV . objectOrEmpty ( params ) ; return this . get ( \"/relations\" , params ) ; } , createRelation ( data ) { return this . post ( \"/relations\" , data ) ; } , updateRelation ( primaryKey , data ) { return this . patch ( ` ${ primaryKey } ` , data ) ; } , /**\n     * Get the relationship information for the given collection\n     * @param  {String} collection The collection name\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getCollectionRelations ( collection , params = { } ) { AV . string ( collection , \"collection\" ) ; AV . objectOrEmpty ( params ) ; return Promise . all ( [ this . get ( \"/relations\" , { \"filter[collection_a][eq]\" : collection } ) , this . get ( \"/relations\" , { \"filter[collection_b][eq]\" : collection } ) ] ) ; } , // REVISIONS // ------------------------------------------------------------------------- /**\n     * Get a single item's revisions by primary key\n     * @param  {String} collection  The collection to fetch the revisions from\n     * @param  {String|Number} primaryKey Primary key of the item\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getItemRevisions ( collection , primaryKey , params = { } ) { AV . string ( collection , \"collection\" ) ; AV . notNull ( primaryKey , \"primaryKey\" ) ; AV . objectOrEmpty ( params , \"params\" ) ; if ( collection . startsWith ( \"directus_\" ) ) { return this . get ( ` ${ collection . substring ( 9 ) } ${ primaryKey } ` , params ) ; } return this . get ( ` ${ collection } ${ primaryKey } ` , params ) ; } , /**\n     * revert an item to a previous state\n     * @param  {String} collection  The collection to fetch the revisions from\n     * @param  {String|Number} primaryKey Primary key of the item\n     * @param  {Number} revisionID The ID of the revision to revert to\n     * @return {RequestPromise}\n     */ revert ( collection , primaryKey , revisionID ) { AV . string ( collection , \"collection\" ) ; AV . notNull ( primaryKey , \"primaryKey\" ) ; AV . number ( revisionID , \"revisionID\" ) ; if ( collection . startsWith ( \"directus_\" ) ) { return this . patch ( ` ${ collection . substring ( 9 ) } ${ primaryKey } ${ revisionID } ` ) ; } return this . patch ( ` ${ collection } ${ primaryKey } ${ revisionID } ` ) ; } , // ROLES // ------------------------------------------------------------------------- /**\n     * Get a single user role\n     * @param  {Number} primaryKey  The id of the user rol to get\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getRole ( primaryKey , params = { } ) { AV . number ( primaryKey , \"primaryKey\" ) ; AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( ` ${ primaryKey } ` , params ) ; } , /**\n     * Get the user roles\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getRoles ( params = { } ) { AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( \"/roles\" , params ) ; } , /**\n     * Update a user role\n     * @param  {Number} primaryKey The ID of the role\n     * @param  {Object} body       The fields to update\n     * @return {RequestPromise}\n     */ updateRole ( primaryKey , body ) { AV . notNull ( primaryKey , \"primaryKey\" ) ; AV . object ( body , \"body\" ) ; return this . updateItem ( \"directus_roles\" , primaryKey , body ) ; } , /**\n     * Create a new user role\n     * @param  {Object} body The role information\n     * @return {RequestPromise}\n     */ createRole ( body ) { AV . object ( body , \"body\" ) ; return this . createItem ( \"directus_roles\" , body ) ; } , /**\n     * Delete a user rol by primary key\n     * @param  {Number | String} primaryKey Primary key of the user role\n     * @return {RequestPromise}\n     */ deleteRole ( primaryKey ) { AV . notNull ( primaryKey , \"primaryKey\" ) ; return this . deleteItem ( \"directus_roles\" , primaryKey ) ; } , // SETTINGS // ------------------------------------------------------------------------- /**\n     * Get Directus' global settings\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getSettings ( params = { } ) { AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( \"/settings\" , params ) ; } , /**\n     * Get the \"fields\" for directus_settings\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getSettingsFields ( params = { } ) { AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( \"/settings/fields\" , params ) ; } , // USERS // ------------------------------------------------------------------------- /**\n     * Get a list of available users in Directus\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getUsers ( params = { } ) { AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( \"/users\" , params ) ; } , /**\n     * Get a single Directus user\n     * @param  {String} primaryKey  The unique identifier of the user\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getUser ( primaryKey , params = { } ) { AV . notNull ( primaryKey , \"primaryKey\" ) ; AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( ` ${ primaryKey } ` , params ) ; } , /**\n     * Get the user info of the currently logged in user\n     * @param  {Object} [params={}] Query parameters\n     * @return {RequestPromise}\n     */ getMe ( params = { } ) { AV . objectOrEmpty ( params , \"params\" ) ; return this . get ( \"/users/me\" , params ) ; } , /**\n     * Update a single user based on primaryKey\n     * @param  {String|Number} primaryKey The primary key of the user\n     * @param  {Object} body              The fields to update\n     * @return {RequestPromise}\n     */ updateUser ( primaryKey , body ) { AV . notNull ( primaryKey , \"primaryKey\" ) ; AV . object ( body , \"body\" ) ; return this . updateItem ( \"directus_users\" , primaryKey , body ) ; } , // UTILS // ------------------------------------------------------------------------- /**\n     * Ping the API to check if it exists / is up and running\n     * @return {RequestPromise}\n     */ ping ( ) { return this . request ( \"get\" , \"/server/ping\" , { } , { } , true , true ) ; } , /**\n     * Get the server info from the API\n     * @return {RequestPromise}\n     */ serverInfo ( ) { return this . request ( \"get\" , \"/\" , { } , { } , true ) ; } , /**\n     * Get the server info from the project\n     * @return {RequestPromise}\n     */ projectInfo ( ) { return this . request ( \"get\" , \"/\" ) ; } , /**\n     * Get all the setup third party auth providers\n     * @return {RequestPromise}\n     */ getThirdPartyAuthProviders ( ) { return this . get ( \"/auth/sso\" ) ; } } ; // Only start the auto refresh interval if the token exists and it's a JWT if ( SDK . token && SDK . token . includes ( \".\" ) ) { SDK . startInterval ( true ) ; } return SDK ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Scroll to a specific hash tag in the content [CODESPLIT] function scrollToHash ( hash ) { var $scroller = getScroller ( ) , dest = 0 ; // Don't try to scroll if element doesn't exist if ( ! pageHasElement ( hash ) ) { return ; } if ( hash ) { dest = getElementTopPosition ( hash ) ; } // Unbind scroll detection $scroller . unbind ( 'scroll' ) ; $scroller . animate ( { scrollTop : dest } , 800 , 'swing' , function ( ) { // Reset scroll binding when finished $scroller . scroll ( handleScrolling ) ; } ) ; // Directly set chapter as active setChapterActive ( null , hash ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Return the top position of an element [CODESPLIT] function getElementTopPosition ( id ) { // Get actual position of element if nested var $scroller = getScroller ( ) , $container = $scroller . find ( '.page-inner' ) , $el = $scroller . find ( id ) , $parent = $el . offsetParent ( ) , dest = 0 ; // Exit early if we can't find any of those elements if ( any ( [ $scroller , $container , $el , $parent ] , isEmpty ) ) { return 0 ; } dest = $el . position ( ) . top ; // Note: this could be a while loop, but to avoid any chances of infinite loops // we'll limit the max iterations to 10 var MAX_ITERATIONS = 10 ; for ( var i = 0 ; i < MAX_ITERATIONS ; i ++ ) { // Stop when we find the element's ancestor just below $container // or if we hit the top of the dom (parent's parent is itself) if ( $parent . is ( $container ) || $parent . is ( $parent . offsetParent ( ) ) ) { break ; } // Go up the DOM tree, to the next parent $el = $parent ; dest += $el . position ( ) . top ; $parent = $el . offsetParent ( ) ; } // Return rounded value since // jQuery scrollTop() returns an integer return Math . floor ( dest ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a chapter as active in summary and update state [CODESPLIT] function setChapterActive ( $chapter , hash ) { // No chapter and no hash means first chapter if ( ! $chapter && ! hash ) { $chapter = $chapters . first ( ) ; } // If hash is provided, set as active chapter if ( ! ! hash ) { // Multiple chapters for this file if ( $chapters . length > 1 ) { $chapter = $chapters . filter ( function ( ) { var titleId = getChapterHash ( $ ( this ) ) ; return titleId == hash ; } ) . first ( ) ; } // Only one chapter, no need to search else { $chapter = $chapters . first ( ) ; } } // Don't update current chapter if ( $chapter . is ( $activeChapter ) ) { return ; } // Update current active chapter $activeChapter = $chapter ; // Add class to selected chapter $chapters . removeClass ( 'active' ) ; $chapter . addClass ( 'active' ) ; // Update history state if needed hash = getChapterHash ( $chapter ) ; var oldUri = window . location . pathname + window . location . hash , uri = window . location . pathname + hash ; if ( uri != oldUri ) { history . replaceState ( { path : uri } , null , uri ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the hash of link for a chapter [CODESPLIT] function getChapterHash ( $chapter ) { var $link = $chapter . children ( 'a' ) , hash = $link . attr ( 'href' ) . split ( '#' ) [ 1 ] ; if ( hash ) hash = '#' + hash ; return ( ! ! hash ) ? hash : '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle user scrolling [CODESPLIT] function handleScrolling ( ) { // Get current page scroll var $scroller = getScroller ( ) , scrollTop = $scroller . scrollTop ( ) , scrollHeight = $scroller . prop ( 'scrollHeight' ) , clientHeight = $scroller . prop ( 'clientHeight' ) , nbChapters = $chapters . length , $chapter = null ; // Find each title position in reverse order $ ( $chapters . get ( ) . reverse ( ) ) . each ( function ( index ) { var titleId = getChapterHash ( $ ( this ) ) , titleTop ; if ( ! ! titleId && ! $chapter ) { titleTop = getElementTopPosition ( titleId ) ; // Set current chapter as active if scroller passed it if ( scrollTop >= titleTop ) { $chapter = $ ( this ) ; } } // If no active chapter when reaching first chapter, set it as active if ( index == ( nbChapters - 1 ) && ! $chapter ) { $chapter = $ ( this ) ; } } ) ; // ScrollTop is at 0, set first chapter anyway if ( ! $chapter && ! scrollTop ) { $chapter = $chapters . first ( ) ; } // Set last chapter as active if scrolled to bottom of page if ( ! ! scrollTop && ( scrollHeight - scrollTop == clientHeight ) ) { $chapter = $chapters . last ( ) ; } setChapterActive ( $chapter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Handle click on a link [CODESPLIT] function handleLinkClick ( e ) { var $this = $ ( this ) ; var target = $this . attr ( 'target' ) ; if ( isModifiedEvent ( e ) || ! isLeftClickEvent ( e ) || target ) { return ; } e . stopPropagation ( ) ; e . preventDefault ( ) ; var url = $this . attr ( 'href' ) ; if ( url ) handleNavigation ( url , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert a jquery element at a specific position [CODESPLIT] function insertAt ( parent , selector , index , element ) { var lastIndex = parent . children ( selector ) . length ; if ( index < 0 ) { index = Math . max ( 0 , lastIndex + 1 + index ) ; } parent . append ( element ) ; if ( index < lastIndex ) { parent . children ( selector ) . eq ( index ) . before ( parent . children ( selector ) . last ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a dropdown menu [CODESPLIT] function createDropdownMenu ( dropdown ) { var $menu = $ ( '<div>' , { 'class' : 'dropdown-menu' , 'html' : '<div class=\"dropdown-caret\"><span class=\"caret-outer\"></span><span class=\"caret-inner\"></span></div>' } ) ; if ( typeof dropdown == 'string' ) { $menu . append ( dropdown ) ; } else { var groups = dropdown . map ( function ( group ) { if ( $ . isArray ( group ) ) return group ; else return [ group ] ; } ) ; // Create buttons groups groups . forEach ( function ( group ) { var $group = $ ( '<div>' , { 'class' : 'buttons' } ) ; var sizeClass = 'size-' + group . length ; // Append buttons group . forEach ( function ( btn ) { btn = $ . extend ( { text : '' , className : '' , onClick : defaultOnClick } , btn || { } ) ; var $btn = $ ( '<button>' , { 'class' : 'button ' + sizeClass + ' ' + btn . className , 'text' : btn . text } ) ; $btn . click ( btn . onClick ) ; $group . append ( $btn ) ; } ) ; $menu . append ( $group ) ; } ) ; } return $menu ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new button in the toolbar [CODESPLIT] function createButton ( opts ) { opts = $ . extend ( { // Aria label for the button label : '' , // Icon to show icon : '' , // Inner text text : '' , // Right or left position position : 'left' , // Other class name to add to the button className : '' , // Triggered when user click on the button onClick : defaultOnClick , // Button is a dropdown dropdown : null , // Position in the toolbar index : null , // Button id for removal id : generateId ( ) } , opts || { } ) ; buttons . push ( opts ) ; updateButton ( opts ) ; return opts . id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a button provided its id [CODESPLIT] function removeButton ( id ) { buttons = $ . grep ( buttons , function ( button ) { return button . id != id ; } ) ; updateAllButtons ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove multiple buttons from an array of ids [CODESPLIT] function removeButtons ( ids ) { buttons = $ . grep ( buttons , function ( button ) { return ids . indexOf ( button . id ) == - 1 ; } ) ; updateAllButtons ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Toggle sidebar with or withour animation [CODESPLIT] function toggleSidebar ( _state , animation ) { if ( gitbook . state != null && isOpen ( ) == _state ) return ; if ( animation == null ) animation = true ; gitbook . state . $book . toggleClass ( 'without-animation' , ! animation ) ; gitbook . state . $book . toggleClass ( 'with-summary' , _state ) ; gitbook . storage . set ( 'sidebar' , isOpen ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare sidebar : state and toggle button [CODESPLIT] function init ( ) { // Init last state if not mobile if ( ! platform . isMobile ( ) ) { toggleSidebar ( gitbook . storage . get ( 'sidebar' , true ) , false ) ; } // Close sidebar after clicking a link on mobile $ ( document ) . on ( 'click' , '.book-summary li.chapter a' , function ( e ) { if ( platform . isMobile ( ) ) toggleSidebar ( false , false ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter summary with a list of path [CODESPLIT] function filterSummary ( paths ) { var $summary = $ ( '.book-summary' ) ; $summary . find ( 'li' ) . each ( function ( ) { var path = $ ( this ) . data ( 'path' ) ; var st = paths == null || paths . indexOf ( path ) !== - 1 ; $ ( this ) . toggle ( st ) ; if ( st ) $ ( this ) . parents ( 'li' ) . show ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind all dropdown [CODESPLIT] function init ( ) { $ ( document ) . on ( 'click' , '.toggle-dropdown' , toggleDropdown ) ; $ ( document ) . on ( 'click' , '.dropdown-menu' , function ( e ) { e . stopPropagation ( ) ; } ) ; $ ( document ) . on ( 'click' , closeDropdown ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind keyboard shortcuts [CODESPLIT] function init ( ) { // Next bindShortcut ( [ 'right' ] , function ( e ) { navigation . goNext ( ) ; } ) ; // Prev bindShortcut ( [ 'left' ] , function ( e ) { navigation . goPrev ( ) ; } ) ; // Toggle Summary bindShortcut ( [ 's' ] , function ( e ) { sidebar . toggle ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Signal that page has changed this function must be called by themes after page is loaded and when navigation changed [CODESPLIT] function hasChanged ( ctx ) { console . log ( 'page has changed' , ctx ) ; // eslint-disable-line no-console setState ( ctx ) ; if ( ! started ) { // Notify that gitbook is ready started = true ; events . trigger ( 'start' , ctx . config . pluginsConfig ) ; } events . trigger ( 'page.change' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Update current state [CODESPLIT] function setState ( newState ) { // API since GitBook v3 state . page = newState . page ; state . file = newState . file ; state . gitbook = newState . gitbook ; state . config = newState . config ; state . basePath = newState . basePath ; state . book = newState . book ; // Deprecated state . $book = $ ( '.book' ) ; state . revision = state . gitbook . time ; state . level = state . page . level ; state . filepath = state . file . path ; state . chapterTitle = state . page . title ; state . innerLanguage = state . book . language || '' ; // Absolute url to the root of the book (inner book) state . root = url . resolve ( location . protocol + '//' + location . host , path . dirname ( path . resolve ( location . pathname . replace ( / \\/$ / , '/index.html' ) , state . basePath ) ) ) . replace ( / \\/?$ / , '/' ) ; // Absolute root to the language (for multilingual book) state . bookRoot = state . innerLanguage ? url . resolve ( state . root , '..' ) : state . root ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add directive helper . [CODESPLIT] function addDirective ( type ) { return function ( name , directive ) { if ( typeof name === 'function' ) { directive = name } if ( typeof directive !== 'function' ) { throw new TypeError ( 'Directive must be a function' ) } name = typeof name === 'string' ? name : directive . name if ( ! name ) { throw new TypeError ( 'Directive function must have a name' ) } directive . $name = name Toxy [ type ] [ name ] = directive return Toxy } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private helpers [CODESPLIT] function outgoingInterceptor ( proxy ) { const responseBody = rocky . middleware . responseBody responseBody . $name = '$outgoingInterceptor$' const interceptor = responseBody ( function ( req , res , next ) { proxy . _outPoisons . run ( req , res , next ) } ) proxy . _outgoingEnabled = true proxy . poison ( interceptor ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Directive encapsulates a directive function providing convenient methods and abstractions used by toxy higher layers to manage and configure directives . [CODESPLIT] function Directive ( directive ) { Rule . call ( this ) this . enabled = true this . directive = directive this . name = directive . $name || directive . name }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Toxy HTTP proxy . [CODESPLIT] function Toxy ( opts ) { if ( ! ( this instanceof Toxy ) ) return new Toxy ( opts ) opts = Object . assign ( { } , Toxy . defaults , opts ) Proxy . call ( this , opts ) this . routes = [ ] this . _rules = midware ( ) this . _inPoisons = midware ( ) this . _outPoisons = midware ( ) setupMiddleware ( this ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private helpers [CODESPLIT] function finalHandler ( route ) { var isFinalHandler = false route . use ( function ( req , res , next ) { if ( ! isFinalHandler ) { isFinalHandler = true useRouteFinalHandler ( route ) } next ( ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GRID INTERNAL FUNCTIONS ===================== [CODESPLIT] function appendRow ( row ) { var that = this ; function exists ( item ) { return that . identifier && item [ that . identifier ] === row [ that . identifier ] ; } if ( ! this . rows . contains ( exists ) ) { this . rows . push ( row ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * response = { current : 1 rowCount : 10 rows : [ {} {} ] sort : [ { columnId : asc } ] total : 101 } [CODESPLIT] function loadData ( ) { var that = this ; this . element . _bgBusyAria ( true ) . trigger ( \"load\" + namespace ) ; showLoading . call ( this ) ; function containsPhrase ( row ) { var column , searchPattern = new RegExp ( that . searchPhrase , ( that . options . caseSensitive ) ? \"g\" : \"gi\" ) ; for ( var i = 0 ; i < that . columns . length ; i ++ ) { column = that . columns [ i ] ; if ( column . searchable && column . visible && column . converter . to ( row [ column . id ] ) . search ( searchPattern ) > - 1 ) { return true ; } } return false ; } function update ( rows , total ) { that . currentRows = rows ; setTotals . call ( that , total ) ; if ( ! that . options . keepSelection ) { that . selectedRows = [ ] ; } renderRows . call ( that , rows ) ; renderInfos . call ( that ) ; renderPagination . call ( that ) ; that . element . _bgBusyAria ( false ) . trigger ( \"loaded\" + namespace ) ; } if ( this . options . ajax ) { var request = getRequest . call ( this ) , url = getUrl . call ( this ) ; if ( url == null || typeof url !== \"string\" || url . length === 0 ) { throw new Error ( \"Url setting must be a none empty string or a function that returns one.\" ) ; } // aborts the previous ajax request if not already finished or failed if ( this . xqr ) { this . xqr . abort ( ) ; } var settings = { url : url , data : request , success : function ( response ) { that . xqr = null ; if ( typeof ( response ) === \"string\" ) { response = $ . parseJSON ( response ) ; } response = that . options . responseHandler ( response ) ; that . current = response . current ; update ( response . rows , response . total ) ; } , error : function ( jqXHR , textStatus , errorThrown ) { that . xqr = null ; if ( textStatus !== \"abort\" ) { renderNoResultsRow . call ( that ) ; // overrides loading mask that . element . _bgBusyAria ( false ) . trigger ( \"loaded\" + namespace ) ; } } } ; settings = $ . extend ( this . options . ajaxSettings , settings ) ; this . xqr = $ . ajax ( settings ) ; } else { var rows = ( this . searchPhrase . length > 0 ) ? this . rows . where ( containsPhrase ) : this . rows , total = rows . length ; if ( this . rowCount !== - 1 ) { rows = rows . page ( this . current , this . rowCount ) ; } // todo: improve the following comment // setTimeout decouples the initialization so that adding event handlers happens before window . setTimeout ( function ( ) { update ( rows , total ) ; } , 10 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GRID PUBLIC CLASS DEFINITION ==================== Represents the jQuery Bootgrid plugin . [CODESPLIT] function ( element , options ) { this . element = $ ( element ) ; this . origin = this . element . clone ( ) ; this . options = $ . extend ( true , { } , Grid . defaults , this . element . data ( ) , options ) ; // overrides rowCount explicitly because deep copy ($.extend) leads to strange behaviour var rowCount = this . options . rowCount = this . element . data ( ) . rowCount || options . rowCount || this . options . rowCount ; this . columns = [ ] ; this . current = 1 ; this . currentRows = [ ] ; this . identifier = null ; // The first column ID that is marked as identifier this . selection = false ; this . converter = null ; // The converter for the column that is marked as identifier this . rowCount = ( $ . isArray ( rowCount ) ) ? rowCount [ 0 ] : rowCount ; this . rows = [ ] ; this . searchPhrase = \"\" ; this . selectedRows = [ ] ; this . sortDictionary = { } ; this . total = 0 ; this . totalPages = 0 ; this . cachedParams = { lbl : this . options . labels , css : this . options . css , ctx : { } } ; this . header = null ; this . footer = null ; this . xqr = null ; // todo: implement cache }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns updated index module requiring and exporting the newly created environment . [CODESPLIT] function getModifiedConfigModuleIndex ( fileStr , snakedEnv , classedEnv ) { // TODO [sthzg] we might want to rewrite the AST-mods in this function using a walker. const moduleFileAst = acorn . parse ( fileStr , { module : true } ) ; // if required env was already created, just return the original string if ( jp . paths ( moduleFileAst , ` ${ classedEnv } ` ) . length > 0 ) { return fileStr ; } // insert require call for the new env const envImportAst = acorn . parse ( ` ${ snakedEnv } ${ classedEnv } ` ) ; const insertAt = jp . paths ( moduleFileAst , '$..[?(@.name==\"require\")]' ) . pop ( ) [ 2 ] + 1 ; moduleFileAst . body . splice ( insertAt , 0 , envImportAst ) ; // add new env to module.exports const exportsAt = jp . paths ( moduleFileAst , '$..[?(@.name==\"exports\")]' ) . pop ( ) [ 2 ] ; moduleFileAst . body [ exportsAt ] . expression . right . properties . push ( createExportNode ( snakedEnv ) ) ; return escodegen . generate ( moduleFileAst , { format : { indent : { style : '  ' } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add postcss support to the given webpack base configuration object [CODESPLIT] function ( path ) { const data = fs . readFileSync ( path , 'utf8' ) ; const ast = esprima . parse ( data ) ; // List of css dialects we want to add postCSS for // On regular css, we can add the loader to the end // of the chain. If we have a preprocessor, we will add // it before the initial loader const cssDialects = [ '\\\\.cssmodule\\\\.css$' , '^.((?!cssmodule).)*\\\\.css$' ] ; const preprocessorDialects = [ '\\\\.cssmodule\\\\.(sass|scss)$' , '^.((?!cssmodule).)*\\\\.(sass|scss)$' , '\\\\.cssmodule\\\\.less$' , '^.((?!cssmodule).)*\\\\.less$' , '\\\\.cssmodule\\\\.styl$' , '^.((?!cssmodule).)*\\\\.styl$' ] ; // Prepare postCSS statement for inclusion const postcssFunction = 'var postcss = { postcss: function() { return []; } }' ; const postcssAst = esprima . parse ( postcssFunction ) ; const postcss = postcssAst . body [ 0 ] . declarations [ 0 ] . init . properties [ 0 ] ; // The postcss loader item to add const postcssLoaderObject = 'var postcss = [{ loader: \\'postcss-loader\\'}]' ; const postcssLoaderAst = esprima . parse ( postcssLoaderObject ) ; const postcssLoader = postcssLoaderAst . body [ 0 ] . declarations [ 0 ] . init . elements [ 0 ] ; // Add postcss to the loaders array walk . walkAddParent ( ast , ( node ) => { // Add the postcss key to the global configuration if ( node . type === 'MethodDefinition' && node . key . name === 'defaultSettings' ) { const returnStatement = node . value . body . body [ 1 ] ; returnStatement . argument . properties . push ( postcss ) ; } // Parse all property nodes that use a regex. // This should only be available under module.(pre)loaders if ( node . type === 'Property' && node . key . type === 'Identifier' && node . key . name === 'test' && typeof node . value . regex !== 'undefined' ) { // Regular css usage if ( cssDialects . indexOf ( node . value . regex . pattern ) !== - 1 ) { const loaderData = node . parent . properties [ 1 ] ; loaderData . value . elements . push ( postcssLoader ) ; } if ( preprocessorDialects . indexOf ( node . value . regex . pattern ) !== - 1 ) { const loaderData = node . parent . properties [ 1 ] ; const lastElm = loaderData . value . elements . pop ( ) ; loaderData . value . elements . push ( postcssLoader ) ; loaderData . value . elements . push ( lastElm ) ; } } } ) ; // Prepare the final code and write it back const finalCode = escodegen . generate ( ast , { format : { indent : { adjustMultilineComment : true , style : '  ' } } , comment : true } ) ; fs . writeFileSync ( path , finalCode , 'utf8' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * istanbul ignore next [CODESPLIT] function ( e ) { if ( e . code === 'EADDRINUSE' ) { logger . error ( 'Error: Port ' + port + ' is already in use.' ) ; logger . error ( 'Try another one, e.g. pouchdb-server -p ' + ( parseInt ( port ) + 1 ) + '\\n' ) ; } else { logger . error ( 'Uncaught error: ' + e ) ; logger . error ( e . stack ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "utils [CODESPLIT] function redirectToSkimdb ( req , res ) { var skimUrl = 'http://localhost:' + pouchPort + '/skimdb' ; var get = request . get ( req . originalUrl . replace ( / ^\\/_skimdb / , skimUrl ) ) ; get . on ( 'error' , ( err ) => { logger . warn ( \"couldn't proxy to skimdb\" ) ; logger . warn ( err ) ; } ) ; get . pipe ( res ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents cluster and schema information . The metadata class acts as a internal state of the driver . [CODESPLIT] function Metadata ( options , controlConnection ) { if ( ! options ) { throw new errors . ArgumentError ( 'Options are not defined' ) ; } Object . defineProperty ( this , 'options' , { value : options , enumerable : false , writable : false } ) ; Object . defineProperty ( this , 'controlConnection' , { value : controlConnection , enumerable : false , writable : false } ) ; this . keyspaces = { } ; this . initialized = false ; this . _schemaParser = schemaParserFactory . getByVersion ( options , controlConnection , this . getUdt . bind ( this ) ) ; const self = this ; this . _preparedQueries = new PreparedQueries ( options . maxPrepared , function ( ) { self . log . apply ( self , arguments ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check for udts and get the metadata [CODESPLIT] function checkUdtTypes ( type ) { if ( type . code === types . dataTypes . udt ) { const udtName = type . info . split ( '.' ) ; type . info = { keyspace : udtName [ 0 ] , name : udtName [ 1 ] } ; if ( ! type . info . name ) { if ( ! keyspace ) { throw new TypeError ( 'No keyspace specified for udt: ' + udtName . join ( '.' ) ) ; } //use the provided keyspace type . info . name = type . info . keyspace ; type . info . keyspace = keyspace ; } udts . push ( type ) ; return ; } if ( ! type . info ) { return ; } if ( type . code === types . dataTypes . list || type . code === types . dataTypes . set ) { return checkUdtTypes ( type . info ) ; } if ( type . code === types . dataTypes . map ) { checkUdtTypes ( type . info [ 0 ] ) ; checkUdtTypes ( type . info [ 1 ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows to store prepared queries and retrieval by query or query id . [CODESPLIT] function PreparedQueries ( maxPrepared , logger ) { this . length = 0 ; this . _maxPrepared = maxPrepared ; this . _mapByKey = { } ; this . _mapById = { } ; this . _logger = logger ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Contains the error classes exposed by the driver . [CODESPLIT] function DriverError ( message ) { Error . call ( this , message ) ; Error . captureStackTrace ( this , this . constructor ) ; this . name = this . constructor . name ; this . info = 'Cassandra Driver Error' ; // Explicitly set the message property as the Error.call() doesn't set the property on v8 this . message = message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents an error when a query cannot be performed because no host is available or could be reached by the driver . [CODESPLIT] function NoHostAvailableError ( innerErrors , message ) { DriverError . call ( this , message ) ; this . innerErrors = innerErrors ; this . info = 'Represents an error when a query cannot be performed because no host is available or could be reached by the driver.' ; if ( ! message ) { this . message = 'All host(s) tried for query failed.' ; if ( innerErrors ) { const hostList = Object . keys ( innerErrors ) ; if ( hostList . length > 0 ) { const host = hostList [ 0 ] ; this . message += util . format ( ' First host tried, %s: %s. See innerErrors.' , host , innerErrors [ host ] ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents a client - side error that is raised when the client didn t hear back from the server within { [CODESPLIT] function OperationTimedOutError ( message , host ) { DriverError . call ( this , message , this . constructor ) ; this . info = 'Represents a client-side error that is raised when the client did not hear back from the server ' + 'within socketOptions.readTimeout' ; /**\n   * When defined, it gets the address of the host that caused the operation to time out.\n   * @type {String|undefined}\n   */ this . host = host ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents a client - side error indicating that all connections to a certain host have reached the maximum amount of in - flight requests supported . [CODESPLIT] function BusyConnectionError ( address , maxRequestsPerConnection , connectionLength ) { const message = util . format ( 'All connections to host %s are busy, %d requests are in-flight on %s' , address , maxRequestsPerConnection , connectionLength === 1 ? 'a single connection' : 'each connection' ) ; DriverError . call ( this , message , this . constructor ) ; this . info = 'Represents a client-side error indicating that all connections to a certain host have reached ' + 'the maximum amount of in-flight requests supported (pooling.maxRequestsPerConnection)' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extends and validates the user options [CODESPLIT] function extend ( baseOptions , userOptions ) { if ( arguments . length === 1 ) { userOptions = arguments [ 0 ] ; baseOptions = { } ; } const options = utils . deepExtend ( baseOptions , defaultOptions ( ) , userOptions ) ; if ( ! util . isArray ( options . contactPoints ) || options . contactPoints . length === 0 ) { throw new TypeError ( 'Contacts points are not defined.' ) ; } for ( let i = 0 ; i < options . contactPoints . length ; i ++ ) { const hostName = options . contactPoints [ i ] ; if ( ! hostName ) { throw new TypeError ( util . format ( 'Contact point %s (%s) is not a valid host name, ' + 'the following values are valid contact points: ipAddress, hostName or ipAddress:port' , i , hostName ) ) ; } } if ( ! options . logEmitter ) { options . logEmitter = function ( ) { } ; } if ( ! options . queryOptions ) { throw new TypeError ( 'queryOptions not defined in options' ) ; } if ( options . requestTracker !== null && ! ( options . requestTracker instanceof tracker . RequestTracker ) ) { throw new TypeError ( 'requestTracker must be an instance of RequestTracker' ) ; } if ( ! ( options . metrics instanceof metrics . ClientMetrics ) ) { throw new TypeError ( 'metrics must be an instance of ClientMetrics' ) ; } validatePoliciesOptions ( options . policies ) ; validateProtocolOptions ( options . protocolOptions ) ; validateSocketOptions ( options . socketOptions ) ; options . encoding = options . encoding || { } ; validateEncodingOptions ( options . encoding ) ; if ( options . profiles && ! util . isArray ( options . profiles ) ) { throw new TypeError ( 'profiles must be an Array of ExecutionProfile instances' ) ; } return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the policies from the client options . [CODESPLIT] function validatePoliciesOptions ( policiesOptions ) { if ( ! policiesOptions ) { throw new TypeError ( 'policies not defined in options' ) ; } if ( ! ( policiesOptions . loadBalancing instanceof policies . loadBalancing . LoadBalancingPolicy ) ) { throw new TypeError ( 'Load balancing policy must be an instance of LoadBalancingPolicy' ) ; } if ( ! ( policiesOptions . reconnection instanceof policies . reconnection . ReconnectionPolicy ) ) { throw new TypeError ( 'Reconnection policy must be an instance of ReconnectionPolicy' ) ; } if ( ! ( policiesOptions . retry instanceof policies . retry . RetryPolicy ) ) { throw new TypeError ( 'Retry policy must be an instance of RetryPolicy' ) ; } if ( ! ( policiesOptions . addressResolution instanceof policies . addressResolution . AddressTranslator ) ) { throw new TypeError ( 'Address resolution policy must be an instance of AddressTranslator' ) ; } if ( policiesOptions . timestampGeneration !== null && ! ( policiesOptions . timestampGeneration instanceof policies . timestampGeneration . TimestampGenerator ) ) { throw new TypeError ( 'Timestamp generation policy must be an instance of TimestampGenerator' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the protocol options . [CODESPLIT] function validateProtocolOptions ( protocolOptions ) { if ( ! protocolOptions ) { throw new TypeError ( 'protocolOptions not defined in options' ) ; } const version = protocolOptions . maxVersion ; if ( version && ( typeof version !== 'number' || ! types . protocolVersion . isSupported ( version ) ) ) { throw new TypeError ( util . format ( 'protocolOptions.maxVersion provided (%s) is invalid' , version ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the socket options . [CODESPLIT] function validateSocketOptions ( socketOptions ) { if ( ! socketOptions ) { throw new TypeError ( 'socketOptions not defined in options' ) ; } if ( typeof socketOptions . readTimeout !== 'number' ) { throw new TypeError ( 'socketOptions.readTimeout must be a Number' ) ; } if ( typeof socketOptions . coalescingThreshold !== 'number' || socketOptions . coalescingThreshold <= 0 ) { throw new TypeError ( 'socketOptions.coalescingThreshold must be a positive Number' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the encoding options . [CODESPLIT] function validateEncodingOptions ( encodingOptions ) { if ( encodingOptions . map ) { const mapConstructor = encodingOptions . map ; if ( typeof mapConstructor !== 'function' || typeof mapConstructor . prototype . forEach !== 'function' || typeof mapConstructor . prototype . set !== 'function' ) { throw new TypeError ( 'Map constructor not valid' ) ; } } if ( encodingOptions . set ) { const setConstructor = encodingOptions . set ; if ( typeof setConstructor !== 'function' || typeof setConstructor . prototype . forEach !== 'function' || typeof setConstructor . prototype . add !== 'function' ) { throw new TypeError ( 'Set constructor not valid' ) ; } } if ( ( encodingOptions . useBigIntAsLong || encodingOptions . useBigIntAsVarint ) && typeof BigInt === 'undefined' ) { throw new TypeError ( 'BigInt is not supported by the JavaScript engine' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the default options that depend on the protocol version . [CODESPLIT] function setProtocolDependentDefaults ( options , version ) { let coreConnectionsPerHost = coreConnectionsPerHostV3 ; let maxRequestsPerConnection = maxRequestsPerConnectionV3 ; if ( ! types . protocolVersion . uses2BytesStreamIds ( version ) ) { coreConnectionsPerHost = coreConnectionsPerHostV2 ; maxRequestsPerConnection = maxRequestsPerConnectionV2 ; } options . pooling = utils . deepExtend ( { } , { coreConnectionsPerHost , maxRequestsPerConnection } , options . pooling ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the typeInfo of a given type name [CODESPLIT] function ( name ) { name = name . toLowerCase ( ) ; if ( name . indexOf ( '<' ) > 0 ) { const listMatches = / ^(list|set)<(.+)>$ / . exec ( name ) ; if ( listMatches ) { return { code : this [ listMatches [ 1 ] ] , info : this . getByName ( listMatches [ 2 ] ) } ; } const mapMatches = / ^(map)< *(.+) *, *(.+)>$ / . exec ( name ) ; if ( mapMatches ) { return { code : this [ mapMatches [ 1 ] ] , info : [ this . getByName ( mapMatches [ 2 ] ) , this . getByName ( mapMatches [ 3 ] ) ] } ; } const udtMatches = / ^(udt)<(.+)>$ / . exec ( name ) ; if ( udtMatches ) { //udt name as raw string return { code : this [ udtMatches [ 1 ] ] , info : udtMatches [ 2 ] } ; } const tupleMatches = / ^(tuple)<(.+)>$ / . exec ( name ) ; if ( tupleMatches ) { //tuple info as an array of types return { code : this [ tupleMatches [ 1 ] ] , info : tupleMatches [ 2 ] . split ( ',' ) . map ( function ( x ) { return this . getByName ( x . trim ( ) ) ; } , this ) } ; } } const typeInfo = { code : this [ name ] , info : null } ; if ( typeof typeInfo . code !== 'number' ) { throw new TypeError ( 'Data type with name ' + name + ' not valid' ) ; } return typeInfo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > <strong > Backward compatibility only use [ TimeUuid ] { [CODESPLIT] function timeuuid ( options , buffer , offset ) { let date ; let ticks ; let nodeId ; let clockId ; if ( options ) { if ( typeof options . msecs === 'number' ) { date = new Date ( options . msecs ) ; } if ( options . msecs instanceof Date ) { date = options . msecs ; } if ( util . isArray ( options . node ) ) { nodeId = utils . allocBufferFromArray ( options . node ) ; } if ( typeof options . clockseq === 'number' ) { clockId = utils . allocBufferUnsafe ( 2 ) ; clockId . writeUInt16BE ( options . clockseq , 0 ) ; } if ( typeof options . nsecs === 'number' ) { ticks = options . nsecs ; } } const uuid = new TimeUuid ( date , ticks , nodeId , clockId ) ; if ( buffer instanceof Buffer ) { //copy the values into the buffer uuid . getBuffer ( ) . copy ( buffer , offset || 0 ) ; return buffer ; } return uuid . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > <strong > Backward compatibility only use [ Uuid ] { [CODESPLIT] function uuid ( options , buffer , offset ) { let uuid ; if ( options ) { if ( util . isArray ( options . random ) ) { uuid = new Uuid ( utils . allocBufferFromArray ( options . random ) ) ; } } if ( ! uuid ) { uuid = Uuid . random ( ) ; } if ( buffer instanceof Buffer ) { //copy the values into the buffer uuid . getBuffer ( ) . copy ( buffer , offset || 0 ) ; return buffer ; } return uuid . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the data type name for a given type definition [CODESPLIT] function getDataTypeNameByCode ( item ) { if ( ! item || typeof item . code !== 'number' ) { throw new errors . ArgumentError ( 'Invalid signature type definition' ) ; } const typeName = _dataTypesByCode [ item . code ] ; if ( ! typeName ) { throw new errors . ArgumentError ( util . format ( 'Type with code %d not found' , item . code ) ) ; } if ( ! item . info ) { return typeName ; } if ( util . isArray ( item . info ) ) { return ( typeName + '<' + item . info . map ( function ( t ) { return getDataTypeNameByCode ( t ) ; } ) . join ( ', ' ) + '>' ) ; } if ( typeof item . info . code === 'number' ) { return typeName + '<' + getDataTypeNameByCode ( item . info ) + '>' ; } return typeName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "classes Represents a frame header that could be used to read from a Buffer or to write to a Buffer [CODESPLIT] function FrameHeader ( version , flags , streamId , opcode , bodyLength ) { this . version = version ; this . flags = flags ; this . streamId = streamId ; this . opcode = opcode ; this . bodyLength = bodyLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a value representing the timestamp for the query in microseconds based on the date and the microseconds provided [CODESPLIT] function generateTimestamp ( date , microseconds ) { if ( ! date ) { date = new Date ( ) ; } let longMicro = Long . ZERO ; if ( typeof microseconds === 'number' && microseconds >= 0 && microseconds < 1000 ) { longMicro = Long . fromInt ( microseconds ) ; } else { if ( _timestampTicks > 999 ) { _timestampTicks = 0 ; } longMicro = Long . fromInt ( _timestampTicks ) ; _timestampTicks ++ ; } return Long . fromNumber ( date . getTime ( ) ) . multiply ( _longOneThousand ) . add ( longMicro ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "error classes [CODESPLIT] function QueryParserError ( e ) { QueryParserError . super_ . call ( this , e . message , this . constructor ) ; this . internalError = e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a signed int64 representation . [CODESPLIT] function MutableLong ( b00 , b16 , b32 , b48 ) { // Use an array of uint16 this . _arr = [ b00 & 0xffff , b16 & 0xffff , b32 & 0xffff , b48 & 0xffff ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Aggregate . [CODESPLIT] function Aggregate ( ) { /**\n   * Name of the aggregate.\n   * @type {String}\n   */ this . name = null ; /**\n   * Name of the keyspace where the aggregate is declared.\n   */ this . keyspaceName = null ; /**\n   * Signature of the aggregate.\n   * @type {Array.<String>}\n   */ this . signature = null ; /**\n   * List of the CQL aggregate argument types.\n   * @type {Array.<{code, info}>}\n   */ this . argumentTypes = null ; /**\n   * State Function.\n   * @type {String}\n   */ this . stateFunction = null ; /**\n   * State Type.\n   * @type {{code, info}}\n   */ this . stateType = null ; /**\n   * Final Function.\n   * @type {String}\n   */ this . finalFunction = null ; this . initConditionRaw = null ; /**\n   * Initial state value of this aggregate.\n   * @type {String}\n   */ this . initCondition = null ; /**\n   * Type of the return value.\n   * @type {{code: number, info: (Object|Array|null)}}\n   */ this . returnType = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Host instance . [CODESPLIT] function Host ( address , protocolVersion , options , metadata ) { events . EventEmitter . call ( this ) ; /**\n   * Gets ip address and port number of the node separated by `:`.\n   * @type {String}\n   */ this . address = address ; this . setDownAt = 0 ; /**\n   * Gets the timestamp of the moment when the Host was marked as UP.\n   * @type {Number|null}\n   * @ignore\n   * @internal\n   */ this . isUpSince = null ; Object . defineProperty ( this , 'options' , { value : options , enumerable : false , writable : false } ) ; /**\n   * The host pool.\n   * @internal\n   * @ignore\n   * @type {HostConnectionPool}\n   */ Object . defineProperty ( this , 'pool' , { value : new HostConnectionPool ( this , protocolVersion ) , enumerable : false } ) ; const self = this ; this . pool . on ( 'open' , this . _onNewConnectionOpen . bind ( this ) ) ; this . pool . on ( 'remove' , function onConnectionRemovedFromPool ( ) { self . _checkPoolState ( ) ; } ) ; /**\n   * Gets string containing the Cassandra version.\n   * @type {String}\n   */ this . cassandraVersion = null ; /**\n   * Gets data center name of the node.\n   * @type {String}\n   */ this . datacenter = null ; /**\n   * Gets rack name of the node.\n   * @type {String}\n   */ this . rack = null ; /**\n   * Gets the tokens assigned to the node.\n   * @type {Array}\n   */ this . tokens = null ; /**\n   * Gets the id of the host.\n   * <p>This identifier is used by the server for internal communication / gossip.</p>\n   * @type {Uuid}\n   */ this . hostId = null ; // the distance as last set using the load balancing policy this . _distance = types . distance . ignored ; this . _healthResponseCounter = 0 ; // Make some of the private instance variables not enumerable to prevent from showing when inspecting Object . defineProperty ( this , '_metadata' , { value : metadata , enumerable : false } ) ; Object . defineProperty ( this , '_healthResponseCountTimer' , { value : null , enumerable : false , writable : true } ) ; this . reconnectionSchedule = this . options . policies . reconnection . newSchedule ( ) ; this . reconnectionDelay = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents an associative - array of { [CODESPLIT] function HostMap ( ) { events . EventEmitter . call ( this ) ; this . _items = { } ; this . _values = null ; Object . defineProperty ( this , 'length' , { get : function ( ) { return this . values ( ) . length ; } , enumerable : true } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of ConstantSpeculativeExecutionPolicy . [CODESPLIT] function ConstantSpeculativeExecutionPolicy ( delay , maxSpeculativeExecutions ) { if ( ! ( delay >= 0 ) ) { throw new errors . ArgumentError ( 'delay must be a positive number or zero' ) ; } if ( ! ( maxSpeculativeExecutions > 0 ) ) { throw new errors . ArgumentError ( 'maxSpeculativeExecutions must be a positive number' ) ; } this . _delay = delay ; this . _maxSpeculativeExecutions = maxSpeculativeExecutions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new MaterializedView . [CODESPLIT] function MaterializedView ( name ) { DataCollection . call ( this , name ) ; /**\n   * Name of the table.\n   * @type {String}\n   */ this . tableName = null ; /**\n   * View where clause.\n   * @type {String}\n   */ this . whereClause = null ; /**\n   * Determines if all the table columns where are included in the view.\n   * @type {boolean}\n   */ this . includeAllColumns = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of { [CODESPLIT] function ExecutionProfile ( name , options ) { if ( typeof name !== 'string' ) { throw new TypeError ( 'Execution profile name must be a string' ) ; } options = options || utils . emptyObject ; /**\n   * Name of the execution profile.\n   * @type {String}\n   */ this . name = name ; /**\n   * Consistency level.\n   * @type {Number}\n   */ this . consistency = options . consistency ; /**\n   * Load-balancing policy\n   * @type {LoadBalancingPolicy}\n   */ this . loadBalancing = options . loadBalancing ; /**\n   * Client read timeout.\n   * @type {Number}\n   */ this . readTimeout = options . readTimeout ; /**\n   * Retry policy.\n   * @type {RetryPolicy}\n   */ this . retry = options . retry ; /**\n   * Serial consistency level.\n   * @type {Number}\n   */ this . serialConsistency = options . serialConsistency ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates for a IPv4 - Mapped IPv6 according to https : // tools . ietf . org / html / rfc4291#section - 2 . 5 . 5 [CODESPLIT] function isValidIPv4Mapped ( buffer ) { // check the form // |      80 bits   | 16 |   32 bits // +----------------+----+------------- // |0000........0000|FFFF| IPv4 address for ( let i = 0 ; i < buffer . length - 6 ; i ++ ) { if ( buffer [ i ] !== 0 ) { return false ; } } return ! ( buffer [ 10 ] !== 255 || buffer [ 11 ] !== 255 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of DataCollection [CODESPLIT] function DataCollection ( name ) { events . EventEmitter . call ( this ) ; this . setMaxListeners ( 0 ) ; //private Object . defineProperty ( this , 'loading' , { value : false , enumerable : false , writable : true } ) ; Object . defineProperty ( this , 'loaded' , { value : false , enumerable : false , writable : true } ) ; /**\n   * Name of the object\n   * @type {String}\n   */ this . name = name ; /**\n   * False-positive probability for SSTable Bloom filters.\n   * @type {number}\n   */ this . bloomFilterFalsePositiveChance = 0 ; /**\n   * Level of caching: all, keys_only, rows_only, none\n   * @type {String}\n   */ this . caching = null ; /**\n   * A human readable comment describing the table.\n   * @type {String}\n   */ this . comment = null ; /**\n   * Specifies the time to wait before garbage collecting tombstones (deletion markers)\n   * @type {number}\n   */ this . gcGraceSeconds = 0 ; /**\n   * Compaction strategy class used for the table.\n   * @type {String}\n   */ this . compactionClass = null ; /**\n   * Associative-array containing the compaction options keys and values.\n   * @type {Object}\n   */ this . compactionOptions = null ; /**\n   * Associative-array containing the compression options.\n   * @type {Object}\n   */ this . compression = null ; /**\n   * Specifies the probability of read repairs being invoked over all replicas in the current data center.\n   * @type {number}\n   */ this . localReadRepairChance = 0 ; /**\n   * Specifies the probability with which read repairs should be invoked on non-quorum reads. The value must be\n   * between 0 and 1.\n   * @type {number}\n   */ this . readRepairChance = 0 ; /**\n   * An associative Array containing extra metadata for the table.\n   * <p>\n   * For Apache Cassandra versions prior to 3.0.0, this method always returns <code>null</code>.\n   * </p>\n   * @type {Object}\n   */ this . extensions = null ; /**\n   * When compression is enabled, this option defines the probability\n   * with which checksums for compressed blocks are checked during reads.\n   * The default value for this options is 1.0 (always check).\n   * <p>\n   *   For Apache Cassandra versions prior to 3.0.0, this method always returns <code>null</code>.\n   * </p>\n   * @type {Number|null}\n   */ this . crcCheckChance = null ; /**\n   * Whether the populate I/O cache on flush is set on this table.\n   * @type {Boolean}\n   */ this . populateCacheOnFlush = false ; /**\n   * Returns the default TTL for this table.\n   * @type {Number}\n   */ this . defaultTtl = 0 ; /**\n   * * Returns the speculative retry option for this table.\n   * @type {String}\n   */ this . speculativeRetry = 'NONE' ; /**\n   * Returns the minimum index interval option for this table.\n   * <p>\n   *   Note: this option is available in Apache Cassandra 2.1 and above, and will return <code>null</code> for\n   *   earlier versions.\n   * </p>\n   * @type {Number|null}\n   */ this . minIndexInterval = 128 ; /**\n   * Returns the maximum index interval option for this table.\n   * <p>\n   * Note: this option is available in Apache Cassandra 2.1 and above, and will return <code>null</code> for\n   * earlier versions.\n   * </p>\n   * @type {Number|null}\n   */ this . maxIndexInterval = 2048 ; /**\n   * Array describing the table columns.\n   * @type {Array}\n   */ this . columns = null ; /**\n   * An associative Array of columns by name.\n   * @type {Object}\n   */ this . columnsByName = null ; /**\n   * Array describing the columns that are part of the partition key.\n   * @type {Array}\n   */ this . partitionKeys = [ ] ; /**\n   * Array describing the columns that form the clustering key.\n   * @type {Array}\n   */ this . clusteringKeys = [ ] ; /**\n   * Array describing the clustering order of the columns in the same order as the clusteringKeys.\n   * @type {Array}\n   */ this . clusteringOrder = [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a two s - complement integer an array containing bits of the integer in 32 - bit ( signed ) pieces given in little - endian order ( i . e . lowest - order bits in the first piece ) and the sign of - 1 or 0 . [CODESPLIT] function Integer ( bits , sign ) { /**\n   * @type {!Array.<number>}\n   * @private\n   */ this . bits_ = [ ] ; /**\n   * @type {number}\n   * @private\n   */ this . sign_ = sign ; // Copy the 32-bit signed integer values passed in.  We prune out those at the // top that equal the sign since they are redundant. var top = true ; for ( var i = bits . length - 1 ; i >= 0 ; i -- ) { var val = bits [ i ] | 0 ; if ( ! top || val != sign ) { this . bits_ [ i ] = val ; top = false ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms chunks emits data objects { header chunk } [CODESPLIT] function Protocol ( options ) { Transform . call ( this , options ) ; this . header = null ; this . bodyLength = 0 ; this . clearHeaderChunks ( ) ; this . version = 0 ; this . headerSize = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts multiple rows in a table limiting the amount of parallel requests . [CODESPLIT] async function example ( ) { await client . connect ( ) ; await client . execute ( ` ` ) ; await client . execute ( ` ` ) ; await client . execute ( ` ` ) ; // The maximum amount of async executions that are going to be launched in parallel // at any given time const concurrencyLevel = 32 ; const promises = new Array ( concurrencyLevel ) ; const info = { totalLength : 10000 , counter : 0 } ; // Launch in parallel n async operations (n being the concurrency level) for ( let i = 0 ; i < concurrencyLevel ; i ++ ) { promises [ i ] = executeOneAtATime ( info ) ; } try { // The n promises are going to be resolved when all the executions are completed. await Promise . all ( promises ) ; console . log ( ` ${ info . totalLength } ${ concurrencyLevel } ` ) ; } finally { client . shutdown ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of TableMetadata [CODESPLIT] function TableMetadata ( name ) { DataCollection . call ( this , name ) ; /**\n   * Applies only to counter tables.\n   * When set to true, replicates writes to all affected replicas regardless of the consistency level specified by\n   * the client for a write request. For counter tables, this should always be set to true.\n   * @type {Boolean}\n   */ this . replicateOnWrite = true ; /**\n   * Returns the memtable flush period (in milliseconds) option for this table.\n   * @type {Number}\n   */ this . memtableFlushPeriod = 0 ; /**\n   * Returns the index interval option for this table.\n   * <p>\n   * Note: this option is only available in Apache Cassandra 2.0. It is deprecated in Apache Cassandra 2.1 and\n   * above, and will therefore return <code>null</code> for 2.1 nodes.\n   * </p>\n   * @type {Number|null}\n   */ this . indexInterval = null ; /**\n   * Determines  whether the table uses the COMPACT STORAGE option.\n   * @type {Boolean}\n   */ this . isCompact = false ; /**\n   *\n   * @type {Array.<Index>}\n   */ this . indexes = null ; /**\n   * Determines whether the Change Data Capture (CDC) flag is set for the table.\n   * @type {Boolean|null}\n   */ this . cdc = null ; /**\n   * Determines whether the table is a virtual table or not.\n   * @type {Boolean}\n   */ this . virtual = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to parse schema information for Cassandra versions 1 . 2 . x and 2 . x [CODESPLIT] function SchemaParserV1 ( options , cc ) { SchemaParser . call ( this , options , cc ) ; this . selectTable = _selectTableV1 ; this . selectColumns = _selectColumnsV1 ; this . selectUdt = _selectUdtV1 ; this . selectAggregates = _selectAggregatesV1 ; this . selectFunctions = _selectFunctionsV1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to parse schema information for Cassandra versions 3 . x and above [CODESPLIT] function SchemaParserV2 ( options , cc , udtResolver ) { SchemaParser . call ( this , options , cc ) ; this . udtResolver = udtResolver ; this . selectTable = _selectTableV2 ; this . selectColumns = _selectColumnsV2 ; this . selectUdt = _selectUdtV2 ; this . selectAggregates = _selectAggregatesV2 ; this . selectFunctions = _selectFunctionsV2 ; this . selectIndexes = _selectIndexesV2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to parse schema information for Cassandra versions 4 . x and above . [CODESPLIT] function SchemaParserV3 ( options , cc , udtResolver ) { SchemaParserV2 . call ( this , options , cc , udtResolver ) ; this . supportsVirtual = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upon migration from thrift to CQL we internally create a pair of surrogate clustering / regular columns for compact static tables . These columns shouldn t be exposed to the user but are currently returned by C * . We also need to remove the static keyword for all other columns in the table . [CODESPLIT] function pruneStaticCompactTableColumns ( tableInfo ) { let i ; let c ; //remove \"column1 text\" clustering column for ( i = 0 ; i < tableInfo . clusteringKeys . length ; i ++ ) { c = tableInfo . clusteringKeys [ i ] ; const index = tableInfo . columns . indexOf ( c ) ; tableInfo . columns . splice ( index , 1 ) ; delete tableInfo . columnsByName [ c . name ] ; } tableInfo . clusteringKeys = utils . emptyArray ; tableInfo . clusteringOrder = utils . emptyArray ; //remove regular columns and set the static columns to non-static i = tableInfo . columns . length ; while ( i -- ) { c = tableInfo . columns [ i ] ; if ( ! c . isStatic && tableInfo . partitionKeys . indexOf ( c ) === - 1 ) { // remove \"value blob\" regular column tableInfo . columns . splice ( i , 1 ) ; delete tableInfo . columnsByName [ c . name ] ; continue ; } c . isStatic = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upon migration from thrift to CQL we internally create a surrogate column value of type custom . This column shouldn t be exposed to the user but is currently returned by C * . [CODESPLIT] function pruneDenseTableColumns ( tableInfo ) { let i = tableInfo . columns . length ; while ( i -- ) { const c = tableInfo . columns [ i ] ; if ( ! c . isStatic && c . type . code === types . dataTypes . custom && c . type . info === 'empty' ) { // remove \"value blob\" regular column tableInfo . columns . splice ( i , 1 ) ; delete tableInfo . columnsByName [ c . name ] ; continue ; } c . isStatic = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance if the currentInstance is not valid for the provided Cassandra version [CODESPLIT] function getByVersion ( options , cc , udtResolver , version , currentInstance ) { let parserConstructor = SchemaParserV1 ; if ( version && version [ 0 ] === 3 ) { parserConstructor = SchemaParserV2 ; } else if ( version && version [ 0 ] >= 4 ) { parserConstructor = SchemaParserV3 ; } if ( ! currentInstance || ! ( currentInstance instanceof parserConstructor ) ) { return new parserConstructor ( options , cc , udtResolver ) ; } return currentInstance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query options [CODESPLIT] function Client ( options ) { events . EventEmitter . call ( this ) ; this . options = clientOptions . extend ( { logEmitter : this . emit . bind ( this ) } , options ) ; Object . defineProperty ( this , 'profileManager' , { value : new ProfileManager ( this . options ) } ) ; Object . defineProperty ( this , 'controlConnection' , { value : new ControlConnection ( this . options , this . profileManager ) , writable : true } ) ; //Unlimited amount of listeners for internal event queues by default this . setMaxListeners ( 0 ) ; this . connected = false ; this . isShuttingDown = false ; /**\n   * Gets the name of the active keyspace.\n   * @type {String}\n   */ this . keyspace = options . keyspace ; /**\n   * Gets the schema and cluster metadata information.\n   * @type {Metadata}\n   */ this . metadata = this . controlConnection . metadata ; /**\n   * Gets an associative array of cluster hosts.\n   * @type {HostMap}\n   */ this . hosts = this . controlConnection . hosts ; /**\n   * The [ClientMetrics]{@link module:metrics~ClientMetrics} instance used to expose measurements of its internal\n   * behavior and of the server as seen from the driver side.\n   * <p>By default, a [DefaultMetrics]{@link module:metrics~DefaultMetrics} instance is used.</p>\n   * @type {ClientMetrics}\n   */ this . metrics = this . options . metrics ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper function as encoding a routing key could throw a TypeError [CODESPLIT] function encodeRoutingKey ( fromUser ) { const encoder = self . _getEncoder ( ) ; try { if ( fromUser ) { encoder . setRoutingKeyFromUser ( params , execOptions ) ; } else { encoder . setRoutingKeyFromMeta ( meta , params , execOptions ) ; } } catch ( err ) { return callback ( err ) ; } callback ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This script is used to check that the samples run correctly . It is not a valid example see README . md and subdirectories for more information . List all js files in the directory [CODESPLIT] function getJsFiles ( dir , fileArray ) { const files = fs . readdirSync ( dir ) ; fileArray = fileArray || [ ] ; files . forEach ( function ( file ) { if ( file === 'node_modules' ) { return ; } if ( fs . statSync ( dir + file ) . isDirectory ( ) ) { getJsFiles ( dir + file + '/' , fileArray ) ; return ; } if ( file . substring ( file . length - 3 , file . length ) !== '.js' ) { return ; } fileArray . push ( dir + file ) ; } ) ; return fileArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts multiple rows in a table from an Array using the built in method <code > executeConcurrent () < / code > limiting the amount of parallel requests . [CODESPLIT] async function example ( ) { await client . connect ( ) ; await client . execute ( ` ` ) ; await client . execute ( ` ` ) ; await client . execute ( ` ` ) ; // The maximum amount of async executions that are going to be launched in parallel // at any given time const concurrencyLevel = 32 ; // Use an Array with 10000 different values const values = Array . from ( new Array ( 10000 ) . keys ( ) ) . map ( x => [ Uuid . random ( ) , x . toString ( ) ] ) ; try { const query = 'INSERT INTO tbl_sample_kv (id, value) VALUES (?, ?)' ; await executeConcurrent ( client , query , values ) ; console . log ( ` ${ values . length } ${ concurrencyLevel } ` ) ; } finally { client . shutdown ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new SchemaFunction . [CODESPLIT] function SchemaFunction ( ) { /**\n   * Name of the cql function.\n   * @type {String}\n   */ this . name = null ; /**\n   * Name of the keyspace where the cql function is declared.\n   */ this . keyspaceName = null ; /**\n   * Signature of the function.\n   * @type {Array.<String>}\n   */ this . signature = null ; /**\n   * List of the function argument names.\n   * @type {Array.<String>}\n   */ this . argumentNames = null ; /**\n   * List of the function argument types.\n   * @type {Array.<{code, info}>}\n   */ this . argumentTypes = null ; /**\n   * Body of the function.\n   * @type {String}\n   */ this . body = null ; /**\n   * Determines if the function is called when the input is null.\n   * @type {Boolean}\n   */ this . calledOnNullInput = null ; /**\n   * Name of the programming language, for example: java, javascript, ...\n   * @type {String}\n   */ this . language = null ; /**\n   * Type of the return value.\n   * @type {{code: number, info: (Object|Array|null)}}\n   */ this . returnType = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utilities for concurrent query execution with the DataStax Node . js Driver . @module concurrent Executes multiple queries concurrently at the defined concurrency level . @static @param { Client } client The { @link Client } instance . @param { String|Array< { query params } > } query The query to execute per each parameter item . @param { Array<Array > |Stream|Object } parameters An { @link Array } or a readable { @link Stream } composed of { @link Array } items representing each individual set of parameters . Per each item in the { @link Array } or { @link Stream } an execution is going to be made . @param { Object } [ options ] The execution options . @param { String } [ options . executionProfile ] The execution profile to be used . @param { Number } [ options . concurrencyLevel = 100 ] The concurrency level to determine the maximum amount of in - flight operations at any given time @param { Boolean } [ options . raiseOnFirstError = true ] Determines whether execution should stop after the first failed execution and the corresponding exception will be raised . @param { Boolean } [ options . collectResults = false ] Determines whether each individual [ ResultSet ] { @link module : types~ResultSet } instance should be collected in the grouped result . @param { Number } [ options . maxErrors = 100 ] The maximum amount of errors to be collected before ignoring the rest of the error results . @returns { Promise<ResultSetGroup > } A <code > Promise< / code > of { @link ResultSetGroup } that is resolved when all the executions completed and it s rejected when <code > raiseOnFirstError< / code > is <code > true< / code > and there is one or more failures . @example <caption > Using a fixed query and an Array of Arrays as parameters< / caption > const query = INSERT INTO table1 ( id value ) VALUES ( ? ? ) ; const parameters = [[ 1 a ] [ 2 b ] [ 3 c ] ] ; // ... const result = await executeConcurrent ( client query parameters ) ; @example <caption > Using a fixed query and a readable stream< / caption > const stream = csvStream . pipe ( transformLineToArrayStream ) ; const result = await executeConcurrent ( client query stream ) ; @example <caption > Using a different queries< / caption > const queryAndParameters = [ { query : INSERT INTO videos ( id name user_id ) VALUES ( ? ? ? ) params : [ id name userId ] } { query : INSERT INTO user_videos ( user_id id name ) VALUES ( ? ? ? ) params : [ userId id name ] } { query : INSERT INTO latest_videos ( id name user_id ) VALUES ( ? ? ? ) params : [ id name userId ] } ] ; [CODESPLIT] function executeConcurrent ( client , query , parameters , options ) { if ( ! client ) { throw new TypeError ( 'Client instance is not defined' ) ; } if ( typeof query === 'string' ) { if ( Array . isArray ( parameters ) ) { return new ArrayBasedExecutor ( client , query , parameters , options ) . execute ( ) ; } if ( parameters instanceof Stream ) { return new StreamBasedExecutor ( client , query , parameters , options ) . execute ( ) ; } throw new TypeError ( 'parameters should be an Array or a Stream instance' ) ; } if ( Array . isArray ( query ) ) { options = parameters ; return new ArrayBasedExecutor ( client , null , query , options ) . execute ( ) ; } throw new TypeError ( 'A string query or query and parameters array should be provided' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a copy of a buffer [CODESPLIT] function copyBuffer ( buf ) { const targetBuffer = allocBufferUnsafe ( buf . length ) ; buf . copy ( targetBuffer ) ; return targetBuffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends the original stack trace to the error after a tick of the event loop [CODESPLIT] function fixStack ( stackTrace , error ) { if ( stackTrace ) { error . stack += '\\n  (event loop)\\n' + stackTrace . substr ( stackTrace . indexOf ( \"\\n\" ) + 1 ) ; } return error ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the logEmitter to emit log events [CODESPLIT] function log ( type , info , furtherInfo ) { if ( ! this . logEmitter ) { if ( ! this . options || ! this . options . logEmitter ) { throw new Error ( 'Log emitter not defined' ) ; } this . logEmitter = this . options . logEmitter ; } this . logEmitter ( 'log' , type , this . constructor . name , info , furtherInfo || '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge the contents of two or more objects together into the first object . Similar to jQuery . extend / Object . assign . The main difference between this method is that declared properties with an <code > undefined< / code > value are not set to the target . [CODESPLIT] function extend ( target ) { const sources = Array . prototype . slice . call ( arguments , 1 ) ; sources . forEach ( function ( source ) { if ( ! source ) { return ; } const keys = Object . keys ( source ) ; for ( let i = 0 ; i < keys . length ; i ++ ) { const key = keys [ i ] ; const value = source [ key ] ; if ( value === undefined ) { continue ; } target [ key ] = value ; } } ) ; return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new object with the property names set to lowercase . [CODESPLIT] function toLowerCaseProperties ( obj ) { const keys = Object . keys ( obj ) ; const result = { } ; for ( let i = 0 ; i < keys . length ; i ++ ) { const k = keys [ i ] ; result [ k . toLowerCase ( ) ] = obj [ k ] ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extends the target by the most inner props of sources [CODESPLIT] function deepExtend ( target ) { const sources = Array . prototype . slice . call ( arguments , 1 ) ; sources . forEach ( function ( source ) { for ( const prop in source ) { if ( ! source . hasOwnProperty ( prop ) ) { continue ; } const targetProp = target [ prop ] ; const targetType = ( typeof targetProp ) ; //target prop is // a native single type // or not existent // or is not an anonymous object (not class instance) if ( ! targetProp || targetType === 'number' || targetType === 'string' || util . isArray ( targetProp ) || util . isDate ( targetProp ) || targetProp . constructor . name !== 'Object' ) { target [ prop ] = source [ prop ] ; } else { //inner extend target [ prop ] = deepExtend ( { } , targetProp , source [ prop ] ) ; } } } ) ; return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the iterator protocol to go through the items of the Array [CODESPLIT] function arrayIterator ( arr ) { let index = 0 ; return { next : function ( ) { if ( index >= arr . length ) { return { done : true } ; } return { value : arr [ index ++ ] , done : false } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the iterator values into an array [CODESPLIT] function iteratorToArray ( iterator ) { const values = [ ] ; let item = iterator . next ( ) ; while ( ! item . done ) { values . push ( item . value ) ; item = iterator . next ( ) ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches the specified Array for the provided key using the binary search algorithm . The Array must be sorted . [CODESPLIT] function binarySearch ( arr , key , compareFunc ) { let low = 0 ; let high = arr . length - 1 ; while ( low <= high ) { const mid = ( low + high ) >>> 1 ; const midVal = arr [ mid ] ; const cmp = compareFunc ( midVal , key ) ; if ( cmp < 0 ) { low = mid + 1 ; } else if ( cmp > 0 ) { high = mid - 1 ; } else { //The key was found in the Array return mid ; } } // key not found return ~ low ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the value in the position determined by its natural order determined by the compare func [CODESPLIT] function insertSorted ( arr , item , compareFunc ) { if ( arr . length === 0 ) { return arr . push ( item ) ; } let position = binarySearch ( arr , item , compareFunc ) ; if ( position < 0 ) { position = ~ position ; } arr . splice ( position , 0 , item ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the provided parameter is of type function . [CODESPLIT] function validateFn ( fn , name ) { if ( typeof fn !== 'function' ) { throw new errors . ArgumentError ( util . format ( '%s is not a function' , name || 'callback' ) ) ; } return fn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adapts the parameters based on the prepared metadata . If the params are passed as an associative array ( Object ) it adapts the object into an array with the same order as columns [CODESPLIT] function adaptNamedParamsPrepared ( params , columns ) { if ( ! params || util . isArray ( params ) || ! columns || columns . length === 0 ) { // params is an array or there aren't parameters return params ; } const paramsArray = new Array ( columns . length ) ; params = toLowerCaseProperties ( params ) ; const keys = { } ; for ( let i = 0 ; i < columns . length ; i ++ ) { const name = columns [ i ] . name ; if ( ! params . hasOwnProperty ( name ) ) { throw new errors . ArgumentError ( util . format ( 'Parameter \"%s\" not defined' , name ) ) ; } paramsArray [ i ] = params [ name ] ; keys [ name ] = i ; } return paramsArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adapts the associative - array of parameters and hints for simple statements into Arrays based on the ( arbitrary ) position of the keys . [CODESPLIT] function adaptNamedParamsWithHints ( params , execOptions ) { if ( ! params || util . isArray ( params ) ) { //The parameters is an Array or there isn't parameter return { params : params , namedParameters : false , keyIndexes : null } ; } const keys = Object . keys ( params ) ; const paramsArray = new Array ( keys . length ) ; const hints = new Array ( keys . length ) ; const userHints = execOptions . getHints ( ) || emptyObject ; const keyIndexes = { } ; for ( let i = 0 ; i < keys . length ; i ++ ) { const key = keys [ i ] ; // As lower cased identifiers paramsArray [ i ] = { name : key . toLowerCase ( ) , value : params [ key ] } ; hints [ i ] = userHints [ key ] ; keyIndexes [ key ] = i ; } execOptions . setHints ( hints ) ; return { params : paramsArray , namedParameters : true , keyIndexes } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string with a value repeated n times [CODESPLIT] function stringRepeat ( val , times ) { if ( ! times || times < 0 ) { return null ; } if ( times === 1 ) { return val ; } return new Array ( times + 1 ) . join ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array containing the values of the Object similar to Object . values () . If obj is null or undefined it will return an empty array . [CODESPLIT] function objectValues ( obj ) { if ( ! obj ) { return exports . emptyArray ; } const keys = Object . keys ( obj ) ; const values = new Array ( keys . length ) ; for ( let i = 0 ; i < keys . length ; i ++ ) { values [ i ] = obj [ keys [ i ] ] ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the callback - based method . When no originalCallback is not defined it returns a Promise . [CODESPLIT] function promiseWrapper ( options , originalCallback , handler ) { if ( typeof originalCallback === 'function' ) { // Callback-based invocation handler . call ( this , originalCallback ) ; return undefined ; } const factory = options . promiseFactory || defaultPromiseFactory ; const self = this ; return factory ( function handlerWrapper ( callback ) { handler . call ( self , callback ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Similar to async . series () but instead accumulating the result in an Array it callbacks with the result of the last function in the array . [CODESPLIT] function series ( arr , callback ) { if ( ! Array . isArray ( arr ) ) { throw new TypeError ( 'First parameter must be an Array' ) ; } callback = callback || noop ; let index = 0 ; let sync ; next ( ) ; function next ( err , result ) { if ( err ) { return callback ( err ) ; } if ( index === arr . length ) { return callback ( null , result ) ; } if ( sync ) { return process . nextTick ( function ( ) { sync = true ; arr [ index ++ ] ( next ) ; sync = false ; } ) ; } sync = true ; arr [ index ++ ] ( next ) ; sync = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An iterator that holds the context for the subsequent next () calls [CODESPLIT] function TokenAwareIterator ( keyspace , execOptions , replicas , childPolicy ) { this . keyspace = keyspace ; this . childPolicy = childPolicy ; this . options = execOptions ; this . localReplicas = [ ] ; this . replicaIndex = 0 ; this . replicaMap = { } ; this . childIterator = null ; // Memoize the local replicas // The amount of local replicas should be defined before start iterating, in order to select an // appropriate (pseudo random) startIndex for ( let i = 0 ; i < replicas . length ; i ++ ) { const host = replicas [ i ] ; if ( this . childPolicy . getDistance ( host ) !== types . distance . local ) { continue ; } this . replicaMap [ host . address ] = true ; this . localReplicas . push ( host ) ; } // We use a PRNG to set the replica index // We only care about proportional fair scheduling between replicas of a given token // Math.random() has an extremely short permutation cycle length but we don't care about collisions this . startIndex = Math . floor ( Math . random ( ) * this . localReplicas . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new policy that wraps the provided child policy but only allow hosts from the provided while list . [CODESPLIT] function WhiteListPolicy ( childPolicy , whiteList ) { if ( ! childPolicy ) { throw new Error ( \"You must specify a child load balancing policy\" ) ; } if ( ! util . isArray ( whiteList ) ) { throw new Error ( \"You must provide the white list of host addresses\" ) ; } this . childPolicy = childPolicy ; const map = { } ; whiteList . forEach ( function ( address ) { map [ address ] = true ; } ) ; this . whiteList = map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A timestamp generator that guarantees monotonically increasing timestamps and logs warnings when timestamps drift in the future . <p > { [CODESPLIT] function MonotonicTimestampGenerator ( warningThreshold , minLogInterval ) { if ( warningThreshold < 0 ) { throw new errors . ArgumentError ( 'warningThreshold can not be lower than 0' ) ; } this . _warningThreshold = warningThreshold || 1000 ; this . _minLogInterval = 1000 ; if ( typeof minLogInterval === 'number' ) { // A value under 1 will disable logging this . _minLogInterval = minLogInterval ; } this . _micros = - 1 ; this . _lastDate = 0 ; this . _lastLogDate = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A reconnection policy that waits exponentially longer between each reconnection attempt ( but keeps a constant delay once a maximum delay is reached ) . <p > A random amount of jitter ( + / - 15% ) will be added to the pure exponential delay value to avoid situations where many clients are in the reconnection process at exactly the same time . The jitter will never cause the delay to be less than the base delay or more than the max delay . < / p > [CODESPLIT] function ExponentialReconnectionPolicy ( baseDelay , maxDelay , startWithNoDelay ) { this . baseDelay = baseDelay ; this . maxDelay = maxDelay ; this . startWithNoDelay = startWithNoDelay ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of <code > ControlConnection< / code > . [CODESPLIT] function ControlConnection ( options , profileManager , context ) { this . protocolVersion = null ; this . hosts = new HostMap ( ) ; this . setMaxListeners ( 0 ) ; Object . defineProperty ( this , \"options\" , { value : options , enumerable : false , writable : false } ) ; /**\n   * Cluster metadata that is going to be shared between the Client and ControlConnection\n   */ this . metadata = new Metadata ( this . options , this ) ; this . addressTranslator = this . options . policies . addressResolution ; this . reconnectionPolicy = this . options . policies . reconnection ; this . reconnectionSchedule = this . reconnectionPolicy . newSchedule ( ) ; this . initialized = false ; this . isShuttingDown = false ; /**\n   * Host used by the control connection\n   * @type {Host|null}\n   */ this . host = null ; /**\n   * Connection used to retrieve metadata and subscribed to events\n   * @type {Connection|null}\n   */ this . connection = null ; /**\n   * Reference to the encoder of the last valid connection\n   * @type {Encoder|null}\n   */ this . encoder = null ; this . debouncer = new EventDebouncer ( options . refreshSchemaDelay , this . log . bind ( this ) ) ; this . profileManager = profileManager ; /** Timeout used for delayed handling of topology changes */ this . topologyChangeTimeout = null ; /** Timeout used for delayed handling of node status changes */ this . nodeStatusChangeTimeout = null ; this . reconnectionTimeout = null ; this . hostIterator = null ; this . triedHosts = null ; this . _resolvedContactPoints = new Map ( ) ; this . _contactPoints = new Set ( ) ; if ( context && context . borrowHostConnection ) { this . borrowHostConnection = context . borrowHostConnection ; } if ( context && context . createConnection ) { this . createConnection = context . createConnection ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the DNS protocol to resolve a IPv4 and IPv6 addresses ( A and AAAA records ) for the hostname [CODESPLIT] function resolveAll ( name , callback ) { const addresses = [ ] ; utils . parallel ( [ function resolve4 ( next ) { dns . resolve4 ( name , function resolve4Callback ( err , arr ) { if ( arr ) { arr . forEach ( address => addresses . push ( { address , isIPv6 : false } ) ) ; } // Ignore error next ( ) ; } ) ; } , function resolve6 ( next ) { dns . resolve6 ( name , function resolve6Callback ( err , arr ) { if ( arr ) { arr . forEach ( address => addresses . push ( { address , isIPv6 : true } ) ) ; } // Ignore error next ( ) ; } ) ; } ] , function resolveAllCallback ( ) { if ( addresses . length === 0 ) { // In case dns.resolve*() methods don't yield a valid address for the host name // Use system call getaddrinfo() that might resolve according to host system definitions return dns . lookup ( name , function ( err , address , family ) { if ( err ) { return callback ( err ) ; } addresses . push ( { address , isIPv6 : family === 6 } ) ; callback ( null , addresses ) ; } ) ; } callback ( null , addresses ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of <code > ClientState< / code > . [CODESPLIT] function ClientState ( hosts , openConnections , inFlightQueries ) { this . _hosts = hosts ; this . _openConnections = openConnections ; this . _inFlightQueries = inFlightQueries ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Debounce protocol events by acting on those events with a sliding delay . [CODESPLIT] function EventDebouncer ( delay , logger ) { this . _delay = delay ; this . _logger = logger ; this . _queue = null ; this . _timeout = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Buffer forward reader of CQL binary frames [CODESPLIT] function FrameReader ( header , body , offset ) { this . header = header ; this . opcode = header . opcode ; this . offset = offset || 0 ; this . buf = body ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents a connection to a Cassandra node [CODESPLIT] function Connection ( endpoint , protocolVersion , options ) { events . EventEmitter . call ( this ) ; this . setMaxListeners ( 0 ) ; if ( ! options ) { throw new Error ( 'options is not defined' ) ; } /**\n   * Gets the ip and port of the server endpoint.\n   * @type {String}\n   */ this . endpoint = endpoint ; /**\n   * Gets the friendly name of the host, used to identify the connection in log messages.\n   * With direct connect, this is the address and port.\n   * @type {String}\n   */ this . endpointFriendlyName = endpoint ; if ( ! this . endpoint || this . endpoint . indexOf ( ':' ) < 0 ) { throw new Error ( 'EndPoint must contain the ip address and port separated by : symbol' ) ; } const portSeparatorIndex = this . endpoint . lastIndexOf ( ':' ) ; this . address = this . endpoint . substr ( 0 , portSeparatorIndex ) ; this . port = this . endpoint . substr ( portSeparatorIndex + 1 ) ; Object . defineProperty ( this , \"options\" , { value : options , enumerable : false , writable : false } ) ; if ( protocolVersion === null ) { // Set initial protocol version protocolVersion = types . protocolVersion . maxSupported ; if ( options . protocolOptions . maxVersion ) { // User provided the protocol version protocolVersion = options . protocolOptions . maxVersion ; } // Allow to check version using this connection instance this . _checkingVersion = true ; } this . protocolVersion = protocolVersion ; /** @type {Object.<String, OperationState>} */ this . _operations = { } ; this . _pendingWrites = [ ] ; this . _preparing = { } ; /**\n   * The timeout state for the idle request (heartbeat)\n   */ this . _idleTimeout = null ; this . timedOutOperations = 0 ; this . _streamIds = new StreamIdStack ( this . protocolVersion ) ; this . _metrics = options . metrics ; this . encoder = new Encoder ( protocolVersion , options ) ; this . keyspace = null ; this . emitDrain = false ; /**\n   * Determines if the socket is open and startup succeeded, whether the connection can be used to send requests / \n   * receive events\n   */ this . connected = false ; /**\n   * Determines if the socket can be considered as open\n   */ this . isSocketOpen = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of Uuid based on the parameters provided according to rfc4122 . If any of the arguments is not provided it will be randomly generated except for the date that will use the current date . <p > Note that when nodeId and / or clockId portions are not provided the constructor will generate them using <code > crypto . randomBytes () < / code > . As it s possible that <code > crypto . randomBytes () < / code > might block it s recommended that you use the callback - based version of the static methods <code > fromDate () < / code > or <code > now () < / code > in that case . < / p > [CODESPLIT] function TimeUuid ( value , ticks , nodeId , clockId ) { let buffer ; if ( value instanceof Buffer ) { if ( value . length !== 16 ) { throw new Error ( 'Buffer for v1 uuid not valid' ) ; } buffer = value ; } else { buffer = generateBuffer ( value , ticks , nodeId , clockId ) ; } Uuid . call ( this , buffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a buffer of length 2 representing the clock identifier [CODESPLIT] function getClockId ( clockId ) { let buffer = clockId ; if ( typeof clockId === 'string' ) { buffer = utils . allocBufferFromString ( clockId , 'ascii' ) ; } if ( ! ( buffer instanceof Buffer ) ) { //Generate buffer = getRandomBytes ( 2 ) ; } else if ( buffer . length !== 2 ) { throw new Error ( 'Clock identifier must have 2 bytes' ) ; } return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a buffer of length 6 representing the clock identifier [CODESPLIT] function getNodeId ( nodeId ) { let buffer = nodeId ; if ( typeof nodeId === 'string' ) { buffer = utils . allocBufferFromString ( nodeId , 'ascii' ) ; } if ( ! ( buffer instanceof Buffer ) ) { //Generate buffer = getRandomBytes ( 6 ) ; } else if ( buffer . length !== 6 ) { throw new Error ( 'Node identifier must have 6 bytes' ) ; } return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the ticks portion of a timestamp . If the ticks are not provided an internal counter is used that gets reset at 10000 . [CODESPLIT] function getTicks ( ticks ) { if ( typeof ticks !== 'number' || ticks >= _ticksInMs ) { _ticks ++ ; if ( _ticks >= _ticksInMs ) { _ticks = 0 ; } ticks = _ticks ; } return ticks ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an object with the time representation of the date expressed in milliseconds since unix epoch and a ticks property for the 100 - nanoseconds precision . [CODESPLIT] function getTimeWithTicks ( date , ticks ) { if ( ! ( date instanceof Date ) || isNaN ( date . getTime ( ) ) ) { // time with ticks for the current time date = new Date ( ) ; const time = date . getTime ( ) ; _ticksForCurrentTime ++ ; if ( _ticksForCurrentTime > _ticksInMs || time > _lastTimestamp ) { _ticksForCurrentTime = 0 ; _lastTimestamp = time ; } ticks = _ticksForCurrentTime ; } return { time : date . getTime ( ) , ticks : getTicks ( ticks ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 16 - length Buffer instance [CODESPLIT] function generateBuffer ( date , ticks , nodeId , clockId ) { const timeWithTicks = getTimeWithTicks ( date , ticks ) ; nodeId = getNodeId ( nodeId ) ; clockId = getClockId ( clockId ) ; const buffer = utils . allocBufferUnsafe ( 16 ) ; //Positions 0-7 Timestamp writeTime ( buffer , timeWithTicks . time , timeWithTicks . ticks ) ; //Position 8-9 Clock clockId . copy ( buffer , 8 , 0 ) ; //Positions 10-15 Node nodeId . copy ( buffer , 10 , 0 ) ; //Version Byte: Time based //0001xxxx //turn off first 4 bits buffer [ 6 ] = buffer [ 6 ] & 0x0f ; //turn on fifth bit buffer [ 6 ] = buffer [ 6 ] | 0x10 ; //IETF Variant Byte: 1.0.x //10xxxxxx //turn off first 2 bits buffer [ 8 ] = buffer [ 8 ] & 0x3f ; //turn on first bit buffer [ 8 ] = buffer [ 8 ] | 0x80 ; return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes and deserializes to and from a CQL type and a Javascript Type . [CODESPLIT] function Encoder ( protocolVersion , options ) { this . encodingOptions = options . encoding || utils . emptyObject ; defineInstanceMembers . call ( this ) ; this . setProtocolVersion ( protocolVersion ) ; setEncoders . call ( this ) ; if ( this . encodingOptions . copyBuffer ) { this . handleBuffer = handleBufferCopy ; } else { this . handleBuffer = handleBufferRef ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Declares the privileged instance members . [CODESPLIT] function defineInstanceMembers ( ) { /**\n   * Sets the protocol version and the encoding/decoding methods depending on the protocol version\n   * @param {Number} value\n   * @ignore\n   * @internal\n   */ this . setProtocolVersion = function ( value ) { this . protocolVersion = value ; //Set the collection serialization based on the protocol version this . decodeCollectionLength = decodeCollectionLengthV3 ; this . getLengthBuffer = getLengthBufferV3 ; this . collectionLengthSize = 4 ; if ( ! types . protocolVersion . uses4BytesCollectionLength ( this . protocolVersion ) ) { this . decodeCollectionLength = decodeCollectionLengthV2 ; this . getLengthBuffer = getLengthBufferV2 ; this . collectionLengthSize = 2 ; } } ; const customDecoders = { } ; const customEncoders = { } ; // Decoding methods this . decodeBlob = function ( bytes ) { return this . handleBuffer ( bytes ) ; } ; this . decodeCustom = function ( bytes , typeName ) { const handler = customDecoders [ typeName ] ; if ( handler ) { return handler . call ( this , bytes ) ; } return this . handleBuffer ( bytes ) ; } ; this . decodeDuration = function ( bytes ) { return types . Duration . fromBuffer ( bytes ) ; } ; this . decodeUtf8String = function ( bytes ) { return bytes . toString ( 'utf8' ) ; } ; this . decodeAsciiString = function ( bytes ) { return bytes . toString ( 'ascii' ) ; } ; this . decodeBoolean = function ( bytes ) { return ! ! bytes . readUInt8 ( 0 ) ; } ; this . decodeDouble = function ( bytes ) { return bytes . readDoubleBE ( 0 ) ; } ; this . decodeFloat = function ( bytes ) { return bytes . readFloatBE ( 0 ) ; } ; this . decodeInt = function ( bytes ) { return bytes . readInt32BE ( 0 ) ; } ; this . decodeSmallint = function ( bytes ) { return bytes . readInt16BE ( 0 ) ; } ; this . decodeTinyint = function ( bytes ) { return bytes . readInt8 ( 0 ) ; } ; this . _decodeCqlLongAsLong = function ( bytes ) { return Long . fromBuffer ( bytes ) ; } ; this . _decodeCqlLongAsBigInt = function ( bytes ) { return BigInt . asIntN ( 64 , ( BigInt ( bytes . readUInt32BE ( 0 ) ) << bigInt32 ) | BigInt ( bytes . readUInt32BE ( 4 ) ) ) ; } ; this . decodeLong = this . encodingOptions . useBigIntAsLong ? this . _decodeCqlLongAsBigInt : this . _decodeCqlLongAsLong ; this . _decodeVarintAsInteger = function ( bytes ) { return Integer . fromBuffer ( bytes ) ; } ; this . _decodeVarintAsBigInt = function decodeVarintAsBigInt ( bytes ) { let result = bigInt0 ; if ( bytes [ 0 ] <= 0x7f ) { for ( let i = 0 ; i < bytes . length ; i ++ ) { const b = BigInt ( bytes [ bytes . length - 1 - i ] ) ; result = result | ( b << BigInt ( i * 8 ) ) ; } } else { for ( let i = 0 ; i < bytes . length ; i ++ ) { const b = BigInt ( bytes [ bytes . length - 1 - i ] ) ; result = result | ( ( ~ b & bigInt8BitsOn ) << BigInt ( i * 8 ) ) ; } result = ~ result ; } return result ; } ; this . decodeVarint = this . encodingOptions . useBigIntAsVarint ? this . _decodeVarintAsBigInt : this . _decodeVarintAsInteger ; this . decodeDecimal = function ( bytes ) { return BigDecimal . fromBuffer ( bytes ) ; } ; this . decodeTimestamp = function ( bytes ) { return new Date ( this . _decodeCqlLongAsLong ( bytes ) . toNumber ( ) ) ; } ; this . decodeDate = function ( bytes ) { return types . LocalDate . fromBuffer ( bytes ) ; } ; this . decodeTime = function ( bytes ) { return types . LocalTime . fromBuffer ( bytes ) ; } ; /*\n   * Reads a list from bytes\n   */ this . decodeList = function ( bytes , subtype ) { const totalItems = this . decodeCollectionLength ( bytes , 0 ) ; let offset = this . collectionLengthSize ; const list = new Array ( totalItems ) ; for ( let i = 0 ; i < totalItems ; i ++ ) { //bytes length of the item const length = this . decodeCollectionLength ( bytes , offset ) ; offset += this . collectionLengthSize ; //slice it list [ i ] = this . decode ( bytes . slice ( offset , offset + length ) , subtype ) ; offset += length ; } return list ; } ; /*\n   * Reads a Set from bytes\n   */ this . decodeSet = function ( bytes , subtype ) { const arr = this . decodeList ( bytes , subtype ) ; if ( this . encodingOptions . set ) { const setConstructor = this . encodingOptions . set ; return new setConstructor ( arr ) ; } return arr ; } ; /*\n   * Reads a map (key / value) from bytes\n   */ this . decodeMap = function ( bytes , subtypes ) { let map ; const totalItems = this . decodeCollectionLength ( bytes , 0 ) ; let offset = this . collectionLengthSize ; const self = this ; function readValues ( callback , thisArg ) { for ( let i = 0 ; i < totalItems ; i ++ ) { const keyLength = self . decodeCollectionLength ( bytes , offset ) ; offset += self . collectionLengthSize ; const key = self . decode ( bytes . slice ( offset , offset + keyLength ) , subtypes [ 0 ] ) ; offset += keyLength ; const valueLength = self . decodeCollectionLength ( bytes , offset ) ; offset += self . collectionLengthSize ; if ( valueLength < 0 ) { callback . call ( thisArg , key , null ) ; continue ; } const value = self . decode ( bytes . slice ( offset , offset + valueLength ) , subtypes [ 1 ] ) ; offset += valueLength ; callback . call ( thisArg , key , value ) ; } } if ( this . encodingOptions . map ) { const mapConstructor = this . encodingOptions . map ; map = new mapConstructor ( ) ; readValues ( map . set , map ) ; } else { map = { } ; readValues ( function ( key , value ) { map [ key ] = value ; } ) ; } return map ; } ; this . decodeUuid = function ( bytes ) { return new types . Uuid ( this . handleBuffer ( bytes ) ) ; } ; this . decodeTimeUuid = function ( bytes ) { return new types . TimeUuid ( this . handleBuffer ( bytes ) ) ; } ; this . decodeInet = function ( bytes ) { return new types . InetAddress ( this . handleBuffer ( bytes ) ) ; } ; /**\n   * Decodes a user defined type into an object\n   * @param {Buffer} bytes\n   * @param {{fields: Array}} udtInfo\n   * @private\n   */ this . decodeUdt = function ( bytes , udtInfo ) { const result = { } ; let offset = 0 ; for ( let i = 0 ; i < udtInfo . fields . length && offset < bytes . length ; i ++ ) { //bytes length of the field value const length = bytes . readInt32BE ( offset ) ; offset += 4 ; //slice it const field = udtInfo . fields [ i ] ; if ( length < 0 ) { result [ field . name ] = null ; continue ; } result [ field . name ] = this . decode ( bytes . slice ( offset , offset + length ) , field . type ) ; offset += length ; } return result ; } ; this . decodeTuple = function ( bytes , tupleInfo ) { const elements = new Array ( tupleInfo . length ) ; let offset = 0 ; for ( let i = 0 ; i < tupleInfo . length ; i ++ ) { const length = bytes . readInt32BE ( offset ) ; offset += 4 ; if ( length < 0 ) { elements [ i ] = null ; continue ; } elements [ i ] = this . decode ( bytes . slice ( offset , offset + length ) , tupleInfo [ i ] ) ; offset += length ; } return new types . Tuple ( elements ) ; } ; //Encoding methods this . encodeFloat = function ( value ) { if ( typeof value !== 'number' ) { throw new TypeError ( 'Expected Number, obtained ' + util . inspect ( value ) ) ; } const buf = utils . allocBufferUnsafe ( 4 ) ; buf . writeFloatBE ( value , 0 ) ; return buf ; } ; this . encodeDouble = function ( value ) { if ( typeof value !== 'number' ) { throw new TypeError ( 'Expected Number, obtained ' + util . inspect ( value ) ) ; } const buf = utils . allocBufferUnsafe ( 8 ) ; buf . writeDoubleBE ( value , 0 ) ; return buf ; } ; /**\n   * @param {Date|String|Long|Number} value\n   * @private\n   */ this . encodeTimestamp = function ( value ) { const originalValue = value ; if ( typeof value === 'string' ) { value = new Date ( value ) ; } if ( value instanceof Date ) { //milliseconds since epoch value = value . getTime ( ) ; if ( isNaN ( value ) ) { throw new TypeError ( 'Invalid date: ' + originalValue ) ; } } return this . encodeLong ( value ) ; } ; /**\n   * @param {Date|String|LocalDate} value\n   * @returns {Buffer}\n   * @throws {TypeError}\n   * @private\n   */ this . encodeDate = function ( value ) { const originalValue = value ; try { if ( typeof value === 'string' ) { value = types . LocalDate . fromString ( value ) ; } if ( value instanceof Date ) { value = types . LocalDate . fromDate ( value ) ; } } catch ( err ) { //Wrap into a TypeError throw new TypeError ( 'LocalDate could not be parsed ' + err ) ; } if ( ! ( value instanceof types . LocalDate ) ) { throw new TypeError ( 'Expected Date/String/LocalDate, obtained ' + util . inspect ( originalValue ) ) ; } return value . toBuffer ( ) ; } ; /**\n   * @param {String|LocalDate} value\n   * @returns {Buffer}\n   * @throws {TypeError}\n   * @private\n   */ this . encodeTime = function ( value ) { const originalValue = value ; try { if ( typeof value === 'string' ) { value = types . LocalTime . fromString ( value ) ; } } catch ( err ) { //Wrap into a TypeError throw new TypeError ( 'LocalTime could not be parsed ' + err ) ; } if ( ! ( value instanceof types . LocalTime ) ) { throw new TypeError ( 'Expected String/LocalTime, obtained ' + util . inspect ( originalValue ) ) ; } return value . toBuffer ( ) ; } ; /**\n   * @param {Uuid|String|Buffer} value\n   * @private\n   */ this . encodeUuid = function ( value ) { if ( typeof value === 'string' ) { try { value = types . Uuid . fromString ( value ) . getBuffer ( ) ; } catch ( err ) { throw new TypeError ( err . message ) ; } } else if ( value instanceof types . Uuid ) { value = value . getBuffer ( ) ; } else { throw new TypeError ( 'Not a valid Uuid, expected Uuid/String/Buffer, obtained ' + util . inspect ( value ) ) ; } return value ; } ; /**\n   * @param {String|InetAddress|Buffer} value\n   * @returns {Buffer}\n   * @private\n   */ this . encodeInet = function ( value ) { if ( typeof value === 'string' ) { value = types . InetAddress . fromString ( value ) ; } if ( value instanceof types . InetAddress ) { value = value . getBuffer ( ) ; } if ( ! ( value instanceof Buffer ) ) { throw new TypeError ( 'Not a valid Inet, expected InetAddress/Buffer, obtained ' + util . inspect ( value ) ) ; } return value ; } ; /**\n   * @param {Long|Buffer|String|Number} value\n   * @private\n   */ this . _encodeBigIntFromLong = function ( value ) { if ( typeof value === 'number' ) { value = Long . fromNumber ( value ) ; } else if ( typeof value === 'string' ) { value = Long . fromString ( value ) ; } let buf = null ; if ( value instanceof Long ) { buf = Long . toBuffer ( value ) ; } else if ( value instanceof MutableLong ) { buf = Long . toBuffer ( value . toImmutable ( ) ) ; } if ( buf === null ) { throw new TypeError ( 'Not a valid bigint, expected Long/Number/String/Buffer, obtained ' + util . inspect ( value ) ) ; } return buf ; } ; this . _encodeBigIntFromBigInt = function ( value ) { // eslint-disable-next-line valid-typeof if ( typeof value !== 'bigint' ) { // Only BigInt values are supported throw new TypeError ( 'Not a valid BigInt value, obtained ' + util . inspect ( value ) ) ; } const buffer = utils . allocBufferUnsafe ( 8 ) ; buffer . writeUInt32BE ( Number ( value >> bigInt32 ) >>> 0 , 0 ) ; buffer . writeUInt32BE ( Number ( value & bigInt32BitsOn ) , 4 ) ; return buffer ; } ; this . encodeLong = this . encodingOptions . useBigIntAsLong ? this . _encodeBigIntFromBigInt : this . _encodeBigIntFromLong ; /**\n   * @param {Integer|Buffer|String|Number} value\n   * @returns {Buffer}\n   * @private\n   */ this . _encodeVarintFromInteger = function ( value ) { if ( typeof value === 'number' ) { value = Integer . fromNumber ( value ) ; } if ( typeof value === 'string' ) { value = Integer . fromString ( value ) ; } let buf = null ; if ( value instanceof Buffer ) { buf = value ; } if ( value instanceof Integer ) { buf = Integer . toBuffer ( value ) ; } if ( buf === null ) { throw new TypeError ( 'Not a valid varint, expected Integer/Number/String/Buffer, obtained ' + util . inspect ( value ) ) ; } return buf ; } ; this . _encodeVarintFromBigInt = function ( value ) { // eslint-disable-next-line valid-typeof if ( typeof value !== 'bigint' ) { throw new TypeError ( 'Not a valid varint, expected BigInt, obtained ' + util . inspect ( value ) ) ; } if ( value === bigInt0 ) { return buffers . int8Zero ; } else if ( value === bigIntMinus1 ) { return buffers . int8MaxValue ; } const parts = [ ] ; if ( value > bigInt0 ) { while ( value !== bigInt0 ) { parts . unshift ( Number ( value & bigInt8BitsOn ) ) ; value = value >> bigInt8 ; } if ( parts [ 0 ] > 0x7f ) { // Positive value needs a padding parts . unshift ( 0 ) ; } } else { while ( value !== bigIntMinus1 ) { parts . unshift ( Number ( value & bigInt8BitsOn ) ) ; value = value >> bigInt8 ; } if ( parts [ 0 ] <= 0x7f ) { // Negative value needs a padding parts . unshift ( 0xff ) ; } } return utils . allocBufferFromArray ( parts ) ; } ; this . encodeVarint = this . encodingOptions . useBigIntAsVarint ? this . _encodeVarintFromBigInt : this . _encodeVarintFromInteger ; /**\n   * @param {BigDecimal|Buffer|String|Number} value\n   * @returns {Buffer}\n   * @private\n   */ this . encodeDecimal = function ( value ) { if ( typeof value === 'number' ) { value = BigDecimal . fromNumber ( value ) ; } else if ( typeof value === 'string' ) { value = BigDecimal . fromString ( value ) ; } let buf = null ; if ( value instanceof BigDecimal ) { buf = BigDecimal . toBuffer ( value ) ; } else { throw new TypeError ( 'Not a valid varint, expected BigDecimal/Number/String/Buffer, obtained ' + util . inspect ( value ) ) ; } return buf ; } ; this . encodeString = function ( value , encoding ) { if ( typeof value !== 'string' ) { throw new TypeError ( 'Not a valid text value, expected String obtained ' + util . inspect ( value ) ) ; } return utils . allocBufferFromString ( value , encoding ) ; } ; this . encodeUtf8String = function ( value ) { return this . encodeString ( value , 'utf8' ) ; } ; this . encodeAsciiString = function ( value ) { return this . encodeString ( value , 'ascii' ) ; } ; this . encodeBlob = function ( value ) { if ( ! ( value instanceof Buffer ) ) { throw new TypeError ( 'Not a valid blob, expected Buffer obtained ' + util . inspect ( value ) ) ; } return value ; } ; this . encodeCustom = function ( value , name ) { const handler = customEncoders [ name ] ; if ( handler ) { return handler . call ( this , value ) ; } throw new TypeError ( 'No encoding handler found for type ' + name ) ; } ; this . encodeDuration = function ( value ) { if ( ! ( value instanceof types . Duration ) ) { throw new TypeError ( 'Not a valid duration, expected Duration/Buffer obtained ' + util . inspect ( value ) ) ; } return value . toBuffer ( ) ; } ; /**\n   * @param {Boolean} value\n   * @returns {Buffer}\n   * @private\n   */ this . encodeBoolean = function ( value ) { return value ? buffers . int8One : buffers . int8Zero ; } ; /**\n   * @param {Number|String} value\n   * @private\n   */ this . encodeInt = function ( value ) { if ( isNaN ( value ) ) { throw new TypeError ( 'Expected Number, obtained ' + util . inspect ( value ) ) ; } const buf = utils . allocBufferUnsafe ( 4 ) ; buf . writeInt32BE ( value , 0 ) ; return buf ; } ; /**\n   * @param {Number|String} value\n   * @private\n   */ this . encodeSmallint = function ( value ) { if ( isNaN ( value ) ) { throw new TypeError ( 'Expected Number, obtained ' + util . inspect ( value ) ) ; } const buf = utils . allocBufferUnsafe ( 2 ) ; buf . writeInt16BE ( value , 0 ) ; return buf ; } ; /**\n   * @param {Number|String} value\n   * @private\n   */ this . encodeTinyint = function ( value ) { if ( isNaN ( value ) ) { throw new TypeError ( 'Expected Number, obtained ' + util . inspect ( value ) ) ; } const buf = utils . allocBufferUnsafe ( 1 ) ; buf . writeInt8 ( value , 0 ) ; return buf ; } ; this . encodeList = function ( value , subtype ) { if ( ! util . isArray ( value ) ) { throw new TypeError ( 'Not a valid list value, expected Array obtained ' + util . inspect ( value ) ) ; } if ( value . length === 0 ) { return null ; } const parts = [ ] ; parts . push ( this . getLengthBuffer ( value ) ) ; for ( let i = 0 ; i < value . length ; i ++ ) { const val = value [ i ] ; if ( val === null || typeof val === 'undefined' || val === types . unset ) { throw new TypeError ( 'A collection can\\'t contain null or unset values' ) ; } const bytes = this . encode ( val , subtype ) ; //include item byte length parts . push ( this . getLengthBuffer ( bytes ) ) ; //include item parts . push ( bytes ) ; } return Buffer . concat ( parts ) ; } ; this . encodeSet = function ( value , subtype ) { if ( this . encodingOptions . set && value instanceof this . encodingOptions . set ) { const arr = [ ] ; value . forEach ( function ( x ) { arr . push ( x ) ; } ) ; return this . encodeList ( arr , subtype ) ; } return this . encodeList ( value , subtype ) ; } ; /**\n   * Serializes a map into a Buffer\n   * @param value\n   * @param {Array} [subtypes]\n   * @returns {Buffer}\n   * @private\n   */ this . encodeMap = function ( value , subtypes ) { const parts = [ ] ; let propCounter = 0 ; let keySubtype = null ; let valueSubtype = null ; const self = this ; if ( subtypes ) { keySubtype = subtypes [ 0 ] ; valueSubtype = subtypes [ 1 ] ; } function addItem ( val , key ) { if ( key === null || typeof key === 'undefined' || key === types . unset ) { throw new TypeError ( 'A map can\\'t contain null or unset keys' ) ; } if ( val === null || typeof val === 'undefined' || val === types . unset ) { throw new TypeError ( 'A map can\\'t contain null or unset values' ) ; } const keyBuffer = self . encode ( key , keySubtype ) ; //include item byte length parts . push ( self . getLengthBuffer ( keyBuffer ) ) ; //include item parts . push ( keyBuffer ) ; //value const valueBuffer = self . encode ( val , valueSubtype ) ; //include item byte length parts . push ( self . getLengthBuffer ( valueBuffer ) ) ; //include item if ( valueBuffer !== null ) { parts . push ( valueBuffer ) ; } propCounter ++ ; } if ( this . encodingOptions . map && value instanceof this . encodingOptions . map ) { //Use Map#forEach() method to iterate value . forEach ( addItem ) ; } else { //Use object for ( const key in value ) { if ( ! value . hasOwnProperty ( key ) ) { continue ; } const val = value [ key ] ; addItem ( val , key ) ; } } parts . unshift ( this . getLengthBuffer ( propCounter ) ) ; return Buffer . concat ( parts ) ; } ; this . encodeUdt = function ( value , udtInfo ) { const parts = [ ] ; let totalLength = 0 ; for ( let i = 0 ; i < udtInfo . fields . length ; i ++ ) { const field = udtInfo . fields [ i ] ; const item = this . encode ( value [ field . name ] , field . type ) ; if ( ! item ) { parts . push ( nullValueBuffer ) ; totalLength += 4 ; continue ; } if ( item === types . unset ) { parts . push ( unsetValueBuffer ) ; totalLength += 4 ; continue ; } const lengthBuffer = utils . allocBufferUnsafe ( 4 ) ; lengthBuffer . writeInt32BE ( item . length , 0 ) ; parts . push ( lengthBuffer ) ; parts . push ( item ) ; totalLength += item . length + 4 ; } return Buffer . concat ( parts , totalLength ) ; } ; this . encodeTuple = function ( value , tupleInfo ) { const parts = [ ] ; let totalLength = 0 ; for ( let i = 0 ; i < tupleInfo . length ; i ++ ) { const type = tupleInfo [ i ] ; const item = this . encode ( value . get ( i ) , type ) ; if ( ! item ) { parts . push ( nullValueBuffer ) ; totalLength += 4 ; continue ; } if ( item === types . unset ) { parts . push ( unsetValueBuffer ) ; totalLength += 4 ; continue ; } const lengthBuffer = utils . allocBufferUnsafe ( 4 ) ; lengthBuffer . writeInt32BE ( item . length , 0 ) ; parts . push ( lengthBuffer ) ; parts . push ( item ) ; totalLength += item . length + 4 ; } return Buffer . concat ( parts , totalLength ) ; } ; /**\n   * If not provided, it uses the array of buffers or the parameters and hints to build the routingKey\n   * @param {Array} params\n   * @param {ExecutionOptions} execOptions\n   * @param [keys] parameter keys and positions in the params array\n   * @throws TypeError\n   * @internal\n   * @ignore\n   */ this . setRoutingKeyFromUser = function ( params , execOptions , keys ) { let totalLength = 0 ; const userRoutingKey = execOptions . getRoutingKey ( ) ; if ( util . isArray ( userRoutingKey ) ) { if ( userRoutingKey . length === 1 ) { execOptions . setRoutingKey ( userRoutingKey [ 0 ] ) ; return ; } // Its a composite routing key totalLength = 0 ; for ( let i = 0 ; i < userRoutingKey . length ; i ++ ) { const item = userRoutingKey [ i ] ; if ( ! item ) { // Invalid routing key part provided by the user, clear the value execOptions . setRoutingKey ( null ) ; return ; } totalLength += item . length + 3 ; } execOptions . setRoutingKey ( concatRoutingKey ( userRoutingKey , totalLength ) ) ; return ; } // If routingKey is present, ensure it is a Buffer, Token, or TokenRange.  Otherwise throw an error. if ( userRoutingKey ) { if ( userRoutingKey instanceof Buffer || userRoutingKey instanceof token . Token || userRoutingKey instanceof token . TokenRange ) { return ; } throw new TypeError ( ` ${ util . inspect ( userRoutingKey ) } ` + ` ` ) ; } // If no params are present, return as routing key cannot be determined. if ( ! params || params . length === 0 ) { return ; } let routingIndexes = execOptions . getRoutingIndexes ( ) ; if ( execOptions . getRoutingNames ( ) ) { routingIndexes = execOptions . getRoutingNames ( ) . map ( k => keys [ k ] ) ; } if ( ! routingIndexes ) { return ; } const parts = [ ] ; const hints = execOptions . getHints ( ) || utils . emptyArray ; const encodeParam = ! keys ? ( i => this . encode ( params [ i ] , hints [ i ] ) ) : ( i => this . encode ( params [ i ] . value , hints [ i ] ) ) ; try { totalLength = this . _encodeRoutingKeyParts ( parts , routingIndexes , encodeParam ) ; } catch ( e ) { // There was an error encoding a parameter that is part of the routing key, // ignore now to fail afterwards } if ( totalLength === 0 ) { return ; } execOptions . setRoutingKey ( concatRoutingKey ( parts , totalLength ) ) ; } ; /**\n   * Sets the routing key in the options based on the prepared statement metadata.\n   * @param {Object} meta Prepared metadata\n   * @param {Array} params Array of parameters\n   * @param {ExecutionOptions} execOptions\n   * @throws TypeError\n   * @internal\n   * @ignore\n   */ this . setRoutingKeyFromMeta = function ( meta , params , execOptions ) { const routingIndexes = execOptions . getRoutingIndexes ( ) ; if ( ! routingIndexes ) { return ; } const parts = new Array ( routingIndexes . length ) ; const encodeParam = i => { const columnInfo = meta . columns [ i ] ; return this . encode ( params [ i ] , columnInfo ? columnInfo . type : null ) ; } ; let totalLength = 0 ; try { totalLength = this . _encodeRoutingKeyParts ( parts , routingIndexes , encodeParam ) ; } catch ( e ) { // There was an error encoding a parameter that is part of the routing key, // ignore now to fail afterwards } if ( totalLength === 0 ) { return ; } execOptions . setRoutingKey ( concatRoutingKey ( parts , totalLength ) ) ; } ; /**\n   * @param {Array} parts\n   * @param {Array} routingIndexes\n   * @param {Function} encodeParam\n   * @returns {Number} The total length\n   * @private\n   */ this . _encodeRoutingKeyParts = function ( parts , routingIndexes , encodeParam ) { let totalLength = 0 ; for ( let i = 0 ; i < routingIndexes . length ; i ++ ) { const paramIndex = routingIndexes [ i ] ; if ( paramIndex === undefined ) { // Bad input from the user, ignore return 0 ; } const item = encodeParam ( paramIndex ) ; if ( item === null || item === undefined || item === types . unset ) { // The encoded partition key should an instance of Buffer // Let it fail later in the pipeline for null/undefined parameter values return 0 ; } // Per each part of the routing key, 3 extra bytes are needed totalLength += item . length + 3 ; parts [ i ] = item ; } return totalLength ; } ; /**\n   * Parses a CQL name string into data type information\n   * @param {String} keyspace\n   * @param {String} typeName\n   * @param {Number} startIndex\n   * @param {Number|null} length\n   * @param {Function} udtResolver\n   * @param {Function} callback Callback invoked with err and  {{code: number, info: Object|Array|null, options: {frozen: Boolean}}}\n   * @internal\n   * @ignore\n   */ this . parseTypeName = function ( keyspace , typeName , startIndex , length , udtResolver , callback ) { startIndex = startIndex || 0 ; if ( ! length ) { length = typeName . length ; } const dataType = { code : 0 , info : null , options : { frozen : false } } ; let innerTypes ; if ( typeName . indexOf ( \"'\" , startIndex ) === startIndex ) { //If quoted, this is a custom type. dataType . info = typeName . substr ( startIndex + 1 , length - 2 ) ; return callback ( null , dataType ) ; } if ( ! length ) { length = typeName . length ; } if ( typeName . indexOf ( cqlNames . frozen , startIndex ) === startIndex ) { //Remove the frozen token startIndex += cqlNames . frozen . length + 1 ; length -= cqlNames . frozen . length + 2 ; dataType . options . frozen = true ; } if ( typeName . indexOf ( cqlNames . list , startIndex ) === startIndex ) { //move cursor across the name and bypass the angle brackets startIndex += cqlNames . list . length + 1 ; length -= cqlNames . list . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length , '<' , '>' ) ; if ( innerTypes . length !== 1 ) { return callback ( new TypeError ( 'Not a valid type ' + typeName ) ) ; } dataType . code = dataTypes . list ; return this . parseTypeName ( keyspace , innerTypes [ 0 ] , 0 , null , udtResolver , function ( err , childType ) { if ( err ) { return callback ( err ) ; } dataType . info = childType ; callback ( null , dataType ) ; } ) ; } if ( typeName . indexOf ( cqlNames . set , startIndex ) === startIndex ) { //move cursor across the name and bypass the angle brackets startIndex += cqlNames . set . length + 1 ; length -= cqlNames . set . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length , '<' , '>' ) ; if ( innerTypes . length !== 1 ) { return callback ( new TypeError ( 'Not a valid type ' + typeName ) ) ; } dataType . code = dataTypes . set ; return this . parseTypeName ( keyspace , innerTypes [ 0 ] , 0 , null , udtResolver , function ( err , childType ) { if ( err ) { return callback ( err ) ; } dataType . info = childType ; callback ( null , dataType ) ; } ) ; } if ( typeName . indexOf ( cqlNames . map , startIndex ) === startIndex ) { //move cursor across the name and bypass the angle brackets startIndex += cqlNames . map . length + 1 ; length -= cqlNames . map . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length , '<' , '>' ) ; //It should contain the key and value types if ( innerTypes . length !== 2 ) { return callback ( new TypeError ( 'Not a valid type ' + typeName ) ) ; } dataType . code = dataTypes . map ; return this . _parseChildTypes ( keyspace , dataType , innerTypes , udtResolver , callback ) ; } if ( typeName . indexOf ( cqlNames . tuple , startIndex ) === startIndex ) { //move cursor across the name and bypass the angle brackets startIndex += cqlNames . tuple . length + 1 ; length -= cqlNames . tuple . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length , '<' , '>' ) ; if ( innerTypes . length < 1 ) { throw new TypeError ( 'Not a valid type ' + typeName ) ; } dataType . code = dataTypes . tuple ; return this . _parseChildTypes ( keyspace , dataType , innerTypes , udtResolver , callback ) ; } const quoted = typeName . indexOf ( '\"' , startIndex ) === startIndex ; if ( quoted ) { //Remove quotes startIndex ++ ; length -= 2 ; } //Quick check if its a single type if ( startIndex > 0 ) { typeName = typeName . substr ( startIndex , length ) ; } // Un-escape double quotes if quoted. if ( quoted ) { typeName = typeName . replace ( '\"\"' , '\"' ) ; } const typeCode = dataTypes [ typeName ] ; if ( typeof typeCode === 'number' ) { dataType . code = typeCode ; return callback ( null , dataType ) ; } if ( typeName === cqlNames . duration ) { dataType . info = durationTypeName ; return callback ( null , dataType ) ; } if ( typeName === cqlNames . empty ) { //set as custom dataType . info = 'empty' ; return callback ( null , dataType ) ; } udtResolver ( keyspace , typeName , function ( err , udtInfo ) { if ( err ) { return callback ( err ) ; } if ( udtInfo ) { dataType . code = dataTypes . udt ; dataType . info = udtInfo ; return callback ( null , dataType ) ; } callback ( new TypeError ( 'Not a valid type \"' + typeName + '\"' ) ) ; } ) ; } ; /**\n   * @param {String} keyspace\n   * @param dataType\n   * @param {Array} typeNames\n   * @param {Function} udtResolver\n   * @param {Function} callback\n   * @private\n   */ this . _parseChildTypes = function ( keyspace , dataType , typeNames , udtResolver , callback ) { const self = this ; utils . mapSeries ( typeNames , function ( name , next ) { self . parseTypeName ( keyspace , name . trim ( ) , 0 , null , udtResolver , next ) ; } , function ( err , childTypes ) { if ( err ) { return callback ( err ) ; } dataType . info = childTypes ; callback ( null , dataType ) ; } ) ; } ; /**\n   * Parses a Cassandra fully-qualified class name string into data type information\n   * @param {String} typeName\n   * @param {Number} [startIndex]\n   * @param {Number} [length]\n   * @throws TypeError\n   * @returns {{code: number, info: Object|Array|null, options: {frozen: Boolean, reversed: Boolean}}}\n   * @internal\n   * @ignore\n   */ this . parseFqTypeName = function ( typeName , startIndex , length ) { const dataType = { code : 0 , info : null , options : { reversed : false , frozen : false } } ; startIndex = startIndex || 0 ; let innerTypes ; if ( ! length ) { length = typeName . length ; } if ( length > complexTypeNames . reversed . length && typeName . indexOf ( complexTypeNames . reversed ) === startIndex ) { //Remove the reversed token startIndex += complexTypeNames . reversed . length + 1 ; length -= complexTypeNames . reversed . length + 2 ; dataType . options . reversed = true ; } if ( length > complexTypeNames . frozen . length && typeName . indexOf ( complexTypeNames . frozen , startIndex ) === startIndex ) { //Remove the frozen token startIndex += complexTypeNames . frozen . length + 1 ; length -= complexTypeNames . frozen . length + 2 ; dataType . options . frozen = true ; } if ( typeName === complexTypeNames . empty ) { //set as custom dataType . info = 'empty' ; return dataType ; } //Quick check if its a single type if ( length <= singleFqTypeNamesLength ) { if ( startIndex > 0 ) { typeName = typeName . substr ( startIndex , length ) ; } const typeCode = singleTypeNames [ typeName ] ; if ( typeof typeCode === 'number' ) { dataType . code = typeCode ; return dataType ; } throw new TypeError ( 'Not a valid type \"' + typeName + '\"' ) ; } if ( typeName . indexOf ( complexTypeNames . list , startIndex ) === startIndex ) { //Its a list //org.apache.cassandra.db.marshal.ListType(innerType) //move cursor across the name and bypass the parenthesis startIndex += complexTypeNames . list . length + 1 ; length -= complexTypeNames . list . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length ) ; if ( innerTypes . length !== 1 ) { throw new TypeError ( 'Not a valid type ' + typeName ) ; } dataType . code = dataTypes . list ; dataType . info = this . parseFqTypeName ( innerTypes [ 0 ] ) ; return dataType ; } if ( typeName . indexOf ( complexTypeNames . set , startIndex ) === startIndex ) { //Its a set //org.apache.cassandra.db.marshal.SetType(innerType) //move cursor across the name and bypass the parenthesis startIndex += complexTypeNames . set . length + 1 ; length -= complexTypeNames . set . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length ) ; if ( innerTypes . length !== 1 ) { throw new TypeError ( 'Not a valid type ' + typeName ) ; } dataType . code = dataTypes . set ; dataType . info = this . parseFqTypeName ( innerTypes [ 0 ] ) ; return dataType ; } if ( typeName . indexOf ( complexTypeNames . map , startIndex ) === startIndex ) { //org.apache.cassandra.db.marshal.MapType(keyType,valueType) //move cursor across the name and bypass the parenthesis startIndex += complexTypeNames . map . length + 1 ; length -= complexTypeNames . map . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length ) ; //It should contain the key and value types if ( innerTypes . length !== 2 ) { throw new TypeError ( 'Not a valid type ' + typeName ) ; } dataType . code = dataTypes . map ; dataType . info = [ this . parseFqTypeName ( innerTypes [ 0 ] ) , this . parseFqTypeName ( innerTypes [ 1 ] ) ] ; return dataType ; } if ( typeName . indexOf ( complexTypeNames . udt , startIndex ) === startIndex ) { //move cursor across the name and bypass the parenthesis startIndex += complexTypeNames . udt . length + 1 ; length -= complexTypeNames . udt . length + 2 ; return this . _parseUdtName ( typeName , startIndex , length ) ; } if ( typeName . indexOf ( complexTypeNames . tuple , startIndex ) === startIndex ) { //move cursor across the name and bypass the parenthesis startIndex += complexTypeNames . tuple . length + 1 ; length -= complexTypeNames . tuple . length + 2 ; innerTypes = parseParams ( typeName , startIndex , length ) ; if ( innerTypes . length < 1 ) { throw new TypeError ( 'Not a valid type ' + typeName ) ; } dataType . code = dataTypes . tuple ; dataType . info = innerTypes . map ( x => this . parseFqTypeName ( x ) ) ; return dataType ; } // Assume custom type if cannot be parsed up to this point. dataType . info = typeName . substr ( startIndex , length ) ; return dataType ; } ; /**\n   * Parses type names with composites\n   * @param {String} typesString\n   * @returns {{types: Array, isComposite: Boolean, hasCollections: Boolean}}\n   * @internal\n   * @ignore\n   */ this . parseKeyTypes = function ( typesString ) { let i = 0 ; let length = typesString . length ; const isComposite = typesString . indexOf ( complexTypeNames . composite ) === 0 ; if ( isComposite ) { i = complexTypeNames . composite . length + 1 ; length -- ; } const types = [ ] ; let startIndex = i ; let nested = 0 ; let inCollectionType = false ; let hasCollections = false ; //as collection types are not allowed, it is safe to split by , while ( ++ i < length ) { switch ( typesString [ i ] ) { case ',' : if ( nested > 0 ) { break ; } if ( inCollectionType ) { //remove type id startIndex = typesString . indexOf ( ':' , startIndex ) + 1 ; } types . push ( typesString . substring ( startIndex , i ) ) ; startIndex = i + 1 ; break ; case '(' : if ( nested === 0 && typesString . indexOf ( complexTypeNames . collection , startIndex ) === startIndex ) { inCollectionType = true ; hasCollections = true ; //skip collection type i ++ ; startIndex = i ; break ; } nested ++ ; break ; case ')' : if ( inCollectionType && nested === 0 ) { types . push ( typesString . substring ( typesString . indexOf ( ':' , startIndex ) + 1 , i ) ) ; startIndex = i + 1 ; break ; } nested -- ; break ; } } if ( startIndex < length ) { types . push ( typesString . substring ( startIndex , length ) ) ; } return { types : types . map ( name => this . parseFqTypeName ( name ) ) , hasCollections : hasCollections , isComposite : isComposite } ; } ; this . _parseUdtName = function ( typeName , startIndex , length ) { const udtParams = parseParams ( typeName , startIndex , length ) ; if ( udtParams . length < 2 ) { //It should contain at least the keyspace, name of the udt and a type throw new TypeError ( 'Not a valid type ' + typeName ) ; } const dataType = { code : dataTypes . udt , info : null } ; const udtInfo = { keyspace : udtParams [ 0 ] , name : utils . allocBufferFromString ( udtParams [ 1 ] , 'hex' ) . toString ( ) , fields : [ ] } ; for ( let i = 2 ; i < udtParams . length ; i ++ ) { const p = udtParams [ i ] ; const separatorIndex = p . indexOf ( ':' ) ; const fieldType = this . parseFqTypeName ( p , separatorIndex + 1 , p . length - ( separatorIndex + 1 ) ) ; udtInfo . fields . push ( { name : utils . allocBufferFromString ( p . substr ( 0 , separatorIndex ) , 'hex' ) . toString ( ) , type : fieldType } ) ; } dataType . info = udtInfo ; return dataType ; } ; customDecoders [ durationTypeName ] = this . decodeDuration ; customEncoders [ durationTypeName ] = this . encodeDuration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the encoder and decoder methods for this instance [CODESPLIT] function setEncoders ( ) { this . decoders = { [ dataTypes . custom ] : this . decodeCustom , [ dataTypes . ascii ] : this . decodeAsciiString , [ dataTypes . bigint ] : this . decodeLong , [ dataTypes . blob ] : this . decodeBlob , [ dataTypes . boolean ] : this . decodeBoolean , [ dataTypes . counter ] : this . decodeLong , [ dataTypes . decimal ] : this . decodeDecimal , [ dataTypes . double ] : this . decodeDouble , [ dataTypes . float ] : this . decodeFloat , [ dataTypes . int ] : this . decodeInt , [ dataTypes . text ] : this . decodeUtf8String , [ dataTypes . timestamp ] : this . decodeTimestamp , [ dataTypes . uuid ] : this . decodeUuid , [ dataTypes . varchar ] : this . decodeUtf8String , [ dataTypes . varint ] : this . decodeVarint , [ dataTypes . timeuuid ] : this . decodeTimeUuid , [ dataTypes . inet ] : this . decodeInet , [ dataTypes . date ] : this . decodeDate , [ dataTypes . time ] : this . decodeTime , [ dataTypes . smallint ] : this . decodeSmallint , [ dataTypes . tinyint ] : this . decodeTinyint , [ dataTypes . list ] : this . decodeList , [ dataTypes . map ] : this . decodeMap , [ dataTypes . set ] : this . decodeSet , [ dataTypes . udt ] : this . decodeUdt , [ dataTypes . tuple ] : this . decodeTuple } ; this . encoders = { [ dataTypes . custom ] : this . encodeCustom , [ dataTypes . ascii ] : this . encodeAsciiString , [ dataTypes . bigint ] : this . encodeLong , [ dataTypes . blob ] : this . encodeBlob , [ dataTypes . boolean ] : this . encodeBoolean , [ dataTypes . counter ] : this . encodeLong , [ dataTypes . decimal ] : this . encodeDecimal , [ dataTypes . double ] : this . encodeDouble , [ dataTypes . float ] : this . encodeFloat , [ dataTypes . int ] : this . encodeInt , [ dataTypes . text ] : this . encodeUtf8String , [ dataTypes . timestamp ] : this . encodeTimestamp , [ dataTypes . uuid ] : this . encodeUuid , [ dataTypes . varchar ] : this . encodeUtf8String , [ dataTypes . varint ] : this . encodeVarint , [ dataTypes . timeuuid ] : this . encodeUuid , [ dataTypes . inet ] : this . encodeInet , [ dataTypes . date ] : this . encodeDate , [ dataTypes . time ] : this . encodeTime , [ dataTypes . smallint ] : this . encodeSmallint , [ dataTypes . tinyint ] : this . encodeTinyint , [ dataTypes . list ] : this . encodeList , [ dataTypes . map ] : this . encodeMap , [ dataTypes . set ] : this . encodeSet , [ dataTypes . udt ] : this . encodeUdt , [ dataTypes . tuple ] : this . encodeTuple } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a buffer containing with the bytes ( BE ) representing the collection length for protocol v2 and below [CODESPLIT] function getLengthBufferV2 ( value ) { if ( ! value ) { return buffers . int16Zero ; } const lengthBuffer = utils . allocBufferUnsafe ( 2 ) ; if ( typeof value === 'number' ) { lengthBuffer . writeUInt16BE ( value , 0 ) ; } else { lengthBuffer . writeUInt16BE ( value . length , 0 ) ; } return lengthBuffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a buffer containing with the bytes ( BE ) representing the collection length for protocol v3 and above [CODESPLIT] function getLengthBufferV3 ( value ) { if ( ! value ) { return buffers . int32Zero ; } const lengthBuffer = utils . allocBufferUnsafe ( 4 ) ; if ( typeof value === 'number' ) { lengthBuffer . writeInt32BE ( value , 0 ) ; } else { lengthBuffer . writeInt32BE ( value . length , 0 ) ; } return lengthBuffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of { [CODESPLIT] function Duration ( months , days , nanoseconds ) { /**\n   * Gets the number of months.\n   * @type {Number}\n   */ this . months = months ; /**\n   * Gets the number of days.\n   * @type {Number}\n   */ this . days = days ; /**\n   * Gets the number of nanoseconds represented as a <code>int64</code>.\n   * @type {Long}\n   */ this . nanoseconds = typeof nanoseconds === 'number' ? Long . fromNumber ( nanoseconds ) : nanoseconds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of zero bits preceding the highest - order one - bit in the binary representation of the value . [CODESPLIT] function numberOfLeadingZeros ( value ) { if ( value . equals ( Long . ZERO ) ) { return 64 ; } let n = 1 ; let x = value . getHighBits ( ) ; if ( x === 0 ) { n += 32 ; x = value . getLowBits ( ) ; } if ( x >>> 16 === 0 ) { n += 16 ; x <<= 16 ; } if ( x >>> 24 === 0 ) { n += 8 ; x <<= 8 ; } if ( x >>> 28 === 0 ) { n += 4 ; x <<= 4 ; } if ( x >>> 30 === 0 ) { n += 2 ; x <<= 2 ; } n -= x >>> 31 ; return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Index instance . [CODESPLIT] function Index ( name , target , kind , options ) { /**\n   * Name of the index.\n   * @type {String}\n   */ this . name = name ; /**\n   * Target of the index.\n   * @type {String}\n   */ this . target = target ; /**\n   * A numeric value representing index kind (0: custom, 1: keys, 2: composite);\n   * @type {Number}\n   */ this . kind = typeof kind === 'string' ? getKindByName ( kind ) : kind ; /**\n   * An associative array containing the index options\n   * @type {Object}\n   */ this . options = options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "work - horse [CODESPLIT] function ( key ) { return _ . sortBy ( files , function ( el ) { return Number ( $ ( el ) . find ( 'span[data-lint]' ) . attr ( key ) ) * - 1 ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resizer () resizes items based on the object width divided by the compressor * 10 [CODESPLIT] function ( ) { $this . css ( 'font-size' , Math . max ( Math . min ( $this . width ( ) / ( compressor * 10 ) , parseFloat ( settings . maxFontSize ) ) , parseFloat ( settings . minFontSize ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CONSTRUCTOR [CODESPLIT] function CodeMirror ( place , options ) { if ( ! ( this instanceof CodeMirror ) ) return new CodeMirror ( place , options ) ; this . options = options = options || { } ; // Determine effective options based on given values and defaults. for ( var opt in defaults ) if ( ! options . hasOwnProperty ( opt ) && defaults . hasOwnProperty ( opt ) ) options [ opt ] = defaults [ opt ] ; setGuttersForLineNumbers ( options ) ; var display = this . display = makeDisplay ( place ) ; display . wrapper . CodeMirror = this ; updateGutters ( this ) ; if ( options . autofocus && ! mobile ) focusInput ( this ) ; this . view = makeView ( new BranchChunk ( [ new LeafChunk ( [ makeLine ( \"\" , null , textHeight ( display ) ) ] ) ] ) ) ; this . nextOpId = 0 ; loadMode ( this ) ; themeChanged ( this ) ; if ( options . lineWrapping ) this . display . wrapper . className += \" CodeMirror-wrap\" ; // Initialize the content. this . setValue ( options . value || \"\" ) ; // Override magic textarea content restore that IE sometimes does // on our hidden textarea on reload if ( ie ) setTimeout ( bind ( resetInput , this , true ) , 20 ) ; this . view . history = makeHistory ( ) ; registerEventHandlers ( this ) ; // IE throws unspecified error in certain cases, when // trying to access activeElement before onload var hasFocus ; try { hasFocus = ( document . activeElement == display . input ) ; } catch ( e ) { } if ( hasFocus || ( options . autofocus && ! mobile ) ) setTimeout ( bind ( onFocus , this ) , 20 ) ; else onBlur ( this ) ; operation ( this , function ( ) { for ( var opt in optionHandlers ) if ( optionHandlers . propertyIsEnumerable ( opt ) ) optionHandlers [ opt ] ( this , options [ opt ] , Init ) ; for ( var i = 0 ; i < initHooks . length ; ++ i ) initHooks [ i ] ( this ) ; } ) ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DISPLAY CONSTRUCTOR [CODESPLIT] function makeDisplay ( place ) { var d = { } ; var input = d . input = elt ( \"textarea\" , null , null , \"position: absolute; padding: 0; width: 1px; height: 1em; outline: none;\" ) ; input . setAttribute ( \"wrap\" , \"off\" ) ; input . setAttribute ( \"autocorrect\" , \"off\" ) ; input . setAttribute ( \"autocapitalize\" , \"off\" ) ; // Wraps and hides input textarea d . inputDiv = elt ( \"div\" , [ input ] , null , \"overflow: hidden; position: relative; width: 3px; height: 0px;\" ) ; // The actual fake scrollbars. d . scrollbarH = elt ( \"div\" , [ elt ( \"div\" , null , null , \"height: 1px\" ) ] , \"CodeMirror-hscrollbar\" ) ; d . scrollbarV = elt ( \"div\" , [ elt ( \"div\" , null , null , \"width: 1px\" ) ] , \"CodeMirror-vscrollbar\" ) ; d . scrollbarFiller = elt ( \"div\" , null , \"CodeMirror-scrollbar-filler\" ) ; // DIVs containing the selection and the actual code d . lineDiv = elt ( \"div\" ) ; d . selectionDiv = elt ( \"div\" , null , null , \"position: relative; z-index: 1\" ) ; // Blinky cursor, and element used to ensure cursor fits at the end of a line d . cursor = elt ( \"pre\" , \"\\u00a0\" , \"CodeMirror-cursor\" ) ; // Secondary cursor, shown when on a 'jump' in bi-directional text d . otherCursor = elt ( \"pre\" , \"\\u00a0\" , \"CodeMirror-cursor CodeMirror-secondarycursor\" ) ; // Used to measure text size d . measure = elt ( \"div\" , null , \"CodeMirror-measure\" ) ; // Wraps everything that needs to exist inside the vertically-padded coordinate system d . lineSpace = elt ( \"div\" , [ d . measure , d . selectionDiv , d . lineDiv , d . cursor , d . otherCursor ] , null , \"position: relative; outline: none\" ) ; // Moved around its parent to cover visible view d . mover = elt ( \"div\" , [ elt ( \"div\" , [ d . lineSpace ] , \"CodeMirror-lines\" ) ] , null , \"position: relative\" ) ; // Set to the height of the text, causes scrolling d . sizer = elt ( \"div\" , [ d . mover ] , \"CodeMirror-sizer\" ) ; // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers d . heightForcer = elt ( \"div\" , \"\\u00a0\" , null , \"position: absolute; height: \" + scrollerCutOff + \"px\" ) ; // Will contain the gutters, if any d . gutters = elt ( \"div\" , null , \"CodeMirror-gutters\" ) ; d . lineGutter = null ; // Helper element to properly size the gutter backgrounds var scrollerInner = elt ( \"div\" , [ d . sizer , d . heightForcer , d . gutters ] , null , \"position: relative; min-height: 100%\" ) ; // Provides scrolling d . scroller = elt ( \"div\" , [ scrollerInner ] , \"CodeMirror-scroll\" ) ; d . scroller . setAttribute ( \"tabIndex\" , \"-1\" ) ; // The element in which the editor lives. d . wrapper = elt ( \"div\" , [ d . inputDiv , d . scrollbarH , d . scrollbarV , d . scrollbarFiller , d . scroller ] , \"CodeMirror\" ) ; // Work around IE7 z-index bug if ( ie_lt8 ) { d . gutters . style . zIndex = - 1 ; d . scroller . style . paddingRight = 0 ; } if ( place . appendChild ) place . appendChild ( d . wrapper ) ; else place ( d . wrapper ) ; // Needed to hide big blue blinking cursor on Mobile Safari if ( ios ) input . style . width = \"0px\" ; if ( ! webkit ) d . scroller . draggable = true ; // Needed to handle Tab key in KHTML if ( khtml ) { d . inputDiv . style . height = \"1px\" ; d . inputDiv . style . position = \"absolute\" ; } // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). else if ( ie_lt8 ) d . scrollbarH . style . minWidth = d . scrollbarV . style . minWidth = \"18px\" ; // Current visible range (may be bigger than the view window). d . viewOffset = d . showingFrom = d . showingTo = d . lastSizeC = 0 ; // Used to only resize the line number gutter when necessary (when // the amount of lines crosses a boundary that makes its width change) d . lineNumWidth = d . lineNumInnerWidth = d . lineNumChars = null ; // See readInput and resetInput d . prevInput = \"\" ; // Set to true when a non-horizontal-scrolling widget is added. As // an optimization, widget aligning is skipped when d is false. d . alignWidgets = false ; // Flag that indicates whether we currently expect input to appear // (after some event like 'keypress' or 'input') and are polling // intensively. d . pollingFast = false ; // Self-resetting timeout for the poller d . poll = new Delayed ( ) ; // True when a drag from the editor is active d . draggingText = false ; d . cachedCharWidth = d . cachedTextHeight = null ; d . measureLineCache = [ ] ; d . measureLineCachePos = 0 ; // Tracks when resetInput has punted to just putting a short // string instead of the (large) selection. d . inaccurateSelection = false ; // Used to adjust overwrite behaviour when a paste has been // detected d . pasteIncoming = false ; return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "VIEW CONSTRUCTOR [CODESPLIT] function makeView ( doc ) { var selPos = { line : 0 , ch : 0 } ; return { doc : doc , // frontier is the point up to which the content has been parsed, frontier : 0 , highlight : new Delayed ( ) , sel : { from : selPos , to : selPos , head : selPos , anchor : selPos , shift : false , extend : false } , scrollTop : 0 , scrollLeft : 0 , overwrite : false , focused : false , // Tracks the maximum line length so that // the horizontal scrollbar can be kept // static when scrolling. maxLine : getLine ( doc , 0 ) , maxLineLength : 0 , maxLineChanged : false , suppressEdits : false , goalColumn : null , cantEdit : false , keyMaps : [ ] } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "STATE UPDATES Used to get the editor into a consistent state again when options change . [CODESPLIT] function loadMode ( cm ) { var doc = cm . view . doc ; cm . view . mode = CodeMirror . getMode ( cm . options , cm . options . mode ) ; doc . iter ( 0 , doc . size , function ( line ) { line . stateAfter = null ; } ) ; cm . view . frontier = 0 ; startWorker ( cm , 100 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - synchronize the fake scrollbars with the actual size of the content . Optionally force a scrollTop . [CODESPLIT] function updateScrollbars ( d /* display */ , docHeight ) { var totalHeight = docHeight + 2 * paddingTop ( d ) ; d . sizer . style . minHeight = d . heightForcer . style . top = totalHeight + \"px\" ; var scrollHeight = Math . max ( totalHeight , d . scroller . scrollHeight ) ; var needsH = d . scroller . scrollWidth > d . scroller . clientWidth ; var needsV = scrollHeight > d . scroller . clientHeight ; if ( needsV ) { d . scrollbarV . style . display = \"block\" ; d . scrollbarV . style . bottom = needsH ? scrollbarWidth ( d . measure ) + \"px\" : \"0\" ; d . scrollbarV . firstChild . style . height = ( scrollHeight - d . scroller . clientHeight + d . scrollbarV . clientHeight ) + \"px\" ; } else d . scrollbarV . style . display = \"\" ; if ( needsH ) { d . scrollbarH . style . display = \"block\" ; d . scrollbarH . style . right = needsV ? scrollbarWidth ( d . measure ) + \"px\" : \"0\" ; d . scrollbarH . firstChild . style . width = ( d . scroller . scrollWidth - d . scroller . clientWidth + d . scrollbarH . clientWidth ) + \"px\" ; } else d . scrollbarH . style . display = \"\" ; if ( needsH && needsV ) { d . scrollbarFiller . style . display = \"block\" ; d . scrollbarFiller . style . height = d . scrollbarFiller . style . width = scrollbarWidth ( d . measure ) + \"px\" ; } else d . scrollbarFiller . style . display = \"\" ; if ( mac_geLion && scrollbarWidth ( d . measure ) === 0 ) d . scrollbarV . style . minWidth = d . scrollbarH . style . minHeight = mac_geMountainLion ? \"18px\" : \"12px\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DISPLAY DRAWING [CODESPLIT] function updateDisplay ( cm , changes , viewPort ) { var oldFrom = cm . display . showingFrom , oldTo = cm . display . showingTo ; var updated = updateDisplayInner ( cm , changes , viewPort ) ; if ( updated ) { signalLater ( cm , cm , \"update\" , cm ) ; if ( cm . display . showingFrom != oldFrom || cm . display . showingTo != oldTo ) signalLater ( cm , cm , \"viewportChange\" , cm , cm . display . showingFrom , cm . display . showingTo ) ; } updateSelection ( cm ) ; updateScrollbars ( cm . display , cm . view . doc . height ) ; return updated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses a set of changes plus the current scroll position to determine which DOM updates have to be made and makes the updates . [CODESPLIT] function updateDisplayInner ( cm , changes , viewPort ) { var display = cm . display , doc = cm . view . doc ; if ( ! display . wrapper . clientWidth ) { display . showingFrom = display . showingTo = display . viewOffset = 0 ; return ; } // Compute the new visible window // If scrollTop is specified, use that to determine which lines // to render instead of the current scrollbar position. var visible = visibleLines ( display , doc , viewPort ) ; // Bail out if the visible area is already rendered and nothing changed. if ( changes !== true && changes . length == 0 && visible . from > display . showingFrom && visible . to < display . showingTo ) return ; if ( changes && maybeUpdateLineNumberWidth ( cm ) ) changes = true ; display . sizer . style . marginLeft = display . scrollbarH . style . left = display . gutters . offsetWidth + \"px\" ; // When merged lines are present, the line that needs to be // redrawn might not be the one that was changed. if ( changes !== true && sawCollapsedSpans ) for ( var i = 0 ; i < changes . length ; ++ i ) { var ch = changes [ i ] , merged ; while ( merged = collapsedSpanAtStart ( getLine ( doc , ch . from ) ) ) { var from = merged . find ( ) . from . line ; if ( ch . diff ) ch . diff -= ch . from - from ; ch . from = from ; } } // Used to determine which lines need their line numbers updated var positionsChangedFrom = changes === true ? 0 : Infinity ; if ( cm . options . lineNumbers && changes && changes !== true ) for ( var i = 0 ; i < changes . length ; ++ i ) if ( changes [ i ] . diff ) { positionsChangedFrom = changes [ i ] . from ; break ; } var from = Math . max ( visible . from - cm . options . viewportMargin , 0 ) ; var to = Math . min ( doc . size , visible . to + cm . options . viewportMargin ) ; if ( display . showingFrom < from && from - display . showingFrom < 20 ) from = display . showingFrom ; if ( display . showingTo > to && display . showingTo - to < 20 ) to = Math . min ( doc . size , display . showingTo ) ; if ( sawCollapsedSpans ) { from = lineNo ( visualLine ( doc , getLine ( doc , from ) ) ) ; while ( to < doc . size && lineIsHidden ( getLine ( doc , to ) ) ) ++ to ; } // Create a range of theoretically intact lines, and punch holes // in that using the change info. var intact = changes === true ? [ ] : computeIntact ( [ { from : display . showingFrom , to : display . showingTo } ] , changes ) ; // Clip off the parts that won't be visible var intactLines = 0 ; for ( var i = 0 ; i < intact . length ; ++ i ) { var range = intact [ i ] ; if ( range . from < from ) range . from = from ; if ( range . to > to ) range . to = to ; if ( range . from >= range . to ) intact . splice ( i -- , 1 ) ; else intactLines += range . to - range . from ; } if ( intactLines == to - from && from == display . showingFrom && to == display . showingTo ) return ; intact . sort ( function ( a , b ) { return a . from - b . from ; } ) ; if ( intactLines < ( to - from ) * .7 ) display . lineDiv . style . display = \"none\" ; patchDisplay ( cm , from , to , intact , positionsChangedFrom ) ; display . lineDiv . style . display = \"\" ; var different = from != display . showingFrom || to != display . showingTo || display . lastSizeC != display . wrapper . clientHeight ; // This is just a bogus formula that detects when the editor is // resized or the font size changes. if ( different ) display . lastSizeC = display . wrapper . clientHeight ; display . showingFrom = from ; display . showingTo = to ; startWorker ( cm , 100 ) ; var prevBottom = display . lineDiv . offsetTop ; for ( var node = display . lineDiv . firstChild , height ; node ; node = node . nextSibling ) if ( node . lineObj ) { if ( ie_lt8 ) { var bot = node . offsetTop + node . offsetHeight ; height = bot - prevBottom ; prevBottom = bot ; } else { var box = node . getBoundingClientRect ( ) ; height = box . bottom - box . top ; } var diff = node . lineObj . height - height ; if ( height < 2 ) height = textHeight ( display ) ; if ( diff > .001 || diff < - .001 ) updateLineHeight ( node . lineObj , height ) ; } display . viewOffset = heightAtLine ( cm , getLine ( doc , from ) ) ; // Position the mover div to align with the current virtual scroll position display . mover . style . top = display . viewOffset + \"px\" ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Highlight selection [CODESPLIT] function updateSelectionRange ( cm ) { var display = cm . display , doc = cm . view . doc , sel = cm . view . sel ; var fragment = document . createDocumentFragment ( ) ; var clientWidth = display . lineSpace . offsetWidth , pl = paddingLeft ( cm . display ) ; function add ( left , top , width , bottom ) { if ( top < 0 ) top = 0 ; fragment . appendChild ( elt ( \"div\" , null , \"CodeMirror-selected\" , \"position: absolute; left: \" + left + \"px; top: \" + top + \"px; width: \" + ( width == null ? clientWidth - left : width ) + \"px; height: \" + ( bottom - top ) + \"px\" ) ) ; } function drawForLine ( line , fromArg , toArg , retTop ) { var lineObj = getLine ( doc , line ) ; var lineLen = lineObj . text . length , rVal = retTop ? Infinity : - Infinity ; function coords ( ch ) { return charCoords ( cm , { line : line , ch : ch } , \"div\" , lineObj ) ; } iterateBidiSections ( getOrder ( lineObj ) , fromArg || 0 , toArg == null ? lineLen : toArg , function ( from , to , dir ) { var leftPos = coords ( dir == \"rtl\" ? to - 1 : from ) ; var rightPos = coords ( dir == \"rtl\" ? from : to - 1 ) ; var left = leftPos . left , right = rightPos . right ; if ( rightPos . top - leftPos . top > 3 ) { // Different lines, draw top part add ( left , leftPos . top , null , leftPos . bottom ) ; left = pl ; if ( leftPos . bottom < rightPos . top ) add ( left , leftPos . bottom , null , rightPos . top ) ; } if ( toArg == null && to == lineLen ) right = clientWidth ; if ( fromArg == null && from == 0 ) left = pl ; rVal = retTop ? Math . min ( rightPos . top , rVal ) : Math . max ( rightPos . bottom , rVal ) ; if ( left < pl + 1 ) left = pl ; add ( left , rightPos . top , right - left , rightPos . bottom ) ; } ) ; return rVal ; } if ( sel . from . line == sel . to . line ) { drawForLine ( sel . from . line , sel . from . ch , sel . to . ch ) ; } else { var fromObj = getLine ( doc , sel . from . line ) ; var cur = fromObj , merged , path = [ sel . from . line , sel . from . ch ] , singleLine ; while ( merged = collapsedSpanAtEnd ( cur ) ) { var found = merged . find ( ) ; path . push ( found . from . ch , found . to . line , found . to . ch ) ; if ( found . to . line == sel . to . line ) { path . push ( sel . to . ch ) ; singleLine = true ; break ; } cur = getLine ( doc , found . to . line ) ; } // This is a single, merged line if ( singleLine ) { for ( var i = 0 ; i < path . length ; i += 3 ) drawForLine ( path [ i ] , path [ i + 1 ] , path [ i + 2 ] ) ; } else { var middleTop , middleBot , toObj = getLine ( doc , sel . to . line ) ; if ( sel . from . ch ) // Draw the first line of selection. middleTop = drawForLine ( sel . from . line , sel . from . ch , null , false ) ; else // Simply include it in the middle block. middleTop = heightAtLine ( cm , fromObj ) - display . viewOffset ; if ( ! sel . to . ch ) middleBot = heightAtLine ( cm , toObj ) - display . viewOffset ; else middleBot = drawForLine ( sel . to . line , collapsedSpanAtStart ( toObj ) ? null : 0 , sel . to . ch , true ) ; if ( middleTop < middleBot ) add ( pl , middleTop , null , middleBot ) ; } } removeChildrenAndAdd ( display . selectionDiv , fragment ) ; display . selectionDiv . style . display = \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cursor - blinking [CODESPLIT] function restartBlink ( cm ) { var display = cm . display ; clearInterval ( display . blinker ) ; var on = true ; display . cursor . style . visibility = display . otherCursor . style . visibility = \"\" ; display . blinker = setInterval ( function ( ) { if ( ! display . cursor . offsetHeight ) return ; display . cursor . style . visibility = display . otherCursor . style . visibility = ( on = ! on ) ? \"\" : \"hidden\" ; } , cm . options . cursorBlinkRate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "HIGHLIGHT WORKER [CODESPLIT] function startWorker ( cm , time ) { if ( cm . view . frontier < cm . display . showingTo ) cm . view . highlight . set ( time , bind ( highlightWorker , cm ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Context is one of line div ( display . lineDiv ) local / null ( editor ) or page [CODESPLIT] function intoCoordSystem ( cm , lineObj , rect , context ) { if ( lineObj . widgets ) for ( var i = 0 ; i < lineObj . widgets . length ; ++ i ) if ( lineObj . widgets [ i ] . above ) { var size = lineObj . widgets [ i ] . node . offsetHeight ; rect . top += size ; rect . bottom += size ; } if ( context == \"line\" ) return rect ; if ( ! context ) context = \"local\" ; var yOff = heightAtLine ( cm , lineObj ) ; if ( context != \"local\" ) yOff -= cm . display . viewOffset ; if ( context == \"page\" ) { var lOff = cm . display . lineSpace . getBoundingClientRect ( ) ; yOff += lOff . top + ( window . pageYOffset || ( document . documentElement || document . body ) . scrollTop ) ; var xOff = lOff . left + ( window . pageXOffset || ( document . documentElement || document . body ) . scrollLeft ) ; rect . left += xOff ; rect . right += xOff ; } rect . top += yOff ; rect . bottom += yOff ; return rect ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Coords must be lineSpace - local [CODESPLIT] function coordsChar ( cm , x , y ) { var doc = cm . view . doc ; y += cm . display . viewOffset ; if ( y < 0 ) return { line : 0 , ch : 0 , outside : true } ; var lineNo = lineAtHeight ( doc , y ) ; if ( lineNo >= doc . size ) return { line : doc . size - 1 , ch : getLine ( doc , doc . size - 1 ) . text . length } ; if ( x < 0 ) x = 0 ; for ( ; ; ) { var lineObj = getLine ( doc , lineNo ) ; var found = coordsCharInner ( cm , lineObj , lineNo , x , y ) ; var merged = collapsedSpanAtEnd ( lineObj ) ; if ( merged && found . ch == lineRight ( lineObj ) ) lineNo = merged . find ( ) . to . line ; else return found ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Operations are used to wrap changes in such a way that each change won t have to update the cursor and display ( which would be awkward slow and error - prone ) but instead updates are batched and then all combined and executed at once . [CODESPLIT] function startOperation ( cm ) { if ( cm . curOp ) ++ cm . curOp . depth ; else cm . curOp = { // Nested operations delay update until the outermost one // finishes. depth : 1 , // An array of ranges of lines that have to be updated. See // updateDisplay. changes : [ ] , delayedCallbacks : [ ] , updateInput : null , userSelChange : null , textChanged : null , selectionChanged : false , updateMaxLine : false , id : ++ cm . nextOpId } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prevInput is a hack to work with IME . If we reset the textarea on every change that breaks IME . So we look for changes compared to the previous content instead . ( Modern browsers have events that indicate IME taking place but these are not widely supported or compatible enough yet to rely on . ) [CODESPLIT] function readInput ( cm ) { var input = cm . display . input , prevInput = cm . display . prevInput , view = cm . view , sel = view . sel ; if ( ! view . focused || hasSelection ( input ) || isReadOnly ( cm ) ) return false ; var text = input . value ; if ( text == prevInput && posEq ( sel . from , sel . to ) ) return false ; startOperation ( cm ) ; view . sel . shift = false ; var same = 0 , l = Math . min ( prevInput . length , text . length ) ; while ( same < l && prevInput [ same ] == text [ same ] ) ++ same ; var from = sel . from , to = sel . to ; if ( same < prevInput . length ) from = { line : from . line , ch : from . ch - ( prevInput . length - same ) } ; else if ( view . overwrite && posEq ( from , to ) && ! cm . display . pasteIncoming ) to = { line : to . line , ch : Math . min ( getLine ( cm . view . doc , to . line ) . text . length , to . ch + ( text . length - same ) ) } ; var updateInput = cm . curOp . updateInput ; updateDoc ( cm , from , to , splitLines ( text . slice ( same ) ) , \"end\" , cm . display . pasteIncoming ? \"paste\" : \"input\" , { from : from , to : to } ) ; cm . curOp . updateInput = updateInput ; if ( text . length > 1000 ) input . value = cm . display . prevInput = \"\" ; else cm . display . prevInput = text ; endOperation ( cm ) ; cm . display . pasteIncoming = false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "EVENT HANDLERS [CODESPLIT] function registerEventHandlers ( cm ) { var d = cm . display ; on ( d . scroller , \"mousedown\" , operation ( cm , onMouseDown ) ) ; on ( d . scroller , \"dblclick\" , operation ( cm , e_preventDefault ) ) ; on ( d . lineSpace , \"selectstart\" , function ( e ) { if ( ! mouseEventInWidget ( d , e ) ) e_preventDefault ( e ) ; } ) ; // Gecko browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for Gecko. if ( ! gecko ) on ( d . scroller , \"contextmenu\" , function ( e ) { onContextMenu ( cm , e ) ; } ) ; on ( d . scroller , \"scroll\" , function ( ) { setScrollTop ( cm , d . scroller . scrollTop ) ; setScrollLeft ( cm , d . scroller . scrollLeft , true ) ; signal ( cm , \"scroll\" , cm ) ; } ) ; on ( d . scrollbarV , \"scroll\" , function ( ) { setScrollTop ( cm , d . scrollbarV . scrollTop ) ; } ) ; on ( d . scrollbarH , \"scroll\" , function ( ) { setScrollLeft ( cm , d . scrollbarH . scrollLeft ) ; } ) ; on ( d . scroller , \"mousewheel\" , function ( e ) { onScrollWheel ( cm , e ) ; } ) ; on ( d . scroller , \"DOMMouseScroll\" , function ( e ) { onScrollWheel ( cm , e ) ; } ) ; function reFocus ( ) { if ( cm . view . focused ) setTimeout ( bind ( focusInput , cm ) , 0 ) ; } on ( d . scrollbarH , \"mousedown\" , reFocus ) ; on ( d . scrollbarV , \"mousedown\" , reFocus ) ; // Prevent wrapper from ever scrolling on ( d . wrapper , \"scroll\" , function ( ) { d . wrapper . scrollTop = d . wrapper . scrollLeft = 0 ; } ) ; on ( window , \"resize\" , function resizeHandler ( ) { // Might be a text scaling operation, clear size caches. d . cachedCharWidth = d . cachedTextHeight = null ; clearCaches ( cm ) ; if ( d . wrapper . parentNode ) updateDisplay ( cm , true ) ; else off ( window , \"resize\" , resizeHandler ) ; } ) ; on ( d . input , \"keyup\" , operation ( cm , function ( e ) { if ( cm . options . onKeyEvent && cm . options . onKeyEvent ( cm , addStop ( e ) ) ) return ; if ( e_prop ( e , \"keyCode\" ) == 16 ) cm . view . sel . shift = false ; } ) ) ; on ( d . input , \"input\" , bind ( fastPoll , cm ) ) ; on ( d . input , \"keydown\" , operation ( cm , onKeyDown ) ) ; on ( d . input , \"keypress\" , operation ( cm , onKeyPress ) ) ; on ( d . input , \"focus\" , bind ( onFocus , cm ) ) ; on ( d . input , \"blur\" , bind ( onBlur , cm ) ) ; function drag_ ( e ) { if ( cm . options . onDragEvent && cm . options . onDragEvent ( cm , addStop ( e ) ) ) return ; e_stop ( e ) ; } if ( cm . options . dragDrop ) { on ( d . scroller , \"dragstart\" , function ( e ) { onDragStart ( cm , e ) ; } ) ; on ( d . scroller , \"dragenter\" , drag_ ) ; on ( d . scroller , \"dragover\" , drag_ ) ; on ( d . scroller , \"drop\" , operation ( cm , onDrop ) ) ; } on ( d . scroller , \"paste\" , function ( ) { focusInput ( cm ) ; fastPoll ( cm ) ; } ) ; on ( d . input , \"paste\" , function ( ) { d . pasteIncoming = true ; fastPoll ( cm ) ; } ) ; function prepareCopy ( ) { if ( d . inaccurateSelection ) { d . prevInput = \"\" ; d . inaccurateSelection = false ; d . input . value = cm . getSelection ( ) ; selectInput ( d . input ) ; } } on ( d . input , \"cut\" , prepareCopy ) ; on ( d . input , \"copy\" , prepareCopy ) ; // Needed to handle Tab key in KHTML if ( khtml ) on ( d . sizer , \"mouseup\" , function ( ) { if ( document . activeElement == d . input ) d . input . blur ( ) ; focusInput ( cm ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the range from from to to by the strings in newText . Afterwards set the selection to selFrom selTo . [CODESPLIT] function updateDoc ( cm , from , to , newText , selUpdate , origin ) { // Possibly split or suppress the update based on the presence // of read-only spans in its range. var split = sawReadOnlySpans && removeReadOnlyRanges ( cm . view . doc , from , to ) ; if ( split ) { for ( var i = split . length - 1 ; i >= 1 ; -- i ) updateDocInner ( cm , split [ i ] . from , split [ i ] . to , [ \"\" ] , origin ) ; if ( split . length ) return updateDocInner ( cm , split [ 0 ] . from , split [ 0 ] . to , newText , selUpdate , origin ) ; } else { return updateDocInner ( cm , from , to , newText , selUpdate , origin ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the selection . Last two args are only used by updateDoc since they have to be expressed in the line numbers before the update . [CODESPLIT] function setSelection ( cm , anchor , head , bias , checkAtomic ) { cm . view . goalColumn = null ; var sel = cm . view . sel ; // Skip over atomic spans. if ( checkAtomic || ! posEq ( anchor , sel . anchor ) ) anchor = skipAtomic ( cm , anchor , bias , checkAtomic != \"push\" ) ; if ( checkAtomic || ! posEq ( head , sel . head ) ) head = skipAtomic ( cm , head , bias , checkAtomic != \"push\" ) ; if ( posEq ( sel . anchor , anchor ) && posEq ( sel . head , head ) ) return ; sel . anchor = anchor ; sel . head = head ; var inv = posLess ( head , anchor ) ; sel . from = inv ? head : anchor ; sel . to = inv ? anchor : head ; cm . curOp . updateInput = true ; cm . curOp . selectionChanged = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch the parser token for a given character . Useful for hacks that want to inspect the mode state ( say for completion ) . [CODESPLIT] function ( pos ) { var doc = this . view . doc ; pos = clipPos ( doc , pos ) ; var state = getStateBefore ( this , pos . line ) , mode = this . view . mode ; var line = getLine ( doc , pos . line ) ; var stream = new StringStream ( line . text , this . options . tabSize ) ; while ( stream . pos < pos . ch && ! stream . eol ( ) ) { stream . start = stream . pos ; var style = mode . token ( stream , state ) ; } return { start : stream . start , end : stream . pos , string : stream . current ( ) , className : style || null , // Deprecated, use 'type' instead type : style || null , state : state } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Line objects . These hold state related to a line including highlighting info ( the styles array ) . [CODESPLIT] function makeLine ( text , markedSpans , height ) { var line = { text : text , height : height } ; attachMarkedSpans ( line , markedSpans ) ; if ( lineIsHidden ( line ) ) line . height = 0 ; return line ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the given mode s parser over a line update the styles array which contains alternating fragments of text and CSS classes . [CODESPLIT] function highlightLine ( cm , line , state ) { var mode = cm . view . mode , flattenSpans = cm . options . flattenSpans ; var changed = ! line . styles , pos = 0 , curText = \"\" , curStyle = null ; var stream = new StringStream ( line . text , cm . options . tabSize ) , st = line . styles || ( line . styles = [ ] ) ; if ( line . text == \"\" && mode . blankLine ) mode . blankLine ( state ) ; while ( ! stream . eol ( ) ) { var style = mode . token ( stream , state ) , substr = stream . current ( ) ; stream . start = stream . pos ; if ( ! flattenSpans || curStyle != style ) { if ( curText ) { changed = changed || pos >= st . length || curText != st [ pos ] || curStyle != st [ pos + 1 ] ; st [ pos ++ ] = curText ; st [ pos ++ ] = curStyle ; } curText = substr ; curStyle = style ; } else curText = curText + substr ; // Give up when line is ridiculously long if ( stream . pos > 5000 ) break ; } if ( curText ) { changed = changed || pos >= st . length || curText != st [ pos ] || curStyle != st [ pos + 1 ] ; st [ pos ++ ] = curText ; st [ pos ++ ] = curStyle ; } if ( stream . pos > 5000 ) { st [ pos ++ ] = line . text . slice ( stream . pos ) ; st [ pos ++ ] = null ; } if ( pos != st . length ) { st . length = pos ; changed = true ; } return changed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow 3rd - party code to override event properties by adding an override object to an event object . [CODESPLIT] function e_prop ( e , prop ) { var overridden = e . override && e . override . hasOwnProperty ( prop ) ; return overridden ? e . override [ prop ] : e [ prop ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is somewhat involved . It is needed in order to move visually through bi - directional text -- i . e . pressing left should make the cursor go left even when in RTL text . The tricky part is the jumps where RTL and LTR text touch each other . This often requires the cursor offset to move more than one unit in order to visually move one unit . [CODESPLIT] function moveVisually ( line , start , dir , byUnit ) { var bidi = getOrder ( line ) ; if ( ! bidi ) return moveLogically ( line , start , dir , byUnit ) ; var moveOneUnit = byUnit ? function ( pos , dir ) { do pos += dir ; while ( pos > 0 && isExtendingChar . test ( line . text . charAt ( pos ) ) ) ; return pos ; } : function ( pos , dir ) { return pos + dir ; } ; var linedir = bidi [ 0 ] . level ; for ( var i = 0 ; i < bidi . length ; ++ i ) { var part = bidi [ i ] , sticky = part . level % 2 == linedir ; if ( ( part . from < start && part . to > start ) || ( sticky && ( part . from == start || part . to == start ) ) ) break ; } var target = moveOneUnit ( start , part . level % 2 ? - dir : dir ) ; while ( target != null ) { if ( part . level % 2 == linedir ) { if ( target < part . from || target > part . to ) { part = bidi [ i += dir ] ; target = part && ( dir > 0 == part . level % 2 ? moveOneUnit ( part . to , - 1 ) : moveOneUnit ( part . from , 1 ) ) ; } else break ; } else { if ( target == bidiLeft ( part ) ) { part = bidi [ -- i ] ; target = part && bidiRight ( part ) ; } else if ( target == bidiRight ( part ) ) { part = bidi [ ++ i ] ; target = part && bidiLeft ( part ) ; } else break ; } } return target < 0 || target > line . text . length ? null : target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flow . js is a library providing multiple simultaneous stable and resumable uploads via the HTML5 File API . [CODESPLIT] function Flow ( opts ) { /**\n     * Supported by browser?\n     * @type {boolean}\n     */ this . support = ( typeof File !== 'undefined' && typeof Blob !== 'undefined' && typeof FileList !== 'undefined' && ( ! ! Blob . prototype . slice || ! ! Blob . prototype . webkitSlice || ! ! Blob . prototype . mozSlice || false ) // slicing files support ) ; if ( ! this . support ) { return ; } /**\n     * Check if directory upload is supported\n     * @type {boolean}\n     */ this . supportDirectory = ( / Chrome / . test ( window . navigator . userAgent ) || / Firefox / . test ( window . navigator . userAgent ) || / Edge / . test ( window . navigator . userAgent ) ) ; /**\n     * List of FlowFile objects\n     * @type {Array.<FlowFile>}\n     */ this . files = [ ] ; /**\n     * Default options for flow.js\n     * @type {Object}\n     */ this . defaults = { chunkSize : 1024 * 1024 , forceChunkSize : false , simultaneousUploads : 3 , singleFile : false , fileParameterName : 'file' , progressCallbacksInterval : 500 , speedSmoothingFactor : 0.1 , query : { } , headers : { } , withCredentials : false , preprocess : null , method : 'multipart' , testMethod : 'GET' , uploadMethod : 'POST' , prioritizeFirstAndLastChunk : false , allowDuplicateUploads : false , target : '/' , testChunks : true , generateUniqueIdentifier : null , maxChunkRetries : 0 , chunkRetryInterval : null , permanentErrors : [ 404 , 413 , 415 , 500 , 501 ] , successStatuses : [ 200 , 201 , 202 ] , onDropStopPropagation : false , initFileFn : null , readFileFn : webAPIFileRead } ; /**\n     * Current options\n     * @type {Object}\n     */ this . opts = { } ; /**\n     * List of events:\n     *  key stands for event name\n     *  value array list of callbacks\n     * @type {}\n     */ this . events = { } ; var $ = this ; /**\n     * On drop event\n     * @function\n     * @param {MouseEvent} event\n     */ this . onDrop = function ( event ) { if ( $ . opts . onDropStopPropagation ) { event . stopPropagation ( ) ; } event . preventDefault ( ) ; var dataTransfer = event . dataTransfer ; if ( dataTransfer . items && dataTransfer . items [ 0 ] && dataTransfer . items [ 0 ] . webkitGetAsEntry ) { $ . webkitReadDataTransfer ( event ) ; } else { $ . addFiles ( dataTransfer . files , event ) ; } } ; /**\n     * Prevent default\n     * @function\n     * @param {MouseEvent} event\n     */ this . preventEvent = function ( event ) { event . preventDefault ( ) ; } ; /**\n     * Current options\n     * @type {Object}\n     */ this . opts = Flow . extend ( { } , this . defaults , opts || { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a callback for an event possible events : fileSuccess ( file ) fileProgress ( file ) fileAdded ( file event ) fileRemoved ( file ) fileRetry ( file ) fileError ( file message ) complete () progress () error ( message file ) pause () [CODESPLIT] function ( event , callback ) { event = event . toLowerCase ( ) ; if ( ! this . events . hasOwnProperty ( event ) ) { this . events [ event ] = [ ] ; } this . events [ event ] . push ( callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove event callback [CODESPLIT] function ( event , fn ) { if ( event !== undefined ) { event = event . toLowerCase ( ) ; if ( fn !== undefined ) { if ( this . events . hasOwnProperty ( event ) ) { arrayRemove ( this . events [ event ] , fn ) ; } } else { delete this . events [ event ] ; } } else { this . events = { } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fire an event [CODESPLIT] function ( event , args ) { // `arguments` is an object, not array, in FF, so: args = Array . prototype . slice . call ( arguments ) ; event = event . toLowerCase ( ) ; var preventDefault = false ; if ( this . events . hasOwnProperty ( event ) ) { each ( this . events [ event ] , function ( callback ) { preventDefault = callback . apply ( this , args . slice ( 1 ) ) === false || preventDefault ; } , this ) ; } if ( event != 'catchall' ) { args . unshift ( 'catchAll' ) ; preventDefault = this . fire . apply ( this , args ) === false || preventDefault ; } return ! preventDefault ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read webkit dataTransfer object [CODESPLIT] function ( event ) { var $ = this ; var queue = event . dataTransfer . items . length ; var files = [ ] ; each ( event . dataTransfer . items , function ( item ) { var entry = item . webkitGetAsEntry ( ) ; if ( ! entry ) { decrement ( ) ; return ; } if ( entry . isFile ) { // due to a bug in Chrome's File System API impl - #149735 fileReadSuccess ( item . getAsFile ( ) , entry . fullPath ) ; } else { readDirectory ( entry . createReader ( ) ) ; } } ) ; function readDirectory ( reader ) { reader . readEntries ( function ( entries ) { if ( entries . length ) { queue += entries . length ; each ( entries , function ( entry ) { if ( entry . isFile ) { var fullPath = entry . fullPath ; entry . file ( function ( file ) { fileReadSuccess ( file , fullPath ) ; } , readError ) ; } else if ( entry . isDirectory ) { readDirectory ( entry . createReader ( ) ) ; } } ) ; readDirectory ( reader ) ; } else { decrement ( ) ; } } , readError ) ; } function fileReadSuccess ( file , fullPath ) { // relative path should not start with \"/\" file . relativePath = fullPath . substring ( 1 ) ; files . push ( file ) ; decrement ( ) ; } function readError ( fileError ) { throw fileError ; } function decrement ( ) { if ( -- queue == 0 ) { $ . addFiles ( files , event ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate unique identifier for a file [CODESPLIT] function ( file ) { var custom = this . opts . generateUniqueIdentifier ; if ( typeof custom === 'function' ) { return custom ( file ) ; } // Some confusion in different versions of Firefox var relativePath = file . relativePath || file . webkitRelativePath || file . fileName || file . name ; return file . size + '-' + relativePath . replace ( / [^0-9a-zA-Z_-] / img , '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upload next chunk from the queue [CODESPLIT] function ( preventEvents ) { // In some cases (such as videos) it's really handy to upload the first // and last chunk of a file quickly; this let's the server check the file's // metadata and determine if there's even a point in continuing. var found = false ; if ( this . opts . prioritizeFirstAndLastChunk ) { each ( this . files , function ( file ) { if ( ! file . paused && file . chunks . length && file . chunks [ 0 ] . status ( ) === 'pending' ) { file . chunks [ 0 ] . send ( ) ; found = true ; return false ; } if ( ! file . paused && file . chunks . length > 1 && file . chunks [ file . chunks . length - 1 ] . status ( ) === 'pending' ) { file . chunks [ file . chunks . length - 1 ] . send ( ) ; found = true ; return false ; } } ) ; if ( found ) { return found ; } } // Now, simply look for the next, best thing to upload each ( this . files , function ( file ) { if ( ! file . paused ) { each ( file . chunks , function ( chunk ) { if ( chunk . status ( ) === 'pending' ) { chunk . send ( ) ; found = true ; return false ; } } ) ; } if ( found ) { return false ; } } ) ; if ( found ) { return true ; } // The are no more outstanding chunks to upload, check is everything is done var outstanding = false ; each ( this . files , function ( file ) { if ( ! file . isComplete ( ) ) { outstanding = true ; return false ; } } ) ; if ( ! outstanding && ! preventEvents ) { // All chunks have been uploaded, complete async ( function ( ) { this . fire ( 'complete' ) ; } , this ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assign a browse action to one or more DOM nodes . [CODESPLIT] function ( domNodes , isDirectory , singleFile , attributes ) { if ( domNodes instanceof Element ) { domNodes = [ domNodes ] ; } each ( domNodes , function ( domNode ) { var input ; if ( domNode . tagName === 'INPUT' && domNode . type === 'file' ) { input = domNode ; } else { input = document . createElement ( 'input' ) ; input . setAttribute ( 'type' , 'file' ) ; // display:none - not working in opera 12 extend ( input . style , { visibility : 'hidden' , position : 'absolute' , width : '1px' , height : '1px' } ) ; // for opera 12 browser, input must be assigned to a document domNode . appendChild ( input ) ; // https://developer.mozilla.org/en/using_files_from_web_applications) // event listener is executed two times // first one - original mouse click event // second - input.click(), input is inside domNode domNode . addEventListener ( 'click' , function ( ) { input . click ( ) ; } , false ) ; } if ( ! this . opts . singleFile && ! singleFile ) { input . setAttribute ( 'multiple' , 'multiple' ) ; } if ( isDirectory ) { input . setAttribute ( 'webkitdirectory' , 'webkitdirectory' ) ; } each ( attributes , function ( value , key ) { input . setAttribute ( key , value ) ; } ) ; // When new files are added, simply append them to the overall list var $ = this ; input . addEventListener ( 'change' , function ( e ) { if ( e . target . value ) { $ . addFiles ( e . target . files , e ) ; e . target . value = '' ; } } , false ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assign one or more DOM nodes as a drop target . [CODESPLIT] function ( domNodes ) { if ( typeof domNodes . length === 'undefined' ) { domNodes = [ domNodes ] ; } each ( domNodes , function ( domNode ) { domNode . addEventListener ( 'dragover' , this . preventEvent , false ) ; domNode . addEventListener ( 'dragenter' , this . preventEvent , false ) ; domNode . addEventListener ( 'drop' , this . onDrop , false ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Un - assign drop event from DOM nodes [CODESPLIT] function ( domNodes ) { if ( typeof domNodes . length === 'undefined' ) { domNodes = [ domNodes ] ; } each ( domNodes , function ( domNode ) { domNode . removeEventListener ( 'dragover' , this . preventEvent ) ; domNode . removeEventListener ( 'dragenter' , this . preventEvent ) ; domNode . removeEventListener ( 'drop' , this . onDrop ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a boolean indicating whether or not the instance is currently uploading anything . [CODESPLIT] function ( ) { var uploading = false ; each ( this . files , function ( file ) { if ( file . isUploading ( ) ) { uploading = true ; return false ; } } ) ; return uploading ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "should upload next chunk [CODESPLIT] function ( ) { var num = 0 ; var should = true ; var simultaneousUploads = this . opts . simultaneousUploads ; each ( this . files , function ( file ) { each ( file . chunks , function ( chunk ) { if ( chunk . status ( ) === 'uploading' ) { num ++ ; if ( num >= simultaneousUploads ) { should = false ; return false ; } } } ) ; } ) ; // if should is true then return uploading chunks's length return should && num ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start or resume uploading . [CODESPLIT] function ( ) { // Make sure we don't start too many uploads at once var ret = this . _shouldUploadNext ( ) ; if ( ret === false ) { return ; } // Kick off the queue this . fire ( 'uploadStart' ) ; var started = false ; for ( var num = 1 ; num <= this . opts . simultaneousUploads - ret ; num ++ ) { started = this . uploadNextChunk ( true ) || started ; } if ( ! started ) { async ( function ( ) { this . fire ( 'complete' ) ; } , this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a HTML5 File object to the list of files . [CODESPLIT] function ( fileList , event ) { var files = [ ] ; each ( fileList , function ( file ) { // https://github.com/flowjs/flow.js/issues/55 if ( ( ! ie10plus || ie10plus && file . size > 0 ) && ! ( file . size % 4096 === 0 && ( file . name === '.' || file . fileName === '.' ) ) ) { var uniqueIdentifier = this . generateUniqueIdentifier ( file ) ; if ( this . opts . allowDuplicateUploads || ! this . getFromUniqueIdentifier ( uniqueIdentifier ) ) { var f = new FlowFile ( this , file , uniqueIdentifier ) ; if ( this . fire ( 'fileAdded' , f , event ) ) { files . push ( f ) ; } } } } , this ) ; if ( this . fire ( 'filesAdded' , files , event ) ) { each ( files , function ( file ) { if ( this . opts . singleFile && this . files . length > 0 ) { this . removeFile ( this . files [ 0 ] ) ; } this . files . push ( file ) ; } , this ) ; this . fire ( 'filesSubmitted' , files , event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cancel upload of a specific FlowFile object from the list . [CODESPLIT] function ( file ) { for ( var i = this . files . length - 1 ; i >= 0 ; i -- ) { if ( this . files [ i ] === file ) { this . files . splice ( i , 1 ) ; file . abort ( ) ; this . fire ( 'fileRemoved' , file ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look up a FlowFile object by its unique identifier . [CODESPLIT] function ( uniqueIdentifier ) { var ret = false ; each ( this . files , function ( file ) { if ( file . uniqueIdentifier === uniqueIdentifier ) { ret = file ; } } ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns remaining time to upload all files in seconds . Accuracy is based on average speed . If speed is zero time remaining will be equal to positive infinity Number . POSITIVE_INFINITY [CODESPLIT] function ( ) { var sizeDelta = 0 ; var averageSpeed = 0 ; each ( this . files , function ( file ) { if ( ! file . paused && ! file . error ) { sizeDelta += file . size - file . sizeUploaded ( ) ; averageSpeed += file . averageSpeed ; } } ) ; if ( sizeDelta && ! averageSpeed ) { return Number . POSITIVE_INFINITY ; } if ( ! sizeDelta && ! averageSpeed ) { return 0 ; } return Math . floor ( sizeDelta / averageSpeed ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FlowFile class [CODESPLIT] function FlowFile ( flowObj , file , uniqueIdentifier ) { /**\n     * Reference to parent Flow instance\n     * @type {Flow}\n     */ this . flowObj = flowObj ; /**\n     * Used to store the bytes read\n     * @type {Blob|string}\n     */ this . bytes = null ; /**\n     * Reference to file\n     * @type {File}\n     */ this . file = file ; /**\n     * File name. Some confusion in different versions of Firefox\n     * @type {string}\n     */ this . name = file . fileName || file . name ; /**\n     * File size\n     * @type {number}\n     */ this . size = file . size ; /**\n     * Relative file path\n     * @type {string}\n     */ this . relativePath = file . relativePath || file . webkitRelativePath || this . name ; /**\n     * File unique identifier\n     * @type {string}\n     */ this . uniqueIdentifier = ( uniqueIdentifier === undefined ? flowObj . generateUniqueIdentifier ( file ) : uniqueIdentifier ) ; /**\n     * List of chunks\n     * @type {Array.<FlowChunk>}\n     */ this . chunks = [ ] ; /**\n     * Indicated if file is paused\n     * @type {boolean}\n     */ this . paused = false ; /**\n     * Indicated if file has encountered an error\n     * @type {boolean}\n     */ this . error = false ; /**\n     * Average upload speed\n     * @type {number}\n     */ this . averageSpeed = 0 ; /**\n     * Current upload speed\n     * @type {number}\n     */ this . currentSpeed = 0 ; /**\n     * Date then progress was called last time\n     * @type {number}\n     * @private\n     */ this . _lastProgressCallback = Date . now ( ) ; /**\n     * Previously uploaded file size\n     * @type {number}\n     * @private\n     */ this . _prevUploadedSize = 0 ; /**\n     * Holds previous progress\n     * @type {number}\n     * @private\n     */ this . _prevProgress = 0 ; this . bootstrap ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update speed parameters [CODESPLIT] function ( ) { var timeSpan = Date . now ( ) - this . _lastProgressCallback ; if ( ! timeSpan ) { return ; } var smoothingFactor = this . flowObj . opts . speedSmoothingFactor ; var uploaded = this . sizeUploaded ( ) ; // Prevent negative upload speed after file upload resume this . currentSpeed = Math . max ( ( uploaded - this . _prevUploadedSize ) / timeSpan * 1000 , 0 ) ; this . averageSpeed = smoothingFactor * this . currentSpeed + ( 1 - smoothingFactor ) * this . averageSpeed ; this . _prevUploadedSize = uploaded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For internal usage only . Callback when something happens within the chunk . [CODESPLIT] function ( chunk , event , message ) { switch ( event ) { case 'progress' : if ( Date . now ( ) - this . _lastProgressCallback < this . flowObj . opts . progressCallbacksInterval ) { break ; } this . measureSpeed ( ) ; this . flowObj . fire ( 'fileProgress' , this , chunk ) ; this . flowObj . fire ( 'progress' ) ; this . _lastProgressCallback = Date . now ( ) ; break ; case 'error' : this . error = true ; this . abort ( true ) ; this . flowObj . fire ( 'fileError' , this , message , chunk ) ; this . flowObj . fire ( 'error' , message , this , chunk ) ; break ; case 'success' : if ( this . error ) { return ; } this . measureSpeed ( ) ; this . flowObj . fire ( 'fileProgress' , this , chunk ) ; this . flowObj . fire ( 'progress' ) ; this . _lastProgressCallback = Date . now ( ) ; if ( this . isComplete ( ) ) { this . currentSpeed = 0 ; this . averageSpeed = 0 ; this . flowObj . fire ( 'fileSuccess' , this , message , chunk ) ; } break ; case 'retry' : this . flowObj . fire ( 'fileRetry' , this , chunk ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Abort current upload [CODESPLIT] function ( reset ) { this . currentSpeed = 0 ; this . averageSpeed = 0 ; var chunks = this . chunks ; if ( reset ) { this . chunks = [ ] ; } each ( chunks , function ( c ) { if ( c . status ( ) === 'uploading' ) { c . abort ( ) ; this . flowObj . uploadNextChunk ( ) ; } } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear current chunks and slice file again [CODESPLIT] function ( ) { if ( typeof this . flowObj . opts . initFileFn === \"function\" ) { this . flowObj . opts . initFileFn ( this ) ; } this . abort ( true ) ; this . error = false ; // Rebuild stack of chunks from file this . _prevProgress = 0 ; var round = this . flowObj . opts . forceChunkSize ? Math . ceil : Math . floor ; var chunks = Math . max ( round ( this . size / this . flowObj . opts . chunkSize ) , 1 ) ; for ( var offset = 0 ; offset < chunks ; offset ++ ) { this . chunks . push ( new FlowChunk ( this . flowObj , this , offset ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get current upload progress status [CODESPLIT] function ( ) { if ( this . error ) { return 1 ; } if ( this . chunks . length === 1 ) { this . _prevProgress = Math . max ( this . _prevProgress , this . chunks [ 0 ] . progress ( ) ) ; return this . _prevProgress ; } // Sum up progress across everything var bytesLoaded = 0 ; each ( this . chunks , function ( c ) { // get chunk progress relative to entire file bytesLoaded += c . progress ( ) * ( c . endByte - c . startByte ) ; } ) ; var percent = bytesLoaded / this . size ; // We don't want to lose percentages when an upload is paused this . _prevProgress = Math . max ( this . _prevProgress , percent > 0.9999 ? 1 : percent ) ; return this . _prevProgress ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates if file is has finished uploading and received a response [CODESPLIT] function ( ) { var outstanding = false ; each ( this . chunks , function ( chunk ) { var status = chunk . status ( ) ; if ( status === 'pending' || status === 'uploading' || status === 'reading' || chunk . preprocessState === 1 || chunk . readState === 1 ) { outstanding = true ; return false ; } } ) ; return ! outstanding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns remaining time to finish upload file in seconds . Accuracy is based on average speed . If speed is zero time remaining will be equal to positive infinity Number . POSITIVE_INFINITY [CODESPLIT] function ( ) { if ( this . paused || this . error ) { return 0 ; } var delta = this . size - this . sizeUploaded ( ) ; if ( delta && ! this . averageSpeed ) { return Number . POSITIVE_INFINITY ; } if ( ! delta && ! this . averageSpeed ) { return 0 ; } return Math . floor ( delta / this . averageSpeed ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Default read function using the webAPI [CODESPLIT] function webAPIFileRead ( fileObj , startByte , endByte , fileType , chunk ) { var function_name = 'slice' ; if ( fileObj . file . slice ) function_name = 'slice' ; else if ( fileObj . file . mozSlice ) function_name = 'mozSlice' ; else if ( fileObj . file . webkitSlice ) function_name = 'webkitSlice' ; chunk . readFinished ( fileObj . file [ function_name ] ( startByte , endByte , fileType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Class for storing a single chunk [CODESPLIT] function FlowChunk ( flowObj , fileObj , offset ) { /**\n     * Reference to parent flow object\n     * @type {Flow}\n     */ this . flowObj = flowObj ; /**\n     * Reference to parent FlowFile object\n     * @type {FlowFile}\n     */ this . fileObj = fileObj ; /**\n     * File offset\n     * @type {number}\n     */ this . offset = offset ; /**\n     * Indicates if chunk existence was checked on the server\n     * @type {boolean}\n     */ this . tested = false ; /**\n     * Number of retries performed\n     * @type {number}\n     */ this . retries = 0 ; /**\n     * Pending retry\n     * @type {boolean}\n     */ this . pendingRetry = false ; /**\n     * Preprocess state\n     * @type {number} 0 = unprocessed, 1 = processing, 2 = finished\n     */ this . preprocessState = 0 ; /**\n     * Read state\n     * @type {number} 0 = not read, 1 = reading, 2 = finished\n     */ this . readState = 0 ; /**\n     * Bytes transferred from total request size\n     * @type {number}\n     */ this . loaded = 0 ; /**\n     * Total request size\n     * @type {number}\n     */ this . total = 0 ; /**\n     * Size of a chunk\n     * @type {number}\n     */ this . chunkSize = this . flowObj . opts . chunkSize ; /**\n     * Chunk start byte in a file\n     * @type {number}\n     */ this . startByte = this . offset * this . chunkSize ; /**\n      * Compute the endbyte in a file\n      *\n      */ this . computeEndByte = function ( ) { var endByte = Math . min ( this . fileObj . size , ( this . offset + 1 ) * this . chunkSize ) ; if ( this . fileObj . size - endByte < this . chunkSize && ! this . flowObj . opts . forceChunkSize ) { // The last chunk will be bigger than the chunk size, // but less than 2 * this.chunkSize endByte = this . fileObj . size ; } return endByte ; } /**\n     * Chunk end byte in a file\n     * @type {number}\n     */ this . endByte = this . computeEndByte ( ) ; /**\n     * XMLHttpRequest\n     * @type {XMLHttpRequest}\n     */ this . xhr = null ; var $ = this ; /**\n     * Send chunk event\n     * @param event\n     * @param {...} args arguments of a callback\n     */ this . event = function ( event , args ) { args = Array . prototype . slice . call ( arguments ) ; args . unshift ( $ ) ; $ . fileObj . chunkEvent . apply ( $ . fileObj , args ) ; } ; /**\n     * Catch progress event\n     * @param {ProgressEvent} event\n     */ this . progressHandler = function ( event ) { if ( event . lengthComputable ) { $ . loaded = event . loaded ; $ . total = event . total ; } $ . event ( 'progress' , event ) ; } ; /**\n     * Catch test event\n     * @param {Event} event\n     */ this . testHandler = function ( event ) { var status = $ . status ( true ) ; if ( status === 'error' ) { $ . event ( status , $ . message ( ) ) ; $ . flowObj . uploadNextChunk ( ) ; } else if ( status === 'success' ) { $ . tested = true ; $ . event ( status , $ . message ( ) ) ; $ . flowObj . uploadNextChunk ( ) ; } else if ( ! $ . fileObj . paused ) { // Error might be caused by file pause method // Chunks does not exist on the server side $ . tested = true ; $ . send ( ) ; } } ; /**\n     * Upload has stopped\n     * @param {Event} event\n     */ this . doneHandler = function ( event ) { var status = $ . status ( ) ; if ( status === 'success' || status === 'error' ) { delete this . data ; $ . event ( status , $ . message ( ) ) ; $ . flowObj . uploadNextChunk ( ) ; } else { $ . event ( 'retry' , $ . message ( ) ) ; $ . pendingRetry = true ; $ . abort ( ) ; $ . retries ++ ; var retryInterval = $ . flowObj . opts . chunkRetryInterval ; if ( retryInterval !== null ) { setTimeout ( function ( ) { $ . send ( ) ; } , retryInterval ) ; } else { $ . send ( ) ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a GET request without any data to see if the chunk has already been uploaded in a previous session [CODESPLIT] function ( ) { // Set up request and listen for event this . xhr = new XMLHttpRequest ( ) ; this . xhr . addEventListener ( \"load\" , this . testHandler , false ) ; this . xhr . addEventListener ( \"error\" , this . testHandler , false ) ; var testMethod = evalOpts ( this . flowObj . opts . testMethod , this . fileObj , this ) ; var data = this . prepareXhrRequest ( testMethod , true ) ; this . xhr . send ( data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uploads the actual data in a POST call [CODESPLIT] function ( ) { var preprocess = this . flowObj . opts . preprocess ; var read = this . flowObj . opts . readFileFn ; if ( typeof preprocess === 'function' ) { switch ( this . preprocessState ) { case 0 : this . preprocessState = 1 ; preprocess ( this ) ; return ; case 1 : return ; } } switch ( this . readState ) { case 0 : this . readState = 1 ; read ( this . fileObj , this . startByte , this . endByte , this . fileObj . file . type , this ) ; return ; case 1 : return ; } if ( this . flowObj . opts . testChunks && ! this . tested ) { this . test ( ) ; return ; } this . loaded = 0 ; this . total = 0 ; this . pendingRetry = false ; // Set up request and listen for event this . xhr = new XMLHttpRequest ( ) ; this . xhr . upload . addEventListener ( 'progress' , this . progressHandler , false ) ; this . xhr . addEventListener ( \"load\" , this . doneHandler , false ) ; this . xhr . addEventListener ( \"error\" , this . doneHandler , false ) ; var uploadMethod = evalOpts ( this . flowObj . opts . uploadMethod , this . fileObj , this ) ; var data = this . prepareXhrRequest ( uploadMethod , false , this . flowObj . opts . method , this . bytes ) ; this . xhr . send ( data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve current chunk upload status [CODESPLIT] function ( isTest ) { if ( this . readState === 1 ) { return 'reading' ; } else if ( this . pendingRetry || this . preprocessState === 1 ) { // if pending retry then that's effectively the same as actively uploading, // there might just be a slight delay before the retry starts return 'uploading' ; } else if ( ! this . xhr ) { return 'pending' ; } else if ( this . xhr . readyState < 4 ) { // Status is really 'OPENED', 'HEADERS_RECEIVED' // or 'LOADING' - meaning that stuff is happening return 'uploading' ; } else { if ( this . flowObj . opts . successStatuses . indexOf ( this . xhr . status ) > - 1 ) { // HTTP 200, perfect // HTTP 202 Accepted - The request has been accepted for processing, but the processing has not been completed. return 'success' ; } else if ( this . flowObj . opts . permanentErrors . indexOf ( this . xhr . status ) > - 1 || ! isTest && this . retries >= this . flowObj . opts . maxChunkRetries ) { // HTTP 413/415/500/501, permanent error return 'error' ; } else { // this should never happen, but we'll reset and queue a retry // a likely case for this would be 503 service unavailable this . abort ( ) ; return 'pending' ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare Xhr request . Set query headers and data [CODESPLIT] function ( method , isTest , paramsMethod , blob ) { // Add data from the query options var query = evalOpts ( this . flowObj . opts . query , this . fileObj , this , isTest ) ; query = extend ( query || { } , this . getParams ( ) ) ; var target = evalOpts ( this . flowObj . opts . target , this . fileObj , this , isTest ) ; var data = null ; if ( method === 'GET' || paramsMethod === 'octet' ) { // Add data from the query options var params = [ ] ; each ( query , function ( v , k ) { params . push ( [ encodeURIComponent ( k ) , encodeURIComponent ( v ) ] . join ( '=' ) ) ; } ) ; target = this . getTarget ( target , params ) ; data = blob || null ; } else { // Add data from the query options data = new FormData ( ) ; each ( query , function ( v , k ) { data . append ( k , v ) ; } ) ; if ( typeof blob !== \"undefined\" ) data . append ( this . flowObj . opts . fileParameterName , blob , this . fileObj . file . name ) ; } this . xhr . open ( method , target , true ) ; this . xhr . withCredentials = this . flowObj . opts . withCredentials ; // Add data from header options each ( evalOpts ( this . flowObj . opts . headers , this . fileObj , this , isTest ) , function ( v , k ) { this . xhr . setRequestHeader ( k , v ) ; } , this ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If option is a function evaluate it with given params [CODESPLIT] function evalOpts ( data , args ) { if ( typeof data === \"function\" ) { // `arguments` is an object, not array, in FF, so: args = Array . prototype . slice . call ( arguments ) ; data = data . apply ( null , args . slice ( 1 ) ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extends the destination object dst by copying all of the properties from the src object ( s ) to dst . You can specify multiple src objects . [CODESPLIT] function extend ( dst , src ) { each ( arguments , function ( obj ) { if ( obj !== dst ) { each ( obj , function ( value , key ) { dst [ key ] = value ; } ) ; } } ) ; return dst ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate each element of an object [CODESPLIT] function each ( obj , callback , context ) { if ( ! obj ) { return ; } var key ; // Is Array? // Array.isArray won't work, not only arrays can be iterated by index https://github.com/flowjs/ng-flow/issues/236# if ( typeof ( obj . length ) !== 'undefined' ) { for ( key = 0 ; key < obj . length ; key ++ ) { if ( callback . call ( context , obj [ key ] , key ) === false ) { return ; } } } else { for ( key in obj ) { if ( obj . hasOwnProperty ( key ) && callback . call ( context , obj [ key ] , key ) === false ) { return ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a table | a json file The second argument is optional if ommitted the file will be created at the default location . [CODESPLIT] function createTable ( ) { tableName = arguments [ 0 ] ; var fname = '' ; var callback ; if ( arguments . length === 2 ) { callback = arguments [ 1 ] ; fname = path . join ( userData , tableName + '.json' ) ; } else if ( arguments . length === 3 ) { fname = path . join ( arguments [ 1 ] , arguments [ 0 ] + '.json' ) ; callback = arguments [ 2 ] ; } // Check if the file with the tablename.json exists let exists = fs . existsSync ( fname ) ; if ( exists ) { // The file exists, do not recreate the table/json file callback ( false , tableName + '.json already exists!' ) ; return ; } else { // Create an empty object and pass an empty array as value let obj = new Object ( ) ; obj [ tableName ] = [ ] ; // Write the object to json file try { fs . writeFileSync ( fname , JSON . stringify ( obj , null , 2 ) , ( err ) => { } ) callback ( true , \"Success!\" ) return ; } catch ( e ) { callback ( false , e . toString ( ) ) ; return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a json file contains valid JSON string [CODESPLIT] function valid ( ) { var fName = '' if ( arguments . length == 2 ) { // Given the database name and location const dbName = arguments [ 0 ] const dbLocation = arguments [ 1 ] var fName = path . join ( dbLocation , dbName + '.json' ) } else if ( arguments . length == 1 ) { const dbName = arguments [ 0 ] fname = path . join ( userData , dbName + '.json' ) } const content = fs . readFileSync ( fName , 'utf-8' ) try { JSON . parse ( content ) } catch ( e ) { return false } return true }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert object to table . The object will be appended with the property id which uses timestamp as value . There are 3 required arguments . [CODESPLIT] function insertTableContent ( ) { let tableName = arguments [ 0 ] ; var fname = '' ; var callback ; var tableRow ; if ( arguments . length === 3 ) { callback = arguments [ 2 ] ; fname = path . join ( userData , arguments [ 0 ] + '.json' ) ; tableRow = arguments [ 1 ] ; } else if ( arguments . length === 4 ) { fname = path . join ( arguments [ 1 ] , arguments [ 0 ] + '.json' ) ; callback = arguments [ 3 ] ; tableRow = arguments [ 2 ] ; } let exists = fs . existsSync ( fname ) ; if ( exists ) { // Table | json parsed let table = JSON . parse ( fs . readFileSync ( fname ) ) ; let date = new Date ( ) ; let id = date . getTime ( ) ; tableRow [ 'id' ] = id ; table [ tableName ] . push ( tableRow ) ; try { fs . writeFileSync ( fname , JSON . stringify ( table , null , 2 ) , ( err ) => { } ) callback ( true , \"Object written successfully!\" ) ; return ; } catch ( e ) { callback ( false , \"Error writing object.\" ) ; return ; } } callback ( false , \"Table/json file doesn't exist!\" ) ; return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all contents of the table / json file object [CODESPLIT] function getAll ( ) { var fname = '' ; var callback ; var tableName = arguments [ 0 ] ; if ( arguments . length === 2 ) { fname = path . join ( userData , tableName + '.json' ) ; callback = arguments [ 1 ] ; } else if ( arguments . length === 3 ) { fname = path . join ( arguments [ 1 ] , arguments [ 0 ] + '.json' ) ; callback = arguments [ 2 ] ; } let exists = fs . existsSync ( fname ) ; if ( exists ) { try { let table = JSON . parse ( fs . readFileSync ( fname ) ) ; callback ( true , table [ tableName ] ) ; return ; } catch ( e ) { callback ( false , [ ] ) ; return ; } } else { callback ( false , 'Table file does not exist!' ) ; return ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find rows of a given field / key . [CODESPLIT] function getField ( ) { let fname = '' let tableName = arguments [ 0 ] let callback let key if ( arguments . length === 3 ) { fname = path . join ( userData , tableName + '.json' ) ; callback = arguments [ 2 ] ; key = arguments [ 1 ] } else if ( arguments . length === 4 ) { fname = path . join ( arguments [ 1 ] , arguments [ 0 ] + '.json' ) ; callback = arguments [ 3 ] ; key = arguments [ 2 ] } let exists = fs . existsSync ( fname ) if ( exists ) { let table = JSON . parse ( fs . readFileSync ( fname ) ) ; const rows = table [ tableName ] let data = [ ] for ( let i = 0 ; i < rows . length ; i ++ ) { if ( rows [ i ] . hasOwnProperty ( key ) ) { data . push ( rows [ i ] [ key ] ) } } callback ( true , data ) } else { callback ( false , 'The table you are trying to access does not exist.' ) return } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Count the number of rows for a given table . [CODESPLIT] function count ( ) { let tableName = arguments [ 0 ] let callback if ( arguments . length === 2 ) { callback = arguments [ 1 ] getAll ( tableName , ( succ , data ) => { if ( succ ) { callback ( true , data . length ) return } else { callback ( false , data ) return } } ) } else if ( arguments . length === 3 ) { callback = arguments [ 2 ] getAll ( tableName , arguments [ 1 ] , ( succ , data ) => { if ( succ ) { callback ( true , data . length ) return } else { callback ( false , data ) return } } ) } else { callback ( false , 'Wrong number of arguments. Must be either 2 or 3 arguments including callback function.' ) return } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get row or rows that matched the given condition ( s ) in WHERE argument [CODESPLIT] function getRows ( ) { let tableName = arguments [ 0 ] ; var fname = '' ; var callback ; var where ; if ( arguments . length === 3 ) { fname = path . join ( userData , tableName + '.json' ) ; where = arguments [ 1 ] ; callback = arguments [ 2 ] ; } else if ( arguments . length === 4 ) { fname = path . join ( arguments [ 1 ] , arguments [ 0 ] + '.json' ) ; where = arguments [ 2 ] ; callback = arguments [ 3 ] ; } let exists = fs . existsSync ( fname ) ; let whereKeys ; // Check if where is an object if ( Object . prototype . toString . call ( where ) === \"[object Object]\" ) { // Check for number of keys whereKeys = Object . keys ( where ) ; if ( whereKeys === 0 ) { callback ( false , \"There are no conditions passed to the WHERE clause.\" ) ; return ; } } else { callback ( false , \"WHERE clause should be an object.\" ) ; return ; } // Check if the json file exists, if it is, parse it. if ( exists ) { try { let table = JSON . parse ( fs . readFileSync ( fname ) ) ; let rows = table [ tableName ] ; let objs = [ ] ; for ( let i = 0 ; i < rows . length ; i ++ ) { let matched = 0 ; // Number of matched complete where clause for ( var j = 0 ; j < whereKeys . length ; j ++ ) { // Test if there is a matched key with where clause if ( rows [ i ] . hasOwnProperty ( whereKeys [ j ] ) ) { if ( rows [ i ] [ whereKeys [ j ] ] === where [ whereKeys [ j ] ] ) { matched ++ ; } } } // Check if all conditions in the WHERE clause are matched if ( matched === whereKeys . length ) { objs . push ( rows [ i ] ) } } callback ( true , objs ) ; return ; } catch ( e ) { callback ( false , e . toString ( ) ) ; return ; } } else { callback ( false , 'Table file does not exist!' ) ; return ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update a row or record which satisfies the where clause [CODESPLIT] function updateRow ( ) { let tableName = arguments [ 0 ] ; var fname = '' ; var where ; var set ; var callback ; if ( arguments . length === 4 ) { fname = path . join ( userData , tableName + '.json' ) ; where = arguments [ 1 ] ; set = arguments [ 2 ] ; callback = arguments [ 3 ] ; } else if ( arguments . length === 5 ) { fname = path . join ( arguments [ 1 ] , arguments [ 0 ] + '.json' ) ; where = arguments [ 2 ] ; set = arguments [ 3 ] ; callback = arguments [ 4 ] ; } let exists = fs . existsSync ( fname ) ; let whereKeys = Object . keys ( where ) ; let setKeys = Object . keys ( set ) ; if ( exists ) { let table = JSON . parse ( fs . readFileSync ( fname ) ) ; let rows = table [ tableName ] ; let matched = 0 ; // Number of matched complete where clause let matchedIndex = 0 ; for ( var i = 0 ; i < rows . length ; i ++ ) { for ( var j = 0 ; j < whereKeys . length ; j ++ ) { // Test if there is a matched key with where clause and single row of table if ( rows [ i ] . hasOwnProperty ( whereKeys [ j ] ) ) { if ( rows [ i ] [ whereKeys [ j ] ] === where [ whereKeys [ j ] ] ) { matched ++ ; matchedIndex = i ; } } } } if ( matched === whereKeys . length ) { // All field from where clause are present in this particular // row of the database table try { for ( var k = 0 ; k < setKeys . length ; k ++ ) { // rows[i][setKeys[k]] = set[setKeys[k]]; rows [ matchedIndex ] [ setKeys [ k ] ] = set [ setKeys [ k ] ] ; } // Create a new object and pass the rows let obj = new Object ( ) ; obj [ tableName ] = rows ; // Write the object to json file try { fs . writeFileSync ( fname , JSON . stringify ( obj , null , 2 ) , ( err ) => { } ) callback ( true , \"Success!\" ) return ; } catch ( e ) { callback ( false , e . toString ( ) ) ; return ; } callback ( true , rows ) ; } catch ( e ) { callback ( false , e . toString ( ) ) ; return ; } } else { callback ( false , \"Cannot find the specified record.\" ) ; return ; } } else { callback ( false , 'Table file does not exist!' ) ; return ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searching function [CODESPLIT] function search ( ) { let tableName = arguments [ 0 ] ; var fname = '' ; var field ; var keyword ; var callback ; if ( arguments . length === 4 ) { fname = path . join ( userData , tableName + '.json' ) ; field = arguments [ 1 ] ; keyword = arguments [ 2 ] ; callback = arguments [ 3 ] ; } else if ( arguments . length === 5 ) { fname = path . join ( arguments [ 1 ] , arguments [ 0 ] + '.json' ) ; field = arguments [ 2 ] ; keyword = arguments [ 3 ] ; callback = arguments [ 4 ] ; } let exists = fs . existsSync ( fname ) ; if ( exists ) { let table = JSON . parse ( fs . readFileSync ( fname ) ) ; let rows = table [ tableName ] ; if ( rows . length > 0 ) { // Declare an empty list let foundRows = [ ] ; for ( var i = 0 ; i < rows . length ; i ++ ) { // Check if key exists if ( rows [ i ] . hasOwnProperty ( field ) ) { // Make sure that an object is converted to string before // applying toLowerCase() let value = rows [ i ] [ field ] . toString ( ) . toLowerCase ( ) ; let n = value . search ( keyword . toString ( ) . toLowerCase ( ) ) ; if ( n !== - 1 ) { // The substring is found, add object to the list. foundRows . push ( rows [ i ] ) ; } } else { callback ( false , 2 ) ; return ; } } callback ( true , foundRows ) ; return ; } else { callback ( false , [ ] ) ; return ; } } else { callback ( false , 'Table file does not exist!' ) ; return ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a getter for the given header name . [CODESPLIT] function createHeaderGetter ( str ) { var name = str . toLowerCase ( ) return function ( req , res ) { // set appropriate Vary header vary ( res , str ) // get header var header = req . headers [ name ] if ( ! header ) { return undefined } // multiple headers get joined with comma by node.js core var index = header . indexOf ( ',' ) // return first value return index !== - 1 ? header . substr ( 0 , index ) . trim ( ) : header . trim ( ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assign key value to target when value is not null . <br > This function mutates the target! [CODESPLIT] function assignNotNull ( target , ... sources ) { sources . forEach ( source => { Object . keys ( source ) . forEach ( key => { if ( source [ key ] != null ) { target [ key ] = source [ key ] ; } } ) } ) ; return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Layer [CODESPLIT] function Layer ( options ) { this . options = { } ; if ( options != null ) { [ \"resourceType\" , \"type\" , \"publicId\" , \"format\" ] . forEach ( ( function ( _this ) { return function ( key ) { var ref ; return _this . options [ key ] = ( ref = options [ key ] ) != null ? ref : options [ Util . snakeCase ( key ) ] ; } ; } ) ( this ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents a single parameter [CODESPLIT] function Param ( name , shortName , process ) { if ( process == null ) { process = cloudinary . Util . identity ; } /**\n       * The name of the parameter in snake_case\n       * @member {string} Param#name\n       */ this . name = name ; /**\n       * The name of the serialized form of the parameter\n       * @member {string} Param#shortName\n       */ this . shortName = shortName ; /**\n       * Manipulate origValue when value is called\n       * @member {function} Param#process\n       */ this . process = process ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A parameter that represents an array [CODESPLIT] function ArrayParam ( name , shortName , sep , process ) { if ( sep == null ) { sep = '.' ; } this . sep = sep ; ArrayParam . __super__ . constructor . call ( this , name , shortName , process ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A parameter that represents a transformation [CODESPLIT] function TransformationParam ( name , shortName , sep , process ) { if ( shortName == null ) { shortName = \"t\" ; } if ( sep == null ) { sep = '.' ; } this . sep = sep ; TransformationParam . __super__ . constructor . call ( this , name , shortName , process ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A parameter that represents a range [CODESPLIT] function RangeParam ( name , shortName , process ) { if ( process == null ) { process = this . norm_range_value ; } RangeParam . __super__ . constructor . call ( this , name , shortName , process ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents a transformation expression @param { string } expressionStr - a expression in string format @class Expression [CODESPLIT] function Expression ( expressionStr ) { /**\n        * @protected\n        * @inner Expression-expressions\n       */ this . expressions = [ ] ; if ( expressionStr != null ) { this . expressions . push ( Expression . normalize ( expressionStr ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cloudinary configuration class [CODESPLIT] function Configuration ( options ) { if ( options == null ) { options = { } ; } this . configuration = Util . cloneDeep ( options ) ; Util . defaults ( this . configuration , DEFAULT_CONFIGURATION_PARAMS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The base class for transformations . Members of this class are documented as belonging to the { [CODESPLIT] function TransformationBase ( options ) { var parent , trans ; if ( options == null ) { options = { } ; } /** @private */ parent = void 0 ; /** @private */ trans = { } ; /**\n       * Return an options object that can be used to create an identical Transformation\n       * @function Transformation#toOptions\n       * @return {Object} Returns a plain object representing this transformation\n       */ this . toOptions || ( this . toOptions = function ( withChain ) { var key , list , opt , ref , ref1 , tr , value ; if ( withChain == null ) { withChain = true ; } opt = { } ; for ( key in trans ) { value = trans [ key ] ; opt [ key ] = value . origValue ; } ref = this . otherOptions ; for ( key in ref ) { value = ref [ key ] ; if ( value !== void 0 ) { opt [ key ] = value ; } } if ( withChain && ! Util . isEmpty ( this . chained ) ) { list = ( function ( ) { var j , len , ref1 , results ; ref1 = this . chained ; results = [ ] ; for ( j = 0 , len = ref1 . length ; j < len ; j ++ ) { tr = ref1 [ j ] ; results . push ( tr . toOptions ( ) ) ; } return results ; } ) . call ( this ) ; list . push ( opt ) ; opt = { } ; ref1 = this . otherOptions ; for ( key in ref1 ) { value = ref1 [ key ] ; if ( value !== void 0 ) { opt [ key ] = value ; } } opt . transformation = list ; } return opt ; } ) ; /**\n       * Set a parent for this object for chaining purposes.\n       *\n       * @function Transformation#setParent\n       * @param {Object} object - the parent to be assigned to\n       * @returns {Transformation} Returns this instance for chaining purposes.\n       */ this . setParent || ( this . setParent = function ( object ) { parent = object ; if ( object != null ) { this . fromOptions ( typeof object . toOptions === \"function\" ? object . toOptions ( ) : void 0 ) ; } return this ; } ) ; /**\n       * Returns the parent of this object in the chain\n       * @function Transformation#getParent\n       * @protected\n       * @return {Object} Returns the parent of this object if there is any\n       */ this . getParent || ( this . getParent = function ( ) { return parent ; } ) ; /** @protected */ this . param || ( this . param = function ( value , name , abbr , defaultValue , process ) { if ( process == null ) { if ( Util . isFunction ( defaultValue ) ) { process = defaultValue ; } else { process = Util . identity ; } } trans [ name ] = new Param ( name , abbr , process ) . set ( value ) ; return this ; } ) ; /** @protected */ this . rawParam || ( this . rawParam = function ( value , name , abbr , defaultValue , process ) { if ( process == null ) { process = Util . identity ; } process = lastArgCallback ( arguments ) ; trans [ name ] = new RawParam ( name , abbr , process ) . set ( value ) ; return this ; } ) ; /** @protected */ this . rangeParam || ( this . rangeParam = function ( value , name , abbr , defaultValue , process ) { if ( process == null ) { process = Util . identity ; } process = lastArgCallback ( arguments ) ; trans [ name ] = new RangeParam ( name , abbr , process ) . set ( value ) ; return this ; } ) ; /** @protected */ this . arrayParam || ( this . arrayParam = function ( value , name , abbr , sep , defaultValue , process ) { if ( sep == null ) { sep = \":\" ; } if ( defaultValue == null ) { defaultValue = [ ] ; } if ( process == null ) { process = Util . identity ; } process = lastArgCallback ( arguments ) ; trans [ name ] = new ArrayParam ( name , abbr , sep , process ) . set ( value ) ; return this ; } ) ; /** @protected */ this . transformationParam || ( this . transformationParam = function ( value , name , abbr , sep , defaultValue , process ) { if ( sep == null ) { sep = \".\" ; } if ( process == null ) { process = Util . identity ; } process = lastArgCallback ( arguments ) ; trans [ name ] = new TransformationParam ( name , abbr , sep , process ) . set ( value ) ; return this ; } ) ; this . layerParam || ( this . layerParam = function ( value , name , abbr ) { trans [ name ] = new LayerParam ( name , abbr ) . set ( value ) ; return this ; } ) ; /**\n       * Get the value associated with the given name.\n       * @function Transformation#getValue\n       * @param {string} name - the name of the parameter\n       * @return {*} the processed value associated with the given name\n       * @description Use {@link get}.origValue for the value originally provided for the parameter\n       */ this . getValue || ( this . getValue = function ( name ) { var ref , ref1 ; return ( ref = ( ref1 = trans [ name ] ) != null ? ref1 . value ( ) : void 0 ) != null ? ref : this . otherOptions [ name ] ; } ) ; /**\n       * Get the parameter object for the given parameter name\n       * @function Transformation#get\n       * @param {string} name the name of the transformation parameter\n       * @returns {Param} the param object for the given name, or undefined\n       */ this . get || ( this . get = function ( name ) { return trans [ name ] ; } ) ; /**\n       * Remove a transformation option from the transformation.\n       * @function Transformation#remove\n       * @param {string} name - the name of the option to remove\n       * @return {*} Returns the option that was removed or null if no option by that name was found. The type of the\n       *              returned value depends on the value.\n       */ this . remove || ( this . remove = function ( name ) { var temp ; switch ( false ) { case trans [ name ] == null : temp = trans [ name ] ; delete trans [ name ] ; return temp . origValue ; case this . otherOptions [ name ] == null : temp = this . otherOptions [ name ] ; delete this . otherOptions [ name ] ; return temp ; default : return null ; } } ) ; /**\n       * Return an array of all the keys (option names) in the transformation.\n       * @return {Array<string>} the keys in snakeCase format\n       */ this . keys || ( this . keys = function ( ) { var key ; return ( ( function ( ) { var results ; results = [ ] ; for ( key in trans ) { if ( key != null ) { results . push ( key . match ( VAR_NAME_RE ) ? key : Util . snakeCase ( key ) ) ; } } return results ; } ) ( ) ) . sort ( ) ; } ) ; /**\n       * Returns a plain object representation of the transformation. Values are processed.\n       * @function Transformation#toPlainObject\n       * @return {Object} the transformation options as plain object\n       */ this . toPlainObject || ( this . toPlainObject = function ( ) { var hash , key , list , tr ; hash = { } ; for ( key in trans ) { hash [ key ] = trans [ key ] . value ( ) ; if ( Util . isPlainObject ( hash [ key ] ) ) { hash [ key ] = Util . cloneDeep ( hash [ key ] ) ; } } if ( ! Util . isEmpty ( this . chained ) ) { list = ( function ( ) { var j , len , ref , results ; ref = this . chained ; results = [ ] ; for ( j = 0 , len = ref . length ; j < len ; j ++ ) { tr = ref [ j ] ; results . push ( tr . toPlainObject ( ) ) ; } return results ; } ) . call ( this ) ; list . push ( hash ) ; hash = { transformation : list } ; } return hash ; } ) ; /**\n       * Complete the current transformation and chain to a new one.\n       * In the URL, transformations are chained together by slashes.\n       * @function Transformation#chain\n       * @return {Transformation} Returns this transformation for chaining\n       * @example\n       * var tr = cloudinary.Transformation.new();\n       * tr.width(10).crop('fit').chain().angle(15).serialize()\n       * // produces \"c_fit,w_10/a_15\"\n       */ this . chain || ( this . chain = function ( ) { var names , tr ; names = Object . getOwnPropertyNames ( trans ) ; if ( names . length !== 0 ) { tr = new this . constructor ( this . toOptions ( false ) ) ; this . resetTransformations ( ) ; this . chained . push ( tr ) ; } return this ; } ) ; this . resetTransformations || ( this . resetTransformations = function ( ) { trans = { } ; return this ; } ) ; this . otherOptions || ( this . otherOptions = { } ) ; this . chained = [ ] ; if ( ! Util . isEmpty ( options ) ) { this . fromOptions ( options ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents a single transformation . @class Transformation @example t = new cloudinary . Transformation () ; t . angle ( 20 ) . crop ( scale ) . width ( auto ) ; [CODESPLIT] function Transformation ( options ) { if ( options == null ) { options = { } ; } Transformation . __super__ . constructor . call ( this , options ) ; this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an HTML ( DOM ) Image tag using Cloudinary as the source . [CODESPLIT] function ImageTag ( publicId , options ) { if ( options == null ) { options = { } ; } ImageTag . __super__ . constructor . call ( this , \"img\" , publicId , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an HTML ( DOM ) Video tag using Cloudinary as the source . [CODESPLIT] function VideoTag ( publicId , options ) { if ( options == null ) { options = { } ; } options = Util . defaults ( { } , options , Cloudinary . DEFAULT_VIDEO_PARAMS ) ; VideoTag . __super__ . constructor . call ( this , \"video\" , publicId . replace ( / \\.(mp4|ogv|webm)$ / , '' ) , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an HTML ( DOM ) Meta tag that enables client - hints . [CODESPLIT] function ClientHintsMetaTag ( options ) { ClientHintsMetaTag . __super__ . constructor . call ( this , 'meta' , void 0 , Util . assign ( { \"http-equiv\" : \"Accept-CH\" , content : \"DPR, Viewport-Width, Width\" } , options ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main Cloudinary class [CODESPLIT] function Cloudinary ( options ) { var configuration ; this . devicePixelRatioCache = { } ; this . responsiveConfig = { } ; this . responsiveResizeInitialized = false ; configuration = new Configuration ( options ) ; this . config = function ( newConfig , newValue ) { return configuration . config ( newConfig , newValue ) ; } ; /**\n       * Use \\<meta\\> tags in the document to configure this Cloudinary instance.\n       * @return {Cloudinary} this for chaining\n       */ this . fromDocument = function ( ) { configuration . fromDocument ( ) ; return this ; } ; /**\n       * Use environment variables to configure this Cloudinary instance.\n       * @return {Cloudinary} this for chaining\n       */ this . fromEnvironment = function ( ) { configuration . fromEnvironment ( ) ; return this ; } ; /**\n       * Initialize configuration.\n       * @function Cloudinary#init\n       * @see Configuration#init\n       * @return {Cloudinary} this for chaining\n       */ this . init = function ( ) { configuration . init ( ) ; return this ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the build mode . [CODESPLIT] function getMode ( env , argv ) { // When running from parallel-webpack, grab the cli parameters argv = Object . keys ( argv ) . length ? argv : require ( 'minimist' ) ( process . argv . slice ( 2 ) ) ; var isProd = ( argv . mode || env . mode ) === 'production' || env === 'prod' || env . prod ; return isProd ? 'production' : 'development' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function is used by webpack to resolve individual lodash modules [CODESPLIT] function resolveLodash ( context , request , callback ) { if ( / ^lodash\\/ / . test ( request ) ) { callback ( null , { commonjs : request , commonjs2 : request , amd : request , root : [ '_' , request . split ( '/' ) [ 1 ] ] } ) ; } else { callback ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a webpack configuration [CODESPLIT] function baseConfig ( name , mode ) { const config = { name : ` ${ name } ${ mode } ` , mode , output : { library : 'cloudinary' , libraryTarget : 'umd' , globalObject : \"this\" , pathinfo : false } , optimization : { concatenateModules : true , moduleIds : 'named' , usedExports : true , minimizer : [ new TerserPlugin ( { terserOptions : { mangle : { keep_classnames : true , reserved : reserved , ie8 : true } } , } ) ] } , resolve : { extensions : [ '.js' ] } , externals : [ { jquery : 'jQuery' } ] , node : { Buffer : false , process : false } , devtool : \"source-map\" , module : { rules : [ { test : / \\.m?js$ / , exclude : / (node_modules|bower_components) / , use : { loader : 'babel-loader' } } ] } , plugins : [ new webpack . BannerPlugin ( { banner : ` ${ version } ` , // the banner as string or function, it will be wrapped in a comment raw : true , // if true, banner will not be wrapped in a comment entryOnly : true , // if true, the banner will only be added to the entry chunks } ) ] } ; let filename = ` ${ name } ` ; if ( mode === 'production' ) { filename += '.min' ; } const util = name . startsWith ( 'jquery' ) ? 'jquery' : 'lodash' ; const utilPath = path . resolve ( __dirname , ` ${ util } ` ) ; config . output . filename = ` ${ filename } ` ; config . entry = ` ${ name } ` ; config . resolve . alias = { \"../util$\" : utilPath , \"./util$\" : utilPath } ; // Add reference to each lodash function as a separate module. if ( name === 'core' ) { config . externals . push ( resolveLodash ) ; } config . plugins . push ( new BundleAnalyzerPlugin ( { analyzerMode : 'static' , reportFilename : ` ${ filename } ` , openAnalyzer : false } ) ) ; return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* cdn_subdomain - Boolean ( default : false ) . Whether to automatically build URLs with multiple CDN sub - domains . See this blog post for more details . * private_cdn - Boolean ( default : false ) . Should be set to true for Advanced plan s users that have a private CDN distribution . * secure_distribution - The domain name of the CDN distribution to use for building HTTPS URLs . Relevant only for Advanced plan s users that have a private CDN distribution . * cname - Custom domain name to use for building HTTP URLs . Relevant only for Advanced plan s users that have a private CDN distribution and a custom CNAME . * secure - Boolean ( default : false ) . Force HTTPS URLs of images even if embedded in non - secure HTTP pages . [CODESPLIT] function cloudinaryUrlPrefix ( publicId , options ) { var cdnPart , host , path , protocol , ref , subdomain ; if ( ( ( ref = options . cloud_name ) != null ? ref . indexOf ( \"/\" ) : void 0 ) === 0 ) { return '/res' + options . cloud_name ; } // defaults protocol = \"http://\" ; cdnPart = \"\" ; subdomain = \"res\" ; host = \".cloudinary.com\" ; path = \"/\" + options . cloud_name ; // modifications if ( options . protocol ) { protocol = options . protocol + '//' ; } if ( options . private_cdn ) { cdnPart = options . cloud_name + \"-\" ; path = \"\" ; } if ( options . cdn_subdomain ) { subdomain = \"res-\" + cdnSubdomainNumber ( publicId ) ; } if ( options . secure ) { protocol = \"https://\" ; if ( options . secure_cdn_subdomain === false ) { subdomain = \"res\" ; } if ( ( options . secure_distribution != null ) && options . secure_distribution !== OLD_AKAMAI_SHARED_CDN && options . secure_distribution !== SHARED_CDN ) { cdnPart = \"\" ; subdomain = \"\" ; host = options . secure_distribution ; } } else if ( options . cname ) { protocol = \"http://\" ; cdnPart = \"\" ; subdomain = options . cdn_subdomain ? 'a' + ( ( crc32 ( publicId ) % 5 ) + 1 ) + '.' : '' ; host = options . cname ; } return [ protocol , cdnPart , subdomain , host , path ] . join ( \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the resource type and action type based on the given configuration [CODESPLIT] function finalizeResourceType ( resourceType = \"image\" , type = \"upload\" , urlSuffix , useRootPath , shorten ) { var options ; resourceType = resourceType == null ? \"image\" : resourceType ; type = type == null ? \"upload\" : type ; if ( isPlainObject ( resourceType ) ) { options = resourceType ; resourceType = options . resource_type ; type = options . type ; urlSuffix = options . url_suffix ; useRootPath = options . use_root_path ; shorten = options . shorten ; } if ( type == null ) { type = 'upload' ; } if ( urlSuffix != null ) { resourceType = SEO_TYPES [ ` ${ resourceType } ${ type } ` ] ; type = null ; if ( resourceType == null ) { throw new Error ( ` ${ Object . keys ( SEO_TYPES ) . join ( ', ' ) } ` ) ; } } if ( useRootPath ) { if ( resourceType === 'image' && type === 'upload' || resourceType === \"images\" ) { resourceType = null ; type = null ; } else { throw new Error ( \"Root path only supported for image/upload\" ) ; } } if ( shorten && resourceType === 'image' && type === 'upload' ) { resourceType = 'iu' ; type = null ; } return [ resourceType , type ] . join ( \"/\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private @param { Viewport } parent @param { object } [ options ] @param { number } [ options . percent = 0 . 1 ] percent to scroll with each spin @param { number } [ options . smooth ] smooth the zooming by providing the number of frames to zoom between wheel spins @param { boolean } [ options . interrupt = true ] stop smoothing with any user input on the viewport @param { boolean } [ options . reverse ] reverse the direction of the scroll @param { PIXI . Point } [ options . center ] place this point at center during zoom instead of current mouse position [CODESPLIT] function Wheel ( parent , options ) { _classCallCheck ( this , Wheel ) ; var _this = _possibleConstructorReturn ( this , ( Wheel . __proto__ || Object . getPrototypeOf ( Wheel ) ) . call ( this , parent ) ) ; options = options || { } ; _this . percent = options . percent || 0.1 ; _this . center = options . center ; _this . reverse = options . reverse ; _this . smooth = options . smooth ; _this . interrupt = typeof options . interrupt === 'undefined' ? true : options . interrupt ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scroll viewport when mouse hovers near one of the edges . @private @param { Viewport } parent @param { object } [ options ] @param { number } [ options . radius ] distance from center of screen in screen pixels @param { number } [ options . distance ] distance from all sides in screen pixels @param { number } [ options . top ] alternatively set top distance ( leave unset for no top scroll ) @param { number } [ options . bottom ] alternatively set bottom distance ( leave unset for no top scroll ) @param { number } [ options . left ] alternatively set left distance ( leave unset for no top scroll ) @param { number } [ options . right ] alternatively set right distance ( leave unset for no top scroll ) @param { number } [ options . speed = 8 ] speed in pixels / frame to scroll viewport @param { boolean } [ options . reverse ] reverse direction of scroll @param { boolean } [ options . noDecelerate ] don t use decelerate plugin even if it s installed @param { boolean } [ options . linear ] if using radius use linear movement ( + / - 1 + / - 1 ) instead of angled movement ( Math . cos ( angle from center ) Math . sin ( angle from center )) @param { boolean } [ options . allowButtons ] allows plugin to continue working even when there s a mousedown event [CODESPLIT] function MouseEdges ( parent , options ) { _classCallCheck ( this , MouseEdges ) ; var _this = _possibleConstructorReturn ( this , ( MouseEdges . __proto__ || Object . getPrototypeOf ( MouseEdges ) ) . call ( this , parent ) ) ; options = options || { } ; _this . options = options ; _this . reverse = options . reverse ? 1 : - 1 ; _this . noDecelerate = options . noDecelerate ; _this . linear = options . linear ; _this . radiusSquared = Math . pow ( options . radius , 2 ) ; _this . resize ( ) ; _this . speed = options . speed || 8 ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "enable one - finger touch to drag [CODESPLIT] function Drag ( parent , options ) { _classCallCheck ( this , Drag ) ; options = options || { } ; var _this = _possibleConstructorReturn ( this , ( Drag . __proto__ || Object . getPrototypeOf ( Drag ) ) . call ( this , parent ) ) ; _this . moved = false ; _this . wheelActive = utils . defaults ( options . wheel , true ) ; _this . wheelScroll = options . wheelScroll || 1 ; _this . reverse = options . reverse ? 1 : - 1 ; _this . clampWheel = options . clampWheel ; _this . factor = options . factor || 1 ; _this . xDirection = ! options . direction || options . direction === 'all' || options . direction === 'x' ; _this . yDirection = ! options . direction || options . direction === 'all' || options . direction === 'y' ; _this . parseUnderflow ( options . underflow || 'center' ) ; _this . mouseButtons ( options . mouseButtons ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private @param { Viewport } parent @param { object } [ options ] @param { number } [ options . width ] the desired width to snap ( to maintain aspect ratio choose only width or height ) @param { number } [ options . height ] the desired height to snap ( to maintain aspect ratio choose only width or height ) @param { number } [ options . time = 1000 ] @param { string|function } [ options . ease = easeInOutSine ] ease function or name ( see http : // easings . net / for supported names ) @param { PIXI . Point } [ options . center ] place this point at center during zoom instead of center of the viewport @param { boolean } [ options . interrupt = true ] pause snapping with any user input on the viewport @param { boolean } [ options . removeOnComplete ] removes this plugin after snapping is complete @param { boolean } [ options . removeOnInterrupt ] removes this plugin if interrupted by any user input @param { boolean } [ options . forceStart ] starts the snap immediately regardless of whether the viewport is at the desired zoom @param { boolean } [ options . noMove ] zoom but do not move [CODESPLIT] function SnapZoom ( parent , options ) { _classCallCheck ( this , SnapZoom ) ; var _this = _possibleConstructorReturn ( this , ( SnapZoom . __proto__ || Object . getPrototypeOf ( SnapZoom ) ) . call ( this , parent ) ) ; options = options || { } ; _this . width = options . width ; _this . height = options . height ; if ( _this . width > 0 ) { _this . x_scale = parent . _screenWidth / _this . width ; } if ( _this . height > 0 ) { _this . y_scale = parent . _screenHeight / _this . height ; } _this . xIndependent = utils . exists ( _this . x_scale ) ; _this . yIndependent = utils . exists ( _this . y_scale ) ; _this . x_scale = _this . xIndependent ? _this . x_scale : _this . y_scale ; _this . y_scale = _this . yIndependent ? _this . y_scale : _this . x_scale ; _this . time = utils . defaults ( options . time , 1000 ) ; _this . ease = utils . ease ( options . ease , 'easeInOutSine' ) ; _this . center = options . center ; _this . noMove = options . noMove ; _this . stopOnResize = options . stopOnResize ; _this . removeOnInterrupt = options . removeOnInterrupt ; _this . removeOnComplete = utils . defaults ( options . removeOnComplete , true ) ; _this . interrupt = utils . defaults ( options . interrupt , true ) ; if ( _this . time === 0 ) { parent . container . scale . x = _this . x_scale ; parent . container . scale . y = _this . y_scale ; if ( _this . removeOnComplete ) { _this . parent . removePlugin ( 'snap-zoom' ) ; } } else if ( options . forceStart ) { _this . createSnapping ( ) ; } return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private @param { Viewport } parent @param { number } x @param { number } y @param { object } [ options ] @param { boolean } [ options . topLeft ] snap to the top - left of viewport instead of center @param { number } [ options . friction = 0 . 8 ] friction / frame to apply if decelerate is active @param { number } [ options . time = 1000 ] @param { string|function } [ options . ease = easeInOutSine ] ease function or name ( see http : // easings . net / for supported names ) @param { boolean } [ options . interrupt = true ] pause snapping with any user input on the viewport @param { boolean } [ options . removeOnComplete ] removes this plugin after snapping is complete @param { boolean } [ options . removeOnInterrupt ] removes this plugin if interrupted by any user input @param { boolean } [ options . forceStart ] starts the snap immediately regardless of whether the viewport is at the desired location [CODESPLIT] function Snap ( parent , x , y , options ) { _classCallCheck ( this , Snap ) ; var _this = _possibleConstructorReturn ( this , ( Snap . __proto__ || Object . getPrototypeOf ( Snap ) ) . call ( this , parent ) ) ; options = options || { } ; _this . friction = options . friction || 0.8 ; _this . time = options . time || 1000 ; _this . ease = utils . ease ( options . ease , 'easeInOutSine' ) ; _this . x = x ; _this . y = y ; _this . topLeft = options . topLeft ; _this . interrupt = utils . defaults ( options . interrupt , true ) ; _this . removeOnComplete = options . removeOnComplete ; _this . removeOnInterrupt = options . removeOnInterrupt ; if ( options . forceStart ) { _this . startEase ( ) ; } return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Array - like iteration for objects . [CODESPLIT] function each ( object , fn ) { keys ( object ) . forEach ( function ( key ) { return fn ( object [ key ] , key ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Array - like reduce for objects . [CODESPLIT] function reduce ( object , fn ) { var initial = arguments . length > 2 && arguments [ 2 ] !== undefined ? arguments [ 2 ] : 0 ; return keys ( object ) . reduce ( function ( accum , key ) { return fn ( accum , object [ key ] , key ) ; } , initial ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Object . assign - style object shallow merge / extend . [CODESPLIT] function assign ( target ) { for ( var _len = arguments . length , sources = Array ( _len > 1 ? _len - 1 : 0 ) , _key = 1 ; _key < _len ; _key ++ ) { sources [ _key - 1 ] = arguments [ _key ] ; } if ( Object . assign ) { return Object . assign . apply ( Object , [ target ] . concat ( sources ) ) ; } sources . forEach ( function ( source ) { if ( ! source ) { return ; } each ( source , function ( value , key ) { target [ key ] = value ; } ) ; } ) ; return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether an object appears to be a plain object - that is a direct instance of Object . [CODESPLIT] function isPlain ( value ) { return isObject ( value ) && toString . call ( value ) === '[object Object]' && value . constructor === Object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log messages to the console and history based on the type of message [CODESPLIT] function logByType ( type , args ) { var stringify = arguments . length > 2 && arguments [ 2 ] !== undefined ? arguments [ 2 ] : ! ! IE_VERSION && IE_VERSION < 11 ; var lvl = log . levels [ level ] ; var lvlRegExp = new RegExp ( '^(' + lvl + ')$' ) ; if ( type !== 'log' ) { // Add the type to the front of the message when it's not \"log\". args . unshift ( type . toUpperCase ( ) + ':' ) ; } // Add a clone of the args at this point to history. if ( history ) { history . push ( [ ] . concat ( args ) ) ; } // Add console prefix after adding to history. args . unshift ( 'VIDEOJS:' ) ; // If there's no console then don't try to output messages, but they will // still be stored in history. // // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist // when the module is executed. var fn = window . console && window . console [ type ] ; // Bail out if there's no console or if this type is not allowed by the // current logging level. if ( ! fn || ! lvl || ! lvlRegExp . test ( type ) ) { return ; } // IEs previous to 11 log objects uselessly as \"[object Object]\"; so, JSONify // objects and arrays for those less-capable browsers. if ( stringify ) { args = args . map ( function ( a ) { if ( isObject ( a ) || Array . isArray ( a ) ) { try { return JSON . stringify ( a ) ; } catch ( x ) { return String ( a ) ; } } // Cast to string before joining, so we get null and undefined explicitly // included in output (as we would in a modern console). return String ( a ) ; } ) . join ( ' ' ) ; } // Old IE versions do not allow .apply() for console methods (they are // reported as objects rather than functions). if ( ! fn . apply ) { fn ( args ) ; } else { fn [ Array . isArray ( args ) ? 'apply' : 'call' ] ( window . console , args ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@file computed - style . js @module computed - style A safe getComputedStyle with an IE8 fallback . [CODESPLIT] function computedStyle ( el , prop ) { if ( ! el || ! prop ) { return '' ; } if ( typeof window . getComputedStyle === 'function' ) { var cs = window . getComputedStyle ( el ) ; return cs ? cs [ prop ] : '' ; } return el . currentStyle [ prop ] || '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an element and applies properties . [CODESPLIT] function createEl ( ) { var tagName = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : 'div' ; var properties = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : { } ; var attributes = arguments . length > 2 && arguments [ 2 ] !== undefined ? arguments [ 2 ] : { } ; var content = arguments [ 3 ] ; var el = document . createElement ( tagName ) ; Object . getOwnPropertyNames ( properties ) . forEach ( function ( propName ) { var val = properties [ propName ] ; // See #2176 // We originally were accepting both properties and attributes in the // same object, but that doesn't work so well. if ( propName . indexOf ( 'aria-' ) !== - 1 || propName === 'role' || propName === 'type' ) { log$1 . warn ( tsml ( _templateObject , propName , val ) ) ; el . setAttribute ( propName , val ) ; // Handle textContent since it's not supported everywhere and we have a // method for it. } else if ( propName === 'textContent' ) { textContent ( el , val ) ; } else { el [ propName ] = val ; } } ) ; Object . getOwnPropertyNames ( attributes ) . forEach ( function ( attrName ) { el . setAttribute ( attrName , attributes [ attrName ] ) ; } ) ; if ( content ) { appendContent ( el , content ) ; } return el ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a CSS class name to an element [CODESPLIT] function addClass ( element , classToAdd ) { if ( element . classList ) { element . classList . add ( classToAdd ) ; // Don't need to `throwIfWhitespace` here because `hasElClass` will do it // in the case of classList not being supported. } else if ( ! hasClass ( element , classToAdd ) ) { element . className = ( element . className + ' ' + classToAdd ) . trim ( ) ; } return element ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The callback definition for toggleElClass . [CODESPLIT] function toggleClass ( element , classToToggle , predicate ) { // This CANNOT use `classList` internally because IE does not support the // second parameter to the `classList.toggle()` method! Which is fine because // `classList` will be used by the add/remove functions. var has = hasClass ( element , classToToggle ) ; if ( typeof predicate === 'function' ) { predicate = predicate ( element , classToToggle ) ; } if ( typeof predicate !== 'boolean' ) { predicate = ! has ; } // If the necessary class operation matches the current state of the // element, no action is required. if ( predicate === has ) { return ; } if ( predicate ) { addClass ( element , classToToggle ) ; } else { removeClass ( element , classToToggle ) ; } return element ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identical to the native getBoundingClientRect function but ensures that the method is supported at all ( it is in all browsers we claim to support ) and that the element is in the DOM before continuing . [CODESPLIT] function getBoundingClientRect ( el ) { if ( el && el . getBoundingClientRect && el . parentNode ) { var rect = el . getBoundingClientRect ( ) ; var result = { } ; [ 'bottom' , 'height' , 'left' , 'right' , 'top' , 'width' ] . forEach ( function ( k ) { if ( rect [ k ] !== undefined ) { result [ k ] = rect [ k ] ; } } ) ; if ( ! result . height ) { result . height = parseFloat ( computedStyle ( el , 'height' ) ) ; } if ( ! result . width ) { result . width = parseFloat ( computedStyle ( el , 'width' ) ) ; } return result ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "x and y coordinates for a dom element or mouse pointer [CODESPLIT] function getPointerPosition ( el , event ) { var position = { } ; var box = findPosition ( el ) ; var boxW = el . offsetWidth ; var boxH = el . offsetHeight ; var boxY = box . top ; var boxX = box . left ; var pageY = event . pageY ; var pageX = event . pageX ; if ( event . changedTouches ) { pageX = event . changedTouches [ 0 ] . pageX ; pageY = event . changedTouches [ 0 ] . pageY ; } position . y = Math . max ( 0 , Math . min ( 1 , ( boxY - pageY + boxH ) / boxH ) ) ; position . x = Math . max ( 0 , Math . min ( 1 , ( pageX - boxX ) / boxW ) ) ; return position ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalizes and appends content to an element . [CODESPLIT] function appendContent ( el , content ) { normalizeContent ( content ) . forEach ( function ( node ) { return el . appendChild ( node ) ; } ) ; return el ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the cache object where data for an element is stored [CODESPLIT] function getData ( el ) { var id = el [ elIdAttr ] ; if ( ! id ) { id = el [ elIdAttr ] = newGUID ( ) ; } if ( ! elData [ id ] ) { elData [ id ] = { } ; } return elData [ id ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether or not an element has cached data [CODESPLIT] function hasData ( el ) { var id = el [ elIdAttr ] ; if ( ! id ) { return false ; } return ! ! Object . getOwnPropertyNames ( elData [ id ] ) . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete data for the element from the cache and the guid attr from getElementById [CODESPLIT] function removeData ( el ) { var id = el [ elIdAttr ] ; if ( ! id ) { return ; } // Remove all stored data delete elData [ id ] ; // Remove the elIdAttr property from the DOM node try { delete el [ elIdAttr ] ; } catch ( e ) { if ( el . removeAttribute ) { el . removeAttribute ( elIdAttr ) ; } else { // IE doesn't appear to support removeAttribute on the document element el [ elIdAttr ] = null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@file events . js . An Event System ( John Resig - Secrets of a JS Ninja http : // jsninja . com / ) ( Original book version wasn t completely usable so fixed some things and made Closure Compiler compatible ) This should work very similarly to jQuery s events however it s based off the book version which isn t as robust as jquery s so there s probably some differences . [CODESPLIT] function _cleanUpEvents ( elem , type ) { var data = getData ( elem ) ; // Remove the events of a particular type if there are none left if ( data . handlers [ type ] . length === 0 ) { delete data . handlers [ type ] ; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if ( elem . removeEventListener ) { elem . removeEventListener ( type , data . dispatcher , false ) ; } else if ( elem . detachEvent ) { elem . detachEvent ( 'on' + type , data . dispatcher ) ; } } // Remove the events object if there are no types left if ( Object . getOwnPropertyNames ( data . handlers ) . length <= 0 ) { delete data . handlers ; delete data . dispatcher ; delete data . disabled ; } // Finally remove the element data if there is no data left if ( Object . getOwnPropertyNames ( data ) . length === 0 ) { removeData ( elem ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loops through an array of event types and calls the requested method for each type . [CODESPLIT] function _handleMultipleEvents ( fn , elem , types , callback ) { types . forEach ( function ( type ) { // Call the event method for each one of the types fn ( elem , type , callback ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an event listener to element It stores the handler function in a separate cache object and adds a generic handler to the element s event along with a unique id ( guid ) to the element . [CODESPLIT] function on ( elem , type , fn ) { if ( Array . isArray ( type ) ) { return _handleMultipleEvents ( on , elem , type , fn ) ; } var data = getData ( elem ) ; // We need a place to store all our handler data if ( ! data . handlers ) { data . handlers = { } ; } if ( ! data . handlers [ type ] ) { data . handlers [ type ] = [ ] ; } if ( ! fn . guid ) { fn . guid = newGUID ( ) ; } data . handlers [ type ] . push ( fn ) ; if ( ! data . dispatcher ) { data . disabled = false ; data . dispatcher = function ( event , hash ) { if ( data . disabled ) { return ; } event = fixEvent ( event ) ; var handlers = data . handlers [ event . type ] ; if ( handlers ) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers . slice ( 0 ) ; for ( var m = 0 , n = handlersCopy . length ; m < n ; m ++ ) { if ( event . isImmediatePropagationStopped ( ) ) { break ; } else { try { handlersCopy [ m ] . call ( elem , event , hash ) ; } catch ( e ) { log$1 . error ( e ) ; } } } } } ; } if ( data . handlers [ type ] . length === 1 ) { if ( elem . addEventListener ) { var options = false ; if ( _supportsPassive && passiveEvents . indexOf ( type ) > - 1 ) { options = { passive : true } ; } elem . addEventListener ( type , data . dispatcher , options ) ; } else if ( elem . attachEvent ) { elem . attachEvent ( 'on' + type , data . dispatcher ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes event listeners from an element [CODESPLIT] function off ( elem , type , fn ) { // Don't want to add a cache object through getElData if not needed if ( ! hasData ( elem ) ) { return ; } var data = getData ( elem ) ; // If no events exist, nothing to unbind if ( ! data . handlers ) { return ; } if ( Array . isArray ( type ) ) { return _handleMultipleEvents ( off , elem , type , fn ) ; } // Utility function var removeType = function removeType ( t ) { data . handlers [ t ] = [ ] ; _cleanUpEvents ( elem , t ) ; } ; // Are we removing all bound events? if ( ! type ) { for ( var t in data . handlers ) { removeType ( t ) ; } return ; } var handlers = data . handlers [ type ] ; // If no handlers exist, nothing to unbind if ( ! handlers ) { return ; } // If no listener was provided, remove all listeners for type if ( ! fn ) { removeType ( type ) ; return ; } // We're only removing a single handler if ( fn . guid ) { for ( var n = 0 ; n < handlers . length ; n ++ ) { if ( handlers [ n ] . guid === fn . guid ) { handlers . splice ( n -- , 1 ) ; } } } _cleanUpEvents ( elem , type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trigger a listener only once for an event [CODESPLIT] function one ( elem , type , fn ) { if ( Array . isArray ( type ) ) { return _handleMultipleEvents ( one , elem , type , fn ) ; } var func = function func ( ) { off ( elem , type , func ) ; fn . apply ( this , arguments ) ; } ; // copy the guid to the new function so it can removed using the original function's ID func . guid = fn . guid = fn . guid || newGUID ( ) ; on ( elem , type , func ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set up any tags that have a data - setup attribute when the player is started . [CODESPLIT] function autoSetup ( ) { // Protect against breakage in non-browser environments. if ( ! isReal ( ) ) { return ; } // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop // through each list of elements to build up a new, combined list of elements. var vids = document . getElementsByTagName ( 'video' ) ; var audios = document . getElementsByTagName ( 'audio' ) ; var mediaEls = [ ] ; if ( vids && vids . length > 0 ) { for ( var i = 0 , e = vids . length ; i < e ; i ++ ) { mediaEls . push ( vids [ i ] ) ; } } if ( audios && audios . length > 0 ) { for ( var _i = 0 , _e = audios . length ; _i < _e ; _i ++ ) { mediaEls . push ( audios [ _i ] ) ; } } // Check if any media elements exist if ( mediaEls && mediaEls . length > 0 ) { for ( var _i2 = 0 , _e2 = mediaEls . length ; _i2 < _e2 ; _i2 ++ ) { var mediaEl = mediaEls [ _i2 ] ; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of // 'function' like expected, at least when loading the player immediately. if ( mediaEl && mediaEl . getAttribute ) { // Make sure this player hasn't already been set up. if ( mediaEl . player === undefined ) { var options = mediaEl . getAttribute ( 'data-setup' ) ; // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if ( options !== null ) { // Create new video.js instance. videojs$2 ( mediaEl ) ; } } // If getAttribute isn't defined, we need to wait for the DOM. } else { autoSetupTimeout ( 1 ) ; break ; } } // No videos were found, so keep looping unless page is finished loading. } else if ( ! _windowLoaded ) { autoSetupTimeout ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait until the page is loaded before running autoSetup . This will be called in autoSetup if hasLoaded returns false . [CODESPLIT] function autoSetupTimeout ( wait , vjs ) { if ( vjs ) { videojs$2 = vjs ; } window . setTimeout ( autoSetup , wait ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add text to a DOM element . [CODESPLIT] function setTextContent ( el , content ) { if ( el . styleSheet ) { el . styleSheet . cssText = content ; } else { el . textContent = content ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@file fn . js @module fn Bind ( a . k . a proxy or Context ) . A simple method for changing the context of a function It also stores a unique id on the function so it can be easily removed from events . [CODESPLIT] function bind ( context , fn , uid ) { // Make sure the function has a unique ID if ( ! fn . guid ) { fn . guid = newGUID ( ) ; } // Create the new function that changes the context var bound = function bound ( ) { return fn . apply ( context , arguments ) ; } ; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks bound . guid = uid ? uid + '_' + fn . guid : fn . guid ; return bound ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the given function fn with a new function that only invokes fn at most once per every wait milliseconds . [CODESPLIT] function throttle ( fn , wait ) { var last = Date . now ( ) ; var throttled = function throttled ( ) { var now = Date . now ( ) ; if ( now - last >= wait ) { fn . apply ( undefined , arguments ) ; last = now ; } } ; return throttled ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@file mixins / evented . js @module evented Returns whether or not an object has had the evented mixin applied . [CODESPLIT] function isEvented ( object ) { return object instanceof EventTarget || ! ! object . eventBusEl_ && [ 'on' , 'one' , 'off' , 'trigger' ] . every ( function ( k ) { return typeof object [ k ] === 'function' ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Whether a value is a valid event type - non - empty string or array . [CODESPLIT] function isValidEventType ( type ) { return ( // The regex here verifies that the `type` contains at least one non- // whitespace character. typeof type === 'string' && / \\S / . test ( type ) || Array . isArray ( type ) && ! ! type . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes an array of arguments given to on () or one () validates them and normalizes them into an object . [CODESPLIT] function normalizeListenArgs ( self , args ) { // If the number of arguments is less than 3, the target is always the // evented object itself. var isTargetingSelf = args . length < 3 || args [ 0 ] === self || args [ 0 ] === self . eventBusEl_ ; var target = void 0 ; var type = void 0 ; var listener = void 0 ; if ( isTargetingSelf ) { target = self . eventBusEl_ ; // Deal with cases where we got 3 arguments, but we are still listening to // the evented object itself. if ( args . length >= 3 ) { args . shift ( ) ; } type = args [ 0 ] ; listener = args [ 1 ] ; } else { target = args [ 0 ] ; type = args [ 1 ] ; listener = args [ 2 ] ; } validateTarget ( target ) ; validateEventType ( type ) ; validateListener ( listener ) ; listener = bind ( self , listener ) ; return { isTargetingSelf : isTargetingSelf , target : target , type : type , listener : listener } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the listener to the event type ( s ) on the target normalizing for the type of target . [CODESPLIT] function listen ( target , method , type , listener ) { validateTarget ( target ) ; if ( target . nodeName ) { Events [ method ] ( target , type , listener ) ; } else { target [ method ] ( type , listener ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a listener to an event ( or events ) on this object or another evented object . [CODESPLIT] function on$$1 ( ) { var _this = this ; for ( var _len = arguments . length , args = Array ( _len ) , _key = 0 ; _key < _len ; _key ++ ) { args [ _key ] = arguments [ _key ] ; } var _normalizeListenArgs = normalizeListenArgs ( this , args ) , isTargetingSelf = _normalizeListenArgs . isTargetingSelf , target = _normalizeListenArgs . target , type = _normalizeListenArgs . type , listener = _normalizeListenArgs . listener ; listen ( target , 'on' , type , listener ) ; // If this object is listening to another evented object. if ( ! isTargetingSelf ) { // If this object is disposed, remove the listener. var removeListenerOnDispose = function removeListenerOnDispose ( ) { return _this . off ( target , type , listener ) ; } ; // Use the same function ID as the listener so we can remove it later it // using the ID of the original listener. removeListenerOnDispose . guid = listener . guid ; // Add a listener to the target's dispose event as well. This ensures // that if the target is disposed BEFORE this object, we remove the // removal listener that was just added. Otherwise, we create a memory leak. var removeRemoverOnTargetDispose = function removeRemoverOnTargetDispose ( ) { return _this . off ( 'dispose' , removeListenerOnDispose ) ; } ; // Use the same function ID as the listener so we can remove it later // it using the ID of the original listener. removeRemoverOnTargetDispose . guid = listener . guid ; listen ( this , 'on' , 'dispose' , removeListenerOnDispose ) ; listen ( target , 'on' , 'dispose' , removeRemoverOnTargetDispose ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a listener to an event ( or events ) on this object or another evented object . The listener will only be called once and then removed . [CODESPLIT] function one$$1 ( ) { var _this2 = this ; for ( var _len2 = arguments . length , args = Array ( _len2 ) , _key2 = 0 ; _key2 < _len2 ; _key2 ++ ) { args [ _key2 ] = arguments [ _key2 ] ; } var _normalizeListenArgs2 = normalizeListenArgs ( this , args ) , isTargetingSelf = _normalizeListenArgs2 . isTargetingSelf , target = _normalizeListenArgs2 . target , type = _normalizeListenArgs2 . type , listener = _normalizeListenArgs2 . listener ; // Targeting this evented object. if ( isTargetingSelf ) { listen ( target , 'one' , type , listener ) ; // Targeting another evented object. } else { var wrapper = function wrapper ( ) { for ( var _len3 = arguments . length , largs = Array ( _len3 ) , _key3 = 0 ; _key3 < _len3 ; _key3 ++ ) { largs [ _key3 ] = arguments [ _key3 ] ; } _this2 . off ( target , type , wrapper ) ; listener . apply ( null , largs ) ; } ; // Use the same function ID as the listener so we can remove it later // it using the ID of the original listener. wrapper . guid = listener . guid ; listen ( target , 'one' , type , wrapper ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes listener ( s ) from event ( s ) on an evented object . [CODESPLIT] function off$$1 ( targetOrType , typeOrListener , listener ) { // Targeting this evented object. if ( ! targetOrType || isValidEventType ( targetOrType ) ) { off ( this . eventBusEl_ , targetOrType , typeOrListener ) ; // Targeting another evented object. } else { var target = targetOrType ; var type = typeOrListener ; // Fail fast and in a meaningful way! validateTarget ( target ) ; validateEventType ( type ) ; validateListener ( listener ) ; // Ensure there's at least a guid, even if the function hasn't been used listener = bind ( this , listener ) ; // Remove the dispose listener on this evented object, which was given // the same guid as the event listener in on(). this . off ( 'dispose' , listener ) ; if ( target . nodeName ) { off ( target , type , listener ) ; off ( target , 'dispose' , listener ) ; } else if ( isEvented ( target ) ) { target . off ( type , listener ) ; target . off ( 'dispose' , listener ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies { @link module : evented~EventedMixin|EventedMixin } to a target object . [CODESPLIT] function evented ( target ) { var options = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : { } ; var eventBusKey = options . eventBusKey ; // Set or create the eventBusEl_. if ( eventBusKey ) { if ( ! target [ eventBusKey ] . nodeName ) { throw new Error ( 'The eventBusKey \"' + eventBusKey + '\" does not refer to an element.' ) ; } target . eventBusEl_ = target [ eventBusKey ] ; } else { target . eventBusEl_ = createEl ( 'span' , { className : 'vjs-event-bus' } ) ; } assign ( target , EventedMixin ) ; // When any evented object is disposed, it removes all its listeners. target . on ( 'dispose' , function ( ) { return target . off ( ) ; } ) ; return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the state of an object by mutating its { @link module : stateful~StatefulMixin . state|state } object in place . [CODESPLIT] function setState ( stateUpdates ) { var _this = this ; // Support providing the `stateUpdates` state as a function. if ( typeof stateUpdates === 'function' ) { stateUpdates = stateUpdates ( ) ; } var changes = void 0 ; each ( stateUpdates , function ( value , key ) { // Record the change if the value is different from what's in the // current state. if ( _this . state [ key ] !== value ) { changes = changes || { } ; changes [ key ] = { from : _this . state [ key ] , to : value } ; } _this . state [ key ] = value ; } ) ; // Only trigger \"statechange\" if there were changes AND we have a trigger // function. This allows us to not require that the target object be an // evented object. if ( changes && isEvented ( this ) ) { /**\n       * An event triggered on an object that is both\n       * {@link module:stateful|stateful} and {@link module:evented|evented}\n       * indicating that its state has changed.\n       *\n       * @event    module:stateful~StatefulMixin#statechanged\n       * @type     {Object}\n       * @property {Object} changes\n       *           A hash containing the properties that were changed and\n       *           the values they were changed `from` and `to`.\n       */ this . trigger ( { changes : changes , type : 'statechanged' } ) ; } return changes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies { @link module : stateful~StatefulMixin|StatefulMixin } to a target object . [CODESPLIT] function stateful ( target , defaultState ) { assign ( target , StatefulMixin ) ; // This happens after the mixing-in because we need to replace the `state` // added in that step. target . state = assign ( { } , target . state , defaultState ) ; // Auto-bind the `handleStateChanged` method of the target object if it exists. if ( typeof target . handleStateChanged === 'function' && isEvented ( target ) ) { target . on ( 'statechanged' , target . handleStateChanged ) ; } return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@file merge - options . js @module merge - options Deep - merge one or more options objects recursively merging ** only ** plain object properties . [CODESPLIT] function mergeOptions ( ) { var result = { } ; for ( var _len = arguments . length , sources = Array ( _len ) , _key = 0 ; _key < _len ; _key ++ ) { sources [ _key ] = arguments [ _key ] ; } sources . forEach ( function ( source ) { if ( ! source ) { return ; } each ( source , function ( value , key ) { if ( ! isPlain ( value ) ) { result [ key ] = value ; return ; } if ( ! isPlain ( result [ key ] ) ) { result [ key ] = { } ; } result [ key ] = mergeOptions ( result [ key ] , value ) ; } ) ; } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A callback that is called when a component is ready . Does not have any paramters and any callback value will be ignored . [CODESPLIT] function Component ( player , options , ready ) { classCallCheck ( this , Component ) ; // The component might be the player itself and we can't pass `this` to super if ( ! player && this . play ) { this . player_ = player = this ; // eslint-disable-line } else { this . player_ = player ; } // Make a copy of prototype.options_ to protect against overriding defaults this . options_ = mergeOptions ( { } , this . options_ ) ; // Updated options with supplied options options = this . options_ = mergeOptions ( this . options_ , options ) ; // Get ID from options or options element if one is supplied this . id_ = options . id || options . el && options . el . id ; // If there was no ID from the options, generate one if ( ! this . id_ ) { // Don't require the player ID function in the case of mock players var id = player && player . id && player . id ( ) || 'no_player' ; this . id_ = id + '_component_' + newGUID ( ) ; } this . name_ = options . name || null ; // Create element if one wasn't provided in options if ( options . el ) { this . el_ = options . el ; } else if ( options . createEl !== false ) { this . el_ = this . createEl ( ) ; } // Make this an evented object and use `el_`, if available, as its event bus evented ( this , { eventBusKey : this . el_ ? 'el_' : null } ) ; stateful ( this , this . constructor . defaultState ) ; this . children_ = [ ] ; this . childIndex_ = { } ; this . childNameIndex_ = { } ; // Add any child components in options if ( options . initChildren !== false ) { this . initChildren ( ) ; } this . ready ( ready ) ; // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if ( options . reportTouchActivity !== false ) { this . enableTouchActivity ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An object that contains ranges of time for various reasons . [CODESPLIT] function rangeCheck ( fnName , index , maxIndex ) { if ( typeof index !== 'number' || index < 0 || index > maxIndex ) { throw new Error ( 'Failed to execute \\'' + fnName + '\\' on \\'TimeRanges\\': The index provided (' + index + ') is non-numeric or out of bounds (0-' + maxIndex + ').' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if any of the time ranges are over the maximum index . [CODESPLIT] function getRange ( fnName , valueIndex , ranges , rangeIndex ) { rangeCheck ( fnName , rangeIndex , ranges . length - 1 ) ; return ranges [ rangeIndex ] [ valueIndex ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a time range object givent ranges of time . [CODESPLIT] function createTimeRangesObj ( ranges ) { if ( ranges === undefined || ranges . length === 0 ) { return { length : 0 , start : function start ( ) { throw new Error ( 'This TimeRanges object is empty' ) ; } , end : function end ( ) { throw new Error ( 'This TimeRanges object is empty' ) ; } } ; } return { length : ranges . length , start : getRange . bind ( null , 'start' , 0 , ranges ) , end : getRange . bind ( null , 'end' , 1 , ranges ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Should create a fake TimeRange object which mimics an HTML5 time range instance . [CODESPLIT] function createTimeRanges ( start , end ) { if ( Array . isArray ( start ) ) { return createTimeRangesObj ( start ) ; } else if ( start === undefined || end === undefined ) { return createTimeRangesObj ( ) ; } return createTimeRangesObj ( [ [ start , end ] ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@file buffer . js @module buffer Compute the percentage of the media that has been buffered . [CODESPLIT] function bufferedPercent ( buffered , duration ) { var bufferedDuration = 0 ; var start = void 0 ; var end = void 0 ; if ( ! duration ) { return 0 ; } if ( ! buffered || ! buffered . length ) { buffered = createTimeRanges ( 0 , 0 ) ; } for ( var i = 0 ; i < buffered . length ; i ++ ) { start = buffered . start ( i ) ; end = buffered . end ( i ) ; // buffered end can be bigger than duration by a very small fraction if ( end > duration ) { end = duration ; } bufferedDuration += end - start ; } return bufferedDuration / duration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@file media - error . js A Custom MediaError class which mimics the standard HTML5 MediaError class . [CODESPLIT] function MediaError ( value ) { // Allow redundant calls to this constructor to avoid having `instanceof` // checks peppered around the code. if ( value instanceof MediaError ) { return value ; } if ( typeof value === 'number' ) { this . code = value ; } else if ( typeof value === 'string' ) { // default code is zero, so this is a custom error this . message = value ; } else if ( isObject ( value ) ) { // We assign the `code` property manually because native `MediaError` objects // do not expose it as an own/enumerable property of the object. if ( typeof value . code === 'number' ) { this . code = value . code ; } assign ( this , value ) ; } if ( ! this . message ) { this . message = MediaError . defaultMessages [ this . code ] || '' ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@file text - track - list - converter . js Utilities for capturing text track state and re - creating tracks based on a capture . [CODESPLIT] function trackToJson_ ( track ) { var ret = [ 'kind' , 'label' , 'language' , 'id' , 'inBandMetadataTrackDispatchType' , 'mode' , 'src' ] . reduce ( function ( acc , prop , i ) { if ( track [ prop ] ) { acc [ prop ] = track [ prop ] ; } return acc ; } , { cues : track . cues && Array . prototype . map . call ( track . cues , function ( cue ) { return { startTime : cue . startTime , endTime : cue . endTime , text : cue . text , id : cue . id } ; } ) } ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Examine a { @link Tech } and return a JSON - compatible javascript array that represents the state of all { @link TextTrack } s currently configured . The return array is compatible with { @link text - track - list - converter : jsonToTextTracks } . [CODESPLIT] function textTracksToJson ( tech ) { var trackEls = tech . $$ ( 'track' ) ; var trackObjs = Array . prototype . map . call ( trackEls , function ( t ) { return t . track ; } ) ; var tracks = Array . prototype . map . call ( trackEls , function ( trackEl ) { var json = trackToJson_ ( trackEl . track ) ; if ( trackEl . src ) { json . src = trackEl . src ; } return json ; } ) ; return tracks . concat ( Array . prototype . filter . call ( tech . textTracks ( ) , function ( track ) { return trackObjs . indexOf ( track ) === - 1 ; } ) . map ( trackToJson_ ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a set of remote { @link TextTrack } s on a { @link Tech } based on an array of javascript object { @link TextTrack } representations . [CODESPLIT] function jsonToTextTracks ( json , tech ) { json . forEach ( function ( track ) { var addedTrack = tech . addRemoteTextTrack ( track ) . track ; if ( ! track . src && track . cues ) { track . cues . forEach ( function ( cue ) { return addedTrack . addCue ( cue ) ; } ) ; } } ) ; return tech . textTracks ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of this class [CODESPLIT] function TrackList ( ) { var tracks = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : [ ] ; var _ret ; var list = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : null ; classCallCheck ( this , TrackList ) ; var _this = possibleConstructorReturn ( this , _EventTarget . call ( this ) ) ; if ( ! list ) { list = _this ; // eslint-disable-line if ( IS_IE8 ) { list = document . createElement ( 'custom' ) ; for ( var prop in TrackList . prototype ) { if ( prop !== 'constructor' ) { list [ prop ] = TrackList . prototype [ prop ] ; } } } } list . tracks_ = [ ] ; /**\n     * @memberof TrackList\n     * @member {number} length\n     *         The current number of `Track`s in the this Trackist.\n     * @instance\n     */ Object . defineProperty ( list , 'length' , { get : function get$$1 ( ) { return this . tracks_ . length ; } } ) ; for ( var i = 0 ; i < tracks . length ; i ++ ) { list . addTrack ( tracks [ i ] ) ; } // must return the object, as for ie8 it will not be this // but a reference to a document object return _ret = list , possibleConstructorReturn ( _this , _ret ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of this class . [CODESPLIT] function AudioTrackList ( ) { var _this , _ret ; var tracks = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : [ ] ; classCallCheck ( this , AudioTrackList ) ; var list = void 0 ; // make sure only 1 track is enabled // sorted from last index to first index for ( var i = tracks . length - 1 ; i >= 0 ; i -- ) { if ( tracks [ i ] . enabled ) { disableOthers ( tracks , tracks [ i ] ) ; break ; } } // IE8 forces us to implement inheritance ourselves // as it does not support Object.defineProperty properly if ( IS_IE8 ) { list = document . createElement ( 'custom' ) ; for ( var prop in TrackList . prototype ) { if ( prop !== 'constructor' ) { list [ prop ] = TrackList . prototype [ prop ] ; } } for ( var _prop in AudioTrackList . prototype ) { if ( _prop !== 'constructor' ) { list [ _prop ] = AudioTrackList . prototype [ _prop ] ; } } } list = ( _this = possibleConstructorReturn ( this , _TrackList . call ( this , tracks , list ) ) , _this ) ; list . changing_ = false ; return _ret = list , possibleConstructorReturn ( _this , _ret ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@file video - track - list . js Un - select all other { @link VideoTrack } s that are selected . [CODESPLIT] function disableOthers ( list , track ) { for ( var i = 0 ; i < list . length ; i ++ ) { if ( ! Object . keys ( list [ i ] ) . length || track . id === list [ i ] . id ) { continue ; } // another video track is enabled, disable it list [ i ] . selected = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of this class . [CODESPLIT] function VideoTrackList ( ) { var _this , _ret ; var tracks = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : [ ] ; classCallCheck ( this , VideoTrackList ) ; var list = void 0 ; // make sure only 1 track is enabled // sorted from last index to first index for ( var i = tracks . length - 1 ; i >= 0 ; i -- ) { if ( tracks [ i ] . selected ) { disableOthers$1 ( tracks , tracks [ i ] ) ; break ; } } // IE8 forces us to implement inheritance ourselves // as it does not support Object.defineProperty properly if ( IS_IE8 ) { list = document . createElement ( 'custom' ) ; for ( var prop in TrackList . prototype ) { if ( prop !== 'constructor' ) { list [ prop ] = TrackList . prototype [ prop ] ; } } for ( var _prop in VideoTrackList . prototype ) { if ( _prop !== 'constructor' ) { list [ _prop ] = VideoTrackList . prototype [ _prop ] ; } } } list = ( _this = possibleConstructorReturn ( this , _TrackList . call ( this , tracks , list ) ) , _this ) ; list . changing_ = false ; /**\n     * @member {number} VideoTrackList#selectedIndex\n     *         The current index of the selected {@link VideoTrack`}.\n     */ Object . defineProperty ( list , 'selectedIndex' , { get : function get$$1 ( ) { for ( var _i = 0 ; _i < this . length ; _i ++ ) { if ( this [ _i ] . selected ) { return _i ; } } return - 1 ; } , set : function set$$1 ( ) { } } ) ; return _ret = list , possibleConstructorReturn ( _this , _ret ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of this class . [CODESPLIT] function TextTrackList ( ) { var _this , _ret ; var tracks = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : [ ] ; classCallCheck ( this , TextTrackList ) ; var list = void 0 ; // IE8 forces us to implement inheritance ourselves // as it does not support Object.defineProperty properly if ( IS_IE8 ) { list = document . createElement ( 'custom' ) ; for ( var prop in TrackList . prototype ) { if ( prop !== 'constructor' ) { list [ prop ] = TrackList . prototype [ prop ] ; } } for ( var _prop in TextTrackList . prototype ) { if ( _prop !== 'constructor' ) { list [ _prop ] = TextTrackList . prototype [ _prop ] ; } } } list = ( _this = possibleConstructorReturn ( this , _TrackList . call ( this , tracks , list ) ) , _this ) ; return _ret = list , possibleConstructorReturn ( _this , _ret ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of this class . [CODESPLIT] function HtmlTrackElementList ( ) { var trackElements = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : [ ] ; classCallCheck ( this , HtmlTrackElementList ) ; var list = this ; // eslint-disable-line if ( IS_IE8 ) { list = document . createElement ( 'custom' ) ; for ( var prop in HtmlTrackElementList . prototype ) { if ( prop !== 'constructor' ) { list [ prop ] = HtmlTrackElementList . prototype [ prop ] ; } } } list . trackElements_ = [ ] ; /**\n     * @memberof HtmlTrackElementList\n     * @member {number} length\n     *         The current number of `Track`s in the this Trackist.\n     * @instance\n     */ Object . defineProperty ( list , 'length' , { get : function get$$1 ( ) { return this . trackElements_ . length ; } } ) ; for ( var i = 0 , length = trackElements . length ; i < length ; i ++ ) { list . addTrackElement_ ( trackElements [ i ] ) ; } if ( IS_IE8 ) { return list ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of this class .. [CODESPLIT] function TextTrackCueList ( cues ) { classCallCheck ( this , TextTrackCueList ) ; var list = this ; // eslint-disable-line if ( IS_IE8 ) { list = document . createElement ( 'custom' ) ; for ( var prop in TextTrackCueList . prototype ) { if ( prop !== 'constructor' ) { list [ prop ] = TextTrackCueList . prototype [ prop ] ; } } } TextTrackCueList . prototype . setCues_ . call ( list , cues ) ; /**\n     * @memberof TextTrackCueList\n     * @member {number} length\n     *         The current number of `TextTrackCue`s in the TextTrackCueList.\n     * @instance\n     */ Object . defineProperty ( list , 'length' , { get : function get$$1 ( ) { return this . length_ ; } } ) ; if ( IS_IE8 ) { return list ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the extension of the passed file name . It will return an empty string if passed an invalid path . [CODESPLIT] function getFileExtension ( path ) { if ( typeof path === 'string' ) { var splitPathRe = / ^(\\/?)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?)(\\.([^\\.\\/\\?]+)))(?:[\\/]*|[\\?].*)$ / i ; var pathParts = splitPathRe . exec ( path ) ; if ( pathParts ) { return pathParts . pop ( ) . toLowerCase ( ) ; } } return '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@file text - track . js Takes a webvtt file contents and parses it into cues [CODESPLIT] function parseCues ( srcContent , track ) { var parser = new window . WebVTT . Parser ( window , window . vttjs , window . WebVTT . StringDecoder ( ) ) ; var errors = [ ] ; parser . oncue = function ( cue ) { track . addCue ( cue ) ; } ; parser . onparsingerror = function ( error ) { errors . push ( error ) ; } ; parser . onflush = function ( ) { track . trigger ( { type : 'loadeddata' , target : track } ) ; } ; parser . parse ( srcContent ) ; if ( errors . length > 0 ) { if ( window . console && window . console . groupCollapsed ) { window . console . groupCollapsed ( 'Text Track parsing errors for ' + track . src ) ; } errors . forEach ( function ( error ) { return log$1 . error ( error ) ; } ) ; if ( window . console && window . console . groupEnd ) { window . console . groupEnd ( ) ; } } parser . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load a TextTrack from a specifed url . [CODESPLIT] function loadTrack ( src , track ) { var opts = { uri : src } ; var crossOrigin = isCrossOrigin ( src ) ; if ( crossOrigin ) { opts . cors = crossOrigin ; } xhr ( opts , bind ( this , function ( err , response , responseBody ) { if ( err ) { return log$1 . error ( err , response ) ; } track . loaded_ = true ; // Make sure that vttjs has loaded, otherwise, wait till it finished loading // NOTE: this is only used for the alt/video.novtt.js build if ( typeof window . WebVTT !== 'function' ) { if ( track . tech_ ) { var loadHandler = function loadHandler ( ) { return parseCues ( responseBody , track ) ; } ; track . tech_ . on ( 'vttjsloaded' , loadHandler ) ; track . tech_ . on ( 'vttjserror' , function ( ) { log$1 . error ( 'vttjs failed to load, stopping trying to process ' + track . src ) ; track . tech_ . off ( 'vttjsloaded' , loadHandler ) ; } ) ; } } else { parseCues ( responseBody , track ) ; } } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An Object containing a structure like : { src : url type : mimetype } or string that just contains the src url alone . * var SourceObject = { src : http : // ex . com / video . mp4 type : video / mp4 } ; var SourceString = http : // example . com / some - video . mp4 ; [CODESPLIT] function createTrackHelper ( self , kind , label , language ) { var options = arguments . length > 4 && arguments [ 4 ] !== undefined ? arguments [ 4 ] : { } ; var tracks = self . textTracks ( ) ; options . kind = kind ; if ( label ) { options . label = label ; } if ( language ) { options . language = language ; } options . tech = self ; var track = new ALL . text . TrackClass ( options ) ; tracks . addTrack ( track ) ; return track ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of this Tech . [CODESPLIT] function Tech ( ) { var options = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : { } ; var ready = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : function ( ) { } ; classCallCheck ( this , Tech ) ; // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options . reportTouchActivity = false ; // keep track of whether the current source has played at all to // implement a very limited played() var _this = possibleConstructorReturn ( this , _Component . call ( this , null , options , ready ) ) ; _this . hasStarted_ = false ; _this . on ( 'playing' , function ( ) { this . hasStarted_ = true ; } ) ; _this . on ( 'loadstart' , function ( ) { this . hasStarted_ = false ; } ) ; ALL . names . forEach ( function ( name ) { var props = ALL [ name ] ; if ( options && options [ props . getterName ] ) { _this [ props . privateName ] = options [ props . getterName ] ; } } ) ; // Manually track progress in cases where the browser/flash player doesn't report it. if ( ! _this . featuresProgressEvents ) { _this . manualProgressOn ( ) ; } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if ( ! _this . featuresTimeupdateEvents ) { _this . manualTimeUpdatesOn ( ) ; } [ 'Text' , 'Audio' , 'Video' ] . forEach ( function ( track ) { if ( options [ 'native' + track + 'Tracks' ] === false ) { _this [ 'featuresNative' + track + 'Tracks' ] = false ; } } ) ; if ( options . nativeCaptions === false || options . nativeTextTracks === false ) { _this . featuresNativeTextTracks = false ; } else if ( options . nativeCaptions === true || options . nativeTextTracks === true ) { _this . featuresNativeTextTracks = true ; } if ( ! _this . featuresNativeTextTracks ) { _this . emulateTextTracks ( ) ; } _this . autoRemoteTextTracks_ = new ALL . text . ListClass ( ) ; _this . initTrackListeners ( ) ; // Turn on component tap events only if not using native controls if ( ! options . nativeControlsForTouch ) { _this . emitTapEvents ( ) ; } if ( _this . constructor ) { _this . name_ = _this . constructor . name || 'Unknown Tech' ; } return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module filter - source Filter out single bad source objects or multiple source objects in an array . Also flattens nested source object arrays into a 1 dimensional array of source objects . [CODESPLIT] function filterSource ( src ) { // traverse array if ( Array . isArray ( src ) ) { var newsrc = [ ] ; src . forEach ( function ( srcobj ) { srcobj = filterSource ( srcobj ) ; if ( Array . isArray ( srcobj ) ) { newsrc = newsrc . concat ( srcobj ) ; } else if ( isObject ( srcobj ) ) { newsrc . push ( srcobj ) ; } } ) ; src = newsrc ; } else if ( typeof src === 'string' && src . trim ( ) ) { // convert string into object src = [ { src : src } ] ; } else if ( isObject ( src ) && typeof src . src === 'string' && src . src && src . src . trim ( ) ) { // src is already valid src = [ src ] ; } else { // invalid source, turn it into an empty array src = [ ] ; } return src ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function ClickableComponent ( player , options ) { classCallCheck ( this , ClickableComponent ) ; var _this = possibleConstructorReturn ( this , _Component . call ( this , player , options ) ) ; _this . emitTapEvents ( ) ; _this . enable ( ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of this class . [CODESPLIT] function PosterImage ( player , options ) { classCallCheck ( this , PosterImage ) ; var _this = possibleConstructorReturn ( this , _ClickableComponent . call ( this , player , options ) ) ; _this . update ( ) ; player . on ( 'posterchange' , bind ( _this , _this . update ) ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct an rgba color from a given hex color code . [CODESPLIT] function constructColor ( color , opacity ) { return 'rgba(' + // color looks like \"#f0e\" parseInt ( color [ 1 ] + color [ 1 ] , 16 ) + ',' + parseInt ( color [ 2 ] + color [ 2 ] , 16 ) + ',' + parseInt ( color [ 3 ] + color [ 3 ] , 16 ) + ',' + opacity + ')' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function TextTrackDisplay ( player , options , ready ) { classCallCheck ( this , TextTrackDisplay ) ; var _this = possibleConstructorReturn ( this , _Component . call ( this , player , options , ready ) ) ; player . on ( 'loadstart' , bind ( _this , _this . toggleDisplay ) ) ; player . on ( 'texttrackchange' , bind ( _this , _this . updateDisplay ) ) ; player . on ( 'loadstart' , bind ( _this , _this . preselectTrack ) ) ; // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. player . ready ( bind ( _this , function ( ) { if ( player . tech_ && player . tech_ . featuresNativeTextTracks ) { this . hide ( ) ; return ; } player . on ( 'fullscreenchange' , bind ( this , this . updateDisplay ) ) ; var tracks = this . options_ . playerOptions . tracks || [ ] ; for ( var i = 0 ; i < tracks . length ; i ++ ) { this . player_ . addRemoteTextTrack ( tracks [ i ] , true ) ; } this . preselectTrack ( ) ; } ) ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of the this class . [CODESPLIT] function CloseButton ( player , options ) { classCallCheck ( this , CloseButton ) ; var _this = possibleConstructorReturn ( this , _Button . call ( this , player , options ) ) ; _this . controlText ( options && options . controlText || _this . localize ( 'Close' ) ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function PlayToggle ( player , options ) { classCallCheck ( this , PlayToggle ) ; var _this = possibleConstructorReturn ( this , _Button . call ( this , player , options ) ) ; _this . on ( player , 'play' , _this . handlePlay ) ; _this . on ( player , 'pause' , _this . handlePause ) ; _this . on ( player , 'ended' , _this . handleEnded ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@file format - time . js @module Format - time Format seconds as a time string H : MM : SS or M : SS . Supplying a guide ( in seconds ) will force a number of leading zeros to cover the length of the guide . [CODESPLIT] function formatTime ( seconds ) { var guide = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : seconds ; seconds = seconds < 0 ? 0 : seconds ; var s = Math . floor ( seconds % 60 ) ; var m = Math . floor ( seconds / 60 % 60 ) ; var h = Math . floor ( seconds / 3600 ) ; var gm = Math . floor ( guide / 60 % 60 ) ; var gh = Math . floor ( guide / 3600 ) ; // handle invalid times if ( isNaN ( seconds ) || seconds === Infinity ) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-' ; } // Check if we need to show hours h = h > 0 || gh > 0 ? h + ':' : '' ; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = ( ( h || gm >= 10 ) && m < 10 ? '0' + m : m ) + ':' ; // Check if leading zero is need for seconds s = s < 10 ? '0' + s : s ; return h + m + s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function RemainingTimeDisplay ( player , options ) { classCallCheck ( this , RemainingTimeDisplay ) ; var _this = possibleConstructorReturn ( this , _Component . call ( this , player , options ) ) ; _this . throttledUpdateContent = throttle ( bind ( _this , _this . updateContent ) , 25 ) ; _this . on ( player , [ 'timeupdate' , 'durationchange' ] , _this . throttledUpdateContent ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function LiveDisplay ( player , options ) { classCallCheck ( this , LiveDisplay ) ; var _this = possibleConstructorReturn ( this , _Component . call ( this , player , options ) ) ; _this . updateShowing ( ) ; _this . on ( _this . player ( ) , 'durationchange' , _this . updateShowing ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of this class [CODESPLIT] function Slider ( player , options ) { classCallCheck ( this , Slider ) ; // Set property names to bar to match with the child Slider class is looking for var _this = possibleConstructorReturn ( this , _Component . call ( this , player , options ) ) ; _this . bar = _this . getChild ( _this . options_ . barName ) ; // Set a horizontal or vertical class on the slider depending on the slider type _this . vertical ( ! ! _this . options_ . vertical ) ; _this . on ( 'mousedown' , _this . handleMouseDown ) ; _this . on ( 'touchstart' , _this . handleMouseDown ) ; _this . on ( 'focus' , _this . handleFocus ) ; _this . on ( 'blur' , _this . handleBlur ) ; _this . on ( 'click' , _this . handleClick ) ; _this . on ( player , 'controlsvisible' , _this . update ) ; if ( _this . playerEvent ) { _this . on ( player , _this . playerEvent , _this . update ) ; } return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function LoadProgressBar ( player , options ) { classCallCheck ( this , LoadProgressBar ) ; var _this = possibleConstructorReturn ( this , _Component . call ( this , player , options ) ) ; _this . partEls_ = [ ] ; _this . on ( player , 'progress' , _this . update ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function MouseTimeDisplay ( player , options ) { classCallCheck ( this , MouseTimeDisplay ) ; var _this = possibleConstructorReturn ( this , _Component . call ( this , player , options ) ) ; _this . update = throttle ( bind ( _this , _this . update ) , 25 ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function SeekBar ( player , options ) { classCallCheck ( this , SeekBar ) ; var _this = possibleConstructorReturn ( this , _Slider . call ( this , player , options ) ) ; _this . update = throttle ( bind ( _this , _this . update ) , 50 ) ; _this . on ( player , [ 'timeupdate' , 'ended' ] , _this . update ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function ProgressControl ( player , options ) { classCallCheck ( this , ProgressControl ) ; var _this = possibleConstructorReturn ( this , _Component . call ( this , player , options ) ) ; _this . handleMouseMove = throttle ( bind ( _this , _this . handleMouseMove ) , 25 ) ; _this . on ( _this . el_ , 'mousemove' , _this . handleMouseMove ) ; _this . throttledHandleMouseSeek = throttle ( bind ( _this , _this . handleMouseSeek ) , 25 ) ; _this . on ( [ 'mousedown' , 'touchstart' ] , _this . handleMouseDown ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function FullscreenToggle ( player , options ) { classCallCheck ( this , FullscreenToggle ) ; var _this = possibleConstructorReturn ( this , _Button . call ( this , player , options ) ) ; _this . on ( player , 'fullscreenchange' , _this . handleFullscreenChange ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if volume control is supported and if it isn t hide the Component that was passed using the vjs - hidden class . [CODESPLIT] function checkVolumeSupport ( self , player ) { // hide volume controls when they're not supported by the current tech if ( player . tech_ && ! player . tech_ . featuresVolumeControl ) { self . addClass ( 'vjs-hidden' ) ; } self . on ( player , 'loadstart' , function ( ) { if ( ! player . tech_ . featuresVolumeControl ) { self . addClass ( 'vjs-hidden' ) ; } else { self . removeClass ( 'vjs-hidden' ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function VolumeBar ( player , options ) { classCallCheck ( this , VolumeBar ) ; var _this = possibleConstructorReturn ( this , _Slider . call ( this , player , options ) ) ; _this . on ( 'slideractive' , _this . updateLastVolume_ ) ; _this . on ( player , 'volumechange' , _this . updateARIAAttributes ) ; player . ready ( function ( ) { return _this . updateARIAAttributes ( ) ; } ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function VolumeControl ( player ) { var options = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : { } ; classCallCheck ( this , VolumeControl ) ; options . vertical = options . vertical || false ; // Pass the vertical option down to the VolumeBar if // the VolumeBar is turned on. if ( typeof options . volumeBar === 'undefined' || isPlain ( options . volumeBar ) ) { options . volumeBar = options . volumeBar || { } ; options . volumeBar . vertical = options . vertical ; } // hide this control if volume support is missing var _this = possibleConstructorReturn ( this , _Component . call ( this , player , options ) ) ; checkVolumeSupport ( _this , player ) ; _this . throttledHandleMouseMove = throttle ( bind ( _this , _this . handleMouseMove ) , 25 ) ; _this . on ( 'mousedown' , _this . handleMouseDown ) ; _this . on ( 'touchstart' , _this . handleMouseDown ) ; // while the slider is active (the mouse has been pressed down and // is dragging) or in focus we do not want to hide the VolumeBar _this . on ( _this . volumeBar , [ 'focus' , 'slideractive' ] , function ( ) { _this . volumeBar . addClass ( 'vjs-slider-active' ) ; _this . addClass ( 'vjs-slider-active' ) ; _this . trigger ( 'slideractive' ) ; } ) ; _this . on ( _this . volumeBar , [ 'blur' , 'sliderinactive' ] , function ( ) { _this . volumeBar . removeClass ( 'vjs-slider-active' ) ; _this . removeClass ( 'vjs-slider-active' ) ; _this . trigger ( 'sliderinactive' ) ; } ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function MuteToggle ( player , options ) { classCallCheck ( this , MuteToggle ) ; // hide this control if volume support is missing var _this = possibleConstructorReturn ( this , _Button . call ( this , player , options ) ) ; checkVolumeSupport ( _this , player ) ; _this . on ( player , [ 'loadstart' , 'volumechange' ] , _this . update ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function VolumePanel ( player ) { var options = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : { } ; classCallCheck ( this , VolumePanel ) ; if ( typeof options . inline !== 'undefined' ) { options . inline = options . inline ; } else { options . inline = true ; } // pass the inline option down to the VolumeControl as vertical if // the VolumeControl is on. if ( typeof options . volumeControl === 'undefined' || isPlain ( options . volumeControl ) ) { options . volumeControl = options . volumeControl || { } ; options . volumeControl . vertical = ! options . inline ; } // hide this control if volume support is missing var _this = possibleConstructorReturn ( this , _Component . call ( this , player , options ) ) ; checkVolumeSupport ( _this , player ) ; // while the slider is active (the mouse has been pressed down and // is dragging) or in focus we do not want to hide the VolumeBar _this . on ( _this . volumeControl , [ 'slideractive' ] , _this . sliderActive_ ) ; _this . on ( _this . muteToggle , 'focus' , _this . sliderActive_ ) ; _this . on ( _this . volumeControl , [ 'sliderinactive' ] , _this . sliderInactive_ ) ; _this . on ( _this . muteToggle , 'blur' , _this . sliderInactive_ ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of this class . [CODESPLIT] function Menu ( player , options ) { classCallCheck ( this , Menu ) ; var _this = possibleConstructorReturn ( this , _Component . call ( this , player , options ) ) ; if ( options ) { _this . menuButton_ = options . menuButton ; } _this . focusedChild_ = - 1 ; _this . on ( 'keydown' , _this . handleKeyPress ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function MenuButton ( player ) { var options = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : { } ; classCallCheck ( this , MenuButton ) ; var _this = possibleConstructorReturn ( this , _Component . call ( this , player , options ) ) ; _this . menuButton_ = new Button ( player , options ) ; _this . menuButton_ . controlText ( _this . controlText_ ) ; _this . menuButton_ . el_ . setAttribute ( 'aria-haspopup' , 'true' ) ; // Add buildCSSClass values to the button, not the wrapper var buttonClass = Button . prototype . buildCSSClass ( ) ; _this . menuButton_ . el_ . className = _this . buildCSSClass ( ) + ' ' + buttonClass ; _this . menuButton_ . removeClass ( 'vjs-control' ) ; _this . addChild ( _this . menuButton_ ) ; _this . update ( ) ; _this . enabled_ = true ; _this . on ( _this . menuButton_ , 'tap' , _this . handleClick ) ; _this . on ( _this . menuButton_ , 'click' , _this . handleClick ) ; _this . on ( _this . menuButton_ , 'focus' , _this . handleFocus ) ; _this . on ( _this . menuButton_ , 'blur' , _this . handleBlur ) ; _this . on ( 'keydown' , _this . handleSubmenuKeyPress ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of the this class . [CODESPLIT] function MenuItem ( player , options ) { classCallCheck ( this , MenuItem ) ; var _this = possibleConstructorReturn ( this , _ClickableComponent . call ( this , player , options ) ) ; _this . selectable = options . selectable ; _this . selected ( options . selected ) ; if ( _this . selectable ) { // TODO: May need to be either menuitemcheckbox or menuitemradio, //       and may need logical grouping of menu items. _this . el_ . setAttribute ( 'role' , 'menuitemcheckbox' ) ; } else { _this . el_ . setAttribute ( 'role' , 'menuitem' ) ; } return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function TextTrackMenuItem ( player , options ) { classCallCheck ( this , TextTrackMenuItem ) ; var track = options . track ; var tracks = player . textTracks ( ) ; // Modify options for parent MenuItem class's init. options . label = track . label || track . language || 'Unknown' ; options . selected = track . mode === 'showing' ; var _this = possibleConstructorReturn ( this , _MenuItem . call ( this , player , options ) ) ; _this . track = track ; var changeHandler = bind ( _this , _this . handleTracksChange ) ; var selectedLanguageChangeHandler = bind ( _this , _this . handleSelectedLanguageChange ) ; player . on ( [ 'loadstart' , 'texttrackchange' ] , changeHandler ) ; tracks . addEventListener ( 'change' , changeHandler ) ; tracks . addEventListener ( 'selectedlanguagechange' , selectedLanguageChangeHandler ) ; _this . on ( 'dispose' , function ( ) { tracks . removeEventListener ( 'change' , changeHandler ) ; tracks . removeEventListener ( 'selectedlanguagechange' , selectedLanguageChangeHandler ) ; } ) ; // iOS7 doesn't dispatch change events to TextTrackLists when an // associated track's mode changes. Without something like // Object.observe() (also not present on iOS7), it's not // possible to detect changes to the mode attribute and polyfill // the change event. As a poor substitute, we manually dispatch // change events whenever the controls modify the mode. if ( tracks . onchange === undefined ) { var event = void 0 ; _this . on ( [ 'tap' , 'click' ] , function ( ) { if ( _typeof ( window . Event ) !== 'object' ) { // Android 2.3 throws an Illegal Constructor error for window.Event try { event = new window . Event ( 'change' ) ; } catch ( err ) { // continue regardless of error } } if ( ! event ) { event = document . createEvent ( 'Event' ) ; event . initEvent ( 'change' , true , true ) ; } tracks . dispatchEvent ( event ) ; } ) ; } return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function OffTextTrackMenuItem ( player , options ) { classCallCheck ( this , OffTextTrackMenuItem ) ; // Create pseudo track info // Requires options['kind'] options . track = { player : player , kind : options . kind , kinds : options . kinds , 'default' : false , mode : 'disabled' } ; if ( ! options . kinds ) { options . kinds = [ options . kind ] ; } if ( options . label ) { options . track . label = options . label ; } else { options . track . label = options . kinds . join ( ' and ' ) + ' off' ; } // MenuItem is selectable options . selectable = true ; var _this = possibleConstructorReturn ( this , _TextTrackMenuItem . call ( this , player , options ) ) ; _this . selected ( true ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function TextTrackButton ( player ) { var options = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : { } ; classCallCheck ( this , TextTrackButton ) ; options . tracks = player . textTracks ( ) ; return possibleConstructorReturn ( this , _TrackButton . call ( this , player , options ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function ChaptersTrackMenuItem ( player , options ) { classCallCheck ( this , ChaptersTrackMenuItem ) ; var track = options . track ; var cue = options . cue ; var currentTime = player . currentTime ( ) ; // Modify options for parent MenuItem class's init. options . selectable = true ; options . label = cue . text ; options . selected = cue . startTime <= currentTime && currentTime < cue . endTime ; var _this = possibleConstructorReturn ( this , _MenuItem . call ( this , player , options ) ) ; _this . track = track ; _this . cue = cue ; track . addEventListener ( 'cuechange' , bind ( _this , _this . update ) ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function ChaptersButton ( player , options , ready ) { classCallCheck ( this , ChaptersButton ) ; return possibleConstructorReturn ( this , _TextTrackButton . call ( this , player , options , ready ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function DescriptionsButton ( player , options , ready ) { classCallCheck ( this , DescriptionsButton ) ; var _this = possibleConstructorReturn ( this , _TextTrackButton . call ( this , player , options , ready ) ) ; var tracks = player . textTracks ( ) ; var changeHandler = bind ( _this , _this . handleTracksChange ) ; tracks . addEventListener ( 'change' , changeHandler ) ; _this . on ( 'dispose' , function ( ) { tracks . removeEventListener ( 'change' , changeHandler ) ; } ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function SubtitlesButton ( player , options , ready ) { classCallCheck ( this , SubtitlesButton ) ; return possibleConstructorReturn ( this , _TextTrackButton . call ( this , player , options , ready ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function CaptionSettingsMenuItem ( player , options ) { classCallCheck ( this , CaptionSettingsMenuItem ) ; options . track = { player : player , kind : options . kind , label : options . kind + ' settings' , selectable : false , 'default' : false , mode : 'disabled' } ; // CaptionSettingsMenuItem has no concept of 'selected' options . selectable = false ; options . name = 'CaptionSettingsMenuItem' ; var _this = possibleConstructorReturn ( this , _TextTrackMenuItem . call ( this , player , options ) ) ; _this . addClass ( 'vjs-texttrack-settings' ) ; _this . controlText ( ', opens ' + options . kind + ' settings dialog' ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function CaptionsButton ( player , options , ready ) { classCallCheck ( this , CaptionsButton ) ; return possibleConstructorReturn ( this , _TextTrackButton . call ( this , player , options , ready ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function AudioTrackMenuItem ( player , options ) { classCallCheck ( this , AudioTrackMenuItem ) ; var track = options . track ; var tracks = player . audioTracks ( ) ; // Modify options for parent MenuItem class's init. options . label = track . label || track . language || 'Unknown' ; options . selected = track . enabled ; var _this = possibleConstructorReturn ( this , _MenuItem . call ( this , player , options ) ) ; _this . track = track ; var changeHandler = bind ( _this , _this . handleTracksChange ) ; tracks . addEventListener ( 'change' , changeHandler ) ; _this . on ( 'dispose' , function ( ) { tracks . removeEventListener ( 'change' , changeHandler ) ; } ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function AudioTrackButton ( player ) { var options = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : { } ; classCallCheck ( this , AudioTrackButton ) ; options . tracks = player . audioTracks ( ) ; return possibleConstructorReturn ( this , _TrackButton . call ( this , player , options ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function PlaybackRateMenuItem ( player , options ) { classCallCheck ( this , PlaybackRateMenuItem ) ; var label = options . rate ; var rate = parseFloat ( label , 10 ) ; // Modify options for parent MenuItem class's init. options . label = label ; options . selected = rate === 1 ; options . selectable = true ; var _this = possibleConstructorReturn ( this , _MenuItem . call ( this , player , options ) ) ; _this . label = label ; _this . rate = rate ; _this . on ( player , 'ratechange' , _this . update ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function PlaybackRateMenuButton ( player , options ) { classCallCheck ( this , PlaybackRateMenuButton ) ; var _this = possibleConstructorReturn ( this , _MenuButton . call ( this , player , options ) ) ; _this . updateVisibility ( ) ; _this . updateLabel ( ) ; _this . on ( player , 'loadstart' , _this . updateVisibility ) ; _this . on ( player , 'ratechange' , _this . updateLabel ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function ErrorDisplay ( player , options ) { classCallCheck ( this , ErrorDisplay ) ; var _this = possibleConstructorReturn ( this , _ModalDialog . call ( this , player , options ) ) ; _this . on ( player , 'error' , _this . open ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the actual value of an option . [CODESPLIT] function parseOptionValue ( value , parser ) { if ( parser ) { value = parser ( value ) ; } if ( value && value !== 'none' ) { return value ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the selected <option > element within a <select > element . [CODESPLIT] function getSelectedOptionValue ( el , parser ) { var value = el . options [ el . options . selectedIndex ] . value ; return parseOptionValue ( value , parser ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the selected <option > element within a <select > element based on a given value . [CODESPLIT] function setSelectedOption ( el , value , parser ) { if ( ! value ) { return ; } for ( var i = 0 ; i < el . options . length ; i ++ ) { if ( parseOptionValue ( el . options [ i ] . value , parser ) === value ) { el . selectedIndex = i ; break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function TextTrackSettings ( player , options ) { classCallCheck ( this , TextTrackSettings ) ; options . temporary = false ; var _this = possibleConstructorReturn ( this , _ModalDialog . call ( this , player , options ) ) ; _this . updateDisplay = bind ( _this , _this . updateDisplay ) ; // fill the modal and pretend we have opened it _this . fill ( ) ; _this . hasBeenOpened_ = _this . hasBeenFilled_ = true ; _this . endDialog = createEl ( 'p' , { className : 'vjs-control-text' , textContent : _this . localize ( 'End of dialog window.' ) } ) ; _this . el ( ) . appendChild ( _this . endDialog ) ; _this . setDefaults ( ) ; // Grab `persistTextTrackSettings` from the player options if not passed in child options if ( options . persistTextTrackSettings === undefined ) { _this . options_ . persistTextTrackSettings = _this . options_ . playerOptions . persistTextTrackSettings ; } _this . on ( _this . $ ( '.vjs-done-button' ) , 'click' , function ( ) { _this . saveSettings ( ) ; _this . close ( ) ; } ) ; _this . on ( _this . $ ( '.vjs-default-button' ) , 'click' , function ( ) { _this . setDefaults ( ) ; _this . updateDisplay ( ) ; } ) ; each ( selectConfigs , function ( config ) { _this . on ( _this . $ ( config . selector ) , 'change' , _this . updateDisplay ) ; } ) ; if ( _this . options_ . persistTextTrackSettings ) { _this . restoreSettings ( ) ; } return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of this Tech . [CODESPLIT] function Html5 ( options , ready ) { classCallCheck ( this , Html5 ) ; var _this = possibleConstructorReturn ( this , _Tech . call ( this , options , ready ) ) ; var source = options . source ; var crossoriginTracks = false ; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if ( source && ( _this . el_ . currentSrc !== source . src || options . tag && options . tag . initNetworkState_ === 3 ) ) { _this . setSource ( source ) ; } else { _this . handleLateInit_ ( _this . el_ ) ; } if ( _this . el_ . hasChildNodes ( ) ) { var nodes = _this . el_ . childNodes ; var nodesLength = nodes . length ; var removeNodes = [ ] ; while ( nodesLength -- ) { var node = nodes [ nodesLength ] ; var nodeName = node . nodeName . toLowerCase ( ) ; if ( nodeName === 'track' ) { if ( ! _this . featuresNativeTextTracks ) { // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks removeNodes . push ( node ) ; } else { // store HTMLTrackElement and TextTrack to remote list _this . remoteTextTrackEls ( ) . addTrackElement_ ( node ) ; _this . remoteTextTracks ( ) . addTrack ( node . track ) ; _this . textTracks ( ) . addTrack ( node . track ) ; if ( ! crossoriginTracks && ! _this . el_ . hasAttribute ( 'crossorigin' ) && isCrossOrigin ( node . src ) ) { crossoriginTracks = true ; } } } } for ( var i = 0 ; i < removeNodes . length ; i ++ ) { _this . el_ . removeChild ( removeNodes [ i ] ) ; } } _this . proxyNativeTracks_ ( ) ; if ( _this . featuresNativeTextTracks && crossoriginTracks ) { log$1 . warn ( tsml ( _templateObject$2 ) ) ; } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if ( ( TOUCH_ENABLED || IS_IPHONE || IS_NATIVE_ANDROID ) && options . nativeControlsForTouch === true ) { _this . setControls ( true ) ; } // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen` // into a `fullscreenchange` event _this . proxyWebkitFullscreen_ ( ) ; _this . triggerReady ( ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait for the first timeupdate with currentTime > 0 - there may be several with 0 [CODESPLIT] function checkProgress ( ) { if ( _this3 . el_ . currentTime > 0 ) { // Trigger durationchange for genuinely live video if ( _this3 . el_ . duration === Infinity ) { _this3 . trigger ( 'durationchange' ) ; } _this3 . off ( 'timeupdate' , checkProgress ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of this class . [CODESPLIT] function Player ( tag , options , ready ) { classCallCheck ( this , Player ) ; // Make sure tag ID exists tag . id = tag . id || 'vjs_video_' + newGUID ( ) ; // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = assign ( Player . getTagSettings ( tag ) , options ) ; // Delay the initialization of children because we need to set up // player properties first, and can't use `this` before `super()` options . initChildren = false ; // Same with creating the element options . createEl = false ; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options . reportTouchActivity = false ; // If language is not set, get the closest lang attribute if ( ! options . language ) { if ( typeof tag . closest === 'function' ) { var closest = tag . closest ( '[lang]' ) ; if ( closest ) { options . language = closest . getAttribute ( 'lang' ) ; } } else { var element = tag ; while ( element && element . nodeType === 1 ) { if ( getAttributes ( element ) . hasOwnProperty ( 'lang' ) ) { options . language = element . getAttribute ( 'lang' ) ; break ; } element = element . parentNode ; } } } // Run base component initializing with new options // Turn off API access because we're loading a new tech that might load asynchronously var _this = possibleConstructorReturn ( this , _Component . call ( this , null , options , ready ) ) ; _this . isReady_ = false ; // if the global option object was accidentally blown away by // someone, bail early with an informative error if ( ! _this . options_ || ! _this . options_ . techOrder || ! _this . options_ . techOrder . length ) { throw new Error ( 'No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?' ) ; } // Store the original tag used to set options _this . tag = tag ; // Store the tag attributes used to restore html5 element _this . tagAttributes = tag && getAttributes ( tag ) ; // Update current language _this . language ( _this . options_ . language ) ; // Update Supported Languages if ( options . languages ) { // Normalise player option languages to lowercase var languagesToLower = { } ; Object . getOwnPropertyNames ( options . languages ) . forEach ( function ( name$$1 ) { languagesToLower [ name$$1 . toLowerCase ( ) ] = options . languages [ name$$1 ] ; } ) ; _this . languages_ = languagesToLower ; } else { _this . languages_ = Player . prototype . options_ . languages ; } // Cache for video property values. _this . cache_ = { } ; // Set poster _this . poster_ = options . poster || '' ; // Set controls _this . controls_ = ! ! options . controls ; // Set default values for lastVolume _this . cache_ . lastVolume = 1 ; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag . controls = false ; /*\n     * Store the internal state of scrubbing\n     *\n     * @private\n     * @return {Boolean} True if the user is scrubbing\n     */ _this . scrubbing_ = false ; _this . el_ = _this . createEl ( ) ; // Make this an evented object and use `el_` as its event bus. evented ( _this , { eventBusKey : 'el_' } ) ; // We also want to pass the original player options to each component and plugin // as well so they don't need to reach back into the player for options later. // We also need to do another copy of this.options_ so we don't end up with // an infinite loop. var playerOptionsCopy = mergeOptions ( _this . options_ ) ; // Load plugins if ( options . plugins ) { var plugins = options . plugins ; Object . keys ( plugins ) . forEach ( function ( name$$1 ) { if ( typeof this [ name$$1 ] === 'function' ) { this [ name$$1 ] ( plugins [ name$$1 ] ) ; } else { throw new Error ( 'plugin \"' + name$$1 + '\" does not exist' ) ; } } , _this ) ; } _this . options_ . playerOptions = playerOptionsCopy ; _this . middleware_ = [ ] ; _this . initChildren ( ) ; // Set isAudio based on whether or not an audio tag was used _this . isAudio ( tag . nodeName . toLowerCase ( ) === 'audio' ) ; // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if ( _this . controls ( ) ) { _this . addClass ( 'vjs-controls-enabled' ) ; } else { _this . addClass ( 'vjs-controls-disabled' ) ; } // Set ARIA label and region role depending on player type _this . el_ . setAttribute ( 'role' , 'region' ) ; if ( _this . isAudio ( ) ) { _this . el_ . setAttribute ( 'aria-label' , _this . localize ( 'Audio Player' ) ) ; } else { _this . el_ . setAttribute ( 'aria-label' , _this . localize ( 'Video Player' ) ) ; } if ( _this . isAudio ( ) ) { _this . addClass ( 'vjs-audio' ) ; } if ( _this . flexNotSupported_ ( ) ) { _this . addClass ( 'vjs-no-flex' ) ; } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (browser.TOUCH_ENABLED) { //   this.addClass('vjs-touch-enabled'); // } // iOS Safari has broken hover handling if ( ! IS_IOS ) { _this . addClass ( 'vjs-workinghover' ) ; } // Make player easily findable by ID Player . players [ _this . id_ ] = _this ; // Add a major version class to aid css in plugins var majorVersion = version . split ( '.' ) [ 0 ] ; _this . addClass ( 'vjs-v' + majorVersion ) ; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed _this . userActive ( true ) ; _this . reportUserActivity ( ) ; _this . listenForUserActivity_ ( ) ; _this . on ( 'fullscreenchange' , _this . handleFullscreenChange_ ) ; _this . on ( 'stageclick' , _this . handleStageClick_ ) ; _this . changingSrc_ = false ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate over each innerArray element once per outerArray element and execute tester with both . If tester returns a non - falsy value exit early and return that value . [CODESPLIT] function findFirstPassingTechSourcePair ( outerArray , innerArray , tester ) { var found = void 0 ; outerArray . some ( function ( outerChoice ) { return innerArray . some ( function ( innerChoice ) { found = tester ( outerChoice , innerChoice ) ; if ( found ) { return true ; } } ) ; } ) ; return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marks a plugin as active on a player . [CODESPLIT] function markPluginAsActive ( player , name ) { player [ PLUGIN_CACHE_KEY ] = player [ PLUGIN_CACHE_KEY ] || { } ; player [ PLUGIN_CACHE_KEY ] [ name ] = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers a pair of plugin setup events . [CODESPLIT] function triggerSetupEvent ( player , hash , before ) { var eventName = ( before ? 'before' : '' ) + 'pluginsetup' ; player . trigger ( eventName , hash ) ; player . trigger ( eventName + ':' + hash . name , hash ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a basic plugin function and returns a wrapper function which marks on the player that the plugin has been activated . [CODESPLIT] function createBasicPlugin ( name , plugin ) { var basicPluginWrapper = function basicPluginWrapper ( ) { // We trigger the \"beforepluginsetup\" and \"pluginsetup\" events on the player // regardless, but we want the hash to be consistent with the hash provided // for advanced plugins. // // The only potentially counter-intuitive thing here is the `instance` in // the \"pluginsetup\" event is the value returned by the `plugin` function. triggerSetupEvent ( this , { name : name , plugin : plugin , instance : null } , true ) ; var instance = plugin . apply ( this , arguments ) ; markPluginAsActive ( this , name ) ; triggerSetupEvent ( this , { name : name , plugin : plugin , instance : instance } ) ; return instance ; } ; Object . keys ( plugin ) . forEach ( function ( prop ) { basicPluginWrapper [ prop ] = plugin [ prop ] ; } ) ; return basicPluginWrapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a plugin sub - class and returns a factory function for generating instances of it . [CODESPLIT] function createPluginFactory ( name , PluginSubClass ) { // Add a `name` property to the plugin prototype so that each plugin can // refer to itself by name. PluginSubClass . prototype . name = name ; return function ( ) { triggerSetupEvent ( this , { name : name , plugin : PluginSubClass , instance : null } , true ) ; for ( var _len = arguments . length , args = Array ( _len ) , _key = 0 ; _key < _len ; _key ++ ) { args [ _key ] = arguments [ _key ] ; } var instance = new ( Function . prototype . bind . apply ( PluginSubClass , [ null ] . concat ( [ this ] . concat ( args ) ) ) ) ( ) ; // The plugin is replaced by a function that returns the current instance. this [ name ] = function ( ) { return instance ; } ; triggerSetupEvent ( this , instance . getEventHash ( ) ) ; return instance ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this class . [CODESPLIT] function Plugin ( player ) { classCallCheck ( this , Plugin ) ; if ( this . constructor === Plugin ) { throw new Error ( 'Plugin must be sub-classed; not directly instantiated.' ) ; } this . player = player ; // Make this object evented, but remove the added `trigger` method so we // use the prototype version instead. evented ( this ) ; delete this . trigger ; stateful ( this , this . constructor . defaultState ) ; markPluginAsActive ( player , this . name ) ; // Auto-bind the dispose method so we can use it as a listener and unbind // it later easily. this . dispose = bind ( this , this . dispose ) ; // If the player is disposed, dispose the plugin. player . on ( 'dispose' , this . dispose ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Doubles as the main function for users to create a player instance and also the main library object . The videojs function can be used to initialize or retrieve a player . [CODESPLIT] function videojs ( id , options , ready ) { var tag = void 0 ; // Allow for element or ID to be passed in // String ID if ( typeof id === 'string' ) { var players = videojs . getPlayers ( ) ; // Adjust for jQuery ID syntax if ( id . indexOf ( '#' ) === 0 ) { id = id . slice ( 1 ) ; } // If a player instance has already been created for this ID return it. if ( players [ id ] ) { // If options or ready function are passed, warn if ( options ) { log$1 . warn ( 'Player \"' + id + '\" is already initialised. Options will not be applied.' ) ; } if ( ready ) { players [ id ] . ready ( ready ) ; } return players [ id ] ; } // Otherwise get element for ID tag = $ ( '#' + id ) ; // ID is a media element } else { tag = id ; } // Check for a useable element // re: nodeName, could be a box div also if ( ! tag || ! tag . nodeName ) { throw new TypeError ( 'The element or ID supplied is not valid. (videojs)' ) ; } // Element may have a player attr referring to an already created player instance. // If so return that otherwise set up a new player below if ( tag . player || Player . players [ tag . playerId ] ) { return tag . player || Player . players [ tag . playerId ] ; } options = options || { } ; videojs . hooks ( 'beforesetup' ) . forEach ( function ( hookFunction ) { var opts = hookFunction ( tag , mergeOptions ( options ) ) ; if ( ! isObject ( opts ) || Array . isArray ( opts ) ) { log$1 . error ( 'please return an object in beforesetup hooks' ) ; return ; } options = mergeOptions ( options , opts ) ; } ) ; var PlayerComponent = Component . getComponent ( 'Player' ) ; // If not, set up a new player var player = new PlayerComponent ( tag , options , ready ) ; videojs . hooks ( 'setup' ) . forEach ( function ( hookFunction ) { return hookFunction ( player ) ; } ) ; return player ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ [CODESPLIT] function ( component , name , animation ) { var html5 = exports var transition = { property : html5 . getPrefixedName ( 'transition-property' ) , delay : html5 . getPrefixedName ( 'transition-delay' ) , duration : html5 . getPrefixedName ( 'transition-duration' ) , timing : html5 . getPrefixedName ( 'transition-timing-function' ) } var element = component . element element . forceLayout ( ) //flush styles before setting transition name = html5 . getPrefixedName ( name ) || name //replace transform: <prefix>rotate hack var transitions = element . _transitions var property = transitions [ transition . property ] || [ ] var duration = transitions [ transition . duration ] || [ ] var timing = transitions [ transition . timing ] || [ ] var delay = transitions [ transition . delay ] || [ ] var idx = property . indexOf ( name ) if ( idx === - 1 ) { //if property not set if ( animation ) { property . push ( name ) duration . push ( animation . duration + 'ms' ) timing . push ( animation . easing ) delay . push ( animation . delay + 'ms' ) } } else { //property already set, adjust the params if ( animation && animation . active ( ) ) { duration [ idx ] = animation . duration + 'ms' timing [ idx ] = animation . easing delay [ idx ] = animation . delay + 'ms' } else { property . splice ( idx , 1 ) duration . splice ( idx , 1 ) timing . splice ( idx , 1 ) delay . splice ( idx , 1 ) } } transitions [ transition . property ] = property transitions [ transition . duration ] = duration transitions [ transition . timing ] = timing transitions [ transition . delay ] = delay //FIXME: orsay animation is not working without this shit =( if ( component . _context . system . os === 'orsay' || component . _context . system . os === 'netcast' ) { transitions [ \"transition-property\" ] = property transitions [ \"transition-duration\" ] = duration transitions [ \"transition-delay\" ] = delay transitions [ \"transition-timing-function\" ] = timing } component . style ( transitions ) return true }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Comment out if you didn t npm install lz - string [CODESPLIT] function byteCount ( testName , len , baseLen ) { console . log ( testName + \" Byte Count: \" + len + ( baseLen ? ', ' + Math . round ( len / baseLen * 100 ) + '%' : '' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The number of bytes of data that have been queued using calls to send () but not yet transmitted to the network . This value resets to zero once all queued data has been sent . This value does not reset to zero when the connection is closed ; if you keep calling send () this will continue to climb . Read only [CODESPLIT] function ( ) { var bytes = this . _messageQueue . reduce ( function ( acc , message ) { if ( typeof message === 'string' ) { acc += message . length ; // not byte size\r } else if ( message instanceof Blob ) { acc += message . size ; } else { acc += message . byteLength ; } return acc ; } , 0 ) ; return bytes + ( this . _ws ? this . _ws . bufferedAmount : 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Randomizes whatever colors are currently being used . [CODESPLIT] function ( ) { var colors = [ ] var trs = _$sortableDataList . find ( \"li\" ) ; for ( var i = 0 ; i < trs . length ; i ++ ) { colors . push ( utils . rgb2hex ( $ ( trs [ i ] ) . find ( \".segmentColor\" ) . css ( \"background-color\" ) ) ) ; } colors = utils . shuffleArray ( colors ) ; _setColors ( colors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Publishes a message to anyone who s subscribed to it . [CODESPLIT] function ( moduleID , message , data ) { if ( C . DEBUG ) { console . log ( \"[\" + moduleID + \"] publish(): \" , message , data ) ; } for ( var i in _modules ) { var subscriptions = _modules [ i ] . subscriptions ; // if this module has subscribed to this event, call the callback function if ( subscriptions . hasOwnProperty ( message ) ) { subscriptions [ message ] ( { sender : moduleID , data : data } ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this catches ALL nav clicks not just in the main navbar [CODESPLIT] function ( ) { $ ( document ) . on ( \"click\" , \".selectPage\" , function ( e ) { e . preventDefault ( ) ; _selectPage ( this . hash ) ; } ) ; $ ( window ) . on ( \"resize\" , function ( ) { var width = $ ( window ) . width ( ) ; var height = $ ( window ) . height ( ) ; var breakPoint = _updateBodySizeClass ( width ) ; mediator . publish ( _MODULE_ID , C . EVENT . PAGE . RESIZE , { width : width , height : height , breakPoint : breakPoint } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This was added to get around some CSS nonsense with the homepage slider script . It adds a class to the body element that specifies the current viewport width . [CODESPLIT] function ( width ) { var breakPointIndex = null ; for ( var i = 0 ; i < C . OTHER . BREAKPOINTS . length ; i ++ ) { if ( width >= C . OTHER . BREAKPOINTS [ i ] ) { breakPointIndex = i ; } } $ ( \"body\" ) . removeClass ( \"size768 size992 size1200\" ) ; var breakPoint = null ; if ( breakPointIndex !== null ) { breakPoint = C . OTHER . BREAKPOINTS [ breakPointIndex ] ; $ ( \"body\" ) . addClass ( \"size\" + breakPoint ) ; } return breakPoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Our main hideous navigation function . This accepts a page identifier ( string ) listed in the _pages array above . This function validates the page string and fade in / out the appropriate page . [CODESPLIT] function ( pageCandidate ) { // remove any hashes that may be there var pageCandidateNoHash = pageCandidate . replace ( / # / , \"\" ) ; var hashParts = pageCandidateNoHash . split ( \"-\" ) ; var page = hashParts [ 0 ] ; // check the page is valid. If not, default to the About page page = ( $ . inArray ( page , _pages ) !== - 1 ) ? page : \"about\" ; if ( pageCandidate === _currentPageHash ) { return ; } var publishData = { page : page , prevPage : _currentPage , pageHash : pageCandidateNoHash } ; if ( page !== _currentPage ) { // fade out the old page, if one was selected (not the case for first load) if ( _currentPage ) { _$topNav . find ( \".active\" ) . removeClass ( \"active\" ) ; $ ( \"#\" + _currentPage ) . removeClass ( \"hidden fadeIn\" ) . addClass ( \"fadeOut\" ) ; ( function ( cp ) { setTimeout ( function ( ) { $ ( \"#\" + cp ) . addClass ( \"hidden\" ) . removeClass ( \"fadeOut\" ) ; // show the new one. Good lord. Nested setTimeouts? What the gibbering fuck... setTimeout ( function ( ) { _$topNav . find ( \"a[href=#\" + page + \"]\" ) . closest ( \"li\" ) . addClass ( \"active\" ) ; // select the tab $ ( \"#\" + page ) . removeClass ( \"hidden fadeOut\" ) . addClass ( \"fadeIn\" ) ; // select the page mediator . publish ( _MODULE_ID , C . EVENT . PAGE . LOAD , publishData ) ; } , 10 ) ; } , C . OTHER . PAGE_LOAD_SPEED ) ; } ) ( _currentPage ) ; } else { _$topNav . find ( \"a[href=#\" + page + \"]\" ) . closest ( \"li\" ) . addClass ( \"active\" ) ; // select the tab $ ( \"#\" + page ) . removeClass ( \"hidden fadeOut\" ) ; // weird, we need the timeout for the initial page load otherwise it doesn't fade in setTimeout ( function ( ) { $ ( \"#\" + page ) . addClass ( \"fadeIn\" ) ; mediator . publish ( _MODULE_ID , C . EVENT . PAGE . LOAD , publishData ) ; } , 10 ) ; } } else { mediator . publish ( _MODULE_ID , C . EVENT . PAGE . LOAD , publishData ) ; } window . location . hash = pageCandidate ; // store the current page & full hash _currentPage = page ; _currentPageHash = pageCandidate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Remove this line and break up compilePartial [CODESPLIT] function template ( templateSpec , env ) { if ( ! env ) { throw new Exception ( \"No environment passed to template\" ) ; } // Note: Using env.VM references rather than local var references throughout this section to allow // for external users to override these as psuedo-supported APIs. var invokePartialWrapper = function ( partial , name , context , helpers , partials , data ) { var result = env . VM . invokePartial . apply ( this , arguments ) ; if ( result != null ) { return result ; } if ( env . compile ) { var options = { helpers : helpers , partials : partials , data : data } ; partials [ name ] = env . compile ( partial , { data : data !== undefined } , env ) ; return partials [ name ] ( context , options ) ; } else { throw new Exception ( \"The partial \" + name + \" could not be compiled when running in runtime-only mode\" ) ; } } ; // Just add water var container = { escapeExpression : Utils . escapeExpression , invokePartial : invokePartialWrapper , programs : [ ] , program : function ( i , fn , data ) { var programWrapper = this . programs [ i ] ; if ( data ) { programWrapper = program ( i , fn , data ) ; } else if ( ! programWrapper ) { programWrapper = this . programs [ i ] = program ( i , fn ) ; } return programWrapper ; } , merge : function ( param , common ) { var ret = param || common ; if ( param && common && ( param !== common ) ) { ret = { } ; Utils . extend ( ret , common ) ; Utils . extend ( ret , param ) ; } return ret ; } , programWithDepth : env . VM . programWithDepth , noop : env . VM . noop , compilerInfo : null } ; return function ( context , options ) { options = options || { } ; var namespace = options . partial ? options : env , helpers , partials ; if ( ! options . partial ) { helpers = options . helpers ; partials = options . partials ; } var result = templateSpec . call ( container , namespace , context , helpers , partials , options . data ) ; if ( ! options . partial ) { env . VM . checkRevision ( container . compilerInfo ) ; } return result ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Note : Using env . VM references rather than local var references throughout this section to allow for external users to override these as psuedo - supported APIs . [CODESPLIT] function ( partial , name , context , helpers , partials , data ) { var result = env . VM . invokePartial . apply ( this , arguments ) ; if ( result != null ) { return result ; } if ( env . compile ) { var options = { helpers : helpers , partials : partials , data : data } ; partials [ name ] = env . compile ( partial , { data : data !== undefined } , env ) ; return partials [ name ] ( context , options ) ; } else { throw new Exception ( \"The partial \" + name + \" could not be compiled when running in runtime-only mode\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For compatibility and usage outside of module systems make the Handlebars object a namespace [CODESPLIT] function ( ) { var hb = new base . HandlebarsEnvironment ( ) ; Utils . extend ( hb , base ) ; hb . SafeString = SafeString ; hb . Exception = Exception ; hb . Utils = Utils ; hb . VM = runtime ; hb . template = function ( spec ) { return runtime . template ( spec , hb ) ; } ; return hb ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PUBLIC API : You can override these methods in a subclass to provide alternative compiled forms for name lookup and buffering semantics [CODESPLIT] function ( parent , name /* , type*/ ) { var wrap , ret ; if ( parent . indexOf ( 'depth' ) === 0 ) { wrap = true ; } if ( / ^[0-9]+$ / . test ( name ) ) { ret = parent + \"[\" + name + \"]\" ; } else if ( JavaScriptCompiler . isValidJavaScriptVariableName ( name ) ) { ret = parent + \".\" + name ; } else { ret = parent + \"['\" + name + \"']\" ; } if ( wrap ) { return '(' + parent + ' && ' + ret + ')' ; } else { return ret ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "END PUBLIC API [CODESPLIT] function ( environment , options , context , asObject ) { this . environment = environment ; this . options = options || { } ; log ( 'debug' , this . environment . disassemble ( ) + \"\\n\\n\" ) ; this . name = this . environment . name ; this . isChild = ! ! context ; this . context = context || { programs : [ ] , environments : [ ] , aliases : { } } ; this . preamble ( ) ; this . stackSlot = 0 ; this . stackVars = [ ] ; this . registers = { list : [ ] } ; this . hashes = [ ] ; this . compileStack = [ ] ; this . inlineStack = [ ] ; this . compileChildren ( environment , options ) ; var opcodes = environment . opcodes , opcode ; this . i = 0 ; for ( var l = opcodes . length ; this . i < l ; this . i ++ ) { opcode = opcodes [ this . i ] ; if ( opcode . opcode === 'DECLARE' ) { this [ opcode . name ] = opcode . value ; } else { this [ opcode . opcode ] . apply ( this , opcode . args ) ; } // Reset the stripNext flag if it was not set by this operation. if ( opcode . opcode !== this . stripNext ) { this . stripNext = false ; } } // Flush any trailing content that might be pending. this . pushSource ( '' ) ; if ( this . stackSlot || this . inlineStack . length || this . compileStack . length ) { throw new Exception ( 'Compile completed with content left on stack' ) ; } return this . createFunctionContext ( asObject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ ambiguousBlockValue ] On stack before : hash inverse program value Compiler value before : lastHelper = value of last found helper if any On stack after if no lastHelper : same as [ blockValue ] On stack after if lastHelper : value [CODESPLIT] function ( ) { this . context . aliases . blockHelperMissing = 'helpers.blockHelperMissing' ; var params = [ \"depth0\" ] ; this . setupParams ( 0 , params ) ; var current = this . topStack ( ) ; params . splice ( 1 , 0 , current ) ; this . pushSource ( \"if (!\" + this . lastHelper + \") { \" + current + \" = blockHelperMissing.call(\" + params . join ( \", \" ) + \"); }\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ appendContent ] On stack before : ... On stack after : ... Appends the string value of content to the current buffer [CODESPLIT] function ( content ) { if ( this . pendingContent ) { content = this . pendingContent + content ; } if ( this . stripNext ) { content = content . replace ( / ^\\s+ / , '' ) ; } this . pendingContent = content ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ pushStringParam ] On stack before : ... On stack after : string currentContext ... This opcode is designed for use in string mode which provides the string value of a parameter along with its depth rather than resolving it immediately . [CODESPLIT] function ( string , type ) { this . pushStackLiteral ( 'depth' + this . lastContext ) ; this . pushString ( type ) ; // If it's a subexpression, the string result // will be pushed after this opcode. if ( type !== 'sexpr' ) { if ( typeof string === 'string' ) { this . pushString ( string ) ; } else { this . pushStackLiteral ( string ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ invokeHelper ] On stack before : hash inverse program params ... ... On stack after : result of helper invocation Pops off the helper s parameters invokes the helper and pushes the helper s return value onto the stack . If the helper is not found helperMissing is called . [CODESPLIT] function ( paramSize , name , isRoot ) { this . context . aliases . helperMissing = 'helpers.helperMissing' ; this . useRegister ( 'helper' ) ; var helper = this . lastHelper = this . setupHelper ( paramSize , name , true ) ; var nonHelper = this . nameLookup ( 'depth' + this . lastContext , name , 'context' ) ; var lookup = 'helper = ' + helper . name + ' || ' + nonHelper ; if ( helper . paramsInit ) { lookup += ',' + helper . paramsInit ; } this . push ( '(' + lookup + ',helper ' + '? helper.call(' + helper . callParams + ') ' + ': helperMissing.call(' + helper . helperMissingParams + '))' ) ; // Always flush subexpressions. This is both to prevent the compounding size issue that // occurs when the code has to be duplicated for inlining and also to prevent errors // due to the incorrect options object being passed due to the shared register. if ( ! isRoot ) { this . flushInline ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ invokeKnownHelper ] On stack before : hash inverse program params ... ... On stack after : result of helper invocation This operation is used when the helper is known to exist so a helperMissing fallback is not required . [CODESPLIT] function ( paramSize , name ) { var helper = this . setupHelper ( paramSize , name ) ; this . push ( helper . name + \".call(\" + helper . callParams + \")\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ invokeAmbiguous ] On stack before : hash inverse program params ... ... On stack after : result of disambiguation This operation is used when an expression like {{ foo }} is provided but we don t know at compile - time whether it is a helper or a path . This operation emits more code than the other options and can be avoided by passing the knownHelpers and knownHelpersOnly flags at compile - time . [CODESPLIT] function ( name , helperCall ) { this . context . aliases . functionType = '\"function\"' ; this . useRegister ( 'helper' ) ; this . emptyHash ( ) ; var helper = this . setupHelper ( 0 , name , helperCall ) ; var helperName = this . lastHelper = this . nameLookup ( 'helpers' , name , 'helper' ) ; var nonHelper = this . nameLookup ( 'depth' + this . lastContext , name , 'context' ) ; var nextStack = this . nextStack ( ) ; if ( helper . paramsInit ) { this . pushSource ( helper . paramsInit ) ; } this . pushSource ( 'if (helper = ' + helperName + ') { ' + nextStack + ' = helper.call(' + helper . callParams + '); }' ) ; this . pushSource ( 'else { helper = ' + nonHelper + '; ' + nextStack + ' = typeof helper === functionType ? helper.call(' + helper . callParams + ') : helper; }' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ assignToHash ] On stack before : value hash ... On stack after : hash ... Pops a value and hash off the stack assigns hash [ key ] = value and pushes the hash back onto the stack . [CODESPLIT] function ( key ) { var value = this . popStack ( ) , context , type ; if ( this . options . stringParams ) { type = this . popStack ( ) ; context = this . popStack ( ) ; } var hash = this . hash ; if ( context ) { hash . contexts . push ( \"'\" + key + \"': \" + context ) ; } if ( type ) { hash . types . push ( \"'\" + key + \"': \" + type ) ; } hash . values . push ( \"'\" + key + \"': (\" + value + \")\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the params and contexts arguments are passed in arrays to fill in [CODESPLIT] function ( paramSize , params , useRegister ) { var options = '{' + this . setupOptions ( paramSize , params ) . join ( ',' ) + '}' ; if ( useRegister ) { this . useRegister ( 'options' ) ; params . push ( 'options' ) ; return 'options=' + options ; } else { params . push ( options ) ; return '' ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Listen for data changes so we can keep track of the current canvas size . [CODESPLIT] function ( msg ) { _canvasWidth = msg . data . config . size . canvasWidth ; _canvasHeight = msg . data . config . size . canvasHeight ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------------------------------------------- [CODESPLIT] function ( ) { var scope = this ; THREE . Geometry . call ( this ) ; v ( 5 , 0 , 0 ) ; v ( - 5 , - 2 , 1 ) ; v ( - 5 , 0 , 0 ) ; v ( - 5 , - 2 , - 1 ) ; v ( 0 , 2 , - 6 ) ; v ( 0 , 2 , 6 ) ; v ( 2 , 0 , 0 ) ; v ( - 3 , 0 , 0 ) ; f3 ( 0 , 2 , 1 ) ; f3 ( 4 , 7 , 6 ) ; f3 ( 5 , 6 , 7 ) ; this . computeCentroids ( ) ; this . computeFaceNormals ( ) ; function v ( x , y , z ) { scope . vertices . push ( new THREE . Vector3 ( x , y , z ) ) ; } function f3 ( a , b , c ) { scope . faces . push ( new THREE . Face3 ( a , b , c ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Based on http : // www . openprocessing . org / visuals / ?visualID = 6910 [CODESPLIT] function ( ) { var vector = new THREE . Vector3 ( ) , _acceleration , _width = 500 , _height = 500 , _depth = 200 , _goal , _neighborhoodRadius = 100 , _maxSpeed = 4 , _maxSteerForce = 0.1 , _avoidWalls = false ; this . position = new THREE . Vector3 ( ) ; this . velocity = new THREE . Vector3 ( ) ; _acceleration = new THREE . Vector3 ( ) ; this . setGoal = function ( target ) { _goal = target ; } ; this . setAvoidWalls = function ( value ) { _avoidWalls = value ; } ; this . setWorldSize = function ( width , height , depth ) { _width = width ; _height = height ; _depth = depth ; } ; this . run = function ( boids ) { if ( _avoidWalls ) { vector . set ( - _width , this . position . y , this . position . z ) ; vector = this . avoid ( vector ) ; vector . multiplyScalar ( 5 ) ; _acceleration . add ( vector ) ; vector . set ( _width , this . position . y , this . position . z ) ; vector = this . avoid ( vector ) ; vector . multiplyScalar ( 5 ) ; _acceleration . add ( vector ) ; vector . set ( this . position . x , - _height , this . position . z ) ; vector = this . avoid ( vector ) ; vector . multiplyScalar ( 5 ) ; _acceleration . add ( vector ) ; vector . set ( this . position . x , _height , this . position . z ) ; vector = this . avoid ( vector ) ; vector . multiplyScalar ( 5 ) ; _acceleration . add ( vector ) ; vector . set ( this . position . x , this . position . y , - _depth ) ; vector = this . avoid ( vector ) ; vector . multiplyScalar ( 5 ) ; _acceleration . add ( vector ) ; vector . set ( this . position . x , this . position . y , _depth ) ; vector = this . avoid ( vector ) ; vector . multiplyScalar ( 5 ) ; _acceleration . add ( vector ) ; } if ( Math . random ( ) > 0.5 ) { this . flock ( boids ) ; } this . move ( ) ; } this . flock = function ( boids ) { if ( _goal ) { _acceleration . add ( this . reach ( _goal , 0.005 ) ) ; } _acceleration . add ( this . alignment ( boids ) ) ; _acceleration . add ( this . cohesion ( boids ) ) ; _acceleration . add ( this . separation ( boids ) ) ; } this . move = function ( ) { this . velocity . add ( _acceleration ) ; var l = this . velocity . length ( ) ; if ( l > _maxSpeed ) { this . velocity . divideScalar ( l / _maxSpeed ) ; } this . position . add ( this . velocity ) ; _acceleration . set ( 0 , 0 , 0 ) ; } this . checkBounds = function ( ) { if ( this . position . x > _width ) this . position . x = - _width ; if ( this . position . x < - _width ) this . position . x = _width ; if ( this . position . y > _height ) this . position . y = - _height ; if ( this . position . y < - _height ) this . position . y = _height ; if ( this . position . z > _depth ) this . position . z = - _depth ; if ( this . position . z < - _depth ) this . position . z = _depth ; } this . avoid = function ( target ) { var steer = new THREE . Vector3 ( ) ; steer . copy ( this . position ) ; steer . sub ( target ) ; steer . multiplyScalar ( 1 / this . position . distanceToSquared ( target ) ) ; return steer ; } this . repulse = function ( target ) { var distance = this . position . distanceTo ( target ) ; if ( distance < 150 ) { var steer = new THREE . Vector3 ( ) ; steer . subVectors ( this . position , target ) ; steer . multiplyScalar ( 0.5 / distance ) ; _acceleration . add ( steer ) ; } } this . reach = function ( target , amount ) { var steer = new THREE . Vector3 ( ) ; steer . subVectors ( target , this . position ) ; steer . multiplyScalar ( amount ) ; return steer ; } this . alignment = function ( boids ) { var boid , velSum = new THREE . Vector3 ( ) , count = 0 ; for ( var i = 0 , il = boids . length ; i < il ; i ++ ) { if ( Math . random ( ) > 0.6 ) continue ; boid = boids [ i ] ; distance = boid . position . distanceTo ( this . position ) ; if ( distance > 0 && distance <= _neighborhoodRadius ) { velSum . add ( boid . velocity ) ; count ++ ; } } if ( count > 0 ) { velSum . divideScalar ( count ) ; var l = velSum . length ( ) ; if ( l > _maxSteerForce ) { velSum . divideScalar ( l / _maxSteerForce ) ; } } return velSum ; } this . cohesion = function ( boids ) { var boid , distance , posSum = new THREE . Vector3 ( ) , steer = new THREE . Vector3 ( ) , count = 0 ; for ( var i = 0 , il = boids . length ; i < il ; i ++ ) { if ( Math . random ( ) > 0.6 ) continue ; boid = boids [ i ] ; distance = boid . position . distanceTo ( this . position ) ; if ( distance > 0 && distance <= _neighborhoodRadius ) { posSum . add ( boid . position ) ; count ++ ; } } if ( count > 0 ) { posSum . divideScalar ( count ) ; } steer . subVectors ( posSum , this . position ) ; var l = steer . length ( ) ; if ( l > _maxSteerForce ) { steer . divideScalar ( l / _maxSteerForce ) ; } return steer ; } this . separation = function ( boids ) { var boid , distance , posSum = new THREE . Vector3 ( ) , repulse = new THREE . Vector3 ( ) ; for ( var i = 0 , il = boids . length ; i < il ; i ++ ) { if ( Math . random ( ) > 0.6 ) continue ; boid = boids [ i ] ; distance = boid . position . distanceTo ( this . position ) ; if ( distance > 0 && distance <= _neighborhoodRadius ) { repulse . subVectors ( this . position , boid . position ) ; repulse . normalize ( ) ; repulse . divideScalar ( distance ) ; posSum . add ( repulse ) ; } } return posSum ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a bit fussy but unavoidable . Whenever a page changes we need to re - draw the pies IFF ( if and only if ) the initial page load wasn t the about page [CODESPLIT] function ( msg ) { if ( ! _firstPageLoaded ) { _firstPage = msg . data . page ; _firstPageLoaded = true ; if ( _firstPage === \"about\" ) { setTimeout ( function ( ) { _renderContent ( ) ; var width = $ ( window ) . width ( ) ; var breakPointIndex = null ; for ( var i = 0 ; i < C . OTHER . BREAKPOINTS . length ; i ++ ) { if ( width >= C . OTHER . BREAKPOINTS [ i ] ) { breakPointIndex = i ; } } if ( breakPointIndex === null ) { _handleViewport ( \"small\" ) ; } } , 10 ) ; } return ; } if ( msg . data . page === \"about\" ) { if ( ! _isRendered ) { _renderContent ( ) ; } $ ( \"#aboutPageSlides\" ) . slidesjs ( \"refresh\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "bah! God this plugin sucks . Doesn t even pass in the slide number we re going TO . [CODESPLIT] function ( number ) { switch ( number ) { case 1 : _demoPie2 . redraw ( ) ; _demoPie3 . redraw ( ) ; break ; case 2 : _demoPie1 . redraw ( ) ; _demoPie3 . redraw ( ) ; break ; case 3 : _demoPie1 . redraw ( ) ; _demoPie2 . redraw ( ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The first step of the build process . This sets various settings in the main grunt config for the current build environment . These govern how the subsequent tasks behave . [CODESPLIT] function ( ) { config . template . indexFile . options . data . C = _CONSTANTS . DEV ; config . template . indexFile . options . data . D3PIE_VERSION = packageFile . version ; config . template . devRequireConfig . options . data . handlebarsLib = _CONSTANTS . DEV . HANDLEBARS_LIB ; config . template . devRequireConfig . options . data . baseUrl = _CONSTANTS . DEV . BASE_URL ; var lines = [ ] ; for ( var i in _requireJSModulePaths ) { var file = _requireJSModulePaths [ i ] . replace ( / \\.js$ / , \"\" ) ; lines . push ( '\\t\\t\"' + i + '\": \"' + file + '\"' ) ; } config . template . devRequireConfig . options . data . moduleStr = lines . join ( \",\\n\" ) ; config . template . constants . options . data . VERSION = packageFile . version ; config . template . constants . options . data . MINIMIZED = _CONSTANTS . DEV . MINIMIZED ; config . template . constants . options . data . DEBUG = _CONSTANTS . DEV . DEBUG ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Our initialization function . Called on page load . [CODESPLIT] function ( ) { mediator . register ( _MODULE_ID ) ; var subscriptions = { } ; subscriptions [ C . EVENT . DEMO_PIE . SEND_DATA ] = _onSelectTab ; mediator . subscribe ( _MODULE_ID , subscriptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "yikes . The reason for all this hideousness is that we want to construct the * smallest * config object that we can . So each field needs to be examined separately . I looked into object diffing scripts but honestly there was too much custom stuff needed to be done with many properties - ensuring they re the right types etc . This is prime real estate for later refactoring but right now it s near the end of the project and I want this thing out the door ... don t judge me . ; - ) [CODESPLIT] function ( allSettings ) { var finalObj = { } ; // header title var headerTitleTextDiff = allSettings . header . title . text != defaultSettings . header . title . text ; var headerTitleColorDiff = allSettings . header . title . color != defaultSettings . header . title . color ; var headerTitleFontSizeDiff = allSettings . header . title . fontSize != defaultSettings . header . title . fontSize ; var headerTitleFontDiff = allSettings . header . title . font != defaultSettings . header . title . font ; if ( headerTitleTextDiff || headerTitleColorDiff || headerTitleFontSizeDiff || headerTitleFontDiff ) { finalObj . header = { title : { } } ; if ( headerTitleTextDiff ) { finalObj . header . title . text = allSettings . header . title . text ; } if ( headerTitleColorDiff ) { finalObj . header . title . color = allSettings . header . title . color ; } if ( headerTitleFontSizeDiff ) { finalObj . header . title . fontSize = parseInt ( allSettings . header . title . fontSize , 10 ) ; } if ( headerTitleFontDiff ) { finalObj . header . title . font = allSettings . header . title . font ; } } // header subtitle var headerSubtitleTextDiff = allSettings . header . subtitle . text != defaultSettings . header . subtitle . text ; var headerSubtitleColorDiff = allSettings . header . subtitle . color != defaultSettings . header . subtitle . color ; var headerSubtitleFontSizeDiff = allSettings . header . subtitle . fontSize != defaultSettings . header . subtitle . fontSize ; var headerSubtitleFontDiff = allSettings . header . subtitle . font != defaultSettings . header . subtitle . font ; if ( headerSubtitleTextDiff || headerSubtitleColorDiff || headerSubtitleFontSizeDiff || headerSubtitleFontDiff ) { if ( ! finalObj . hasOwnProperty ( \"header\" ) ) { finalObj . header = { } ; } finalObj . header . subtitle = { } ; if ( headerSubtitleTextDiff ) { finalObj . header . subtitle . text = allSettings . header . subtitle . text ; } if ( headerSubtitleColorDiff ) { finalObj . header . subtitle . color = allSettings . header . subtitle . color ; } if ( headerSubtitleFontSizeDiff ) { finalObj . header . subtitle . fontSize = parseInt ( allSettings . header . subtitle . fontSize , 10 ) ; } if ( headerSubtitleFontDiff ) { finalObj . header . subtitle . font = allSettings . header . subtitle . font ; } } if ( allSettings . header . location != defaultSettings . header . location ) { if ( ! finalObj . hasOwnProperty ( \"header\" ) ) { finalObj . header = { } ; } finalObj . header . location = allSettings . header . location ; } if ( allSettings . header . titleSubtitlePadding != defaultSettings . header . titleSubtitlePadding ) { if ( ! finalObj . hasOwnProperty ( \"header\" ) ) { finalObj . header = { } ; } finalObj . header . titleSubtitlePadding = parseInt ( allSettings . header . titleSubtitlePadding , 10 ) ; } // footer var footerTextDiff = allSettings . footer . text != defaultSettings . footer . text ; var footerColorDiff = allSettings . footer . color != defaultSettings . footer . color ; var footerFontSizeDiff = allSettings . footer . fontSize != defaultSettings . footer . fontSize ; var footerFontDiff = allSettings . footer . font != defaultSettings . footer . font ; var footerLocationDiff = allSettings . footer . font != defaultSettings . footer . location ; if ( footerTextDiff || footerColorDiff || footerFontSizeDiff || footerFontDiff ) { finalObj . footer = { } ; if ( footerTextDiff ) { finalObj . footer . text = allSettings . footer . text ; } if ( footerColorDiff ) { finalObj . footer . color = allSettings . footer . color ; } if ( footerFontSizeDiff ) { finalObj . footer . fontSize = parseInt ( allSettings . footer . fontSize , 10 ) ; } if ( footerFontDiff ) { finalObj . footer . font = allSettings . footer . font ; } if ( footerLocationDiff ) { finalObj . footer . location = allSettings . footer . location ; } } // size var canvasHeightDiff = allSettings . size . canvasHeight != defaultSettings . size . canvasHeight ; var canvasWidthDiff = allSettings . size . canvasWidth != defaultSettings . size . canvasWidth ; var pieInnerRadiusDiff = allSettings . size . pieInnerRadius != defaultSettings . size . pieInnerRadius ; var pieOuterRadiusDiff = allSettings . size . pieOuterRadius != defaultSettings . size . pieOuterRadius ; if ( canvasHeightDiff || canvasWidthDiff || pieInnerRadiusDiff || pieOuterRadiusDiff ) { finalObj . size = { } ; if ( canvasHeightDiff ) { finalObj . size . canvasHeight = parseFloat ( allSettings . size . canvasHeight , 10 ) ; } if ( canvasWidthDiff ) { finalObj . size . canvasWidth = parseFloat ( allSettings . size . canvasWidth , 10 ) ; } if ( pieInnerRadiusDiff ) { finalObj . size . pieInnerRadius = allSettings . size . pieInnerRadius ; } if ( pieOuterRadiusDiff ) { finalObj . size . pieOuterRadius = allSettings . size . pieOuterRadius ; } } // data finalObj . data = { } ; if ( allSettings . data . sortOrder != defaultSettings . data . sortOrder ) { finalObj . data . sortOrder = allSettings . data . sortOrder ; } var smallSegmentGroupingEnabledDiff = allSettings . data . smallSegmentGrouping . enabled != defaultSettings . data . smallSegmentGrouping . enabled ; if ( smallSegmentGroupingEnabledDiff ) { finalObj . data . smallSegmentGrouping = { } ; finalObj . data . smallSegmentGrouping . enabled = allSettings . data . smallSegmentGrouping . enabled ; var smallSegmentGroupingValDiff = allSettings . data . smallSegmentGrouping . value != defaultSettings . data . smallSegmentGrouping . value ; var smallSegmentGroupingValTypeDiff = allSettings . data . smallSegmentGrouping . valueType != defaultSettings . data . smallSegmentGrouping . valueType ; var smallSegmentGroupingLabelDiff = allSettings . data . smallSegmentGrouping . label != defaultSettings . data . smallSegmentGrouping . label ; var smallSegmentGroupingColorDiff = allSettings . data . smallSegmentGrouping . color != defaultSettings . data . smallSegmentGrouping . color ; if ( smallSegmentGroupingValDiff ) { finalObj . data . smallSegmentGrouping . value = allSettings . data . smallSegmentGrouping . value ; } if ( smallSegmentGroupingValTypeDiff ) { finalObj . data . smallSegmentGrouping . valueType = allSettings . data . smallSegmentGrouping . valueType ; } if ( smallSegmentGroupingLabelDiff ) { finalObj . data . smallSegmentGrouping . label = allSettings . data . smallSegmentGrouping . label ; } if ( smallSegmentGroupingColorDiff ) { finalObj . data . smallSegmentGrouping . color = allSettings . data . smallSegmentGrouping . color ; } } finalObj . data . content = allSettings . data . content ; // outer labels var outerLabelFormatDiff = allSettings . labels . outer . format != defaultSettings . labels . outer . format ; var outerLabelHideDiff = allSettings . labels . outer . hideWhenLessThanPercentage != defaultSettings . labels . outer . hideWhenLessThanPercentage ; var outerLabelPieDistDiff = allSettings . labels . outer . pieDistance != defaultSettings . labels . outer . pieDistance ; if ( outerLabelFormatDiff || outerLabelHideDiff || outerLabelPieDistDiff ) { finalObj . labels = { outer : { } } ; if ( outerLabelFormatDiff ) { finalObj . labels . outer . format = allSettings . labels . outer . format ; } if ( outerLabelHideDiff ) { finalObj . labels . outer . hideWhenLessThanPercentage = parseFloat ( allSettings . labels . outer . hideWhenLessThanPercentage ) ; } if ( outerLabelPieDistDiff ) { finalObj . labels . outer . pieDistance = allSettings . labels . outer . pieDistance ; } } var innerLabelFormatDiff = allSettings . labels . inner . format != defaultSettings . labels . inner . format ; var innerLabelHideDiff = allSettings . labels . inner . hideWhenLessThanPercentage != defaultSettings . labels . inner . hideWhenLessThanPercentage ; if ( innerLabelFormatDiff || innerLabelHideDiff ) { if ( ! finalObj . hasOwnProperty ( \"labels\" ) ) { finalObj . labels = { } ; } finalObj . labels . inner = { } ; if ( innerLabelFormatDiff ) { finalObj . labels . inner . format = allSettings . labels . inner . format ; } if ( innerLabelHideDiff ) { finalObj . labels . inner . hideWhenLessThanPercentage = parseFloat ( allSettings . labels . inner . hideWhenLessThanPercentage ) ; } } var mainLabelColorDiff = allSettings . labels . mainLabel . color != defaultSettings . labels . mainLabel . color ; var mainLabelFontDiff = allSettings . labels . mainLabel . font != defaultSettings . labels . mainLabel . font ; var mainLabelFontSizeDiff = allSettings . labels . mainLabel . fontSize != defaultSettings . labels . mainLabel . fontSize ; if ( mainLabelColorDiff || mainLabelFontDiff || mainLabelFontSizeDiff ) { if ( ! finalObj . hasOwnProperty ( \"labels\" ) ) { finalObj . labels = { } ; } finalObj . labels . mainLabel = { } ; if ( mainLabelColorDiff ) { finalObj . labels . mainLabel . color = allSettings . labels . mainLabel . color ; } if ( mainLabelFontDiff ) { finalObj . labels . mainLabel . font = allSettings . labels . mainLabel . font ; } if ( mainLabelFontSizeDiff ) { finalObj . labels . mainLabel . fontSize = parseInt ( allSettings . labels . mainLabel . fontSize , 10 ) ; } } var percentageColorDiff = allSettings . labels . percentage . color != defaultSettings . labels . percentage . color ; var percentageFontDiff = allSettings . labels . percentage . font != defaultSettings . labels . percentage . font ; var percentageFontSizeDiff = allSettings . labels . percentage . fontSize != defaultSettings . labels . percentage . fontSize ; var percentageDecimalDiff = allSettings . labels . percentage . decimalPlaces != defaultSettings . labels . percentage . decimalPlaces ; if ( percentageColorDiff || percentageFontDiff || percentageFontSizeDiff || percentageDecimalDiff ) { if ( ! finalObj . hasOwnProperty ( \"labels\" ) ) { finalObj . labels = { } ; } finalObj . labels . percentage = { } ; if ( percentageColorDiff ) { finalObj . labels . percentage . color = allSettings . labels . percentage . color ; } if ( percentageFontDiff ) { finalObj . labels . percentage . font = allSettings . labels . percentage . font ; } if ( percentageFontSizeDiff ) { finalObj . labels . percentage . fontSize = parseInt ( allSettings . labels . percentage . fontSize , 10 ) ; } if ( percentageColorDiff ) { finalObj . labels . percentage . decimalPlaces = parseInt ( allSettings . labels . percentage . decimalPlaces , 10 ) ; } } var valueColorDiff = allSettings . labels . value . color != defaultSettings . labels . value . color ; var valueFontDiff = allSettings . labels . value . font != defaultSettings . labels . value . font ; var valueFontSizeDiff = allSettings . labels . value . fontSize != defaultSettings . labels . value . fontSize ; if ( valueColorDiff || valueFontDiff || valueFontSizeDiff ) { if ( ! finalObj . hasOwnProperty ( \"labels\" ) ) { finalObj . labels = { } ; } finalObj . labels . value = { } ; if ( valueColorDiff ) { finalObj . labels . value . color = allSettings . labels . value . color ; } if ( valueFontDiff ) { finalObj . labels . value . font = allSettings . labels . value . font ; } if ( valueFontSizeDiff ) { finalObj . labels . value . fontSize = parseInt ( allSettings . labels . value . fontSize , 10 ) ; } } // label lines var labelLinesDiff = allSettings . labels . lines . enabled != defaultSettings . labels . lines . enabled ; if ( ! labelLinesDiff ) { if ( ! finalObj . hasOwnProperty ( \"labels\" ) ) { finalObj . labels = { } ; } finalObj . labels . lines = { enabled : allSettings . labels . lines . enabled } ; if ( allSettings . labels . lines . style != defaultSettings . labels . lines . style ) { finalObj . labels . lines . style = allSettings . labels . lines . style ; } if ( allSettings . labels . lines . color != defaultSettings . labels . lines . color ) { finalObj . labels . lines . color = allSettings . labels . lines . color ; } } // label truncation var labelTruncationDiff = allSettings . labels . truncation . enabled != defaultSettings . labels . truncation . enabled ; if ( labelTruncationDiff ) { if ( ! finalObj . hasOwnProperty ( \"labels\" ) ) { finalObj . labels = { } ; } finalObj . labels . truncation = { enabled : allSettings . labels . truncation . enabled } ; if ( allSettings . labels . truncation . truncateLength != defaultSettings . labels . truncation . truncateLength ) { finalObj . labels . truncation . truncateLength = allSettings . labels . truncation . truncateLength ; } } // tooltips var tooltipsDiff = allSettings . tooltips . enabled != defaultSettings . tooltips . enabled ; if ( tooltipsDiff ) { finalObj . tooltips = { enabled : allSettings . tooltips . enabled , type : \"placeholder\" , string : allSettings . tooltips . string } ; if ( allSettings . tooltips . styles . fadeInSpeed !== defaultSettings . tooltips . styles . fadeInSpeed ) { if ( ! finalObj . tooltips . hasOwnProperty ( \"styles\" ) ) { finalObj . tooltips . styles = { } ; } finalObj . tooltips . styles . fadeInSpeed = allSettings . tooltips . styles . fadeInSpeed ; } if ( allSettings . tooltips . styles . backgroundColor !== defaultSettings . tooltips . styles . backgroundColor ) { if ( ! finalObj . tooltips . hasOwnProperty ( \"styles\" ) ) { finalObj . tooltips . styles = { } ; } finalObj . tooltips . styles . backgroundColor = allSettings . tooltips . styles . backgroundColor ; } if ( allSettings . tooltips . styles . backgroundOpacity !== defaultSettings . tooltips . styles . backgroundOpacity ) { if ( ! finalObj . tooltips . hasOwnProperty ( \"styles\" ) ) { finalObj . tooltips . styles = { } ; } finalObj . tooltips . styles . backgroundOpacity = allSettings . tooltips . styles . backgroundOpacity ; } if ( allSettings . tooltips . styles . color !== defaultSettings . tooltips . styles . color ) { if ( ! finalObj . tooltips . hasOwnProperty ( \"styles\" ) ) { finalObj . tooltips . styles = { } ; } finalObj . tooltips . styles . color = allSettings . tooltips . styles . color ; } if ( allSettings . tooltips . styles . borderRadius !== defaultSettings . tooltips . styles . borderRadius ) { if ( ! finalObj . tooltips . hasOwnProperty ( \"styles\" ) ) { finalObj . tooltips . styles = { } ; } finalObj . tooltips . styles . borderRadius = allSettings . tooltips . styles . borderRadius ; } if ( allSettings . tooltips . styles . font !== defaultSettings . tooltips . styles . font ) { if ( ! finalObj . tooltips . hasOwnProperty ( \"styles\" ) ) { finalObj . tooltips . styles = { } ; } finalObj . tooltips . styles . font = allSettings . tooltips . styles . font ; } if ( allSettings . tooltips . styles . fontSize !== defaultSettings . tooltips . styles . fontSize ) { if ( ! finalObj . tooltips . hasOwnProperty ( \"styles\" ) ) { finalObj . tooltips . styles = { } ; } finalObj . tooltips . styles . fontSize = allSettings . tooltips . styles . fontSize ; } if ( allSettings . tooltips . styles . padding !== defaultSettings . tooltips . styles . padding ) { if ( ! finalObj . tooltips . hasOwnProperty ( \"styles\" ) ) { finalObj . tooltips . styles = { } ; } finalObj . tooltips . styles . padding = allSettings . tooltips . styles . padding ; } } // effects var effectsLoadDiff = allSettings . effects . load . effect != defaultSettings . effects . load . effect ; var effectsSpeedDiff = allSettings . effects . load . speed != defaultSettings . effects . load . speed ; if ( effectsLoadDiff || effectsSpeedDiff ) { if ( ! finalObj . hasOwnProperty ( \"effects\" ) ) { finalObj . effects = { } ; } finalObj . effects . load = { } ; if ( effectsLoadDiff ) { finalObj . effects . load . effect = allSettings . effects . load . effect ; } if ( effectsSpeedDiff ) { finalObj . effects . load . speed = parseInt ( allSettings . effects . load . speed , 10 ) ; } } var effectsPullOutDiff = allSettings . effects . pullOutSegmentOnClick . effect != defaultSettings . effects . pullOutSegmentOnClick . effect ; var effectsPullOutSpeedDiff = allSettings . effects . pullOutSegmentOnClick . speed != defaultSettings . effects . pullOutSegmentOnClick . speed ; var effectsPullOutSizeDiff = allSettings . effects . pullOutSegmentOnClick . size != defaultSettings . effects . pullOutSegmentOnClick . size ; if ( effectsPullOutDiff || effectsPullOutSpeedDiff || effectsPullOutSizeDiff ) { if ( ! finalObj . hasOwnProperty ( \"effects\" ) ) { finalObj . effects = { } ; } finalObj . effects . pullOutSegmentOnClick = { } ; if ( effectsPullOutDiff ) { finalObj . effects . pullOutSegmentOnClick . effect = allSettings . effects . pullOutSegmentOnClick . effect ; } if ( effectsPullOutSpeedDiff ) { finalObj . effects . pullOutSegmentOnClick . speed = parseInt ( allSettings . effects . pullOutSegmentOnClick . speed , 10 ) ; } if ( effectsPullOutSizeDiff ) { finalObj . effects . pullOutSegmentOnClick . size = parseInt ( allSettings . effects . pullOutSegmentOnClick . size , 10 ) ; } } if ( allSettings . effects . highlightSegmentOnMouseover != defaultSettings . effects . highlightSegmentOnMouseover ) { if ( ! finalObj . hasOwnProperty ( \"effects\" ) ) { finalObj . effects = { } ; } finalObj . effects . highlightSegmentOnMouseover = allSettings . effects . highlightSegmentOnMouseover ; if ( allSettings . effects . highlightLuminosity != defaultSettings . effects . highlightLuminosity ) { finalObj . effects . highlightLuminosity = parseFloat ( allSettings . effects . highlightLuminosity , 10 ) ; } } // misc var miscColorBgDiff = allSettings . misc . colors . background != defaultSettings . misc . colors . background ; // N.B. It's not possible in the generator to generate the misc.colors.segments property. This is missing on purpose. var miscSegmentStrokeDiff = allSettings . misc . colors . segmentStroke != defaultSettings . misc . colors . segmentStroke ; if ( miscColorBgDiff || miscSegmentStrokeDiff ) { if ( ! finalObj . hasOwnProperty ( \"misc\" ) ) { finalObj . misc = { } ; } finalObj . misc . colors = { } ; if ( miscColorBgDiff ) { finalObj . misc . colors . background = allSettings . misc . colors . background ; } if ( miscSegmentStrokeDiff ) { finalObj . misc . colors . segmentStroke = allSettings . misc . colors . segmentStroke ; } } var gradientEnabledDiff = allSettings . misc . gradient . enabled != defaultSettings . misc . gradient . enabled ; if ( gradientEnabledDiff ) { if ( ! finalObj . hasOwnProperty ( \"misc\" ) ) { finalObj . misc = { } ; } finalObj . misc . gradient = { enabled : true } ; var gradientPercentageDiff = allSettings . misc . gradient . percentage != defaultSettings . misc . gradient . percentage ; var gradientColorDiff = allSettings . misc . gradient . color != defaultSettings . misc . gradient . color ; if ( gradientPercentageDiff ) { finalObj . misc . gradient . percentage = parseInt ( allSettings . misc . gradient . percentage , 10 ) ; } if ( gradientColorDiff ) { finalObj . misc . gradient . color = allSettings . misc . gradient . color ; } } var canvasPaddingTopDiff = allSettings . misc . canvasPadding . top != defaultSettings . misc . canvasPadding . top ; var canvasPaddingRightDiff = allSettings . misc . canvasPadding . right != defaultSettings . misc . canvasPadding . right ; var canvasPaddingBottomDiff = allSettings . misc . canvasPadding . bottom != defaultSettings . misc . canvasPadding . bottom ; var canvasPaddingLeftDiff = allSettings . misc . canvasPadding . left != defaultSettings . misc . canvasPadding . left ; if ( canvasPaddingTopDiff || canvasPaddingRightDiff || canvasPaddingBottomDiff || canvasPaddingLeftDiff ) { if ( ! finalObj . hasOwnProperty ( \"misc\" ) ) { finalObj . misc = { } ; } finalObj . misc . canvasPadding = { } ; if ( canvasPaddingTopDiff ) { finalObj . misc . canvasPadding . top = parseInt ( allSettings . misc . canvasPadding . top , 10 ) ; } if ( canvasPaddingRightDiff ) { finalObj . misc . canvasPadding . right = parseInt ( allSettings . misc . canvasPadding . right , 10 ) ; } if ( canvasPaddingBottomDiff ) { finalObj . misc . canvasPadding . bottom = parseInt ( allSettings . misc . canvasPadding . bottom , 10 ) ; } if ( canvasPaddingTopDiff ) { finalObj . misc . canvasPadding . left = parseInt ( allSettings . misc . canvasPadding . left , 10 ) ; } } var pieCenterOffsetXDiff = allSettings . misc . pieCenterOffset . x != defaultSettings . misc . pieCenterOffset . x ; var pieCenterOffsetYDiff = allSettings . misc . pieCenterOffset . y != defaultSettings . misc . pieCenterOffset . y ; if ( pieCenterOffsetXDiff || pieCenterOffsetYDiff ) { if ( ! finalObj . hasOwnProperty ( \"misc\" ) ) { finalObj . misc = { } ; } finalObj . misc . pieCenterOffset = { } ; if ( pieCenterOffsetXDiff ) { finalObj . misc . pieCenterOffset . x = parseInt ( allSettings . misc . pieCenterOffset . x , 10 ) ; } if ( pieCenterOffsetYDiff ) { finalObj . misc . pieCenterOffset . y = parseInt ( allSettings . misc . pieCenterOffset . y , 10 ) ; } } var miscPrefixDiff = allSettings . misc . cssPrefix != defaultSettings . misc . cssPrefix ; if ( miscPrefixDiff ) { if ( ! finalObj . hasOwnProperty ( \"misc\" ) ) { finalObj . misc = { } ; } finalObj . misc . cssPrefix = allSettings . misc . cssPrefix ; } var callbackOnloadDiff = allSettings . callbacks . onload != defaultSettings . callbacks . onload ; var callbackOnmouseoverDiff = allSettings . callbacks . onMouseoverSegment != defaultSettings . callbacks . onMouseoverSegment ; var callbackOnmouseoutDiff = allSettings . callbacks . onMouseoutSegment != defaultSettings . callbacks . onMouseoutSegment ; var callbackOnclickDiff = allSettings . callbacks . onClickSegment != defaultSettings . callbacks . onClickSegment ; if ( callbackOnloadDiff || callbackOnmouseoverDiff || callbackOnmouseoutDiff || callbackOnclickDiff ) { finalObj . callbacks = { } ; if ( callbackOnloadDiff ) { finalObj . callbacks . onload = allSettings . callbacks . onload ; } if ( callbackOnloadDiff ) { finalObj . callbacks . onMouseoverSegment = allSettings . callbacks . onMouseoverSegment ; } if ( callbackOnloadDiff ) { finalObj . callbacks . onMouseoutSegment = allSettings . callbacks . onMouseoutSegment ; } if ( callbackOnloadDiff ) { finalObj . callbacks . onClickSegment = allSettings . callbacks . onClickSegment ; } } return finalObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Our initialization function . Called on page load . [CODESPLIT] function ( ) { _addTabEventHandlers ( ) ; var config = { hideMainContent : false } ; if ( document . location . hash === \"#generator-result\" ) { config = { hideMainContent : true } } $ ( \"#generator\" ) . html ( generatorPageTemplate ( config ) ) ; // now fade in the three sections: nav, main content & footer row $ ( \"#generatorTabs,#mainContent,#footerRow\" ) . hide ( ) . removeClass ( \"hidden\" ) . fadeIn ( 400 ) ; // always initialize the sidebar with whatever's in the selected example (always first item right now) var index = pageHelper . getDemoPieChartIndex ( EXAMPLE_PIES ) ; _loadDemoPie ( EXAMPLE_PIES [ index ] ) ; // focus on the title field, just to be nice $ ( \"#pieTitle\" ) . focus ( ) ; var subscriptions = { } ; subscriptions [ C . EVENT . DEMO_PIE . LOAD ] = _onRequestLoadDemoPie ; subscriptions [ C . EVENT . DEMO_PIE . RENDER . NO_ANIMATION ] = _renderWithNoAnimation ; subscriptions [ C . EVENT . DEMO_PIE . RENDER . WITH_ANIMATION ] = _renderWithAnimation ; subscriptions [ C . EVENT . DEMO_PIE . RENDER . UPDATE_PROP ] = _updateProperty ; subscriptions [ C . EVENT . DEMO_PIE . SELECT_SEGMENT ] = _selectPieSegment ; subscriptions [ C . EVENT . PAGE . LOAD ] = _onPageSelected ; subscriptions [ C . EVENT . PAGE . RESIZE ] = _onPageResize ; mediator . subscribe ( _MODULE_ID , subscriptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the generator fields and get the latest values . [CODESPLIT] function ( ) { return { header : titleTab . getTabData ( ) , footer : footerTab . getTabData ( ) , size : sizeTab . getTabData ( ) , data : dataTab . getTabData ( ) , labels : labelsTab . getTabData ( ) , tooltips : tooltipsTab . getTabData ( ) , effects : effectsTab . getTabData ( ) , callbacks : eventsTab . getTabData ( ) , misc : miscTab . getTabData ( ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bloody awful function! This is called whenever the page / tab is changed . It got way out of control . Nav should be moved to a single top - level area . [CODESPLIT] function ( msg ) { if ( ! _firstPageLoaded ) { if ( msg . data . pageHash !== \"generator-result\" ) { _firstPage = msg . data . page ; } _firstPageLoaded = true ; } if ( msg . data . page !== \"generator\" ) { return ; } var pageHash = msg . data . pageHash ; var tab = ( _currentTab ) ? _currentTab : \"generator-start\" ; if ( $ . inArray ( pageHash , _tabs ) !== - 1 ) { tab = pageHash ; } if ( pageHash === \"generator-result\" ) { _sendDemoPieData ( ) ; $ ( \"#sidebar,#pieChartDiv\" ) . addClass ( \"fadeOut\" ) ; setTimeout ( function ( ) { $ ( \"#sidebar,#pieChartDiv\" ) . addClass ( \"hidden\" ) . removeClass ( \"fadeOut\" ) ; $ ( \"#generator-result\" ) . removeClass ( \"hidden fadeOut\" ) . addClass ( \"fadeIn\" ) ; } , C . OTHER . PAGE_LOAD_SPEED ) ; } else if ( pageHash === \"generator\" && tab === \"generator-result\" ) { // do nothing. This happens when a user's on the generator-result tab, goes to // another page (not tab), then clicks back to the generator tab } else { // if the previous tab was generator-result if ( _currentTab === \"generator-result\" ) { $ ( \"#generator-result\" ) . addClass ( \"fadeOut\" ) ; setTimeout ( function ( ) { $ ( \"#generator-result\" ) . addClass ( \"hidden\" ) . removeClass ( \"fadeOut\" ) ; _renderWithNoAnimation ( ) ; $ ( \"#sidebar,#pieChartDiv\" ) . removeClass ( \"hidden fadeOut\" ) . addClass ( \"fadeIn\" ) ; } , C . OTHER . PAGE_LOAD_SPEED ) ; } } if ( msg . data . pageHash . match ( / pie\\d$ / ) ) { var index = pageHelper . getDemoPieChartIndex ( EXAMPLE_PIES ) ; _loadDemoPie ( EXAMPLE_PIES [ index ] ) ; } var $generatorTabs = $ ( \"#generatorTabs\" ) ; // now show the appropriate tab if ( _currentTab === null ) { $generatorTabs . find ( \"a[href=#\" + tab + \"]\" ) . closest ( \"li\" ) . addClass ( \"active\" ) ; $ ( \"#\" + tab ) . removeClass ( \"fadeOut hidden\" ) . addClass ( \"fadeIn\" ) ; _renderWithAnimation ( ) ; } else { $generatorTabs . find ( \"a[href=#\" + _currentTab + \"]\" ) . closest ( \"li\" ) . removeClass ( \"active\" ) ; $generatorTabs . find ( \"a[href=#\" + tab + \"]\" ) . closest ( \"li\" ) . addClass ( \"active\" ) ; $ ( \"#\" + _currentTab ) . removeClass ( \"hidden fadeIn\" ) . addClass ( \"fadeOut\" ) ; // another klutzy workaround if ( pageHash === \"generator\" && tab === \"generator-result\" ) { $ ( \"#\" + tab ) . removeClass ( \"hidden fadeOut\" ) ; } else { ( function ( ct ) { setTimeout ( function ( ) { $ ( \"#\" + ct ) . addClass ( \"hidden\" ) . removeClass ( \"fadeOut\" ) ; $ ( \"#\" + tab ) . removeClass ( \"hidden fadeOut\" ) . addClass ( \"fadeIn\" ) ; } , C . OTHER . PAGE_LOAD_SPEED ) ; } ) ( _currentTab ) ; } } _currentTab = tab ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return options . prop if obj . prop is undefined otherwise return obj . prop [CODESPLIT] function getOrDef ( obj , prop ) { return obj [ prop ] === undefined ? options [ prop ] : obj [ prop ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process function / object event handler [CODESPLIT] function triggerEvent ( event , $el ) { var handler = options [ 'on' + event ] ; if ( handler ) { if ( $isFunction ( handler ) ) { handler . call ( $el [ 0 ] ) ; } else { if ( handler . addClass ) { $el . addClass ( handler . addClass ) ; } if ( handler . removeClass ) { $el . removeClass ( handler . removeClass ) ; } } } $el . trigger ( 'lazy' + event , [ $el ] ) ; // queue next check as images may be resized after loading of actual file queueCheckLazyElements ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load visible elements [CODESPLIT] function checkLazyElements ( force ) { if ( ! elements . length ) { return ; } force = force || options . forceLoad ; topLazy = Infinity ; var viewportTop = scrollTop ( ) , viewportHeight = window . innerHeight || docElement . clientHeight , viewportWidth = window . innerWidth || docElement . clientWidth , i , length ; for ( i = 0 , length = elements . length ; i < length ; i ++ ) { var $el = elements [ i ] , el = $el [ 0 ] , objData = $el [ lazyLoadXT ] , removeNode = false , visible = force || $data ( el , dataLazied ) < 0 , topEdge ; // remove items that are not in DOM if ( ! $ . contains ( docElement , el ) ) { removeNode = true ; } else if ( force || ! objData . visibleOnly || el . offsetWidth || el . offsetHeight ) { if ( ! visible ) { var elPos = el . getBoundingClientRect ( ) , edgeX = objData . edgeX , edgeY = objData . edgeY ; topEdge = ( elPos . top + viewportTop - edgeY ) - viewportHeight ; visible = ( topEdge <= viewportTop && elPos . bottom > - edgeY && elPos . left <= viewportWidth + edgeX && elPos . right > - edgeX ) ; } if ( visible ) { $el . on ( load_error , triggerLoadOrError ) ; triggerEvent ( 'show' , $el ) ; var srcAttr = objData . srcAttr , src = $isFunction ( srcAttr ) ? srcAttr ( $el ) : el . getAttribute ( srcAttr ) ; if ( src ) { el . src = src ; } removeNode = true ; } else { if ( topEdge < topLazy ) { topLazy = topEdge ; } } } if ( removeNode ) { $data ( el , dataLazied , 0 ) ; elements . splice ( i -- , 1 ) ; length -- ; } } if ( ! length ) { triggerEvent ( 'complete' , $ ( docElement ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queue check of lazy elements because of event e [CODESPLIT] function queueCheckLazyElements ( e ) { if ( ! elements . length ) { return ; } // fast check for scroll event without new visible elements if ( e && e . type === 'scroll' && e . currentTarget === window ) { if ( topLazy >= scrollTop ( ) ) { return ; } } if ( ! waitingMode ) { setTimeout ( timeoutLazyElements , 0 ) ; } waitingMode = 2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save visible viewport boundary to viewportXXX variables [CODESPLIT] function calcViewport ( ) { var scrollTop = $window . scrollTop ( ) , scrollLeft = window . pageXOffset || 0 , edgeX = options . edgeX , edgeY = options . edgeY ; viewportTop = scrollTop - edgeY ; viewportBottom = scrollTop + ( window . innerHeight || $window . height ( ) ) + edgeY ; viewportLeft = scrollLeft - edgeX ; viewportRight = scrollLeft + ( window . innerWidth || $window . width ( ) ) + edgeX ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load visible elements [CODESPLIT] function checkLazyElements ( ) { if ( ! elements . length ) { return ; } topLazy = Infinity ; calcViewport ( ) ; var i = elements . length - 1 , srcAttr = options . srcAttr ; for ( ; i >= 0 ; i -- ) { var $el = elements [ i ] , el = $el [ 0 ] ; // remove items that are not in DOM if ( ! $ . contains ( document . documentElement , el ) ) { elements . splice ( i , 1 ) ; } else if ( ! options . visibleOnly || el . offsetWidth > 0 || el . offsetHeight > 0 ) { var offset = $el . offset ( ) , elTop = offset . top , elLeft = offset . left ; if ( ( elTop < viewportBottom ) && ( elTop + $el . height ( ) > viewportTop ) && ( elLeft < viewportRight ) && ( elLeft + $el . width ( ) > viewportLeft ) ) { var src = $el . attr ( srcAttr ) ; if ( src ) { el . src = src ; } elements . splice ( i , 1 ) ; } else { if ( elTop < topLazy ) { topLazy = elTop ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queue check of lazy elements because of event e [CODESPLIT] function queueCheckLazyElements ( e ) { if ( ! elements . length ) { return ; } // fast check for scroll event without new visible elements if ( e && e . type === 'scroll' ) { calcViewport ( ) ; if ( topLazy >= viewportBottom ) { return ; } } if ( ! waitingMode ) { setTimeout ( timeoutLazyElements , 0 ) ; } waitingMode = 2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the release version in GitHub compare it with the installed version and notify the user if a new version is available . [CODESPLIT] function checkVersion ( ) { var nextVersionCheckTimestamp = parseInt ( Cookies . get ( 'nextVersionCheckTimestamp' ) ) || 0 ; if ( ! nextVersionCheckTimestamp || ( Date . now ( ) >= nextVersionCheckTimestamp ) ) { $http . get ( '/api/build-info' ) . then ( function success ( res ) { var currentVersion = parseVersion ( res . data && res . data . version ) ; $http . get ( 'https://api.github.com/repos/mcdcorp/opentest/releases' ) . then ( function success ( res ) { var eightDaysLater = Date . now ( ) + ( 8 * 24 * 60 * 60 * 1000 ) ; Cookies . set ( 'nextVersionCheckTimestamp' , eightDaysLater ) ; var latestVersionStr = res . data && res . data [ 0 ] && res . data [ 0 ] . tag_name ; var latestVersionUrl = res . data && res . data [ 0 ] && res . data [ 0 ] . html_url ; var latestVersion = parseVersion ( latestVersionStr ) ; if ( latestVersion && ( compareVersions ( latestVersion , currentVersion ) === 1 ) ) { $ . notify ( { message : 'A new OpenTest version is now available: <a href=\"' + latestVersionUrl + '\" target=\"_blank\">' + latestVersionStr + '</a>. ' + 'You should always stay on the latest version to benefit from new features and security updates.' } , { type : 'info' , delay : 0 , placement : { from : 'bottom' } } ) } } , function error ( res ) { var oneHourLater = Date . now ( ) + ( 60 * 60 * 1000 ) ; Cookies . set ( 'nextVersionCheckTimestamp' , oneHourLater ) ; } ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a semantic version string into an array of three integers . [CODESPLIT] function parseVersion ( versionString ) { if ( typeof versionString !== 'string' ) { return null ; } var versionRegexMatch = versionString . match ( / v?(\\d+)\\.(\\d+)\\.(\\d+) / i ) ; if ( versionRegexMatch ) { return [ parseInt ( versionRegexMatch [ 1 ] ) , parseInt ( versionRegexMatch [ 2 ] ) , parseInt ( versionRegexMatch [ 3 ] ) ] ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a random string with the specified length by randomly selecting characters from the pool provided . If the character pool is not provided the default pool will contain all numbers and letters ( both uppercase and lowercase ) . Usage : $randomString ( 5 ) ; // 2U8cA $randomString ( 5 ABC123 ) ; // AB2AC [CODESPLIT] function $randomString ( length , characterPool ) { if ( typeof characterPool !== 'string' ) { characterPool = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\" ; } var text = \"\" ; for ( var i = 0 ; i < length ; i ++ ) { text += characterPool . charAt ( Math . floor ( Math . random ( ) * characterPool . length ) ) ; } return text ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create and return an array of integers . Usage : $range ( 5 3 ) ; // [ 5 6 7 ] $range ( 5 ) ; // [ 0 1 2 3 4 ] [CODESPLIT] function $range ( start , length ) { if ( arguments . length === 1 ) { length = arguments [ 0 ] ; start = 0 ; } return Array . apply ( null , Array ( length ) ) . map ( function ( _ , index ) { return index + start ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The list of valid characters is #x9 | #xA | #xD | [ #x20 - #xD7FF ] | [ #xE000 - #xFFFD ] | [ #x10000 - #x10FFFF ] [CODESPLIT] function removeInvalidXml ( str ) { return Array . from ( str ) . map ( c => { const cp = c . codePointAt ( 0 ) ; if ( cp >= 65536 && cp <= 1114111 ) { return c } else if ( c . match ( validXmlRegex ) ) { return c ; } else { return '' ; } } ) . join ( '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Module repesenting a Cell Accessor [CODESPLIT] function cellAccessor ( row1 , col1 , row2 , col2 , isMerged ) { let theseCells = new cellBlock ( ) ; theseCells . ws = this ; row2 = row2 ? row2 : row1 ; col2 = col2 ? col2 : col1 ; if ( row2 > this . lastUsedRow ) { this . lastUsedRow = row2 ; } if ( col2 > this . lastUsedCol ) { this . lastUsedCol = col2 ; } for ( let r = row1 ; r <= row2 ; r ++ ) { for ( let c = col1 ; c <= col2 ; c ++ ) { let ref = ` ${ utils . getExcelAlpha ( c ) } ${ r } ` ; if ( ! this . cells [ ref ] ) { this . cells [ ref ] = new Cell ( r , c ) ; } if ( ! this . rows [ r ] ) { this . rows [ r ] = new Row ( r , this ) ; } if ( this . rows [ r ] . cellRefs . indexOf ( ref ) < 0 ) { this . rows [ r ] . cellRefs . push ( ref ) ; } theseCells . cells . push ( this . cells [ ref ] ) ; theseCells . excelRefs . push ( ref ) ; } } if ( isMerged ) { theseCells . merged = true ; mergeCells ( theseCells ) ; } return theseCells ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "done ( err userExisted inviteExisted ) [CODESPLIT] function add ( project , email , accessLevel , inviter , done ) { User . findOne ( { email : email } , function ( err , user ) { if ( err ) { return done ( err ) ; } if ( user ) { var p = _ . find ( user . projects , function ( p ) { return p . name === project . toLowerCase ( ) ; } ) ; if ( p ) { return done ( 'user already a collaborator' , true ) ; } User . update ( { email : email } , { $push : { 'projects' : { name : project . toLowerCase ( ) , display_name : project , access_level : accessLevel } } } , function ( err ) { if ( err ) return done ( err , true ) ; done ( null , true ) ; } ) ; } else { var collaboration = { project : project , invited_by : inviter . _id , access_level : accessLevel } ; InviteCode . findOne ( { emailed_to : email , consumed_timestamp : null } , function ( err , invite ) { if ( err ) return done ( err ) ; if ( invite ) { return updateInvite ( invite , collaboration , done ) ; } sendInvite ( inviter , email , collaboration , done ) ; } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a sanitized listing of all projects along with the users who have access [CODESPLIT] function allProjects ( done ) { User . find ( { } , function ( err , users ) { if ( err ) return done ( err ) ; Project . find ( ) . sort ( { _id : - 1 } ) . exec ( function ( err , projects ) { if ( err ) return done ( err ) ; done ( null , projects . map ( function ( project ) { project = utils . sanitizeProject ( project ) ; project . created_date = utils . timeFromId ( project . _id ) ; project . users = [ ] ; for ( var i = 0 ; i < users . length ; i ++ ) { if ( 'undefined' !== typeof users [ i ] . projects [ project . name ] ) { project . users . push ( { email : users [ i ] . email , access : users [ i ] . projects [ project . name ] } ) ; } } return project ; } ) ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "main function . Get the config using rc [CODESPLIT] function getConfig ( ) { process . env = filterEnv ( deprecated ( process . env ) , envDefaults ) ; var rc = require ( 'rc' ) ( 'strider' , defaults ) ; if ( ! rc . smtp ) rc . smtp = smtp ( rc ) ; if ( ! rc . smtp ) rc . stubSmtp = true ; rc . ldap = getConfigByName ( 'ldap' ) ; addPlugins ( rc , process . env ) ; // BACK COMPAT until we get strider config into plugins... if ( hasGithub ) { rc . plugins . github = rc . plugins . github || { } ; rc . plugins . github . hostname = rc . server_name ; } debug ( rc ) ; return rc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter process . env . FOO to process . env . strider_foo for rc s benefit [CODESPLIT] function filterEnv ( env , defaults ) { var res = { } ; for ( var k in env ) { if ( defaults [ k . toLowerCase ( ) ] !== undefined ) { res [ ` ${ k . toLowerCase ( ) } ` ] = env [ k ] ; } else { res [ k ] = env [ k ] ; } } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "merge plugins from the DB with ones from strider . json . The latter overrides the former [CODESPLIT] function mergePlugins ( branch , sjson ) { if ( ! branch ) return sjson ; if ( ! sjson ) return branch ; // if strict_plugins is not turned on, we merge each plugin config instead of overwriting. var plugins = [ ] ; var pluginMap = { } ; for ( var pluginIndex = 0 ; pluginIndex < sjson . length ; pluginIndex ++ ) { plugins . push ( sjson [ pluginIndex ] ) ; pluginMap [ sjson [ pluginIndex ] . id ] = true ; } for ( var branchIndex = 0 ; branchIndex < branch . length ; branchIndex ++ ) { if ( ! pluginMap [ branch [ branchIndex ] . id ] ) plugins . push ( branch [ branchIndex ] ) ; } return plugins ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * GET / org / repo / [ job / : job_id ] - view latest build for repo [CODESPLIT] function multijob ( req , res ) { var type = req . accepts ( 'html' , 'json' , 'plain' ) ; switch ( type ) { case 'json' : return data ( req , res ) ; case 'plain' : return output ( req , res ) ; default : return html ( req , res ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Require a request parameter is present or return a 400 response . [CODESPLIT] function requireBody ( key , req , res ) { var val = req . body [ key ] ; if ( val === undefined ) { return res . status ( 400 ) . json ( { status : 'error' , errors : [ ` ${ key } ` ] } ) ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * loading all of the email templates at server start [CODESPLIT] function loadTemplates ( list , type ) { if ( ! list ) { return ; } var result = { } ; type = type || 'plaintext' ; list . forEach ( function ( name ) { var templatePath = path . join ( templateBasePath , type , ` ${ name } ` ) ; result [ name ] = renderPug ( templatePath ) ; } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate func for string template names [CODESPLIT] function registerTemplate ( name , template , dir ) { cache [ name ] = function ( context , cb ) { if ( / \\.html$ / . test ( template ) ) { dir = dir || '.' ; template = fs . readFileSync ( path . join ( dir , template ) , 'utf8' ) ; } cb ( null , template ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This generates a generator that will render the appropriate block in a form suitable for async . parallel . [CODESPLIT] function getPluginTemplate ( name , context ) { return function ( cb ) { if ( cache [ name ] ) { cache [ name ] ( context , function ( err , res ) { if ( err ) return cb ( err ) ; cb ( null , [ name , res ] ) ; } ) ; } else { cb ( null , null ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Express 3 Template Engine [CODESPLIT] function engine ( path , options , fn ) { options . filename = path ; fs . readFile ( path , 'utf8' , function ( err , str ) { if ( err ) return fn ( err ) ; engine . render ( str , options , fn ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * websockets . init () [CODESPLIT] function UserSockets ( sio , sessionStore ) { this . sio = sio ; this . sockets = { } ; this . sessionStore = sessionStore ; //sio.enable('browser client minification');  // send minified client //sio.enable('browser client etag');          // apply etag caching logic based on version number //sio.enable('browser client gzip'); //sio.set('log level', 1); //sio.set('authorization', authorize.bind(this, sessionStore)) sio . use ( authorize . bind ( this , sessionStore ) ) ; sio . sockets . on ( 'connection' , this . connected . bind ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- > true if the socket was found and removed . false if it wasn t found [CODESPLIT] function ( uid , socket ) { var socks = this . sockets [ uid ] ; if ( ! socks ) return false ; return socks . remove ( socket ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "socket callback . Adds a new socket [CODESPLIT] function ( socket ) { var session = socket . handshake . session ; if ( session && session . passport ) { this . addSocket ( session . passport . user , socket ) ; } else { console . debug ( 'Websocket connection does not have authorization - nothing to do.' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "send a message to a number of users send ( [ uid uid ... ] arguments ) [CODESPLIT] function ( users , args ) { for ( var i = 0 ; i < users . length ; i ++ ) { if ( ! this . sockets [ users [ i ] ] ) continue ; this . sockets [ users [ i ] ] . emit ( args ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "send a message to a number of users running callback to get args send ( [ uid uid ... ] callback ) [CODESPLIT] function ( users , fn ) { for ( var i = 0 ; i < users . length ; i ++ ) { if ( ! this . sockets [ users [ i ] ] || ! this . sockets [ users [ i ] ] . user ) continue ; this . sockets [ users [ i ] ] . emit ( fn ( this . sockets [ users [ i ] ] . user ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "send a public message - to all / but / the specified users [CODESPLIT] function ( users , args ) { for ( var id in this . sockets ) { if ( users . indexOf ( id ) !== - 1 ) continue ; this . sockets [ id ] . emit ( args ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "failed passed errored running submitted [CODESPLIT] function status ( job ) { if ( job . errored ) return 'errored' ; if ( ! job . started ) return 'submitted' ; if ( ! job . finished ) return 'running' ; if ( job . test_exitcode !== 0 ) return 'failed' ; if ( job . type !== TEST_ONLY && job . deploy_exitcode !== 0 ) return 'failed' ; return 'passed' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Events we care about : - job . new ( job access ) - job . done ( job access ) - browser . update ( event args access ) [CODESPLIT] function Dashboard ( socket , $scope ) { JobMonitor . call ( this , socket , $scope . $digest . bind ( $scope ) ) ; this . scope = $scope ; this . scope . loadingJobs = false ; this . scope . jobs = global . jobs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare the job for execution save to database and fire off a job . new event . [CODESPLIT] function prepareJob ( emitter , job ) { Project . findOne ( { name : job . project } ) . populate ( 'creator' ) . exec ( function ( err , project ) { if ( err || ! project ) return debug ( 'job.prepare - failed to get project' , job . project , err ) ; // ok so the project is real, we can go ahead and save this job var provider = common . extensions . provider [ project . provider . id ] ; if ( ! provider ) { return debug ( 'job.prepare - provider not found for project' , job . project , project . provider . id ) ; } Job . create ( job , function ( err , mjob ) { if ( err ) return debug ( 'job.prepare - failed to save job' , job , err ) ; var jjob = mjob . toJSON ( ) ; jjob . project = project ; jjob . providerConfig = project . provider . config ; jjob . fromStriderJson = true ; striderJson ( provider , project , job . ref , function ( err , config ) { if ( err ) { if ( err . status === 403 || err . statusCode === 403 ) { debug ( 'job.prepare - access to strider.json is forbidden, skipping config merge' ) ; config = { } ; jjob . fromStriderJson = false ; } else if ( err . status === 404 || err . statusCode === 404 ) { debug ( 'job.prepare - strider.json not found, skipping config merge' ) ; config = { } ; jjob . fromStriderJson = false ; } else { debug ( 'job.prepare - error opening/processing project\\'s `strider.json` file: ' , err ) ; config = { } ; jjob . fromStriderJson = false ; } } else { debug ( 'Using configuration from \"strider.json\".' ) ; } var branch = project . branch ( job . ref . branch || 'master' ) ; if ( ! branch ) { return debug ( 'job.prepare - branch not found' , job . ref . branch || 'master' , project . name ) ; } branch = branch . mirror_master ? project . branch ( 'master' ) : branch ; jjob . providerConfig = _ . extend ( { } , project . provider . config , config . provider || { } ) ; config . runner = config . runner || branch . runner ; if ( ! common . extensions . runner [ config . runner . id ] ) { debug ( ` ${ config . runner . id } ` ) ; } if ( config ) { delete config . provider ; config = utils . mergeConfigs ( branch , config ) ; } emitter . emit ( 'job.new' , jjob , config ) ; if ( ! mjob . runner ) mjob . runner = { } ; mjob . runner . id = config . runner . id ; mjob . save ( ) . then ( ( ) => debug ( 'job saved' ) ) . catch ( e => debug ( e ) ) ; } ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ project name event name [ list of arguments ]] [CODESPLIT] function ( project , event , args ) { if ( this . waiting [ project ] ) { return this . waiting [ project ] . push ( [ event , args ] ) ; } this . send ( project , event , args ) ; if ( event === 'job.status.started' ) { Job . findById ( args [ 0 ] , function ( err , job ) { if ( err ) return debug ( '[backchannel][job.status.started] error getting job' , args [ 0 ] , err ) ; if ( ! job ) return debug ( '[backchannel][job.status.started] job not found' , args [ 0 ] ) ; job . started = args [ 1 ] ; job . save ( ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 0 seconds && < 60 seconds Now 60 seconds 1 Minute > 60 seconds && < 60 minutes X Minutes 60 minutes 1 Hour > 60 minutes && < 24 hours X Hours 24 hours 1 Day > 24 hours && < 7 days X Days 7 days 1 Week > 7 days && < ~ 1 Month X Weeks ~ 1 Month 1 Month > ~ 1 Month && < 1 Year X Months 1 Year 1 Year > 1 Year X Years [CODESPLIT] function normalize ( val , single ) { var margin = 0.1 ; if ( val >= single && val <= single * ( 1 + margin ) ) { return single ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove attributes from a model [CODESPLIT] function killAttrs ( model , attrs ) { for ( var i = 0 ; i < attrs . length ; i ++ ) { delete model [ attrs [ i ] ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Custom middleware to save unparsed request body to req . content [CODESPLIT] function bodySetter ( req , res , next ) { if ( req . _post_body ) { return next ( ) ; } req . post_body = req . post_body || '' ; if ( 'POST' !== req . method ) { return next ( ) ; } req . _post_body = true ; req . on ( 'data' , function ( chunk ) { req . post_body += chunk ; } ) ; next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Require the specified req . body parameters or else return a 400 with a descriptive JSON body [CODESPLIT] function requireBody ( paramsList ) { return function ( req , res , next ) { var errors = [ ] ; var status = 'ok' ; for ( var i = 0 ; i < paramsList . length ; i ++ ) { var val = req . body [ paramsList [ i ] ] ; if ( ! val ) { errors . push ( ` \\` ${ paramsList [ i ] } \\` ` ) ; status = 'error' ; } } if ( errors . length === 0 ) { next ( ) ; } else { return res . status ( 400 ) . json ( { errors : errors , status : status } ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create helper function to get or set the provifer config . Expects req . project req . providerConfig function providerConfig () - > return the config providerConfig ( config next ( err )) . save the config For hosted providers the following function is also available accountConfig () - > return the account confi acountConfig ( config next ( err )) . save the account config [CODESPLIT] function projectProvider ( req , res , next ) { var project = req . project ; req . providerConfig = function ( config , next ) { if ( arguments . length === 0 ) { return project . provider . config ; } project . provider . config = config ; project . markModified ( 'provider' ) ; project . save ( next ) ; } ; // make this conditional? if ( project . provider . account ) { var account = project . creator . account ( project . provider . id , project . provider . account ) ; req . accountConfig = function ( config , next ) { if ( arguments . length === 0 ) { return account . config ; } account . config = config ; project . creator . markModified ( 'accounts' ) ; project . creator . save ( next ) ; } ; } next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get plugin config . Expects req . project Sets req . pluginConfig function pluginConfig () - > return the config pluginConfig ( config next ( err )) . save the config [CODESPLIT] function projectPlugin ( req , res , next ) { var pluginid ; // if only 3 args, then get pluginid from params \":plugin\" if ( arguments . length === 4 ) { pluginid = req ; req = res ; res = next ; next = arguments [ 3 ] ; } else { pluginid = req . params . plugin ; } var branch = req . project . branch ( req . query . branch ) ; var plugin = null ; if ( ! branch ) { return res . status ( 404 ) . send ( 'Specified branch not found for the project' ) ; } // if it's just mirroring master if ( branch . mirror_master ) { return res . status ( 400 ) . send ( 'Branch not individually configurable' ) ; } for ( var i = 0 ; i < branch . plugins . length ; i ++ ) { if ( branch . plugins [ i ] . id === pluginid ) { plugin = branch . plugins [ i ] ; break ; } } if ( plugin === null ) { return res . status ( 404 ) . send ( 'Plugin not enabled for the specified project' ) ; } req . pluginConfig = function ( config , next ) { if ( arguments . length === 0 ) { return plugin . config ; } plugin . config = config ; req . project . markModified ( 'branches' ) ; req . project . save ( function ( err ) { next ( err , config ) ; } ) ; } ; req . userConfig = function ( config , next ) { if ( ! req . user . isProjectCreator ) { if ( arguments . length === 0 ) { return false ; } return next ( new Error ( 'Current user is not the creator - cannot set the creator config' ) ) ; } if ( arguments . length === 0 ) { return req . project . creator . jobplugins [ pluginid ] ; } var schema = common . userConfigs . job && common . userConfigs . job [ pluginid ] ; if ( ! schema ) { return next ( new Error ( ` ${ pluginid } ` ) ) ; } config = utils . validateAgainstSchema ( config , schema ) ; // TODO: validation req . project . creator . jobplugins [ pluginid ] = config ; req . project . creator . markModified ( 'jobplugins' ) ; req . project . creator . save ( function ( err ) { next ( err , config ) ; } ) ; } ; next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "just link project but doesn t fail if there s no auth [CODESPLIT] function anonProject ( req , res , next ) { var name = ` ${ req . params . org } ${ req . params . repo } ` ; name = name . toLowerCase ( ) ; Project . findOne ( { name : name } ) . populate ( 'creator' ) . exec ( function ( err , project ) { if ( err ) { return res . status ( 500 ) . send ( { error : 'Failed to find project' , info : err } ) ; } if ( ! project ) { return res . status ( 404 ) . send ( 'Project not found' ) ; } if ( ! project . creator ) { return res . status ( 400 ) . send ( 'Project malformed; project creator user is missing.' ) ; } req . project = project ; req . accessLevel = User . projectAccessLevel ( req . user , project ) ; if ( req . user && project . creator ) { req . user . isProjectCreator = project . creator . _id . toString ( ) === req . user . _id . toString ( ) ; } next ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getProject Middleware assumes two url parameters : org and : repo and req . user checks user access level and sets the following properties on the request object . req . project = the project req . accessLevel = - 1 for no access 0 for public 1 for normal 2 for admin Errors : 404 : not found 401 : not public and you don t have access 500 : something strange happened w / the DB lookup [CODESPLIT] function project ( req , res , next ) { if ( req . params . org === 'auth' ) { return next ( ) ; } anonProject ( req , res , function ( ) { if ( req . accessLevel > - 1 ) { return next ( ) ; } if ( ! req . user ) { req . session . return_to = req . url ; return res . redirect ( '/login' ) ; } res . status ( 401 ) . send ( 'Not authorized' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render a plugin management web interface GET / admin / plugins [CODESPLIT] function ( req , res , next ) { getPluginList ( function ( err , list ) { if ( err ) return next ( err ) ; res . render ( 'admin/plugins.html' , { plugins : list } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change a plugin ( uninstall install upgrade ) PUT / admin / plugins [CODESPLIT] function ( req , res ) { pluginManager [ req . body . action ] ( req . body . id , function ( err ) { if ( err ) return res . status ( 500 ) . end ( err . message ) ; res . json ( { ok : 'restarting strider' } ) ; restart ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Require a logged in session [CODESPLIT] function requireUser ( req , res , next ) { if ( req . user ) { next ( ) ; } else { req . session . return_to = req . url ; res . redirect ( '/login' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Require admin privileges [CODESPLIT] function requireAdminOr401 ( req , res , next ) { if ( ! req . user || ! req . user [ 'account_level' ] || req . user . account_level < 1 ) { res . status ( 401 ) . send ( 'not authorized' ) ; } else { next ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Require the logged - in user to have admin access to the repository in the URI path . E . g . http : // striderapp . com / beyondfog / strider / latest_build [CODESPLIT] function requireProjectAdmin ( req , res , next ) { if ( ! req . project ) return res . status ( 404 ) . send ( 'Project not loaded' ) ; if ( ! req . user ) return res . status ( 401 ) . send ( 'No user' ) ; var isAdmin = req . user . account_level && req . user . account_level > 0 ; var notAuthed = ( ! req . accessLevel || req . accessLevel < 2 ) && ! isAdmin ; if ( notAuthed ) return res . status ( 401 ) . send ( 'Not authorized for configuring this project' ) ; next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Plugin block is the tag used to specify that the contents can be overridden by extensions . [CODESPLIT] function pluginBlock ( indent , parser ) { var template = this . args [ 0 ] ; var output = '' ; // Register that the template is needed, for 1st pass; output += ` ${ template } \\n ` ; // Generate code to see if pluginTemplates has block output += ` ${ template } \\n ` ; output += 'if (_pg){ ' ; output += '_output += _pg;' ; output += '} else {\\n' ; output += parser . compile . call ( this , ` ${ indent } ` ) ; output += '}\\n' ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Auth0 Angular e2e tests : [CODESPLIT] function findAnchorByContent ( content , cb ) { element . all ( by . css ( 'a' ) ) . then ( function ( anchors ) { anchors . forEach ( function ( anchor ) { anchor . getText ( ) . then ( function ( anchorText ) { if ( anchorText === content ) { cb ( anchor ) ; } } ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function ( fun ) { var ret = fun . toString ( ) ; ret = ret . substr ( 'function ' . length ) ; ret = ret . substr ( 0 , ret . indexOf ( '(' ) ) ; return ret ? ret . trim ( ) : ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function getInnerLibraryMethod ( name , libName ) { libName = libName || config . lib ; var library = innerAuth0libraryConfiguration [ libName ] . library ( ) ; return library [ innerAuth0libraryConfiguration [ libName ] [ name ] ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function getInnerLibraryConfigField ( name , libName ) { libName = libName || config . lib ; return innerAuth0libraryConfiguration [ libName ] [ name ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function constructorName ( fun ) { if ( fun ) { return { lib : authUtilsProvider . fnName ( fun ) , constructor : fun } ; } /* jshint ignore:start */ if ( null != window . Auth0Lock ) { return { lib : 'Auth0Lock' , constructor : window . Auth0Lock } ; } if ( null != window . Auth0 ) { return { lib : 'Auth0' , constructor : window . Auth0 } ; } if ( typeof Auth0Widget !== 'undefined' ) { throw new Error ( 'Auth0Widget is not supported with this version of auth0-angular' + 'anymore. Please try with an older one' ) ; } throw new Error ( 'Cannot initialize Auth0Angular. Auth0Lock or Auth0 must be available' ) ; /* jshint ignore:end */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SignIn [CODESPLIT] function ( idToken , accessToken , state , refreshToken , profile , isRefresh ) { idToken = idToken || ( profile ? profile . idToken : null ) ; accessToken = accessToken || ( profile ? profile . accessToken : null ) ; state = state || ( profile ? profile . state : null ) ; refreshToken = refreshToken || ( profile ? profile . refreshToken : null ) ; var profilePromise = auth . getProfile ( idToken ) ; var response = { idToken : idToken , accessToken : accessToken , state : state , refreshToken : refreshToken , profile : profile , isAuthenticated : true } ; $rootScope . isAuthenticated = true ; angular . extend ( auth , response ) ; callHandler ( ! isRefresh ? 'loginSuccess' : 'authenticated' , angular . extend ( { profilePromise : profilePromise } , response ) ) ; return profilePromise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * jshint latedef : nofunc [CODESPLIT] function verifyRoute ( requiresLogin , e , getState , redirectToLogin ) { if ( ! auth . isAuthenticated && ! auth . refreshTokenPromise ) { if ( config . sso ) { if ( requiresLogin ) { e . preventDefault ( ) ; } config . auth0js . getSSOData ( authUtils . applied ( function ( err , ssoData ) { if ( ssoData . sso ) { var loginOptions = { popup : false , callbackOnLocationHash : true , connection : ssoData . lastUsedConnection . name , authParams : { state : getState ( ) } } ; callHandler ( 'ssoLogin' , { loginOptions : loginOptions } ) ; auth . signin ( loginOptions , null , null , 'Auth0' ) ; } else if ( requiresLogin ) { e . preventDefault ( ) ; redirectToLogin ( ) ; } } ) ) ; } else if ( requiresLogin ) { e . preventDefault ( ) ; redirectToLogin ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Helpers [CODESPLIT] function string_of_enum ( e , value ) { for ( var k in e ) if ( e [ k ] == value ) return k ; return \"Unknown(\" + value + \")\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Boards [CODESPLIT] function ( ) { this . init = function ( blynk ) { } ; this . process = function ( values ) { switch ( values [ 0 ] ) { case 'pm' : return true ; case 'dw' : case 'dr' : case 'aw' : case 'ar' : console . log ( \"No direct pin operations available.\" ) ; console . log ( \"Maybe you need to install mraa or onoff modules?\" ) ; return true ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Blynk [CODESPLIT] function ( auth , options ) { var self = this ; if ( needsEmitter ( ) ) { events . EventEmitter . call ( this ) ; } this . auth = auth ; var options = options || { } ; this . heartbeat = options . heartbeat || 10000 ; console . log ( \"\\n\\\n    ___  __          __\\n\\\n   / _ )/ /_ _____  / /__\\n\\\n  / _  / / // / _ \\\\/  '_/\\n\\\n /____/_/\\\\_, /_//_/_/\\\\_\\\\\\n\\\n        /___/\\n\\\n\\n\\\n  Give Blynk a Github star! => https://github.com/vshymanskyy/blynk-library-js\\n\\\n\" ) ; // Auto-detect board if ( options . board ) { this . board = options . board ; } else if ( isEspruino ( ) ) { this . board = new BoardEspruinoPico ( ) ; } else if ( isBrowser ( ) ) { this . board = new BoardDummy ( ) ; } else { [ bl_node . BoardMRAA , bl_node . BoardOnOff , BoardDummy ] . some ( function ( b ) { try { self . board = new b ( ) ; return true ; } catch ( e ) { return false ; } } ) ; } self . board . init ( self ) ; // Auto-detect connector if ( options . connector ) { this . conn = options . connector ; } else if ( isEspruino ( ) ) { this . conn = new EspruinoTCP ( options ) ; } else if ( isBrowser ( ) ) { this . conn = new bl_browser . WsClient ( options ) ; } else { this . conn = new bl_node . SslClient ( options ) ; } this . buff_in = '' ; this . msg_id = 1 ; this . vpins = [ ] ; this . profile = options . profile ; this . VirtualPin = function ( vPin ) { if ( needsEmitter ( ) ) { events . EventEmitter . call ( this ) ; } this . pin = vPin ; self . vpins [ vPin ] = this ; this . write = function ( value ) { self . virtualWrite ( this . pin , value ) ; } ; } ; this . WidgetBridge = function ( vPin ) { this . pin = vPin ; this . setAuthToken = function ( token ) { self . sendMsg ( MsgType . BRIDGE , [ this . pin , 'i' , token ] ) ; } ; this . digitalWrite = function ( pin , val ) { self . sendMsg ( MsgType . BRIDGE , [ this . pin , 'dw' , pin , val ] ) ; } ; this . analogWrite = function ( pin , val ) { self . sendMsg ( MsgType . BRIDGE , [ this . pin , 'aw' , pin , val ] ) ; } ; this . virtualWrite = function ( pin , val ) { self . sendMsg ( MsgType . BRIDGE , [ this . pin , 'vw' , pin ] . concat ( val ) ) ; } ; } ; this . WidgetTerminal = function ( vPin ) { if ( needsEmitter ( ) ) { events . EventEmitter . call ( this ) ; } this . pin = vPin ; self . vpins [ vPin ] = this ; this . write = function ( data ) { self . virtualWrite ( this . pin , data ) ; } ; } ; this . WidgetLCD = function ( vPin ) { this . pin = vPin ; this . clear = function ( ) { self . virtualWrite ( this . pin , 'clr' ) ; } ; this . print = function ( x , y , val ) { self . sendMsg ( MsgType . HW , [ 'vw' , this . pin , 'p' , x , y , val ] ) ; } ; } ; this . WidgetTable = function ( vPin ) { this . pin = vPin ; this . clear = function ( ) { self . virtualWrite ( this . pin , 'clr' ) ; } ; this . add_row = function ( id , name , value ) { self . virtualWrite ( this . pin , [ 'add' , id , name , value ] ) ; } ; this . update_row = function ( id , name , value ) { self . virtualWrite ( this . pin , [ 'update' , id , name , value ] ) ; } ; this . highlight_row = function ( id ) { self . virtualWrite ( this . pin , [ 'pick' , id ] ) ; } ; this . select_row = function ( id ) { self . virtualWrite ( this . pin , [ 'select' , id ] ) ; } ; this . deselect_row = function ( id ) { self . virtualWrite ( this . pin , [ 'deselect' , id ] ) ; } ; this . move_row = function ( old_row , new_row ) { self . virtualWrite ( this . pin , [ 'order' , old_row , new_row ] ) ; } ; } ; this . WidgetLED = function ( vPin ) { this . pin = vPin ; this . setValue = function ( val ) { self . virtualWrite ( this . pin , val ) ; } ; this . turnOn = function ( ) { self . virtualWrite ( this . pin , 255 ) ; } ; this . turnOff = function ( ) { self . virtualWrite ( this . pin , 0 ) ; } ; } ; this . WidgetMAP = function ( vPin ) { this . pin = vPin ; this . location = function ( index , lat , lon , value ) { var locationdata = [ index , lat , lon , value ] self . virtualWrite ( this . pin , locationdata ) ; } } ; if ( needsEmitter ( ) ) { util . inherits ( this . VirtualPin , events . EventEmitter ) ; util . inherits ( this . WidgetBridge , events . EventEmitter ) ; util . inherits ( this . WidgetTerminal , events . EventEmitter ) ; } if ( ! options . skip_connect ) { this . connect ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Blynk [CODESPLIT] function ( auth , options ) { var self = this ; this . auth = auth ; var options = options || { } ; this . heartbeat = options . heartbeat || 10000 ; // Auto-detect board if ( options . board ) { this . board = options . board ; } else { this . board = new BoardEspruino ( ) ; } self . board . init ( self ) ; // Auto-detect connector if ( options . connector ) { this . conn = options . connector ; } else { this . conn = new EspruinoTCP ( options ) ; } this . buff_in = '' ; this . msg_id = 1 ; this . vpins = [ ] ; this . profile = options . profile ; this . VirtualPin = function ( vPin ) { this . pin = vPin ; self . vpins [ vPin ] = this ; this . write = function ( value ) { self . virtualWrite ( this . pin , value ) ; } ; } ; this . WidgetBridge = function ( vPin ) { this . pin = vPin ; this . setAuthToken = function ( token ) { self . sendMsg ( MsgType . BRIDGE , [ this . pin , 'i' , token ] ) ; } ; this . digitalWrite = function ( pin , val ) { self . sendMsg ( MsgType . BRIDGE , [ this . pin , 'dw' , pin , val ] ) ; } ; this . analogWrite = function ( pin , val ) { self . sendMsg ( MsgType . BRIDGE , [ this . pin , 'aw' , pin , val ] ) ; } ; this . virtualWrite = function ( pin , val ) { self . sendMsg ( MsgType . BRIDGE , [ this . pin , 'vw' , pin ] . concat ( val ) ) ; } ; } ; this . WidgetTerminal = function ( vPin ) { if ( needsEmitter ( ) ) { events . EventEmitter . call ( this ) ; } this . pin = vPin ; self . vpins [ vPin ] = this ; this . write = function ( data ) { self . virtualWrite ( this . pin , data ) ; } ; } ; this . WidgetLCD = function ( vPin ) { this . pin = vPin ; this . clear = function ( ) { self . virtualWrite ( this . pin , 'clr' ) ; } ; this . print = function ( x , y , val ) { self . sendMsg ( MsgType . HW , [ 'vw' , this . pin , 'p' , x , y , val ] ) ; } ; } ; this . WidgetLED = function ( vPin ) { this . pin = vPin ; this . setValue = function ( val ) { self . virtualWrite ( this . pin , val ) ; } ; this . turnOn = function ( ) { self . virtualWrite ( this . pin , 255 ) ; } ; this . turnOff = function ( ) { self . virtualWrite ( this . pin , 0 ) ; } ; } ; if ( ! options . skip_connect ) { this . connect ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "internal functions // [CODESPLIT] function orphanedLibraries ( src , dst ) { // list all the libs that are not referenced from the main binary and their dependencies const orphan = [ ] ; for ( let lib of dst ) { if ( src . indexOf ( lib ) === - 1 ) { orphan . push ( lib ) ; } } return orphan ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return an array of strings with the absolute paths of the sub - apps found inside appdir [CODESPLIT] function _findNested ( d ) { let nested = [ ] ; walk . walkSync ( d , ( basedir , filename , stat ) => { const file = path . join ( basedir , filename ) ; if ( file . indexOf ( '.app/Info.plist' ) !== - 1 ) { const nest = file . lastIndexOf ( '.app/' ) ; nested . push ( file . substring ( 0 , nest + 4 ) ) ; } } ) ; return nested ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return a list of the libs that must be inside the app [CODESPLIT] function binAbsLibs ( file , o ) { try { return bin . enumerateLibraries ( file ) . filter ( ( l ) => { return ! ( l . startsWith ( '/' ) ) ; } ) . map ( ( l ) => { if ( l [ 0 ] === '@' ) { const ll = depSolver . resolvePath ( o . exe , file , l , o . libs ) ; if ( ll ) { l = ll ; } else { console . error ( 'Warning: Cannot resolve dependency library: ' + file ) ; } } return l ; } ) ; } catch ( e ) { console . error ( 'Warning: missing file:' , file ) ; return [ ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get all dependencies from appbin recursively [CODESPLIT] function _findLibraries ( appdir , appbin , disklibs ) { const exe = path . join ( appdir , appbin ) ; const o = { exe : exe , lib : exe , libs : disklibs } ; const libraries = [ ] ; const pending = [ exe ] ; while ( pending . length > 0 ) { const target = pending . pop ( ) ; if ( libraries . indexOf ( target ) === - 1 ) { libraries . push ( target ) ; } let res = binAbsLibs ( target , o ) ; const unexplored = res . filter ( l => libraries . indexOf ( l ) === - 1 ) ; pending . push ( ... unexplored . filter ( l => pending . indexOf ( l ) === - 1 ) ) ; libraries . push ( ... unexplored ) ; } return libraries ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ES7 is not yet here [CODESPLIT] function fix ( file , options , emit ) { const { appdir , bundleid , forceFamily , allowHttp } = options ; if ( ! file || ! appdir ) { throw new Error ( 'Invalid parameters for fixPlist' ) ; } let changed = false ; const data = plist . readFileSync ( file ) ; delete data [ '' ] ; if ( allowHttp ) { emit ( 'message' , 'Adding NSAllowArbitraryLoads' ) ; if ( ! Object . isObject ( data [ 'NSAppTransportSecurity' ] ) ) { data [ 'NSAppTransportSecurity' ] = { } ; } data [ 'NSAppTransportSecurity' ] [ 'NSAllowsArbitraryLoads' ] = true ; changed = true ; } if ( forceFamily ) { if ( performForceFamily ( data , emit ) ) { changed = true ; } } if ( bundleid ) { setBundleId ( data , bundleid ) ; changed = true ; } if ( changed ) { plist . writeFileSync ( file , data ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helper functions [CODESPLIT] function getResignedFilename ( input ) { if ( ! input ) { return null ; } const pos = input . lastIndexOf ( path . sep ) ; if ( pos !== - 1 ) { const tmp = input . substring ( pos + 1 ) ; const dot = tmp . lastIndexOf ( '.' ) ; input = ( dot !== - 1 ) ? tmp . substring ( 0 , dot ) : tmp ; } else { const dot = input . lastIndexOf ( '.' ) ; if ( dot !== - 1 ) { input = input . substring ( 0 , dot ) ; } } return input + '-resigned.ipa' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an accessor wrapped by error handling and args passing logic [CODESPLIT] function generateAccessor ( accessor ) { return function ( ) { let value = container [ varName ] if ( typeof value === 'undefined' ) { if ( typeof defValue === 'undefined' ) { // Need to return since no value is available. If a value needed to // be available required() should be called, or a default passed return } // Assign the default as the value since process.env does not contain // the desired variable value = defValue } if ( isBase64 ) { if ( ! value . match ( base64Regex ) ) { generateRaiseError ( value ) ( 'should be a valid base64 string if using convertFromBase64' ) } value = Buffer . from ( value , 'base64' ) . toString ( ) } const args = [ generateRaiseError ( value ) , value ] . concat ( Array . prototype . slice . call ( arguments ) ) return accessor . apply ( accessor , args ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures a variable is set in the given environment container . Throws an EnvVarError if the variable is not set or a default is not provided [CODESPLIT] function ( isRequired ) { if ( isRequired === false ) { return accessors } if ( typeof container [ varName ] === 'undefined' && typeof defValue === 'undefined' ) { throw new EnvVarError ( ` ${ varName } ` ) } return accessors }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取引用文本，当引用自身不存在的情况下，需要返回原来的模板字符串 [CODESPLIT] function getRefText ( ast ) { var ret = ast . leader ; var isFn = ast . args !== undefined ; if ( ast . type === 'macro_call' ) { ret = '#' ; } if ( ast . isWraped ) ret += '{' ; if ( isFn ) { ret += getMethodText ( ast ) ; } else { ret += ast . id ; } utils . forEach ( ast . path , function ( ref ) { //不支持method并且传递参数 if ( ref . type == 'method' ) { ret += '.' + getMethodText ( ref ) ; } else if ( ref . type == 'index' ) { var text = '' ; var id = ref . id ; if ( id . type === 'integer' ) { text = id . value ; } else if ( id . type === 'string' ) { var sign = id . isEval ? '\"' : \"'\" ; text = sign + id . value + sign ; } else { text = getRefText ( id ) ; } ret += '[' + text + ']' ; } else if ( ref . type == 'property' ) { ret += '.' + ref . id ; } } , this ) ; if ( ast . isWraped ) ret += '}' ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unicode转码 [CODESPLIT] function convert ( str ) { if ( typeof str !== 'string' ) return str ; var result = \"\" var escape = false var i , c , cstr ; for ( i = 0 ; i < str . length ; i ++ ) { c = str . charAt ( i ) ; if ( ( ' ' <= c && c <= '~' ) || ( c === '\\r' ) || ( c === '\\n' ) ) { if ( c === '&' ) { cstr = \"&amp;\" escape = true } else if ( c === '<' ) { cstr = \"&lt;\" escape = true } else if ( c === '>' ) { cstr = \"&gt;\" escape = true } else { cstr = c . toString ( ) } } else { cstr = \"&#\" + c . charCodeAt ( ) . toString ( ) + \";\" } result = result + cstr } return escape ? result : str }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "增加某些函数，不需要执行html转义 [CODESPLIT] function ( key ) { if ( ! utils . isArray ( key ) ) key = [ key ] utils . forEach ( key , function ( key ) { this . config . unescape [ key ] = true } , this ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "引用求值 [CODESPLIT] function ( ast , isVal ) { if ( ast . prue ) { var define = this . defines [ ast . id ] ; if ( utils . isArray ( define ) ) { return this . _render ( define ) ; } if ( ast . id in this . config . unescape ) ast . prue = false ; } var escape = this . config . escape ; var isSilent = this . silence || ast . leader === \"$!\" ; var isfn = ast . args !== undefined ; var context = this . context ; var ret = context [ ast . id ] ; var local = this . getLocal ( ast ) ; var text = Velocity . Helper . getRefText ( ast ) ; if ( text in context ) { return ( ast . prue && escape ) ? convert ( context [ text ] ) : context [ text ] ; } if ( ret !== undefined && isfn ) { ret = this . getPropMethod ( ast , context , ast ) ; } if ( local . isLocaled ) ret = local [ 'value' ] ; if ( ast . path ) { utils . some ( ast . path , function ( property , i , len ) { if ( ret === undefined ) { this . _throw ( ast , property ) ; } // 第三个参数，返回后面的参数ast ret = this . getAttributes ( property , ret , ast ) ; } , this ) ; } if ( isVal && ret === undefined ) { ret = isSilent ? '' : Velocity . Helper . getRefText ( ast ) ; } ret = ( ast . prue && escape ) ? convert ( ret ) : ret ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取局部变量，在macro和foreach循环中使用 [CODESPLIT] function ( ast ) { var id = ast . id ; var local = this . local ; var ret = false ; var isLocaled = utils . some ( this . conditions , function ( contextId ) { var _local = local [ contextId ] ; if ( id in _local ) { ret = _local [ id ] ; return true ; } return false ; } , this ) ; return { value : ret , isLocaled : isLocaled } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "$foo . bar 属性求值，最后面两个参数在用户传递的函数中用到 [CODESPLIT] function ( property , baseRef , ast ) { // fix #54 if ( baseRef === null || baseRef === undefined ) { return undefined ; } /**\n       * type对应着velocity.yy中的attribute，三种类型: method, index, property\n       */ var type = property . type ; var ret ; var id = property . id ; if ( type === 'method' ) { ret = this . getPropMethod ( property , baseRef , ast ) ; } else if ( type === 'property' ) { ret = baseRef [ id ] ; } else { ret = this . getPropIndex ( property , baseRef ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "$foo . bar [ 1 ] index求值 [CODESPLIT] function ( property , baseRef ) { var ast = property . id ; var key ; if ( ast . type === 'references' ) { key = this . getReferences ( ast ) ; } else if ( ast . type === 'integer' ) { key = ast . value ; } else { key = ast . value ; } return baseRef [ key ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "$foo . bar () 求值 [CODESPLIT] function ( property , baseRef , ast ) { var id = property . id ; var ret = '' ; // getter 处理 if ( id . indexOf ( 'get' ) === 0 && ! ( id in baseRef ) ) { if ( id . length === 3 ) { // get('address') ret = getter ( baseRef , this . getLiteral ( property . args [ 0 ] ) ) ; } else { // getAddress() ret = getter ( baseRef , id . slice ( 3 ) ) ; } return ret ; // setter 处理 } else if ( id . indexOf ( 'set' ) === 0 && ! baseRef [ id ] ) { baseRef [ id . slice ( 3 ) ] = this . getLiteral ( property . args [ 0 ] ) ; // $page.setName(123) baseRef . toString = function ( ) { return '' ; } ; return baseRef ; } else if ( id . indexOf ( 'is' ) === 0 && ! ( id in baseRef ) ) { return getter ( baseRef , id . slice ( 2 ) ) ; } else if ( id === 'keySet' && ! baseRef [ id ] ) { return utils . keys ( baseRef ) ; } else if ( id === 'entrySet' && ! baseRef [ id ] ) { ret = [ ] ; utils . forEach ( baseRef , function ( value , key ) { ret . push ( { key : key , value : value } ) ; } ) ; return ret ; } else if ( id === 'size' && ! baseRef [ id ] ) { return getSize ( baseRef ) ; } else if ( id === 'put' && ! baseRef [ id ] ) { return baseRef [ this . getLiteral ( property . args [ 0 ] ) ] = this . getLiteral ( property . args [ 1 ] ) ; } else if ( id === 'add' && ! baseRef [ id ] && typeof baseRef . push === 'function' ) { return baseRef . push ( this . getLiteral ( property . args [ 0 ] ) ) ; } else if ( id === 'subList' && ! baseRef [ id ] ) { return baseRef . slice ( this . getLiteral ( property . args [ 0 ] ) , this . getLiteral ( property . args [ 1 ] ) ) ; } else { ret = baseRef [ id ] ; var args = [ ] ; utils . forEach ( property . args , function ( exp ) { args . push ( this . getLiteral ( exp ) ) ; } , this ) ; if ( ret && ret . call ) { var that = this ; if ( typeof baseRef === 'object' && baseRef ) { baseRef . eval = function ( ) { return that . eval . apply ( that , arguments ) ; } ; } try { ret = ret . apply ( baseRef , args ) ; } catch ( e ) { var pos = ast . pos ; var text = Velocity . Helper . getRefText ( ast ) ; var err = ' on ' + text + ' at L/N ' + pos . first_line + ':' + pos . first_column ; e . name = '' ; e . message += err ; throw new Error ( e ) ; } } else { this . _throw ( ast , property , 'TypeError' ) ; ret = undefined ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "字面量求值，主要包括string integer array map四种数据结构 [CODESPLIT] function ( literal ) { var type = literal . type ; var ret = '' ; if ( type === 'string' ) { ret = this . getString ( literal ) ; } else if ( type === 'integer' ) { ret = parseInt ( literal . value , 10 ) ; } else if ( type === 'decimal' ) { ret = parseFloat ( literal . value , 10 ) ; } else if ( type === 'array' ) { ret = this . getArray ( literal ) ; } else if ( type === 'map' ) { ret = { } ; var map = literal . value ; utils . forEach ( map , function ( exp , key ) { ret [ key ] = this . getLiteral ( exp ) ; } , this ) ; } else if ( type === 'bool' ) { if ( literal . value === \"null\" ) { ret = null ; } else if ( literal . value === 'false' ) { ret = false ; } else if ( literal . value === 'true' ) { ret = true ; } } else { return this . getReferences ( literal ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对字符串求值，对已双引号字符串，需要做变量替换 [CODESPLIT] function ( literal ) { var val = literal . value ; var ret = val ; if ( literal . isEval && ( val . indexOf ( '#' ) !== - 1 || val . indexOf ( \"$\" ) !== - 1 ) ) { ret = this . evalStr ( val ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对array字面量求值，比如 [ 1 2 ] = > [ 1 2 ] ， [ 1 .. 5 ] = > [ 1 2 3 4 5 ] [CODESPLIT] function ( literal ) { var ret = [ ] ; if ( literal . isRange ) { var begin = literal . value [ 0 ] ; if ( begin . type === 'references' ) { begin = this . getReferences ( begin ) ; } var end = literal . value [ 1 ] ; if ( end . type === 'references' ) { end = this . getReferences ( end ) ; } end = parseInt ( end , 10 ) ; begin = parseInt ( begin , 10 ) ; var i ; if ( ! isNaN ( begin ) && ! isNaN ( end ) ) { if ( begin < end ) { for ( i = begin ; i <= end ; i ++ ) ret . push ( i ) ; } else { for ( i = begin ; i >= end ; i -- ) ret . push ( i ) ; } } } else { utils . forEach ( literal . value , function ( exp ) { ret . push ( this . getLiteral ( exp ) ) ; } , this ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "处理代码库 : if foreach macro [CODESPLIT] function ( block ) { var ast = block [ 0 ] ; var ret = '' ; switch ( ast . type ) { case 'if' : ret = this . getBlockIf ( block ) ; break ; case 'foreach' : ret = this . getBlockEach ( block ) ; break ; case 'macro' : this . setBlockMacro ( block ) ; break ; case 'noescape' : ret = this . _render ( block . slice ( 1 ) ) ; break ; case 'define' : this . setBlockDefine ( block ) ; break ; case 'macro_body' : ret = this . getMacroBody ( block ) ; break ; default : ret = this . _render ( block ) ; } return ret || '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "define [CODESPLIT] function ( block ) { var ast = block [ 0 ] ; var _block = block . slice ( 1 ) ; var defines = this . defines ; defines [ ast . id ] = _block ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "define macro [CODESPLIT] function ( block ) { var ast = block [ 0 ] ; var _block = block . slice ( 1 ) ; var macros = this . macros ; macros [ ast . id ] = { asts : _block , args : ast . args } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse macro call [CODESPLIT] function ( ast , bodyContent ) { var macro = this . macros [ ast . id ] ; var ret = '' ; if ( ! macro ) { var jsmacros = this . jsmacros ; macro = jsmacros [ ast . id ] ; var jsArgs = [ ] ; if ( macro && macro . apply ) { utils . forEach ( ast . args , function ( a ) { jsArgs . push ( this . getLiteral ( a ) ) ; } , this ) ; var self = this ; // bug修复：此处由于闭包特性，导致eval函数执行时的this对象是上一次函数执行时的this对象，渲染时上下文发生错误。 jsmacros . eval = function ( ) { return self . eval . apply ( self , arguments ) ; } ; try { ret = macro . apply ( jsmacros , jsArgs ) ; } catch ( e ) { var pos = ast . pos ; var text = Velocity . Helper . getRefText ( ast ) ; // throws error tree var err = '\\n      at ' + text + ' L/N ' + pos . first_line + ':' + pos . first_column ; e . name = '' ; e . message += err ; throw new Error ( e ) ; } } } else { var asts = macro . asts ; var args = macro . args ; var callArgs = ast . args ; var local = { bodyContent : bodyContent } ; var guid = utils . guid ( ) ; var contextId = 'macro:' + ast . id + ':' + guid ; utils . forEach ( args , function ( ref , i ) { if ( callArgs [ i ] ) { local [ ref . id ] = this . getLiteral ( callArgs [ i ] ) ; } else { local [ ref . id ] = undefined ; } } , this ) ; ret = this . eval ( asts , local , contextId ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eval [CODESPLIT] function ( str , local , contextId ) { if ( ! local ) { if ( utils . isArray ( str ) ) { return this . _render ( str ) ; } else { return this . evalStr ( str ) ; } } else { var asts = [ ] ; var parse = Velocity . parse ; contextId = contextId || ( 'eval:' + utils . guid ( ) ) ; if ( utils . isArray ( str ) ) { asts = str ; } else if ( parse ) { asts = parse ( str ) ; } if ( asts . length ) { this . local [ contextId ] = local ; var ret = this . _render ( asts , contextId ) ; this . local [ contextId ] = { } ; this . conditions . shift ( ) ; this . condition = this . conditions [ 0 ] || '' ; return ret ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse #foreach [CODESPLIT] function ( block ) { var ast = block [ 0 ] ; var _from = this . getLiteral ( ast . from ) ; var _block = block . slice ( 1 ) ; var _to = ast . to ; var local = { foreach : { count : 0 } } ; var ret = '' ; var guid = utils . guid ( ) ; var contextId = 'foreach:' + guid ; var type = ( { } ) . toString . call ( _from ) ; if ( ! _from || ( type !== '[object Array]' && type !== '[object Object]' ) ) { return '' ; } if ( utils . isArray ( _from ) ) { var len = _from . length ; utils . forEach ( _from , function ( val , i ) { if ( this . _state . break ) { return ; } // 构造临时变量 local [ _to ] = val ; local . foreach = { count : i + 1 , index : i , hasNext : i + 1 < len } ; local . velocityCount = i + 1 ; this . local [ contextId ] = local ; ret += this . _render ( _block , contextId ) ; } , this ) ; } else { var len = utils . keys ( _from ) . length ; utils . forEach ( utils . keys ( _from ) , function ( key , i ) { if ( this . _state . break ) { return ; } local [ _to ] = _from [ key ] ; local . foreach = { count : i + 1 , index : i , hasNext : i + 1 < len } ; local . velocityCount = i + 1 ; this . local [ contextId ] = local ; ret += this . _render ( _block , contextId ) ; } , this ) ; } // if foreach items be an empty array, then this code will shift current // conditions, but not this._render call, so this will shift parent context if ( _from && _from . length ) { this . _state . break = false ; // empty current local context object this . local [ contextId ] = { } ; this . conditions . shift ( ) ; this . condition = this . conditions [ 0 ] || '' ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse #if [CODESPLIT] function ( block ) { var received = false ; var asts = [ ] ; utils . some ( block , function ( ast ) { if ( ast . condition ) { if ( received ) { return true ; } received = this . getExpression ( ast . condition ) ; } else if ( ast . type === 'else' ) { if ( received ) { return true ; } received = true ; } else if ( received ) { asts . push ( ast ) ; } return false ; } , this ) ; // keep current condition fix #77 return this . _render ( asts , this . condition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取变量类型 TODO : foreach嵌套处理 [CODESPLIT] function ( ast ) { var local = this . getLocal ( ast ) ; var real = local . real || ast ; var ret = { ignore : false , type : 'string' , real : real , foreach : false } ; if ( local . real === undefined && local . isGlobal !== true ) { ret . ignore = true ; } var m = this . hasMethod ( real ) ; var eachTo ; if ( local . type == 'foreach' ) { if ( ast . id == local . ast . to ) { // 排除get key value size等通用方法 if ( ast . path && ! ( ~ [ 'get' , 'key' , 'value' , 'size' ] . indexOf ( ast . path [ 0 ] . id ) ) ) { local . objectKeys . push ( ast . path [ 0 ] . id ) ; ret . ignore = true ; } else { ret . real = local . ast ; ret . foreach = true ; } } eachTo = ast . id ; } if ( m === 'ignore' ) { ret . ignore = true ; } else if ( m ) { ret . foreach = ret . foreach || this . hasParamInForeach ( real ) ; ret . type = 'method' ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "表达式求值，表达式主要是数学表达式，逻辑运算和比较运算，到最底层数据结构， 基本数据类型，使用 getLiteral求值，getLiteral遇到是引用的时候，使用 getReferences求值 [CODESPLIT] function ( ast ) { var exp = ast . expression ; var ret ; if ( ast . type === 'math' ) { switch ( ast . operator ) { case '+' : ret = this . getExpression ( exp [ 0 ] ) + this . getExpression ( exp [ 1 ] ) ; break ; case '-' : ret = this . getExpression ( exp [ 0 ] ) - this . getExpression ( exp [ 1 ] ) ; break ; case '/' : ret = this . getExpression ( exp [ 0 ] ) / this . getExpression ( exp [ 1 ] ) ; break ; case '%' : ret = this . getExpression ( exp [ 0 ] ) % this . getExpression ( exp [ 1 ] ) ; break ; case '*' : ret = this . getExpression ( exp [ 0 ] ) * this . getExpression ( exp [ 1 ] ) ; break ; case '||' : ret = this . getExpression ( exp [ 0 ] ) || this . getExpression ( exp [ 1 ] ) ; break ; case '&&' : ret = this . getExpression ( exp [ 0 ] ) && this . getExpression ( exp [ 1 ] ) ; break ; case '>' : ret = this . getExpression ( exp [ 0 ] ) > this . getExpression ( exp [ 1 ] ) ; break ; case '<' : ret = this . getExpression ( exp [ 0 ] ) < this . getExpression ( exp [ 1 ] ) ; break ; case '==' : ret = this . getExpression ( exp [ 0 ] ) == this . getExpression ( exp [ 1 ] ) ; break ; case '>=' : ret = this . getExpression ( exp [ 0 ] ) >= this . getExpression ( exp [ 1 ] ) ; break ; case '<=' : ret = this . getExpression ( exp [ 0 ] ) <= this . getExpression ( exp [ 1 ] ) ; break ; case '!=' : ret = this . getExpression ( exp [ 0 ] ) != this . getExpression ( exp [ 1 ] ) ; break ; case 'minus' : ret = - this . getExpression ( exp [ 0 ] ) ; break ; case 'not' : ret = ! this . getExpression ( exp [ 0 ] ) ; break ; case 'parenthesis' : ret = this . getExpression ( exp [ 0 ] ) ; break ; default : return ; // code } return ret ; } else { return this . getLiteral ( ast ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解析入口函数 [CODESPLIT] function ( asts , contextId ) { var str = '' ; asts = asts || this . asts ; if ( contextId ) { if ( contextId !== this . condition && utils . indexOf ( contextId , this . conditions ) === - 1 ) { this . conditions . unshift ( contextId ) ; } this . condition = contextId ; } else { this . condition = null ; } utils . forEach ( asts , function ( ast ) { // 进入stop，直接退出 if ( this . _state . stop === true ) { return false ; } switch ( ast . type ) { case 'references' : str += this . format ( this . getReferences ( ast , true ) ) ; break ; case 'set' : this . setValue ( ast ) ; break ; case 'break' : this . _state . break = true ; break ; case 'macro_call' : str += this . getMacro ( ast ) ; break ; case 'comment' : break ; case 'raw' : str += ast . value ; break ; default : str += typeof ast === 'string' ? ast : this . getBlock ( ast ) ; break ; } } , this ) ; return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all modules from main & child compilations . Merge modules from ConcatenatedModule ( when webpack . optimize . ModuleConcatenationPlugin is used ) [CODESPLIT] function getAllModules ( compilation ) { let modules = compilation . modules ; // Look up in child compilations if ( compilation . children . length > 0 ) { const childModules = compilation . children . map ( getAllModules ) . reduce ( ( acc , compilationModules ) => acc . concat ( compilationModules ) , [ ] ) ; modules = modules . concat ( childModules ) ; } // Merge modules from ConcatenatedModule if ( ConcatenatedModule ) { const concatenatedModules = modules . filter ( m => m instanceof ConcatenatedModule ) . reduce ( ( acc , m ) => { /**\n         * @see https://git.io/v7XDu\n         * In webpack@3.5.1 `modules` public property was removed\n         * To workaround this private `_orderedConcatenationList` property is used to collect modules\n         */ const subModules = 'modules' in m ? m . modules : m . _orderedConcatenationList . map ( entry => entry . module ) ; return acc . concat ( subModules ) ; } , [ ] ) ; if ( concatenatedModules . length > 0 ) { modules = modules . concat ( concatenatedModules ) ; } } return modules . filter ( m => m . rawRequest ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find nearest module chunk ( not sure that is reliable method but who cares ) . [CODESPLIT] function getModuleChunk ( module ) { let chunks ; const webpackVersion = getWebpackMajorVersion ( ) ; if ( webpackVersion >= 4 ) { chunks = Array . from ( module . chunksIterable ) ; } else if ( webpackVersion >= 3 ) { chunks = module . mapChunks ( ) ; } else { chunks = module . chunks ; } if ( Array . isArray ( chunks ) && chunks . length > 0 ) { return chunks [ chunks . length - 1 ] ; } else if ( module . issuer ) { return getModuleChunk ( module . issuer ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Warn if the bin references don t point to anything . This might be better in normalize - package - data if it had access to the file path . [CODESPLIT] function checkBinReferences_ ( file , data , warn , cb ) { if ( ! ( data . bin instanceof Object ) ) return cb ( ) var keys = Object . keys ( data . bin ) var keysLeft = keys . length if ( ! keysLeft ) return cb ( ) function handleExists ( relName , result ) { keysLeft -- if ( ! result ) warn ( 'No bin file found at ' + relName ) if ( ! keysLeft ) cb ( ) } keys . forEach ( function ( key ) { var dirName = path . dirname ( file ) var relName = data . bin [ key ] try { var binPath = path . resolve ( dirName , relName ) fs . stat ( binPath , ( err ) => handleExists ( relName , ! err ) ) } catch ( error ) { if ( error . message === 'Arguments to path.resolve must be strings' || error . message . indexOf ( 'Path must be a string' ) === 0 ) { warn ( 'Bin filename for ' + key + ' is not a string: ' + util . inspect ( relName ) ) handleExists ( relName , true ) } else { cb ( error ) } } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ ** package { name : foo version : 1 . 2 . 3 ... } * [CODESPLIT] function parseIndex ( data ) { data = data . split ( / ^\\/\\*\\*package(?:\\s|$) / m ) if ( data . length < 2 ) return null data = data [ 1 ] data = data . split ( / \\*\\*\\/$ / m ) if ( data . length < 2 ) return null data = data [ 0 ] data = data . replace ( / ^\\s*\\* / mg , '' ) try { return safeJSON ( data ) } catch ( er ) { return null } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the file - picker connects it to runtime and dispatches event ready when done . [CODESPLIT] function ( ) { var self = this ; self . bind ( 'RuntimeInit' , function ( e , runtime ) { self . ruid = runtime . uid ; self . shimid = runtime . shimid ; self . bind ( \"Ready\" , function ( ) { self . trigger ( \"Refresh\" ) ; } , 999 ) ; // re-position and resize shim container self . bind ( 'Refresh' , function ( ) { var pos , size , browseButton , shimContainer , zIndex ; browseButton = Dom . get ( options . browse_button ) ; shimContainer = Dom . get ( runtime . shimid ) ; // do not use runtime.getShimContainer(), since it will create container if it doesn't exist if ( browseButton ) { pos = Dom . getPos ( browseButton , Dom . get ( options . container ) ) ; size = Dom . getSize ( browseButton ) ; zIndex = parseInt ( Dom . getStyle ( browseButton , 'z-index' ) , 10 ) || 0 ; if ( shimContainer ) { Basic . extend ( shimContainer . style , { top : pos . y + 'px' , left : pos . x + 'px' , width : size . w + 'px' , height : size . h + 'px' , zIndex : zIndex + 1 } ) ; } } shimContainer = browseButton = null ; } ) ; runtime . exec . call ( self , 'FileInput' , 'init' , options ) ; } ) ; // runtime needs: options.required_features, options.runtime_order and options.container self . connectRuntime ( Basic . extend ( { } , options , { required_caps : { select_file : true } } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a new value for the option specified by name [CODESPLIT] function ( name , value ) { if ( ! options . hasOwnProperty ( name ) ) { return ; } var oldValue = options [ name ] ; switch ( name ) { case 'accept' : if ( typeof ( value ) === 'string' ) { value = Mime . mimes2extList ( value ) ; } break ; case 'container' : case 'required_caps' : throw new x . FileException ( x . FileException . NO_MODIFICATION_ALLOWED_ERR ) ; } options [ name ] = value ; this . exec ( 'FileInput' , 'setOption' , name , value ) ; this . trigger ( 'OptionChanged' , name , value , oldValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses mimeData string into a mimes and extensions lookup maps . String should have the following format : [CODESPLIT] function ( mimeData ) { var items = mimeData . split ( / , / ) , i , ii , ext ; for ( i = 0 ; i < items . length ; i += 2 ) { ext = items [ i + 1 ] . split ( /   / ) ; // extension to mime lookup for ( ii = 0 ; ii < ext . length ; ii ++ ) { mimes [ ext [ ii ] ] = items [ i ] ; } // mime to extension lookup extensions [ items [ i ] ] = ext ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "String . prototype . replace () does something weird on strings with fancy regexps hence this artifical version [CODESPLIT] function ( from , to , text , all ) { var pos = text . indexOf ( from ) ; if ( pos == - 1 ) { return text ; } text = text . substring ( 0 , pos ) + to + text . substring ( pos + from . length ) ; return ! all ? text : replace . call ( null , from , to , text , all ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we require this to run only once [CODESPLIT] function ( e , runtime ) { self . unbind ( \"RuntimeInit\" , cb ) ; _run . call ( self , type , runtime ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Aborts preloading process . [CODESPLIT] function ( ) { this . result = null ; if ( Basic . inArray ( this . readyState , [ FileReader . EMPTY , FileReader . DONE ] ) !== - 1 ) { return ; } else if ( this . readyState === FileReader . LOADING ) { this . readyState = FileReader . DONE ; } this . exec ( 'FileReader' , 'abort' ) ; this . trigger ( 'abort' ) ; this . trigger ( 'loadend' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////// Constructor ////////////// [CODESPLIT] function ( uastring ) { var ua = uastring || ( ( window && window . navigator && window . navigator . userAgent ) ? window . navigator . userAgent : EMPTY ) ; this . getBrowser = function ( ) { return mapper . rgx . apply ( this , regexes . browser ) ; } ; this . getEngine = function ( ) { return mapper . rgx . apply ( this , regexes . engine ) ; } ; this . getOS = function ( ) { return mapper . rgx . apply ( this , regexes . os ) ; } ; this . getResult = function ( ) { return { ua : this . getUA ( ) , browser : this . getBrowser ( ) , engine : this . getEngine ( ) , os : this . getOS ( ) } ; } ; this . getUA = function ( ) { return ua ; } ; this . setUA = function ( uastring ) { ua = uastring ; return this ; } ; this . setUA ( ua ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "From : http : // phpjs . org / functions + original by : Philippe Jausions ( http : // pear . php . net / user / jausions ) + original by : Aidan Lister ( http : // aidanlister . com / ) + reimplemented by : Kankrelune ( http : // www . webfaktory . info / ) + improved by : Brett Zamir ( http : // brett - zamir . me ) + improved by : Scott Baker + improved by : Theriault * example 1 : version_compare ( 8 . 2 . 5rc 8 . 2 . 5a ) ; * returns 1 : 1 * example 2 : version_compare ( 8 . 2 . 50 8 . 2 . 52 < ) ; * returns 2 : true * example 3 : version_compare ( 5 . 3 . 0 - dev 5 . 3 . 0 ) ; * returns 3 : - 1 * example 4 : version_compare ( 4 . 1 . 0 . 52 4 . 01 . 0 . 51 ) ; * returns 4 : 1 Important : compare must be initialized at 0 . [CODESPLIT] function ( v ) { v = ( '' + v ) . replace ( / [_\\-+] / g , '.' ) ; v = v . replace ( / ([^.\\d]+) / g , '.$1.' ) . replace ( / \\.{2,} / g , '.' ) ; return ( ! v . length ? [ - 8 ] : v . split ( '.' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if any handlers were registered to the specified event [CODESPLIT] function ( type ) { var list ; if ( type ) { type = type . toLowerCase ( ) ; list = eventpool [ this . uid ] && eventpool [ this . uid ] [ type ] ; } else { list = eventpool [ this . uid ] ; } return list ? list : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unregister the handler from the event or if former was not specified - unregister all handlers [CODESPLIT] function ( type , fn ) { var self = this , list , i ; type = type . toLowerCase ( ) ; if ( / \\s / . test ( type ) ) { // multiple event types were passed for one handler Basic . each ( type . split ( / \\s+ / ) , function ( type ) { self . removeEventListener ( type , fn ) ; } ) ; return ; } list = eventpool [ this . uid ] && eventpool [ this . uid ] [ type ] ; if ( list ) { if ( fn ) { for ( i = list . length - 1 ; i >= 0 ; i -- ) { if ( list [ i ] . fn === fn ) { list . splice ( i , 1 ) ; break ; } } } else { list = [ ] ; } // delete event list if it has become empty if ( ! list . length ) { delete eventpool [ this . uid ] [ type ] ; // and object specific entry in a hash if it has no more listeners attached if ( Basic . isEmptyObj ( eventpool [ this . uid ] ) ) { delete eventpool [ this . uid ] ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a handler to the event type that will run only once [CODESPLIT] function ( type , fn , priority , scope ) { var self = this ; self . bind . call ( this , type , function cb ( ) { self . unbind ( type , cb ) ; return fn . apply ( this , arguments ) ; } , priority , scope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle properties of on [ event ] type . [CODESPLIT] function ( dispatches ) { var self = this ; this . bind ( dispatches . join ( ' ' ) , function ( e ) { var prop = 'on' + e . type . toLowerCase ( ) ; if ( Basic . typeOf ( this [ prop ] ) === 'function' ) { this [ prop ] . apply ( this , arguments ) ; } } ) ; // object must have defined event properties, even if it doesn't make use of them Basic . each ( dispatches , function ( prop ) { prop = 'on' + prop . toLowerCase ( prop ) ; if ( Basic . typeOf ( self [ prop ] ) === 'undefined' ) { self [ prop ] = null ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the runtime has specific capability [CODESPLIT] function ( cap , value ) { var refCaps = arguments [ 2 ] || caps ; // if cap var is a comma-separated list of caps, convert it to object (key/value) if ( Basic . typeOf ( cap ) === 'string' && Basic . typeOf ( value ) === 'undefined' ) { cap = Runtime . parseCaps ( cap ) ; } if ( Basic . typeOf ( cap ) === 'object' ) { for ( var key in cap ) { if ( ! this . can ( key , cap [ key ] , refCaps ) ) { return false ; } } return true ; } // check the individual cap if ( Basic . typeOf ( refCaps [ cap ] ) === 'function' ) { return refCaps [ cap ] . call ( this , value ) ; } else { return ( value === refCaps [ cap ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes a method within the runtime itself ( might differ across the runtimes ) [CODESPLIT] function ( component , action ) { var args = [ ] . slice . call ( arguments , 2 ) ; return self . getShim ( ) . exec . call ( this , this . uid , component , action , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Operaional interface that is used by components to invoke specific actions on the runtime ( is invoked in the scope of component ) [CODESPLIT] function ( component , action ) { // this is called in the context of component, not runtime var args = [ ] . slice . call ( arguments , 2 ) ; if ( self [ component ] && self [ component ] [ action ] ) { return self [ component ] [ action ] . apply ( this , args ) ; } return self . shimExec . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Destroys the runtime ( removes all events and deletes DOM structures ) [CODESPLIT] function ( ) { if ( ! self ) { return ; // obviously already destroyed } var shimContainer = Dom . get ( this . shimid ) ; if ( shimContainer ) { shimContainer . parentNode . removeChild ( shimContainer ) ; } if ( _shim ) { _shim . removeAllInstances ( ) ; } this . unbindAll ( ) ; delete runtimes [ this . uid ] ; this . uid = null ; // mark this runtime as destroyed _uid = self = _shim = shimContainer = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the version of the Flash Player [CODESPLIT] function getShimVersion ( ) { var version ; try { version = navigator . plugins [ 'Shockwave Flash' ] ; version = version . description ; } catch ( e1 ) { try { version = new ActiveXObject ( 'ShockwaveFlash.ShockwaveFlash' ) . GetVariable ( '$version' ) ; } catch ( e2 ) { version = '0.0' ; } } version = version . match ( / \\d+ / g ) ; return parseFloat ( version [ 0 ] + '.' + version [ 1 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cross - browser SWF removal - Especially needed to safely and completely remove a SWF in Internet Explorer [CODESPLIT] function removeSWF ( id ) { var obj = Dom . get ( id ) ; if ( obj && obj . nodeName == \"OBJECT\" ) { if ( Env . browser === 'IE' ) { obj . style . display = \"none\" ; ( function onInit ( ) { // http://msdn.microsoft.com/en-us/library/ie/ms534360(v=vs.85).aspx if ( obj . readyState == 4 ) { removeObjectInIE ( id ) ; } else { setTimeout ( onInit , 10 ) ; } } ) ( ) ; } else { obj . parentNode . removeChild ( obj ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if specified url has the same origin as the current document [CODESPLIT] function ( url ) { function origin ( url ) { return [ url . scheme , url . host , url . port ] . join ( '/' ) ; } if ( typeof url === 'string' ) { url = parseUrl ( url ) ; } return origin ( parseUrl ( ) ) === origin ( url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A way to inherit one class from another in a consisstent way ( more or less ) [CODESPLIT] function inherit ( child , parent ) { // copy over all parent properties for ( var key in parent ) { if ( { } . hasOwnProperty . call ( parent , key ) ) { child [ key ] = parent [ key ] ; } } // give child `class` a place to define its own methods function ctor ( ) { this . constructor = child ; if ( MXI_DEBUG ) { var getCtorName = function ( fn ) { var m = fn . toString ( ) . match ( / ^function\\s([^\\(\\s]+) / ) ; return m ? m [ 1 ] : false ; } ; this . ctorName = getCtorName ( child ) ; } } ctor . prototype = parent . prototype ; child . prototype = new ctor ( ) ; // keep a way to reference parent methods child . parent = parent . prototype ; return child ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "give child class a place to define its own methods [CODESPLIT] function ctor ( ) { this . constructor = child ; if ( MXI_DEBUG ) { var getCtorName = function ( fn ) { var m = fn . toString ( ) . match ( / ^function\\s([^\\(\\s]+) / ) ; return m ? m [ 1 ] : false ; } ; this . ctorName = getCtorName ( child ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find an element in array and return it s index if present otherwise return - 1 . [CODESPLIT] function inArray ( needle , array ) { if ( array ) { if ( Array . prototype . indexOf ) { return Array . prototype . indexOf . call ( array , needle ) ; } for ( var i = 0 , length = array . length ; i < length ; i ++ ) { if ( array [ i ] === needle ) { return i ; } } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns elements of first array if they are not present in second . And false - otherwise . [CODESPLIT] function arrayDiff ( needles , array ) { var diff = [ ] ; if ( typeOf ( needles ) !== 'array' ) { needles = [ needles ] ; } if ( typeOf ( array ) !== 'array' ) { array = [ array ] ; } for ( var i in needles ) { if ( inArray ( needles [ i ] , array ) === - 1 ) { diff . push ( needles [ i ] ) ; } } return diff . length ? diff : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find intersection of two arrays . [CODESPLIT] function arrayIntersect ( array1 , array2 ) { var result = [ ] ; each ( array1 , function ( item ) { if ( inArray ( item , array2 ) !== - 1 ) { result . push ( item ) ; } } ) ; return result . length ? result : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the specified size string into a byte value . For example 10kb becomes 10240 . [CODESPLIT] function parseSizeStr ( size ) { if ( typeof ( size ) !== 'string' ) { return size ; } var muls = { t : 1099511627776 , g : 1073741824 , m : 1048576 , k : 1024 } , mul ; size = / ^([0-9\\.]+)([tmgk]?)$ / . exec ( size . toLowerCase ( ) . replace ( / [^0-9\\.tmkg] / g , '' ) ) ; mul = size [ 2 ] ; size = + size [ 1 ] ; if ( muls . hasOwnProperty ( mul ) ) { size *= muls [ mul ] ; } return Math . floor ( size ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pseudo sprintf implementation - simple way to replace tokens with specified values . [CODESPLIT] function sprintf ( str ) { var args = [ ] . slice . call ( arguments , 1 ) ; return str . replace ( / %([a-z]) / g , function ( $0 , $1 ) { var value = args . shift ( ) ; switch ( $1 ) { case 's' : return value + '' ; case 'd' : return parseInt ( value , 10 ) ; case 'f' : return parseFloat ( value ) ; case 'c' : return '' ; default : return value ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append another key - value pair to the FormData object [CODESPLIT] function ( name , value ) { var self = this , valueType = Basic . typeOf ( value ) ; // according to specs value might be either Blob or String if ( value instanceof Blob ) { _blob = { name : name , value : value // unfortunately we can only send single Blob in one FormData } ; } else if ( 'array' === valueType ) { name += '[]' ; Basic . each ( value , function ( value ) { self . append ( name , value ) ; } ) ; } else if ( 'object' === valueType ) { Basic . each ( value , function ( value , key ) { self . append ( name + '[' + key + ']' , value ) ; } ) ; } else if ( 'null' === valueType || 'undefined' === valueType || 'number' === valueType && isNaN ( value ) ) { self . append ( name , \"false\" ) ; } else { _fields . push ( { name : name , value : value . toString ( ) } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loop over the fields in FormData and invoke the callback for each of them . [CODESPLIT] function ( cb ) { Basic . each ( _fields , function ( field ) { cb ( field . value , field . name ) ; } ) ; if ( _blob ) { cb ( _blob . value , _blob . name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if specified DOM element has specified class . [CODESPLIT] function ( obj , name ) { if ( ! obj . className ) { return false ; } var regExp = new RegExp ( \"(^|\\\\s+)\" + name + \"(\\\\s+|$)\" ) ; return regExp . test ( obj . className ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds specified className to specified DOM element . [CODESPLIT] function ( obj , name ) { if ( ! hasClass ( obj , name ) ) { obj . className = ! obj . className ? name : obj . className . replace ( / \\s+$ / , '' ) + ' ' + name ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes specified className from specified DOM element . [CODESPLIT] function ( obj , name ) { if ( obj . className ) { var regExp = new RegExp ( \"(^|\\\\s+)\" + name + \"(\\\\s+|$)\" ) ; obj . className = obj . className . replace ( regExp , function ( $0 , $1 , $2 ) { return $1 === ' ' && $2 === ' ' ? ' ' : '' ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a given computed style of a DOM element . [CODESPLIT] function ( obj , name ) { if ( obj . currentStyle ) { return obj . currentStyle [ name ] ; } else if ( window . getComputedStyle ) { return window . getComputedStyle ( obj , null ) [ name ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the absolute x y position of an Element . The position will be returned in a object with x y fields . [CODESPLIT] function ( node , root ) { var x = 0 , y = 0 , parent , doc = document , nodeRect , rootRect ; node = node ; root = root || doc . body ; // Returns the x, y cordinate for an element on IE 6 and IE 7 function getIEPos ( node ) { var bodyElm , rect , x = 0 , y = 0 ; if ( node ) { rect = node . getBoundingClientRect ( ) ; bodyElm = doc . compatMode === \"CSS1Compat\" ? doc . documentElement : doc . body ; x = rect . left + bodyElm . scrollLeft ; y = rect . top + bodyElm . scrollTop ; } return { x : x , y : y } ; } // Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode if ( node && node . getBoundingClientRect && Env . browser === 'IE' && ( ! doc . documentMode || doc . documentMode < 8 ) ) { nodeRect = getIEPos ( node ) ; rootRect = getIEPos ( root ) ; return { x : nodeRect . x - rootRect . x , y : nodeRect . y - rootRect . y } ; } parent = node ; while ( parent && parent != root && parent . nodeType ) { x += parent . offsetLeft || 0 ; y += parent . offsetTop || 0 ; parent = parent . offsetParent ; } parent = node . parentNode ; while ( parent && parent != root && parent . nodeType ) { x -= parent . scrollLeft || 0 ; y -= parent . scrollTop || 0 ; parent = parent . parentNode ; } return { x : x , y : y } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the x y cordinate for an element on IE 6 and IE 7 [CODESPLIT] function getIEPos ( node ) { var bodyElm , rect , x = 0 , y = 0 ; if ( node ) { rect = node . getBoundingClientRect ( ) ; bodyElm = doc . compatMode === \"CSS1Compat\" ? doc . documentElement : doc . body ; x = rect . left + bodyElm . scrollLeft ; y = rect . top + bodyElm . scrollTop ; } return { x : x , y : y } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the size of the specified node in pixels . [CODESPLIT] function ( node ) { return { w : node . offsetWidth || node . clientWidth , h : node . offsetHeight || node . clientHeight } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an event handler to the specified object and store reference to the handler in objects internal Plupload registry ( @see removeEvent ) . [CODESPLIT] function ( obj , name , callback , key ) { var func , events ; name = name . toLowerCase ( ) ; // Add event listener if ( obj . addEventListener ) { func = callback ; obj . addEventListener ( name , func , false ) ; } else if ( obj . attachEvent ) { func = function ( ) { var evt = window . event ; if ( ! evt . target ) { evt . target = evt . srcElement ; } evt . preventDefault = preventDefault ; evt . stopPropagation = stopPropagation ; callback ( evt ) ; } ; obj . attachEvent ( 'on' + name , func ) ; } // Log event handler to objects internal mOxie registry if ( ! obj [ uid ] ) { obj [ uid ] = Basic . guid ( ) ; } if ( ! eventhash . hasOwnProperty ( obj [ uid ] ) ) { eventhash [ obj [ uid ] ] = { } ; } events = eventhash [ obj [ uid ] ] ; if ( ! events . hasOwnProperty ( name ) ) { events [ name ] = [ ] ; } events [ name ] . push ( { func : func , orig : callback , // store original callback for IE key : key } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove event handler from the specified object . If third argument ( callback ) is not specified remove all events with the specified name . [CODESPLIT] function ( obj , name , callback ) { var type , undef ; name = name . toLowerCase ( ) ; if ( obj [ uid ] && eventhash [ obj [ uid ] ] && eventhash [ obj [ uid ] ] [ name ] ) { type = eventhash [ obj [ uid ] ] [ name ] ; } else { return ; } for ( var i = type . length - 1 ; i >= 0 ; i -- ) { // undefined or not, key should match if ( type [ i ] . orig === callback || type [ i ] . key === callback ) { if ( obj . removeEventListener ) { obj . removeEventListener ( name , type [ i ] . func , false ) ; } else if ( obj . detachEvent ) { obj . detachEvent ( 'on' + name , type [ i ] . func ) ; } type [ i ] . orig = null ; type [ i ] . func = null ; type . splice ( i , 1 ) ; // If callback was passed we are done here, otherwise proceed if ( callback !== undef ) { break ; } } } // If event array got empty, remove it if ( ! type . length ) { delete eventhash [ obj [ uid ] ] [ name ] ; } // If mOxie registry has become empty, remove it if ( Basic . isEmptyObj ( eventhash [ obj [ uid ] ] ) ) { delete eventhash [ obj [ uid ] ] ; // IE doesn't let you remove DOM object property with - delete try { delete obj [ uid ] ; } catch ( e ) { obj [ uid ] = undef ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all kind of events from the specified object [CODESPLIT] function ( obj , key ) { if ( ! obj || ! obj [ uid ] ) { return ; } Basic . each ( eventhash [ obj [ uid ] ] , function ( events , name ) { removeEvent ( obj , name , key ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "here we go ... ugly fix for ugly bug [CODESPLIT] function _preloadAndSend ( meta , data ) { var target = this , blob , fr ; // get original blob blob = data . getBlob ( ) . getSource ( ) ; // preload blob in memory to be sent as binary string fr = new window . FileReader ( ) ; fr . onload = function ( ) { // overwrite original blob data . append ( data . getBlobName ( ) , new Blob ( null , { type : blob . type , data : fr . result } ) ) ; // invoke send operation again self . send . call ( target , meta , data ) ; } ; fr . readAsBinaryString ( blob ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform canvas coordination according to specified frame size and orientation Orientation value is from EXIF tag [CODESPLIT] function _rotateToOrientaion ( img , orientation ) { var RADIANS = Math . PI / 180 ; var canvas = document . createElement ( 'canvas' ) ; var ctx = canvas . getContext ( '2d' ) ; var width = img . width ; var height = img . height ; if ( Basic . inArray ( orientation , [ 5 , 6 , 7 , 8 ] ) > - 1 ) { canvas . width = height ; canvas . height = width ; } else { canvas . width = width ; canvas . height = height ; } /**\n\t\t\t1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.\n\t\t\t2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.\n\t\t\t3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.\n\t\t\t4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.\n\t\t\t5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.\n\t\t\t6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.\n\t\t\t7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.\n\t\t\t8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.\n\t\t\t*/ switch ( orientation ) { case 2 : // horizontal flip ctx . translate ( width , 0 ) ; ctx . scale ( - 1 , 1 ) ; break ; case 3 : // 180 rotate left ctx . translate ( width , height ) ; ctx . rotate ( 180 * RADIANS ) ; break ; case 4 : // vertical flip ctx . translate ( 0 , height ) ; ctx . scale ( 1 , - 1 ) ; break ; case 5 : // vertical flip + 90 rotate right ctx . rotate ( 90 * RADIANS ) ; ctx . scale ( 1 , - 1 ) ; break ; case 6 : // 90 rotate right ctx . rotate ( 90 * RADIANS ) ; ctx . translate ( 0 , - height ) ; break ; case 7 : // horizontal flip + 90 rotate right ctx . rotate ( 90 * RADIANS ) ; ctx . translate ( width , - height ) ; ctx . scale ( - 1 , 1 ) ; break ; case 8 : // 90 rotate left ctx . rotate ( - 90 * RADIANS ) ; ctx . translate ( - width , 0 ) ; break ; } ctx . drawImage ( img , 0 , 0 , width , height ) ; return canvas ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pseudo sprintf implementation - simple way to replace tokens with specified values . [CODESPLIT] function ( str ) { var args = [ ] . slice . call ( arguments , 1 ) ; return str . replace ( / %[a-z] / g , function ( ) { var value = args . shift ( ) ; return Basic . typeOf ( value ) !== 'undefined' ? value : '' ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "keep quering recursively till no more entries [CODESPLIT] function getEntries ( cbcb ) { dirReader . readEntries ( function ( moreEntries ) { if ( moreEntries . length ) { [ ] . push . apply ( entries , moreEntries ) ; getEntries ( cbcb ) ; } else { cbcb ( ) ; } } , cbcb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the request method request URL synchronous flag request username and request password . [CODESPLIT] function ( method , url , async , user , password ) { var urlp ; // first two arguments are required if ( ! method || ! url ) { throw new x . DOMException ( x . DOMException . SYNTAX_ERR ) ; } // 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method if ( / [\\u0100-\\uffff] / . test ( method ) || Encode . utf8_encode ( method ) !== method ) { throw new x . DOMException ( x . DOMException . SYNTAX_ERR ) ; } // 3 if ( ! ! ~ Basic . inArray ( method . toUpperCase ( ) , [ 'CONNECT' , 'DELETE' , 'GET' , 'HEAD' , 'OPTIONS' , 'POST' , 'PUT' , 'TRACE' , 'TRACK' ] ) ) { _method = method . toUpperCase ( ) ; } // 4 - allowing these methods poses a security risk if ( ! ! ~ Basic . inArray ( _method , [ 'CONNECT' , 'TRACE' , 'TRACK' ] ) ) { throw new x . DOMException ( x . DOMException . SECURITY_ERR ) ; } // 5 url = Encode . utf8_encode ( url ) ; // 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a \"SyntaxError\". urlp = Url . parseUrl ( url ) ; _same_origin_flag = Url . hasSameOrigin ( urlp ) ; // 7 - manually build up absolute url _url = Url . resolveUrl ( url ) ; // 9-10, 12-13 if ( ( user || password ) && ! _same_origin_flag ) { throw new x . DOMException ( x . DOMException . INVALID_ACCESS_ERR ) ; } _user = user || urlp . user ; _password = password || urlp . pass ; // 11 _async = async || true ; if ( _async === false && ( _p ( 'timeout' ) || _p ( 'withCredentials' ) || _p ( 'responseType' ) !== \"\" ) ) { throw new x . DOMException ( x . DOMException . INVALID_ACCESS_ERR ) ; } // 14 - terminate abort() // 15 - terminate send() // 18 _sync_flag = ! _async ; _send_flag = false ; _headers = { } ; _reset . call ( this ) ; // 19 _p ( 'readyState' , XMLHttpRequest . OPENED ) ; // 20 this . dispatchEvent ( 'readystatechange' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends an header to the list of author request headers or if header is already in the list of author request headers combines its value with value . [CODESPLIT] function ( header , value ) { var uaHeaders = [ // these headers are controlled by the user agent \"accept-charset\" , \"accept-encoding\" , \"access-control-request-headers\" , \"access-control-request-method\" , \"connection\" , \"content-length\" , \"cookie\" , \"cookie2\" , \"content-transfer-encoding\" , \"date\" , \"expect\" , \"host\" , \"keep-alive\" , \"origin\" , \"referer\" , \"te\" , \"trailer\" , \"transfer-encoding\" , \"upgrade\" , \"user-agent\" , \"via\" ] ; // 1-2 if ( _p ( 'readyState' ) !== XMLHttpRequest . OPENED || _send_flag ) { throw new x . DOMException ( x . DOMException . INVALID_STATE_ERR ) ; } // 3 if ( / [\\u0100-\\uffff] / . test ( header ) || Encode . utf8_encode ( header ) !== header ) { throw new x . DOMException ( x . DOMException . SYNTAX_ERR ) ; } // 4 /* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values\n\t\t\t\tif (/[\\u0100-\\uffff]/.test(value) || Encode.utf8_encode(value) !== value) {\n\t\t\t\t\tthrow new x.DOMException(x.DOMException.SYNTAX_ERR);\n\t\t\t\t}*/ header = Basic . trim ( header ) . toLowerCase ( ) ; // setting of proxy-* and sec-* headers is prohibited by spec if ( ! ! ~ Basic . inArray ( header , uaHeaders ) || / ^(proxy\\-|sec\\-) / . test ( header ) ) { return false ; } // camelize // browsers lowercase header names (at least for custom ones) // header = header.replace(/\\b\\w/g, function($1) { return $1.toUpperCase(); }); if ( ! _headers [ header ] ) { _headers [ header ] = value ; } else { // http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph) _headers [ header ] += ', ' + value ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the header field value from the response of which the field name matches header unless the field name is Set - Cookie or Set - Cookie2 . [CODESPLIT] function ( header ) { header = header . toLowerCase ( ) ; if ( _error_flag || ! ! ~ Basic . inArray ( header , [ 'set-cookie' , 'set-cookie2' ] ) ) { return null ; } if ( _responseHeaders && _responseHeaders !== '' ) { // if we didn't parse response headers until now, do it and keep for later if ( ! _responseHeadersBag ) { _responseHeadersBag = { } ; Basic . each ( _responseHeaders . split ( / \\r\\n / ) , function ( line ) { var pair = line . split ( / :\\s+ / ) ; if ( pair . length === 2 ) { // last line might be empty, omit pair [ 0 ] = Basic . trim ( pair [ 0 ] ) ; // just in case _responseHeadersBag [ pair [ 0 ] . toLowerCase ( ) ] = { // simply to retain header name in original form header : pair [ 0 ] , value : Basic . trim ( pair [ 1 ] ) } ; } } ) ; } if ( _responseHeadersBag . hasOwnProperty ( header ) ) { return _responseHeadersBag [ header ] . header + ': ' + _responseHeadersBag [ header ] . value ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the Content - Type header for the response to mime . Throws an InvalidStateError exception if the state is LOADING or DONE . Throws a SyntaxError exception if mime is not a valid media type . [CODESPLIT] function ( mime ) { var matches , charset ; // 1 if ( ! ! ~ Basic . inArray ( _p ( 'readyState' ) , [ XMLHttpRequest . LOADING , XMLHttpRequest . DONE ] ) ) { throw new x . DOMException ( x . DOMException . INVALID_STATE_ERR ) ; } // 2 mime = Basic . trim ( mime . toLowerCase ( ) ) ; if ( / ; / . test ( mime ) && ( matches = mime . match ( / ^([^;]+)(?:;\\scharset\\=)?(.*)$ / ) ) ) { mime = matches [ 1 ] ; if ( matches [ 2 ] ) { charset = matches [ 2 ] ; } } if ( ! Mime . mimes [ mime ] ) { throw new x . DOMException ( x . DOMException . SYNTAX_ERR ) ; } // 3-4 _finalMime = mime ; _finalCharset = charset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initiates the request . The optional argument provides the request entity body . The argument is ignored if request method is GET or HEAD . [CODESPLIT] function ( data , options ) { if ( Basic . typeOf ( options ) === 'string' ) { _options = { ruid : options } ; } else if ( ! options ) { _options = { } ; } else { _options = options ; } // 1-2 if ( this . readyState !== XMLHttpRequest . OPENED || _send_flag ) { throw new x . DOMException ( x . DOMException . INVALID_STATE_ERR ) ; } // 3 // sending Blob if ( data instanceof Blob ) { _options . ruid = data . ruid ; _mimeType = data . type || 'application/octet-stream' ; } // FormData else if ( data instanceof FormData ) { if ( data . hasBlob ( ) ) { var blob = data . getBlob ( ) ; _options . ruid = blob . ruid ; _mimeType = blob . type || 'application/octet-stream' ; } } // DOMString else if ( typeof data === 'string' ) { _encoding = 'UTF-8' ; _mimeType = 'text/plain;charset=UTF-8' ; // data should be converted to Unicode and encoded as UTF-8 data = Encode . utf8_encode ( data ) ; } // if withCredentials not set, but requested, set it automatically if ( ! this . withCredentials ) { this . withCredentials = ( _options . required_caps && _options . required_caps . send_browser_cookies ) && ! _same_origin_flag ; } // 4 - storage mutex // 5 _upload_events_flag = ( ! _sync_flag && this . upload . hasEventListener ( ) ) ; // DSAP // 6 _error_flag = false ; // 7 _upload_complete_flag = ! data ; // 8 - Asynchronous steps if ( ! _sync_flag ) { // 8.1 _send_flag = true ; // 8.2 // this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr // 8.3 //if (!_upload_complete_flag) { // this.upload.dispatchEvent('loadstart');\t// will be dispatched either by native or runtime xhr //} } // 8.5 - Return the send() method call, but continue running the steps in this algorithm. _doXHR . call ( this , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cancels any network activity . [CODESPLIT] function ( ) { _error_flag = true ; _sync_flag = false ; if ( ! ~ Basic . inArray ( _p ( 'readyState' ) , [ XMLHttpRequest . UNSENT , XMLHttpRequest . OPENED , XMLHttpRequest . DONE ] ) ) { _p ( 'readyState' , XMLHttpRequest . DONE ) ; _send_flag = false ; if ( _xhr ) { _xhr . getRuntime ( ) . exec . call ( _xhr , 'XMLHttpRequest' , 'abort' , _upload_complete_flag ) ; } else { throw new x . DOMException ( x . DOMException . INVALID_STATE_ERR ) ; } _upload_complete_flag = true ; } else { _p ( 'readyState' , XMLHttpRequest . UNSENT ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * this is nice but maybe too lengthy [CODESPLIT] function _p ( prop , value ) { if ( ! props . hasOwnProperty ( prop ) ) { return ; } if ( arguments . length === 1 ) { // get return Env . can ( 'define_property' ) ? props [ prop ] : self [ prop ] ; } else { // set if ( Env . can ( 'define_property' ) ) { props [ prop ] = value ; } else { self [ prop ] = value ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "save original z - index ; [CODESPLIT] function addInput ( ) { var comp = this , I = comp . getRuntime ( ) , shimContainer , browseButton , currForm , form , input , uid ; uid = Basic . guid ( 'uid_' ) ; shimContainer = I . getShimContainer ( ) ; // we get new ref every time to avoid memory leaks in IE if ( _uid ) { // move previous form out of the view currForm = Dom . get ( _uid + '_form' ) ; if ( currForm ) { Basic . extend ( currForm . style , { top : '100%' } ) ; // it shouldn't be possible to tab into the hidden element currForm . firstChild . setAttribute ( 'tabindex' , - 1 ) ; } } // build form in DOM, since innerHTML version not able to submit file for some reason form = document . createElement ( 'form' ) ; form . setAttribute ( 'id' , uid + '_form' ) ; form . setAttribute ( 'method' , 'post' ) ; form . setAttribute ( 'enctype' , 'multipart/form-data' ) ; form . setAttribute ( 'encoding' , 'multipart/form-data' ) ; Basic . extend ( form . style , { overflow : 'hidden' , position : 'absolute' , top : 0 , left : 0 , width : '100%' , height : '100%' } ) ; input = document . createElement ( 'input' ) ; input . setAttribute ( 'id' , uid ) ; input . setAttribute ( 'type' , 'file' ) ; input . setAttribute ( 'accept' , _mimes . join ( ',' ) ) ; if ( I . can ( 'summon_file_dialog' ) ) { input . setAttribute ( 'tabindex' , - 1 ) ; } Basic . extend ( input . style , { fontSize : '999px' , opacity : 0 } ) ; form . appendChild ( input ) ; shimContainer . appendChild ( form ) ; // prepare file input to be placed underneath the browse_button element Basic . extend ( input . style , { position : 'absolute' , top : 0 , left : 0 , width : '100%' , height : '100%' } ) ; if ( Env . browser === 'IE' && Env . verComp ( Env . version , 10 , '<' ) ) { Basic . extend ( input . style , { filter : \"progid:DXImageTransform.Microsoft.Alpha(opacity=0)\" } ) ; } input . onchange = function ( ) { // there should be only one handler for this var file ; if ( ! this . value ) { return ; } if ( this . files ) { // check if browser is fresh enough file = this . files [ 0 ] ; } else { file = { name : this . value } ; } file = new File ( I . uid , file ) ; // clear event handler this . onchange = function ( ) { } ; addInput . call ( comp ) ; comp . files = [ file ] ; // substitute all ids with file uids (consider file.uid read-only - we cannot do it the other way around) input . setAttribute ( 'id' , file . uid ) ; form . setAttribute ( 'id' , file . uid + '_form' ) ; comp . trigger ( 'change' ) ; input = form = null ; } ; // route click event to the input if ( I . can ( 'summon_file_dialog' ) ) { browseButton = Dom . get ( _options . browse_button ) ; Events . removeEvent ( browseButton , 'click' , comp . uid ) ; Events . addEvent ( browseButton , 'click' , function ( e ) { if ( input && ! input . disabled ) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file] input . click ( ) ; } e . preventDefault ( ) ; } , comp . uid ) ; } _uid = uid ; shimContainer = currForm = browseButton = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the callback function for each item in array / object . If you return false in the callback it will break the loop . [CODESPLIT] function ( obj , callback ) { var length , key , i ; if ( obj ) { length = obj . length ; if ( length === undefined ) { // Loop object items for ( key in obj ) { if ( obj . hasOwnProperty ( key ) ) { if ( callback ( obj [ key ] , key ) === false ) { return ; } } } } else { // Loop array items for ( i = 0 ; i < length ; i ++ ) { if ( callback ( obj [ i ] , i ) === false ) { return ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extends the specified object with another object . [CODESPLIT] function ( target ) { var undef ; each ( arguments , function ( arg , i ) { if ( i > 0 ) { each ( arg , function ( value , key ) { if ( value !== undef ) { if ( typeof ( target [ key ] ) === typeof ( value ) && ( typeof ( value ) === 'object' || util . isArray ( value ) ) ) { extend ( target [ key ] , value ) ; } else { target [ key ] = value ; } } } ) ; } } ) ; return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resizes the image to fit the specified width / height . If crop is specified image will also be cropped to the exact dimensions . [CODESPLIT] function ( options ) { var self = this ; var orientation ; var scale ; var srcRect = { x : 0 , y : 0 , width : self . width , height : self . height } ; var opts = Basic . extendIf ( { width : self . width , height : self . height , type : self . type || 'image/jpeg' , quality : 90 , crop : false , fit : true , preserveHeaders : true , resample : 'default' , multipass : true } , options ) ; try { if ( ! self . size ) { // only preloaded image objects can be used as source throw new x . DOMException ( x . DOMException . INVALID_STATE_ERR ) ; } // no way to reliably intercept the crash due to high resolution, so we simply avoid it if ( self . width > Image . MAX_RESIZE_WIDTH || self . height > Image . MAX_RESIZE_HEIGHT ) { throw new x . ImageError ( x . ImageError . MAX_RESOLUTION_ERR ) ; } // take into account orientation tag orientation = ( self . meta && self . meta . tiff && self . meta . tiff . Orientation ) || 1 ; if ( Basic . inArray ( orientation , [ 5 , 6 , 7 , 8 ] ) !== - 1 ) { // values that require 90 degree rotation var tmp = opts . width ; opts . width = opts . height ; opts . height = tmp ; } if ( opts . crop ) { scale = Math . max ( opts . width / self . width , opts . height / self . height ) ; if ( options . fit ) { // first scale it up or down to fit the original image srcRect . width = Math . min ( Math . ceil ( opts . width / scale ) , self . width ) ; srcRect . height = Math . min ( Math . ceil ( opts . height / scale ) , self . height ) ; // recalculate the scale for adapted dimensions scale = opts . width / srcRect . width ; } else { srcRect . width = Math . min ( opts . width , self . width ) ; srcRect . height = Math . min ( opts . height , self . height ) ; // now we do not need to scale it any further scale = 1 ; } if ( typeof ( opts . crop ) === 'boolean' ) { opts . crop = 'cc' ; } switch ( opts . crop . toLowerCase ( ) . replace ( / _ / , '-' ) ) { case 'rb' : case 'right-bottom' : srcRect . x = self . width - srcRect . width ; srcRect . y = self . height - srcRect . height ; break ; case 'cb' : case 'center-bottom' : srcRect . x = Math . floor ( ( self . width - srcRect . width ) / 2 ) ; srcRect . y = self . height - srcRect . height ; break ; case 'lb' : case 'left-bottom' : srcRect . x = 0 ; srcRect . y = self . height - srcRect . height ; break ; case 'lt' : case 'left-top' : srcRect . x = 0 ; srcRect . y = 0 ; break ; case 'ct' : case 'center-top' : srcRect . x = Math . floor ( ( self . width - srcRect . width ) / 2 ) ; srcRect . y = 0 ; break ; case 'rt' : case 'right-top' : srcRect . x = self . width - srcRect . width ; srcRect . y = 0 ; break ; case 'rc' : case 'right-center' : case 'right-middle' : srcRect . x = self . width - srcRect . width ; srcRect . y = Math . floor ( ( self . height - srcRect . height ) / 2 ) ; break ; case 'lc' : case 'left-center' : case 'left-middle' : srcRect . x = 0 ; srcRect . y = Math . floor ( ( self . height - srcRect . height ) / 2 ) ; break ; case 'cc' : case 'center-center' : case 'center-middle' : default : srcRect . x = Math . floor ( ( self . width - srcRect . width ) / 2 ) ; srcRect . y = Math . floor ( ( self . height - srcRect . height ) / 2 ) ; } // original image might be smaller than requested crop, so - avoid negative values srcRect . x = Math . max ( srcRect . x , 0 ) ; srcRect . y = Math . max ( srcRect . y , 0 ) ; } else { scale = Math . min ( opts . width / self . width , opts . height / self . height ) ; // do not upscale if we were asked to not fit it if ( scale > 1 && ! opts . fit ) { scale = 1 ; } } this . exec ( 'Image' , 'resize' , srcRect , scale , opts ) ; } catch ( ex ) { // for now simply trigger error event self . trigger ( 'error' , ex . code ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downsizes the image to fit the specified width / height . If crop is supplied image will be cropped to exact dimensions . [CODESPLIT] function ( options ) { var defaults = { width : this . width , height : this . height , type : this . type || 'image/jpeg' , quality : 90 , crop : false , fit : false , preserveHeaders : true , resample : 'default' } , opts ; if ( typeof ( options ) === 'object' ) { opts = Basic . extend ( defaults , options ) ; } else { // for backward compatibility opts = Basic . extend ( defaults , { width : arguments [ 0 ] , height : arguments [ 1 ] , crop : arguments [ 2 ] , preserveHeaders : arguments [ 3 ] } ) ; } this . resize ( opts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves image in it s current state as moxie . file . Blob object . Cannot be run on empty or image in progress ( throws DOMException . INVALID_STATE_ERR ) . [CODESPLIT] function ( type , quality ) { if ( ! this . size ) { throw new x . DOMException ( x . DOMException . INVALID_STATE_ERR ) ; } return this . exec ( 'Image' , 'getAsBlob' , type || 'image/jpeg' , quality || 90 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves image in it s current state as binary string . Cannot be run on empty or image in progress ( throws DOMException . INVALID_STATE_ERR ) . [CODESPLIT] function ( type , quality ) { var dataUrl = this . getAsDataURL ( type , quality ) ; return Encode . atob ( dataUrl . substring ( dataUrl . indexOf ( 'base64,' ) + 7 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Embeds a visual representation of the image into the specified node . Depending on the runtime it might be a canvas an img node or a thrid party shim object ( Flash or SilverLight - very rare can be used in legacy browsers that do not have canvas or proper dataURI support ) . [CODESPLIT] function ( el , options ) { var self = this , runtime // this has to be outside of all the closures to contain proper runtime ; var opts = Basic . extend ( { width : this . width , height : this . height , type : this . type || 'image/jpeg' , quality : 90 , fit : true , resample : 'nearest' } , options ) ; function render ( type , quality ) { var img = this ; // if possible, embed a canvas element directly if ( Env . can ( 'create_canvas' ) ) { var canvas = img . getAsCanvas ( ) ; if ( canvas ) { el . appendChild ( canvas ) ; canvas = null ; img . destroy ( ) ; self . trigger ( 'embedded' ) ; return ; } } var dataUrl = img . getAsDataURL ( type , quality ) ; if ( ! dataUrl ) { throw new x . ImageError ( x . ImageError . WRONG_FORMAT ) ; } if ( Env . can ( 'use_data_uri_of' , dataUrl . length ) ) { el . innerHTML = '<img src=\"' + dataUrl + '\" width=\"' + img . width + '\" height=\"' + img . height + '\" alt=\"\" />' ; img . destroy ( ) ; self . trigger ( 'embedded' ) ; } else { var tr = new Transporter ( ) ; tr . bind ( \"TransportingComplete\" , function ( ) { runtime = self . connectRuntime ( this . result . ruid ) ; self . bind ( \"Embedded\" , function ( ) { // position and size properly Basic . extend ( runtime . getShimContainer ( ) . style , { //position: 'relative', top : '0px' , left : '0px' , width : img . width + 'px' , height : img . height + 'px' } ) ; // some shims (Flash/SilverLight) reinitialize, if parent element is hidden, reordered or it's // position type changes (in Gecko), but since we basically need this only in IEs 6/7 and // sometimes 8 and they do not have this problem, we can comment this for now /*tr.bind(\"RuntimeInit\", function(e, runtime) {\n\t\t\t\t\t\t\t\t\ttr.destroy();\n\t\t\t\t\t\t\t\t\truntime.destroy();\n\t\t\t\t\t\t\t\t\tonResize.call(self); // re-feed our image data\n\t\t\t\t\t\t\t\t});*/ runtime = null ; // release } , 999 ) ; runtime . exec . call ( self , \"ImageView\" , \"display\" , this . result . uid , width , height ) ; img . destroy ( ) ; } ) ; tr . transport ( Encode . atob ( dataUrl . substring ( dataUrl . indexOf ( 'base64,' ) + 7 ) ) , type , { required_caps : { display_media : true } , runtime_order : 'flash,silverlight' , container : el } ) ; } } try { if ( ! ( el = Dom . get ( el ) ) ) { throw new x . DOMException ( x . DOMException . INVALID_NODE_TYPE_ERR ) ; } if ( ! this . size ) { // only preloaded image objects can be used as source throw new x . DOMException ( x . DOMException . INVALID_STATE_ERR ) ; } // high-resolution images cannot be consistently handled across the runtimes if ( this . width > Image . MAX_RESIZE_WIDTH || this . height > Image . MAX_RESIZE_HEIGHT ) { //throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR); } var imgCopy = new Image ( ) ; imgCopy . bind ( \"Resize\" , function ( ) { render . call ( this , opts . type , opts . quality ) ; } ) ; imgCopy . bind ( \"Load\" , function ( ) { this . downsize ( opts ) ; } ) ; // if embedded thumb data is available and dimensions are big enough, use it if ( this . meta . thumb && this . meta . thumb . width >= opts . width && this . meta . thumb . height >= opts . height ) { imgCopy . load ( this . meta . thumb . data ) ; } else { imgCopy . clone ( this , false ) ; } return imgCopy ; } catch ( ex ) { // for now simply trigger error event this . trigger ( 'error' , ex . code ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Properly destroys the image and frees resources in use . If any . Recommended way to dispose moxie . image . Image object . [CODESPLIT] function ( ) { if ( this . ruid ) { this . getRuntime ( ) . exec . call ( this , 'Image' , 'destroy' ) ; this . disconnectRuntime ( ) ; } if ( this . meta && this . meta . thumb ) { // thumb is blob, make sure we destroy it first this . meta . thumb . data . destroy ( ) ; } this . unbindAll ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines property with specified descriptor on an object [CODESPLIT] function ( obj , prop , desc ) { if ( o . typeOf ( desc ) === 'object' ) { defineGSetter . call ( obj , prop , desc , 'get' ) ; if ( ! Object . defineProperty ) { // additionally call it for setter defineGSetter . call ( obj , prop , desc , 'set' ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines getter or setter depending on a type param [CODESPLIT] function ( prop , desc , type ) { var defaults = { enumerable : true , configurable : true } , fn , camelType , self = this ; type = type . toLowerCase ( ) ; camelType = type . replace ( / ^[gs] / , function ( $1 ) { return $1 . toUpperCase ( ) ; } ) ; // define function object for fallback if ( o . typeOf ( desc ) === 'function' ) { fn = desc ; desc = { } ; desc [ type ] = fn ; } else if ( o . typeOf ( desc [ type ] ) === 'function' ) { fn = desc [ type ] ; } else { return ; } if ( Env . can ( 'define_property' ) ) { if ( Object . defineProperty ) { return Object . defineProperty ( this , prop , o . extend ( { } , defaults , desc ) ) ; } else { return self [ '__define' + camelType + 'ter__' ] ( prop , fn ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Watch files and repeat drill Add a watcher call main wrapper to repeat cycle [CODESPLIT] function initializeWatchers ( ) { var watcher = chokidar . watch ( '**/*.js' , { ignored : 'node_modules' } ) ; watcher . on ( 'change' , main ) . on ( 'unlink' , main ) ; watchersInitialized = true ; console . log ( 'Watchers initialized' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SyntaxError Holds information about bad syntax found in a message pattern [CODESPLIT] function SyntaxError ( message /*: string */ , expected /*: ?string */ , found /*: ?string */ , offset /*: number */ , line /*: number */ , column /*: number */ ) { Error . call ( this , message ) this . name = 'SyntaxError' this . message = message this . expected = expected this . found = found this . offset = offset this . line = line this . column = column }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! Intl . MessageFormat prollyfill Copyright ( c ) 2015 Andy VanWagoner MIT licensed [CODESPLIT] function MessageFormat ( pattern /*: string */ , locales /*:: ?: string | string[] */ , options /*:: ?: Options */ ) { if ( ! ( this instanceof MessageFormat ) || internals . has ( this ) ) { throw new TypeError ( 'calling MessageFormat constructor without new is invalid' ) } var ast = parse ( pattern ) internals . set ( this , { ast : ast , format : interpret ( ast , locales , options && options . types ) , locale : MessageFormat . supportedLocalesOf ( locales ) [ 0 ] || 'en' , locales : locales , options : options } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The twist of the 8 corners 0 < = twist < 3^7 . The orientation of the DRB corner is fully determined by the orientation of the other corners . [CODESPLIT] function ( twist ) { var i , m , o , ori , parity , v ; if ( twist != null ) { parity = 0 ; for ( i = m = 6 ; m >= 0 ; i = -- m ) { ori = twist % 3 ; twist = ( twist / 3 ) | 0 ; this . co [ i ] = ori ; parity += ori ; } this . co [ 7 ] = ( 3 - parity % 3 ) % 3 ; return this ; } else { v = 0 ; for ( i = o = 0 ; o <= 6 ; i = ++ o ) { v = 3 * v + this . co [ i ] ; } return v ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The flip of the 12 edges 0 < = flip < 2^11 . The orientation of the BR edge is fully determined by the orientation of the other edges . [CODESPLIT] function ( flip ) { var i , m , o , ori , parity , v ; if ( flip != null ) { parity = 0 ; for ( i = m = 10 ; m >= 0 ; i = -- m ) { ori = flip % 2 ; flip = flip / 2 | 0 ; this . eo [ i ] = ori ; parity += ori ; } this . eo [ 11 ] = ( 2 - parity % 2 ) % 2 ; return this ; } else { v = 0 ; for ( i = o = 0 ; o <= 10 ; i = ++ o ) { v = 2 * v + this . eo [ i ] ; } return v ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parity of the corner permutation [CODESPLIT] function ( ) { var i , j , m , o , ref , ref1 , ref2 , ref3 , s ; s = 0 ; for ( i = m = ref = DRB , ref1 = URF + 1 ; ( ref <= ref1 ? m <= ref1 : m >= ref1 ) ; i = ref <= ref1 ? ++ m : -- m ) { for ( j = o = ref2 = i - 1 , ref3 = URF ; ( ref2 <= ref3 ? o <= ref3 : o >= ref3 ) ; j = ref2 <= ref3 ? ++ o : -- o ) { if ( this . cp [ j ] > this . cp [ i ] ) { s ++ ; } } } return s % 2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parity of the edges permutation . Parity of corners and edges are the same if the cube is solvable . [CODESPLIT] function ( ) { var i , j , m , o , ref , ref1 , ref2 , ref3 , s ; s = 0 ; for ( i = m = ref = BR , ref1 = UR + 1 ; ( ref <= ref1 ? m <= ref1 : m >= ref1 ) ; i = ref <= ref1 ? ++ m : -- m ) { for ( j = o = ref2 = i - 1 , ref3 = UR ; ( ref2 <= ref3 ? o <= ref3 : o >= ref3 ) ; j = ref2 <= ref3 ? ++ o : -- o ) { if ( this . ep [ j ] > this . ep [ i ] ) { s ++ ; } } } return s % 2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "see [ ChartConfig#parser ] ( #chartconfig / parser ) [CODESPLIT] function parseXY ( config , _chartProps , callback , parseOpts ) { // Build chart settings from defaults or provided settings parseOpts = parseOpts || { } ; // clone so that we aren't modifying original // this can probably be avoided by applying new settings differently var chartProps = JSON . parse ( JSON . stringify ( _chartProps ) ) ; var bySeries = dataBySeries ( chartProps . input . raw , { checkForDate : true , type : chartProps . input . type } ) ; var labels = chartProps . _annotations . labels ; var allColumn = true ; // check if either scale contains columns, as we'll need to zero the axis var _primaryColumn = false ; var _secondaryColumn = false ; var _scaleComputed = { } ; each ( scaleNames , function ( name ) { _scaleComputed [ name ] = { data : [ ] , hasColumn : false , count : 0 } ; } ) ; var chartSettings = map ( bySeries . series , function ( dataSeries , i ) { var settings ; if ( chartProps . chartSettings [ i ] ) { settings = chartProps . chartSettings [ i ] ; } else { settings = clone ( config . defaultProps . chartProps . chartSettings [ 0 ] ) ; settings . colorIndex = i ; } if ( parseOpts . columnsChanged ) { settings . label = dataSeries . name ; } else { settings . label = settings . label || dataSeries . name ; } var values = map ( dataSeries . values , function ( d ) { return + d . value ; } ) ; // add data points to relevant scale if ( settings . altAxis === false ) { var _computed = _scaleComputed . primaryScale ; _computed . data = _computed . data . concat ( values ) ; _computed . count += 1 ; if ( settings . type == \"column\" ) { _computed . hasColumn = true ; } } else { var _computed = _scaleComputed . secondaryScale ; _computed . data = _computed . data . concat ( values ) ; _computed . count += 1 ; if ( settings . type == \"column\" ) { _computed . hasColumn = true ; } } return settings ; } ) ; labels . values = map ( bySeries . series , function ( dataSeries , i ) { if ( labels . values [ i ] ) { return assign ( { } , { name : chartSettings [ i ] . label } , labels . values [ i ] ) ; } else { return { name : dataSeries . name } ; } } ) ; var maxPrecision = 5 ; var factor = Math . pow ( 10 , maxPrecision ) ; var scale = { } ; var mobileScale = { } ; // Calculate domain and tick values for any scales that exist each ( scaleNames , function ( name ) { var _computed = _scaleComputed [ name ] ; if ( _computed . count > 0 ) { var currScale = chartProps . scale [ name ] || clone ( config . defaultProps . chartProps . scale . primaryScale ) ; var domain = help . computeScaleDomain ( currScale , _computed . data , { nice : true , minZero : _computed . hasColumn } ) ; assign ( currScale , domain ) ; var ticks ; if ( name === \"primaryScale\" ) { ticks = currScale . ticks ; } else { ticks = scale . primaryScale . ticks ; } currScale . tickValues = help . exactTicks ( currScale . domain , ticks ) ; each ( currScale . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > currScale . precision ) { currScale . precision = tickPrecision ; } } ) ; scale [ name ] = currScale ; if ( chartProps . mobile ) { if ( chartProps . mobile . scale ) { var currMobile = chartProps . mobile . scale [ name ] ; if ( currMobile ) { var domain = help . computeScaleDomain ( currMobile , _computed . data , { nice : true , minZero : _computed . hasColumn } ) ; assign ( currMobile , domain ) ; var ticks = ( name == \"primaryScale\" ) ? currMobile . ticks : scale . primaryScale . ticks ; currMobile . tickValues = help . exactTicks ( currMobile . domain , ticks ) ; each ( currMobile . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > currMobile . precision ) { currMobile . precision = tickPrecision ; } } ) ; } } } else { chartProps . mobile = { } ; } } } ) ; // If there is only one primary and >0 secondary, color the left axis if ( _scaleComputed . primaryScale . count === 1 && _scaleComputed . secondaryScale . count > 0 ) { scale . primaryScale . colorIndex = filter ( chartSettings , function ( series ) { return ( series . altAxis === false ) ; } ) [ 0 ] . colorIndex ; } else { scale . primaryScale . colorIndex = null ; } // If there is only one secondary and >0 primary, color the right axis if ( _scaleComputed . secondaryScale . count === 1 && _scaleComputed . primaryScale . count > 0 ) { scale . secondaryScale . colorIndex = filter ( chartSettings , function ( series ) { return ( series . altAxis === true ) ; } ) [ 0 ] . colorIndex ; } else if ( _scaleComputed . secondaryScale . count > 0 ) { scale . secondaryScale . colorIndex = null ; } // create the data structure for the renederer based on input if ( bySeries . hasDate ) { scale . hasDate = bySeries . hasDate ; scale . dateSettings = chartProps . scale . dateSettings || clone ( config . defaultProps . chartProps . scale . dateSettings ) ; scale . dateSettings . inputTZ = scale . dateSettings . inputTZ || SessionStore . get ( \"nowOffset\" ) } if ( bySeries . isNumeric ) { scale . isNumeric = bySeries . isNumeric ; _computed = { //TODO look at entries for all series not just the first data : bySeries . series [ 0 ] . values . map ( function ( d ) { return + d . entry } ) , hasColumn : false , count : 0 } ; var currScale = chartProps . scale . numericSettings || clone ( config . defaultProps . chartProps . scale . numericSettings ) ; var domain = help . computeScaleDomain ( currScale , _computed . data , { nice : true , minZero : false } ) ; assign ( currScale , domain ) ; currScale . ticks = currScale . ticks || help . suggestTickNum ( currScale . domain ) ; var ticks = currScale . ticks ; currScale . tickValues = help . exactTicks ( currScale . domain , ticks ) ; each ( currScale . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > currScale . precision ) { currScale . precision = tickPrecision ; } } ) ; scale . numericSettings = currScale ; if ( chartProps . mobile ) { if ( chartProps . mobile . scale ) { var currMobile = chartProps . mobile . scale . numericSettings ; if ( currMobile ) { var domain = help . computeScaleDomain ( currMobile , _computed . data , { nice : true , minZero : false } ) ; assign ( currMobile , domain ) ; var ticks = currMobile . ticks ; currMobile . tickValues = help . exactTicks ( currMobile . domain , ticks ) ; each ( currMobile . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > currMobile . precision ) { currMobile . precision = tickPrecision ; } } ) ; } chartProps . mobile . scale . numericSettings = currMobile ; } } else { chartProps . mobile = { } ; } } var newChartProps = assign ( chartProps , { chartSettings : chartSettings , scale : scale , input : bySeries . input , data : bySeries . series , _numSecondaryAxis : _scaleComputed . secondaryScale . count } ) ; if ( callback ) { callback ( newChartProps ) ; } else { return newChartProps ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "see [ ChartConfig#parser ] ( #chartconfig / parser ) [CODESPLIT] function parseChartgrid ( config , _chartProps , callback , parseOpts ) { // Build chart settings from defaults or provided settings var chartProps = JSON . parse ( JSON . stringify ( _chartProps ) ) ; var chartgrid_defaults = config . defaultProps . chartProps ; var primaryScale = chartProps . scale . primaryScale || clone ( config . defaultProps . chartProps . scale . primaryScale ) ; var scaleData = [ ] ; var domain ; var height ; var isColumnOrBar ; parseOpts = parseOpts || { } ; // dont check for date column if grid type is bar var checkForDate = chartProps . _grid . type !== \"bar\" ; var bySeries = dataBySeries ( chartProps . input . raw , { checkForDate : checkForDate , type : chartProps . input . type } ) ; var gridSettings = { rows : + chartProps . _grid . rows || chartgrid_defaults . _grid . rows , cols : + chartProps . _grid . cols || bySeries . series . length } ; var chartSettings = map ( bySeries . series , function ( dataSeries , i ) { var settings ; // add data points to relevant scale scaleData = scaleData . concat ( map ( dataSeries . values , function ( d ) { return + d . value ; } ) ) ; if ( chartProps . chartSettings [ i ] ) { settings = chartProps . chartSettings [ i ] ; } else { settings = clone ( chartgrid_defaults . chartSettings [ 0 ] ) ; settings . colorIndex = i ; } if ( parseOpts . columnsChanged ) { settings . label = dataSeries . name ; } else { settings . label = settings . label || dataSeries . name ; } return settings ; } ) ; chartProps . scale . hasDate = bySeries . hasDate ; chartProps . scale . isNumeric = bySeries . isNumeric ; if ( bySeries . hasDate ) { chartProps . scale . dateSettings = chartProps . scale . dateSettings || clone ( config . defaultProps . chartProps . scale . dateSettings ) ; chartProps . scale . dateSettings . inputTZ = chartProps . scale . dateSettings . inputTZ || SessionStore . get ( \"nowOffset\" ) // for dates, default type should be line gridSettings . type = _chartProps . _grid . type || \"line\" ; isColumnOrBar = ( gridSettings . type === \"column\" || gridSettings . type === \"bar\" ) ; domain = help . computeScaleDomain ( primaryScale , scaleData , { nice : true , minZero : isColumnOrBar } ) ; assign ( primaryScale , domain ) ; } else if ( bySeries . isNumeric ) { var maxPrecision = 5 ; var factor = Math . pow ( 10 , maxPrecision ) ; gridSettings . type = _chartProps . _grid . type || \"line\" ; _computed = { //TODO look at entries for all series not just the first data : bySeries . series [ 0 ] . values . map ( function ( d ) { return + d . entry } ) , hasColumn : false , count : 0 } ; var currScale = chartProps . scale . numericSettings || clone ( config . defaultProps . chartProps . scale . numericSettings ) ; var domain = help . computeScaleDomain ( currScale , _computed . data , { nice : true , minZero : false } ) ; assign ( currScale , domain ) ; var ticks = currScale . ticks ; currScale . tickValues = help . exactTicks ( currScale . domain , ticks ) ; each ( currScale . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > currScale . precision ) { currScale . precision = tickPrecision ; } } ) ; chartProps . scale . numericSettings = currScale ; if ( chartProps . mobile ) { if ( chartProps . mobile . scale ) { var currMobile = chartProps . mobile . scale . numericSettings ; if ( currMobile ) { var domain = help . computeScaleDomain ( currMobile , _computed . data , { nice : true , minZero : false } ) ; assign ( currMobile , domain ) ; var ticks = currMobile . ticks ; currMobile . tickValues = help . exactTicks ( currMobile . domain , ticks ) ; each ( currMobile . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > currMobile . precision ) { currMobile . precision = tickPrecision ; } } ) ; } chartProps . mobile . scale . numericSettings = currMobile } } else { chartProps . mobile = { } ; } } else { // ordinals default type should be bar gridSettings . type = _chartProps . _grid . type || \"bar\" ; isColumnOrBar = ( gridSettings . type == \"column\" || gridSettings . type == \"bar\" ) ; domain = help . computeScaleDomain ( primaryScale , scaleData , { minZero : isColumnOrBar } ) ; assign ( primaryScale , domain ) ; } chartProps . scale . primaryScale = primaryScale ; if ( ! chartProps . mobile ) { chartProps . mobile = { } ; } if ( chartProps . mobile . scale ) { chartProps . mobile . scale . hasDate = bySeries . hasDate ; } if ( gridSettings . type != \"bar\" ) { // TODO: this function is used in several places and should be factored out primaryScale . ticks = primaryScale . ticks || 5 ; primaryScale . precision = primaryScale . precision || 0 ; primaryScale . tickValues = help . exactTicks ( primaryScale . domain , primaryScale . ticks ) ; each ( primaryScale . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > primaryScale . precision ) { primaryScale . precision = tickPrecision ; } } ) ; } var newChartProps = assign ( chartProps , { chartSettings : chartSettings , scale : chartProps . scale , input : bySeries . input , _grid : gridSettings , data : bySeries . series } ) ; if ( callback ) { callback ( newChartProps ) ; } else { return newChartProps ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "make_mults [CODESPLIT] function make_mults ( Outer , outerProps , data , gridScales , renderDataFunc ) { var colDomain = gridScales . cols . domain ( ) ; var numCols = colDomain [ colDomain . length - 1 ] + 1 ; // only render number of grid blocks that are selected var numCharts = gridScales . cols . domain ( ) . length * gridScales . rows . domain ( ) . length ; var grid_dimensions = { width : gridScales . cols . rangeBand ( ) , height : gridScales . rows . rangeBand ( ) } ; return map ( data . slice ( 0 , numCharts ) , function ( d , i ) { var pos = { col : i % numCols , row : ( i === 0 ) ? 0 : Math . floor ( i / numCols ) } ; var gridProps = assign ( { } , outerProps , { key : i , translate : [ gridScales . cols ( pos . col ) , gridScales . rows ( pos . row ) ] , dimensions : grid_dimensions } ) ; return Outer ( gridProps , renderDataFunc ( d , i ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if all tickValues are modulo some interval value [CODESPLIT] function all_modulo ( tickValues , interval ) { // we can't modulo-check decimals so we need to multiply by 10^Ndecimals var maxDecimals = reduce ( tickValues , function ( prevMax , tick ) { if ( ( tick % 1 ) !== 0 ) { return Math . max ( prevMax , tick . toString ( ) . split ( \".\" ) [ 1 ] . length ) ; } else { return prevMax ; } } , 0 ) ; var decimalOffset = Math . pow ( 10 , maxDecimals ) ; interval = interval * decimalOffset ; return reduce ( tickValues , function ( prev , curr ) { return prev && ( ( curr * decimalOffset ) % interval === 0 ) ; } , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detect delimiter of input algorithm : if numtabs > = numrows then TSV else CSV [CODESPLIT] function detectDelimiter ( input ) { var numRows = input . split ( / \\r\\n|\\r|\\n / ) . length ; var numTabs = input . replace ( tabRegex , \"\" ) . length ; if ( numTabs >= numRows - 1 ) { return \"\\t\" ; } else { return \",\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Automatically calculate date frequency if not selected [CODESPLIT] function autoDateFormatAndFrequency ( minDate , maxDate , dateFormat , availableWidth ) { var timespan = Math . abs ( maxDate - minDate ) ; var years = timespan / 31536000000 ; var months = timespan / 2628000000 ; var days = timespan / 86400000 ; var yearGap ; var hourGap ; var interval ; var targetPixelGap = 64 ; var maximum_ticks = Math . max ( Math . floor ( availableWidth / targetPixelGap ) , 1 ) ; var time_gap = timespan / maximum_ticks ; if ( dateFormat == \"auto\" ) { //lets go small to large if ( days <= 2 ) { dateFormat = \"h\" ; } else if ( days <= 91 ) { dateFormat = \"M1d\" ; } else if ( months < 36 ) { dateFormat = \"M\" ; } else { dateFormat = \"yy\" ; } } var gapInYears = humanReadableNumber ( Math . floor ( time_gap / 31536000000 ) ) ; var gapInMonths = Math . ceil ( time_gap / 2628000000 ) ; var gapInDays = humanReadableNumber ( time_gap / 86400000 ) ; var gapInHours = humanReadableNumber ( time_gap / 3600000 ) ; //make sure that the interval include the maxDate in the interval list maxDate . addMilliseconds ( 0.1 ) ; switch ( dateFormat ) { case \"yy\" : // Add a day to the max date for years to make inclusive of max date // irrespective of time zone / DST maxDate = d3 . time . day . offset ( maxDate , 1 ) ; interval = d3 . time . year . range ( minDate , maxDate , gapInYears ) ; break ; case \"yyyy\" : // See above maxDate = d3 . time . day . offset ( maxDate , 1 ) ; interval = d3 . time . year . range ( minDate , maxDate , gapInYears ) ; break ; case \"MM\" : interval = d3 . time . month . range ( minDate , maxDate , gapInMonths ) ; break ; case \"M\" : interval = d3 . time . month . range ( minDate , maxDate , gapInMonths ) ; break ; case \"Mdd\" : interval = d3 . time . day . range ( minDate , maxDate , gapInDays ) ; break ; case \"M1d\" : interval = d3 . time . day . range ( minDate , maxDate , gapInDays ) ; break ; case \"YY\" : interval = d3 . time . year . range ( minDate , maxDate , gapInYears ) ; break ; case \"QJan\" : interval = d3 . time . month . range ( minDate , maxDate , 4 ) ; break ; case \"QJul\" : interval = d3 . time . month . range ( minDate , maxDate , 4 ) ; break ; case \"h\" : interval = d3 . time . hour . range ( minDate , maxDate , gapInHours ) ; break ; default : interval = d3 . time . year . range ( minDate , maxDate , 1 ) ; } interval = cleanInterval ( interval ) ; return { \"format\" : dateFormat , \"frequency\" : interval } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test whether a string is a valid Chartbuilder model [CODESPLIT] function validate_chart_model ( modelStr ) { var parsed ; try { parsed = JSON . parse ( modelStr ) ; } catch ( e ) { throw new TypeError ( \"Chart model is not valid JSON\" ) ; } var isValidChartModel = ( parsed . hasOwnProperty ( \"chartProps\" ) && parsed . hasOwnProperty ( \"metadata\" ) ) ; if ( isValidChartModel ) { return parsed ; } else { throw new TypeError ( \"Not a valid Chartbuilder model\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "see [ ChartConfig#calculateDimensions ] ( #chartconfig / calculatedimensions ) [CODESPLIT] function chartGridDimensions ( width , opts ) { var height ; var metadata = opts . metadata ; var grid = opts . grid ; if ( metadata . size == \"auto\" || opts . enableResponsive ) { // use current width } else { width = chartSizes [ metadata . size ] . width ; } if ( grid . type == \"bar\" ) { var numDataPoints = opts . data [ 0 ] . values . length ; height = calculate_bar_height ( numDataPoints , grid , opts . displayConfig ) ; } else { height = calculate_cartesian_height ( width , grid , opts . displayConfig ) ; } if ( ! opts . showMetadata ) { height -= opts . displayConfig . padding . bottom ; } return { width : width , height : height } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Respond to actions coming from the dispatcher [CODESPLIT] function registeredCallback ( payload ) { var action = payload . action ; var data ; switch ( action . eventName ) { /*\n\t\t* New chart model is received. Respond by first waiting for\n\t\t* `ChartProptiesStore`\n\t\t*/ case \"receive-model\" : Dispatcher . waitFor ( [ ChartPropertiesStore . dispatchToken ] ) ; _metadata = action . model . metadata ; data = ChartPropertiesStore . get ( \"data\" ) ; _metadata . title = defaultTitle ( data ) ; ChartMetadataStore . emitChange ( ) ; break ; /* Metadata alone is being updated */ case \"update-metadata\" : _metadata [ action . key ] = action . value ; // if title is edited, set dirty to true and dont generate default anymore // TODO: we don't need to do this every time if ( action . key == \"title\" ) { titleDirty = true ; } ChartMetadataStore . emitChange ( ) ; break ; case \"update-and-reparse\" : if ( ! titleDirty ) { data = ChartPropertiesStore . get ( \"data\" ) ; _metadata . title = defaultTitle ( data ) ; ChartMetadataStore . emitChange ( ) ; } break ; case \"update-data-input\" : if ( ! titleDirty ) { data = ChartPropertiesStore . get ( \"data\" ) ; _metadata . title = defaultTitle ( data ) ; ChartMetadataStore . emitChange ( ) ; } break ; default : // do nothing } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate an exact number of ticks given a domain [CODESPLIT] function exact_ticks ( domain , numticks ) { numticks -= 1 ; var ticks = [ ] ; var delta = domain [ 1 ] - domain [ 0 ] ; var i ; for ( i = 0 ; i < numticks ; i ++ ) { ticks . push ( domain [ 0 ] + ( delta / numticks ) * i ) ; } ticks . push ( domain [ 1 ] ) ; if ( domain [ 1 ] * domain [ 0 ] < 0 ) { //if the domain crosses zero, make sure there is a zero line var hasZero = false ; for ( i = ticks . length - 1 ; i >= 0 ; i -- ) { //check if there is already a zero line if ( ticks [ i ] === 0 ) { hasZero = true ; } } if ( ! hasZero ) { ticks . push ( 0 ) ; } } return ticks ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compute_scale_domain [CODESPLIT] function compute_scale_domain ( scaleObj , data , opts ) { // Compute the domain (`[min, max]`) of a scale based on its data points. // `data` is a flat array of all values used in this scale, and is // created by `input-parsers/parse-<chart>.js` opts = opts || { } ; var scaleDomain = scaleObj . domain || [ ] ; var _domain ; var defaultMin ; var defaultMax ; if ( ! isArray ( data ) ) { throw new TypeError ( \"data passed to compute_scale_domain must be an array\" ) ; } var extent = d3 . extent ( data ) ; var niced = d3 . scale . linear ( ) . domain ( extent ) . nice ( ) . domain ( ) ; if ( ! scaleObj . domain || ! scaleObj . custom ) { if ( opts . nice ) { _domain = niced ; } else { _domain = extent ; } defaultMin = true ; defaultMax = true ; } else { _domain = ( opts . nice ) ? niced : extent ; defaultMin = ( _domain [ 0 ] === scaleDomain [ 0 ] || isUndefined ( scaleDomain [ 0 ] ) ) ; defaultMax = ( _domain [ 1 ] === scaleDomain [ 1 ] || isUndefined ( scaleDomain [ 1 ] ) ) ; _domain = scaleDomain ; } if ( opts . minZero ) { _domain [ 0 ] = Math . min ( _domain [ 0 ] , 0 ) ; } return { domain : _domain , custom : ( ! defaultMin || ! defaultMax ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "round_to_precision Round a number to N decimal places [CODESPLIT] function round_to_precision ( num , precision , supress_thou_sep ) { //zero should always be \"0\" if ( num === 0 ) return \"0\" ; var s = Math . round ( num * Math . pow ( 10 , precision ) ) / Math . pow ( 10 , precision ) ; s = s + \"\" ; s = s . split ( \".\" ) ; if ( s . length == 1 ) { s [ 1 ] = \"\" ; } if ( s [ 1 ] . length < precision ) { s [ 1 ] += Array ( precision - s [ 1 ] . length + 1 ) . join ( \"0\" ) ; } if ( ! supress_thou_sep ) { s [ 0 ] = d3 . format ( \",\" ) ( parseInt ( s [ 0 ] ) ) ; } if ( precision === 0 ) { return s [ 0 ] ; } return s . join ( \".\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "combine_margin_pading [CODESPLIT] function combine_margin_pading ( m , p ) { return { top : m . top + p . top , right : m . right + p . right , bottom : m . bottom + p . bottom , left : m . left + p . left } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "precision [CODESPLIT] function precision ( a ) { // http://stackoverflow.com/a/27865285/1181761 // guard for NaN if ( a === a ) { var e = 1 ; while ( Math . round ( a * e ) / e !== a ) e *= 10 ; return Math . round ( Math . log ( e ) / Math . LN10 ) ; } else { return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "transform_coords [CODESPLIT] function transform_coords ( transformString ) { // Split on both space and comma because IE10 likes spaces? var s = transformString . split ( / \\s|, / ) ; return [ s [ 0 ] . split ( \"(\" ) [ 1 ] , s [ 1 ] . split ( \")\" ) [ 0 ] ] . map ( parseFloat ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a defaults object and a source object copy the value from the source if it contains the same key otherwise return the default . Skip keys that only exist in the source object . [CODESPLIT] function merge_or_apply ( defaults , source ) { var defaultKeys = keys ( defaults ) ; var sourceKeys = keys ( source ) ; return reduce ( defaultKeys , function ( result , key ) { if ( sourceKeys . indexOf ( key ) > - 1 ) { result [ key ] = source [ key ] ; return result ; } else { result [ key ] = defaults [ key ] ; return result ; } } , { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a the domain of a scale suggest the most numerous number of round number ticks that it cold be divided into while still containing values evenly divisible by 1 2 2 . 5 5 10 or 25 . [CODESPLIT] function suggest_tick_num ( domain ) { var MAX_TICKS = 10 ; var INTERVAL_BASE_VALS = [ 1 , 2 , 2.5 , 5 , 10 , 25 ] ; var range = Math . abs ( domain [ 0 ] - domain [ 1 ] ) var minimum = range / MAX_TICKS ; var digits = Math . floor ( range ) . toString ( ) . length ; var multiplier = Math . pow ( 10 , ( digits - 2 ) ) ; var acceptable_intervals = reduce ( INTERVAL_BASE_VALS , function ( prev , curr ) { var mult = curr * multiplier ; if ( mult >= minimum ) { prev = prev . concat ( [ mult ] ) ; } return prev ; } , [ ] ) ; for ( var i = 0 ; i < acceptable_intervals . length ; i ++ ) { var interval = acceptable_intervals [ i ] if ( range % interval == 0 ) { return ( range / interval ) + 1 } } ; return 11 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a timezone offset in an hour : minute format and return the equivalent number of minutes as a number only exist in the source object . [CODESPLIT] function tz_offset_to_minutes ( offset ) { if ( offset == \"Z\" ) { return 0 } var offset = offset . split ( \":\" ) if ( offset . length == 1 ) { offset = offset [ 0 ] split_loc = offset . length - 2 offset = [ offset . substring ( 0 , split_loc ) , offset . substring ( split_loc ) ] } sign = offset [ 0 ] . indexOf ( \"-\" ) > - 1 ? - 1 : 1 offset = offset . map ( parseFloat ) return ( offset [ 0 ] * 60 ) + ( sign * offset [ 1 ] ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### Chart config Set up a configuration object for a given chart type [CODESPLIT] function ChartConfig ( settings ) { this . displayName = settings . displayName ; /**\n\t * Func that parses input and settings to return newly parsed `chartProps`\n\t * @param {object} config - The parsed configuration for this chart type\n\t * @param {object} _chartProps - Previous `chartProps`\n\t * @param {function} callback - Function to pass new `chartProps` to upon parse completion\n\t * @param {object} parseOpts - Additional parse options\n\t *\n\t * @return {Object} chartProps - Updated `chartProps`\n\t * @memberof ChartConfig\n\t * @instance\n\t */ this . parser = settings . parser ; /**\n\t * Func that returns an object of `{width: N, height: N}` that will determine\n\t * dimensions of a chart\n\t * @param {number} width - Width of container or area that will contain the chart\n\t * @param {object} model - The `chartProps` and `metadata` of the current chart\n\t * @param {object} chartConfig - Parsed chart configuration\n\t * @param {boolean} enableResponsive - Should we make dimensions relative to\n\t * container or use preset sizes\n\t * @param {number} extraHeight - Additional height we need to account for, eg\n\t * from wrapped text at the footer\n\t *\n\t * @return {Object} dimensions - Dimensions returned by calculation\n\t * @return {number} dimensions.width\n\t * @return {number} dimension.height\n\t * @memberof ChartConfig\n\t * @instance\n\t */ this . calculateDimensions = settings . calculateDimensions ; this . display = settings . display ; this . defaultProps = settings . defaultProps ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse data by series . Options : checkForDate : bool | tell parser to return dates if key column is date / time / year [CODESPLIT] function dataBySeries ( input , opts ) { var series ; opts = opts || { } ; var parsedInput = parseDelimInput ( input , { checkForDate : opts . checkForDate , type : opts . type } ) ; var columnNames = parsedInput . columnNames ; var keyColumn = columnNames . shift ( ) ; if ( columnNames . length === 0 ) { series = [ { name : keyColumn , values : parsedInput . data . map ( function ( d ) { return { name : keyColumn , value : d [ keyColumn ] } ; } ) } ] ; } else { series = columnNames . map ( function ( header , i ) { return { name : header , values : parsedInput . data . map ( function ( d ) { return { name : header , entry : d [ keyColumn ] , value : d [ header ] } ; } ) } ; } ) ; } return { series : series , input : { raw : input , type : opts . type } , hasDate : parsedInput . hasDate && ( ! opts . type || opts . type == \"date\" ) , isNumeric : parsedInput . isNumeric && ( ! opts . type || opts . type == \"numeric\" ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generateScale [CODESPLIT] function generate_scale ( type , scaleOptions , data , range , additionalOpts ) { if ( ! scaleOptions ) return { } ; return scale_types [ type ] ( scaleOptions , data , range , additionalOpts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : make this keyed funcs that accept a type param ( like ordinal time linear ) so that we dont have to check every time [CODESPLIT] function _ordinalAdjust ( scale , value ) { var isOrdinal = scale . hasOwnProperty ( \"bandwidth\" ) ; if ( isOrdinal ) { return scale ( value ) + scale . bandwidth ( ) / 2 ; } else { return scale ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get_tick_widths [CODESPLIT] function get_tick_widths ( scaleOptions , font ) { if ( ! scaleOptions ) return { width : [ ] , max : 0 } ; var numTicks = scaleOptions . tickValues . length - 1 ; var formattedTicks = reduce ( scaleOptions . tickValues , function ( prev , tick , i ) { if ( i === numTicks ) { return prev . concat ( [ scaleOptions . prefix , help . roundToPrecision ( tick , scaleOptions . precision ) , scaleOptions . suffix ] . join ( \"\" ) ) ; } else { return prev . concat ( help . roundToPrecision ( tick , scaleOptions . precision ) ) ; } } , [ ] ) ; var widths = map ( formattedTicks , function ( text ) { return help . computeTextWidth ( text , font ) ; } ) ; return { widths : widths , max : d3 . max ( widths . slice ( 0 , - 1 ) ) // ignore the top tick } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get thousands and decimal separators based on locale [CODESPLIT] function detectNumberSeparators ( ) { var n = 1000.50 ; var l = n . toLocaleString ( ) ; var s = n . toString ( ) ; var o = { decimal : l . substring ( 5 , 6 ) , thousands : l . substring ( 1 , 2 ) } ; if ( l . substring ( 5 , 6 ) == s . substring ( 5 , 6 ) ) { o . decimal = \".\" ; } if ( l . substring ( 1 , 2 ) == s . substring ( 1 , 2 ) ) { o . thousands = \",\" ; } return o ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Max 400k for chartProps [CODESPLIT] function validateDataInput ( chartProps ) { var input = chartProps . input . raw ; var series = chartProps . data ; var hasDate = chartProps . scale . hasDate ; var isNumeric = chartProps . scale . isNumeric ; var type = chartProps . input . type ; var scale = chartProps . scale ; var inputErrors = [ ] ; // Check whether we have input if ( input . length === 0 ) { inputErrors . push ( \"EMPTY\" ) ; return inputErrors ; } if ( series . length && ! series [ 0 ] . values [ 0 ] . entry ) { // Check that we have at least 1 value col (i.e. minimum header + 1 data col) inputErrors . push ( \"TOO_FEW_SERIES\" ) ; } else if ( series . length > 12 ) { // Check whether there are too many series inputErrors . push ( \"TOO_MANY_SERIES\" ) ; } // Whether a column has a different number of values var unevenSeries = dataPointTest ( series , function ( val ) { return val . value !== null ? ( val . value === undefined || val . value . length === 0 ) : false ; } , function ( empty , vals ) { return empty . length !== vals [ 0 ] . length ; } ) ; if ( unevenSeries ) { inputErrors . push ( \"UNEVEN_SERIES\" ) ; } // Whether a column has something that is NaN but is not nothing (blank) or `null` var nanSeries = somePointTest ( series , function ( val ) { return ( isNaN ( val . value ) && val . value !== undefined && val . value !== \"\" ) ; } ) ; if ( nanSeries ) { inputErrors . push ( \"NAN_VALUES\" ) ; } // Are there multiple types of axis entries var entryTypes = unique ( series [ 0 ] . values . map ( function ( d ) { return typeof d . entry ; } ) ) ; if ( entryTypes . length > 1 && ! chartProps . input . type ) { inputErrors . push ( \"CANT_AUTO_TYPE\" ) ; } //Whether an entry column that is supposed to be a Number is not in fact a number if ( isNumeric || chartProps . input . type == \"numeric\" ) { var badNumSeries = somePointTest ( series , function ( val ) { return isNaN ( val . entry ) ; } ) ; if ( badNumSeries ) { inputErrors . push ( \"NAN_VALUES\" ) ; } } // Whether an entry column that is supposed to be a date is not in fact a date if ( hasDate || chartProps . input . type == \"date\" ) { var badDateSeries = somePointTest ( series , function ( val ) { return ! val . entry . getTime || isNaN ( val . entry . getTime ( ) ) ; } ) ; if ( badDateSeries ) { inputErrors . push ( \"NOT_DATES\" ) ; } var tz_pattern = / ([+-]\\d\\d:*\\d\\d) / gi ; var found_timezones = input . match ( tz_pattern ) ; if ( found_timezones && found_timezones . length != series [ 0 ] . values . length ) { inputErrors . push ( \"UNEVEN_TZ\" ) ; } } // Whether a column has numbers that should be divided var largeNumbers = somePointTest ( series , function ( val ) { return Math . floor ( val . value ) . toString ( ) . length > 4 ; } , function ( largeNums , vals ) { return largeNums . length > 0 ; } ) ; if ( largeNumbers ) { inputErrors . push ( \"LARGE_NUMBERS\" ) ; } // Whether the number of bytes in chartProps exceeds our defined maximum if ( catchChartMistakes . tooMuchData ( chartProps ) ) { inputErrors . push ( \"TOO_MUCH_DATA\" ) ; } // Whether axis ticks divide evenly if ( ! catchChartMistakes . axisTicksEven ( scale . primaryScale ) ) { inputErrors . push ( \"UNEVEN_TICKS\" ) ; } // Whether axis is missing pref and suf if ( catchChartMistakes . noPrefixSuffix ( scale . primaryScale ) ) { inputErrors . push ( \"NO_PREFIX_SUFFIX\" ) ; } return inputErrors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Respond to actions coming from the dispatcher [CODESPLIT] function registeredCallback ( payload ) { var action = payload . action ; var chartProps ; var error_messages ; var input_errors ; switch ( action . eventName ) { /* *\n\t\t* Data input updated or reparse called\n\t\t* */ case \"update-data-input\" : case \"update-and-reparse\" : Dispatcher . waitFor ( [ ChartPropertiesStore . dispatchToken ] ) ; chartProps = ChartPropertiesStore . getAll ( ) ; error_messages = [ ] ; input_errors = validateDataInput ( chartProps ) ; error_messages = error_messages . concat ( input_errors ) ; _errors . messages = error_messages . map ( function ( err_name ) { return errorNames [ err_name ] ; } ) ; var isInvalid = some ( _errors . messages , { type : \"error\" } ) ; _errors . valid = ! isInvalid ; ErrorStore . emitChange ( ) ; break ; default : // do nothing } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : jsDocify this if it works see [ ChartConfig#calculateDimensions ] ( #chartconfig / calculatedimensions ) [CODESPLIT] function calculate_xy_dimensions ( width , opts ) { var height ; var aspectRatio = opts . displayConfig . aspectRatio ; var metadata = opts . metadata ; if ( metadata . size == \"auto\" || opts . enableResponsive ) { // use current width } else { width = chartSizes [ metadata . size ] . width ; } switch ( metadata . size ) { case \"auto\" : height = width * aspectRatio . wide ; break ; case 'medium' : height = width * aspectRatio . wide ; break ; case \"spotLong\" : height = width * aspectRatio . longSpot ; break ; case \"spotSmall\" : height = width * aspectRatio . smallSpot ; break ; default : height = width * aspectRatio . wide ; } return { width : width , height : height } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * eslint - disable no - console [CODESPLIT] function getErrorMessage ( key , action ) { var actionType = action && action . type ; var actionName = actionType && ` ${ actionType . toString ( ) } ` || 'an action' ; return ( ` ${ key } ${ actionName } ` + ` ` ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Completer for the CLI ( multiple files and support to add more ) . [CODESPLIT] function cliCompleter ( set , done ) { var exposed = { } set . valueOf ( ) . forEach ( expose ) set . valueOf ( ) . forEach ( checkFactory ( exposed ) ) done ( ) function expose ( file ) { var landmarks = file . data [ landmarkId ] if ( landmarks ) { xtend ( exposed , landmarks ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory to create a transformer based on the given info and set . [CODESPLIT] function transformerFactory ( fileSet , info ) { return transformer // Transformer. Adds references files to the set. function transformer ( ast , file ) { var filePath = file . path var space = file . data var links = [ ] var landmarks = { } var references var current var link var pathname /* istanbul ignore if - stdin */ if ( ! filePath ) { return } references = gatherReferences ( file , ast , info , fileSet ) current = getPathname ( filePath ) for ( link in references ) { pathname = getPathname ( link ) if ( fileSet && pathname !== current && getHash ( link ) && links . indexOf ( pathname ) === - 1 ) { links . push ( pathname ) fileSet . add ( pathname ) } } landmarks [ filePath ] = true slugs . reset ( ) visit ( ast , mark ) space [ referenceId ] = references space [ landmarkId ] = landmarks function mark ( node ) { var data = node . data || { } var props = data . hProperties || { } var id = props . name || props . id || data . id if ( ! id && node . type === 'heading' ) { id = slugs . slug ( toString ( node ) ) } if ( id ) { landmarks [ filePath + '#' + id ] = true } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if file references headings or files not in exposed . [CODESPLIT] function validate ( exposed , file ) { var references = file . data [ referenceId ] var filePath = file . path var reference var nodes var real var hash var pathname var warning var suggestion var ruleId for ( reference in references ) { nodes = references [ reference ] real = exposed [ reference ] hash = getHash ( reference ) // Check if files without `hash` can be linked to.  Because there’s no need // to inspect those files for headings they are not added to remark.  This // is especially useful because they might be non-markdown files. Here we // check if they exist. if ( ( real === undefined || real === null ) && ! hash && fs ) { real = fs . existsSync ( path . join ( file . cwd , decodeURI ( reference ) ) ) references [ reference ] = real } if ( ! real ) { if ( hash ) { pathname = getPathname ( reference ) warning = 'Link to unknown heading' ruleId = headingRuleId if ( pathname !== filePath ) { warning += ' in `' + pathname + '`' ruleId = headingInFileRuleId } warning += ': `' + hash + '`' } else { warning = 'Link to unknown file: `' + decodeURI ( reference ) + '`' ruleId = fileRuleId } suggestion = getClosest ( reference , exposed ) if ( suggestion ) { warning += '. Did you mean `' + suggestion + '`' } warnAll ( file , nodes , warning , ruleId ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gather references : a map of file - paths references to be one or more nodes . [CODESPLIT] function gatherReferences ( file , tree , info , fileSet ) { var cache = { } var getDefinition = definitions ( tree ) var prefix = '' var headingPrefix = '#' var lines if ( info && info . type in viewPaths ) { prefix = '/' + info . path ( ) + '/' + viewPaths [ info . type ] + '/' } if ( info && info . type in headingPrefixes ) { headingPrefix = headingPrefixes [ info . type ] } lines = info && info . type in lineLinks ? lineLinks [ info . type ] : false visit ( tree , [ 'link' , 'image' , 'linkReference' , 'imageReference' ] , onresource ) return cache // Handle resources. function onresource ( node ) { var link = node . url var definition var index var uri var pathname var hash // Handle references. if ( node . identifier ) { definition = getDefinition ( node . identifier ) link = definition && definition . url } // Ignore definitions without url. if ( ! link ) { return } uri = parse ( link ) // Drop `?search` uri . search = '' link = format ( uri ) if ( ! fileSet && ( uri . hostname || uri . pathname ) ) { return } if ( ! uri . hostname ) { if ( lines && lineExpression . test ( uri . hash ) ) { uri . hash = '' } // Handle hashes, or relative files. if ( ! uri . pathname && uri . hash ) { link = file . path + uri . hash uri = parse ( link ) } else { link = urljoin ( file . dirname , link ) if ( uri . hash ) { link += uri . hash } uri = parse ( link ) } } // Handle full links. if ( uri . hostname ) { if ( ! prefix || ! fileSet ) { return } if ( uri . hostname !== info . domain || uri . pathname . slice ( 0 , prefix . length ) !== prefix ) { return } link = uri . pathname . slice ( prefix . length ) + ( uri . hash || '' ) // Things get interesting here: branches: `foo/bar/baz` could be `baz` on // the `foo/bar` branch, or, `baz` in the `bar` directory on the `foo` // branch. //  Currently, we’re ignoring this and just not supporting branches. link = link . slice ( link . indexOf ( '/' ) + 1 ) } // Handle file links, or combinations of files and hashes. index = link . indexOf ( headingPrefix ) if ( index === - 1 ) { pathname = link hash = null } else { pathname = link . slice ( 0 , index ) hash = link . slice ( index + headingPrefix . length ) if ( lines && lineExpression . test ( hash ) ) { hash = null } } if ( ! cache [ pathname ] ) { cache [ pathname ] = [ ] } cache [ pathname ] . push ( node ) if ( hash ) { link = pathname + '#' + hash if ( ! cache [ link ] ) { cache [ link ] = [ ] } cache [ link ] . push ( node ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle resources . [CODESPLIT] function onresource ( node ) { var link = node . url var definition var index var uri var pathname var hash // Handle references. if ( node . identifier ) { definition = getDefinition ( node . identifier ) link = definition && definition . url } // Ignore definitions without url. if ( ! link ) { return } uri = parse ( link ) // Drop `?search` uri . search = '' link = format ( uri ) if ( ! fileSet && ( uri . hostname || uri . pathname ) ) { return } if ( ! uri . hostname ) { if ( lines && lineExpression . test ( uri . hash ) ) { uri . hash = '' } // Handle hashes, or relative files. if ( ! uri . pathname && uri . hash ) { link = file . path + uri . hash uri = parse ( link ) } else { link = urljoin ( file . dirname , link ) if ( uri . hash ) { link += uri . hash } uri = parse ( link ) } } // Handle full links. if ( uri . hostname ) { if ( ! prefix || ! fileSet ) { return } if ( uri . hostname !== info . domain || uri . pathname . slice ( 0 , prefix . length ) !== prefix ) { return } link = uri . pathname . slice ( prefix . length ) + ( uri . hash || '' ) // Things get interesting here: branches: `foo/bar/baz` could be `baz` on // the `foo/bar` branch, or, `baz` in the `bar` directory on the `foo` // branch. //  Currently, we’re ignoring this and just not supporting branches. link = link . slice ( link . indexOf ( '/' ) + 1 ) } // Handle file links, or combinations of files and hashes. index = link . indexOf ( headingPrefix ) if ( index === - 1 ) { pathname = link hash = null } else { pathname = link . slice ( 0 , index ) hash = link . slice ( index + headingPrefix . length ) if ( lines && lineExpression . test ( hash ) ) { hash = null } } if ( ! cache [ pathname ] ) { cache [ pathname ] = [ ] } cache [ pathname ] . push ( node ) if ( hash ) { link = pathname + '#' + hash if ( ! cache [ link ] ) { cache [ link ] = [ ] } cache [ link ] . push ( node ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility to warn reason for each node in nodes on file . [CODESPLIT] function warnAll ( file , nodes , reason , ruleId ) { nodes . forEach ( one ) function one ( node ) { file . message ( reason , node , [ sourceId , ruleId ] . join ( ':' ) ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Suggest a possible similar reference . [CODESPLIT] function getClosest ( pathname , references ) { var hash = getHash ( pathname ) var base = getPathname ( pathname ) var dictionary = [ ] var reference var subhash var subbase for ( reference in references ) { subbase = getPathname ( reference ) subhash = getHash ( reference ) if ( getPathname ( reference ) === base ) { if ( subhash && hash ) { dictionary . push ( subhash ) } } else if ( ! subhash && ! hash ) { dictionary . push ( subbase ) } } return propose ( hash ? hash : base , dictionary , { threshold : 0.7 } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the hash of uri if applicable . [CODESPLIT] function getHash ( uri ) { var hash = parse ( uri ) . hash return hash ? hash . slice ( 1 ) : null }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an input map contents if a custom map path was specified [CODESPLIT] function getPrevMap ( from ) { if ( typeof options . map . prev === 'string' ) { var mapPath = options . map . prev + path . basename ( from ) + '.map' ; if ( grunt . file . exists ( mapPath ) ) { return grunt . file . read ( mapPath ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "to add back in logging comment this line out [CODESPLIT] function ( req , res , next ) { if ( req . url . indexOf ( '.' ) === - 1 && req . url . indexOf ( startDir ) > - 1 ) { req . url = startPath ; } return next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * One node . [CODESPLIT] function one ( node ) { var type = node && node . type if ( type in map ) { node = map [ type ] ( node ) } if ( 'length' in node ) { node = all ( node ) } if ( node . children ) { node . children = all ( node . children ) } return node }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function Server ( options ) { if ( typeof ( options ) !== 'object' ) throw new TypeError ( 'options (object) is required' ) ; this . _log = options . log . child ( { component : 'agent' } , true ) ; this . _name = options . name || \"named\" ; this . _socket = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "turns a dotted - decimal address into a UInt32 [CODESPLIT] function parseIPv4 ( addr ) { if ( typeof ( addr ) !== 'string' ) throw new TypeError ( 'addr (string) is required' ) ; var octets = addr . split ( / \\. / ) . map ( function ( octet ) { return ( parseInt ( octet , 10 ) ) ; } ) ; if ( octets . length !== 4 ) throw new TypeError ( 'valid IP address required' ) ; var uint32 = ( ( octets [ 0 ] * Math . pow ( 256 , 3 ) ) + ( octets [ 1 ] * Math . pow ( 256 , 2 ) ) + ( octets [ 2 ] * 256 ) + octets [ 3 ] ) ; return ( uint32 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterator used to walk down a nested object . [CODESPLIT] function getNested ( obj , prop ) { var service = obj [ prop ] ; if ( service === undefined && Bottle . config . strict ) { throw new Error ( 'Bottle was unable to resolve a service.  `' + prop + '` is undefined.' ) ; } return service ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a nested bottle . Will set and return if not set . [CODESPLIT] function getNestedBottle ( name ) { var bottle ; if ( ! this . nested [ name ] ) { bottle = Bottle . pop ( ) ; this . nested [ name ] = bottle ; this . factory ( name , function SubProviderFactory ( ) { return bottle . container ; } ) ; } return this . nested [ name ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function used by provider to set up middleware for each request . [CODESPLIT] function applyMiddleware ( middleware , name , instance , container ) { var descriptor = { configurable : true , enumerable : true } ; if ( middleware . length ) { descriptor . get = function getWithMiddlewear ( ) { var index = 0 ; var next = function nextMiddleware ( err ) { if ( err ) { throw err ; } if ( middleware [ index ] ) { middleware [ index ++ ] ( instance , next ) ; } } ; next ( ) ; return instance ; } ; } else { descriptor . value = instance ; descriptor . writable = true ; } Object . defineProperty ( container , name , descriptor ) ; return container [ name ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register middleware . [CODESPLIT] function middleware ( fullname , func ) { var parts , name ; if ( typeof fullname === FUNCTION_TYPE ) { func = fullname ; fullname = GLOBAL_NAME ; } parts = fullname . split ( DELIMITER ) ; name = parts . shift ( ) ; if ( parts . length ) { getNestedBottle . call ( this , name ) . middleware ( parts . join ( DELIMITER ) , func ) ; } else { if ( ! this . middlewares [ name ] ) { this . middlewares [ name ] = [ ] ; } this . middlewares [ name ] . push ( func ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the provider properties on the container [CODESPLIT] function createProvider ( name , Provider ) { var providerName , properties , container , id , decorators , middlewares ; id = this . id ; container = this . container ; decorators = this . decorators ; middlewares = this . middlewares ; providerName = name + PROVIDER_SUFFIX ; properties = Object . create ( null ) ; properties [ providerName ] = { configurable : true , enumerable : true , get : function getProvider ( ) { var instance = new Provider ( ) ; delete container [ providerName ] ; container [ providerName ] = instance ; return instance ; } } ; properties [ name ] = { configurable : true , enumerable : true , get : function getService ( ) { var provider = container [ providerName ] ; var instance ; if ( provider ) { // filter through decorators instance = getWithGlobal ( decorators , name ) . reduce ( reducer , provider . $get ( container ) ) ; delete container [ providerName ] ; delete container [ name ] ; } return instance === undefined ? instance : applyMiddleware ( getWithGlobal ( middlewares , name ) , name , instance , container ) ; } } ; Object . defineProperties ( container , properties ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a provider . [CODESPLIT] function provider ( fullname , Provider ) { var parts , name ; parts = fullname . split ( DELIMITER ) ; if ( this . providerMap [ fullname ] && parts . length === 1 && ! this . container [ fullname + PROVIDER_SUFFIX ] ) { return console . error ( fullname + ' provider already instantiated.' ) ; } this . originalProviders [ fullname ] = Provider ; this . providerMap [ fullname ] = true ; name = parts . shift ( ) ; if ( parts . length ) { getNestedBottle . call ( this , name ) . provider ( parts . join ( DELIMITER ) , Provider ) ; return this ; } return createProvider . call ( this , name , Provider ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private helper for creating service and service factories . [CODESPLIT] function createService ( name , Service , isClass ) { var deps = arguments . length > 3 ? slice . call ( arguments , 3 ) : [ ] ; var bottle = this ; return factory . call ( this , name , function GenericFactory ( ) { var serviceFactory = Service ; // alias for jshint var args = deps . map ( getNestedService , bottle . container ) ; if ( ! isClass ) { return serviceFactory . apply ( null , args ) ; } return new ( Service . bind . apply ( Service , [ null ] . concat ( args ) ) ) ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a class service [CODESPLIT] function service ( name , Service ) { return createService . apply ( this , [ name , Service , true ] . concat ( slice . call ( arguments , 2 ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a function service [CODESPLIT] function serviceFactory ( name , factoryService ) { return createService . apply ( this , [ name , factoryService , false ] . concat ( slice . call ( arguments , 2 ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define a mutable property on the container . [CODESPLIT] function defineValue ( name , val ) { Object . defineProperty ( this , name , { configurable : true , enumerable : true , value : val , writable : true } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterator for setting a plain object literal via defineValue [CODESPLIT] function setValueObject ( container , name ) { var nestedContainer = container [ name ] ; if ( ! nestedContainer ) { nestedContainer = { } ; defineValue . call ( container , name , nestedContainer ) ; } return nestedContainer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a value [CODESPLIT] function value ( name , val ) { var parts ; parts = name . split ( DELIMITER ) ; name = parts . pop ( ) ; defineValue . call ( parts . reduce ( setValueObject , this . container ) , name , val ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a constant [CODESPLIT] function constant ( name , value ) { var parts = name . split ( DELIMITER ) ; name = parts . pop ( ) ; defineConstant . call ( parts . reduce ( setValueObject , this . container ) , name , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register decorator . [CODESPLIT] function decorator ( fullname , func ) { var parts , name ; if ( typeof fullname === FUNCTION_TYPE ) { func = fullname ; fullname = GLOBAL_NAME ; } parts = fullname . split ( DELIMITER ) ; name = parts . shift ( ) ; if ( parts . length ) { getNestedBottle . call ( this , name ) . decorator ( parts . join ( DELIMITER ) , func ) ; } else { if ( ! this . decorators [ name ] ) { this . decorators [ name ] = [ ] ; } this . decorators [ name ] . push ( func ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register an instance factory inside a generic factory . [CODESPLIT] function instanceFactory ( name , Factory ) { return factory . call ( this , name , function GenericInstanceFactory ( container ) { return { instance : Factory . bind ( Factory , container ) } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an instance of bottle . [CODESPLIT] function pop ( name ) { var instance ; if ( typeof name === STRING_TYPE ) { instance = bottles [ name ] ; if ( ! instance ) { bottles [ name ] = instance = new Bottle ( ) ; instance . constant ( 'BOTTLE_NAME' , name ) ; } return instance ; } return new Bottle ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a service factory provider or value based on properties on the object . [CODESPLIT] function register ( Obj ) { var value = Obj . $value === undefined ? Obj : Obj . $value ; return this [ Obj . $type || 'service' ] . apply ( this , [ Obj . $name , value ] . concat ( Obj . $inject || [ ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets providers on a bottle instance . If names array is provided only the named providers will be reset . [CODESPLIT] function resetProviders ( names ) { var tempProviders = this . originalProviders ; var shouldFilter = Array . isArray ( names ) ; Object . keys ( this . originalProviders ) . forEach ( function resetProvider ( originalProviderName ) { if ( shouldFilter && names . indexOf ( originalProviderName ) === - 1 ) { return ; } var parts = originalProviderName . split ( DELIMITER ) ; if ( parts . length > 1 ) { parts . forEach ( removeProviderMap , getNestedBottle . call ( this , parts [ 0 ] ) ) ; } removeProviderMap . call ( this , originalProviderName ) ; this . provider ( originalProviderName , tempProviders [ originalProviderName ] ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the coefficient of determination ( r^2 ) of a fit from the observations and predictions . [CODESPLIT] function determinationCoefficient ( data , results ) { const predictions = [ ] ; const observations = [ ] ; data . forEach ( ( d , i ) => { if ( d [ 1 ] !== null ) { observations . push ( d ) ; predictions . push ( results [ i ] ) ; } } ) ; const sum = observations . reduce ( ( a , observation ) => a + observation [ 1 ] , 0 ) ; const mean = sum / observations . length ; const ssyy = observations . reduce ( ( a , observation ) => { const difference = observation [ 1 ] - mean ; return a + ( difference * difference ) ; } , 0 ) ; const sse = observations . reduce ( ( accum , observation , index ) => { const prediction = predictions [ index ] ; const residual = observation [ 1 ] - prediction [ 1 ] ; return accum + ( residual * residual ) ; } , 0 ) ; return 1 - ( sse / ssyy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the solution of a system of linear equations A * x = b using Gaussian elimination . [CODESPLIT] function gaussianElimination ( input , order ) { const matrix = input ; const n = input . length - 1 ; const coefficients = [ order ] ; for ( let i = 0 ; i < n ; i ++ ) { let maxrow = i ; for ( let j = i + 1 ; j < n ; j ++ ) { if ( Math . abs ( matrix [ i ] [ j ] ) > Math . abs ( matrix [ i ] [ maxrow ] ) ) { maxrow = j ; } } for ( let k = i ; k < n + 1 ; k ++ ) { const tmp = matrix [ k ] [ i ] ; matrix [ k ] [ i ] = matrix [ k ] [ maxrow ] ; matrix [ k ] [ maxrow ] = tmp ; } for ( let j = i + 1 ; j < n ; j ++ ) { for ( let k = n ; k >= i ; k -- ) { matrix [ k ] [ j ] -= ( matrix [ k ] [ i ] * matrix [ i ] [ j ] ) / matrix [ i ] [ i ] ; } } } for ( let j = n - 1 ; j >= 0 ; j -- ) { let total = 0 ; for ( let k = j + 1 ; k < n ; k ++ ) { total += matrix [ k ] [ j ] * coefficients [ k ] ; } coefficients [ j ] = ( matrix [ n ] [ j ] - total ) / matrix [ j ] [ j ] ; } return coefficients ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For internal use . Throws if is passed an invalid AST node else does nothing . [CODESPLIT] function throwIfInvalidNode ( node , functionName ) { if ( ! exports . isASTNode ( node ) ) { throw new Error ( functionName + \"(): \" + util . inspect ( node ) + \" is not a valid AST node.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "While entering nodes register all events and all call expressions that are not part of emit statement While exiting determine which of the registered call expressions is an event trigger and flag them NOTE : This rule currently doesn t flag issues where event declaration & non - emit ted event trigger reside in different contracts which are linked through inheritance . [CODESPLIT] function create ( context ) { const events = [ ] , callExpressions = [ ] , sourceCode = context . getSourceCode ( ) ; // Determines whether the given call name refers to an event declaration using scope resolution. function isEvent ( expr , eventDeclarations ) { for ( let { node , enclosingContract } of eventDeclarations ) { if ( expr . callee . name === node . name && sourceCode . isAChildOf ( expr , enclosingContract ) ) { return true ; } } return false ; } // Stores each declared event in the file and its corresponding parent contract function registerEventName ( emitted ) { const { node } = emitted ; ( ! emitted . exit ) && events . push ( { node , enclosingContract : sourceCode . getParent ( node ) } ) ; } function registerNonEmittedCallExpression ( emitted ) { const { node } = emitted ; if ( ! emitted . exit && sourceCode . getParent ( node ) . type !== \"EmitStatement\" ) { callExpressions . push ( node ) ; } } function reportBadEventTriggers ( emitted ) { if ( ! emitted . exit ) { return ; } callExpressions . forEach ( node => { isEvent ( node , events ) && context . report ( { node , fix ( fixer ) { return fixer . insertTextBefore ( node , \"emit \" ) ; } , message : \"Use emit statements for triggering events.\" } ) ; } ) ; } return { EventDeclaration : registerEventName , CallExpression : registerNonEmittedCallExpression , Program : reportBadEventTriggers } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether the given call name refers to an event declaration using scope resolution . [CODESPLIT] function isEvent ( expr , eventDeclarations ) { for ( let { node , enclosingContract } of eventDeclarations ) { if ( expr . callee . name === node . name && sourceCode . isAChildOf ( expr , enclosingContract ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores each declared event in the file and its corresponding parent contract [CODESPLIT] function registerEventName ( emitted ) { const { node } = emitted ; ( ! emitted . exit ) && events . push ( { node , enclosingContract : sourceCode . getParent ( node ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "collect all variable declarations from VariableDeclarators and DeclarativeExpressions [CODESPLIT] function inspectVariableDeclarator ( emitted ) { let node = emitted . node ; if ( ! emitted . exit ) { allVariableDeclarations [ node . id . name ] = node ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "While exiting Progam Node all the vars that haven t been used still exist inside VariableDeclarations . Report them [CODESPLIT] function inspectProgram ( emitted ) { if ( emitted . exit ) { Object . keys ( allVariableDeclarations ) . forEach ( function ( name ) { context . report ( { node : allVariableDeclarations [ name ] , message : \"Variable '\" + name + \"' is declared but never used.\" } ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "As soon as the first use of a variable is encountered delete that variable s node from allVariableDeclarations [CODESPLIT] function inspectIdentifier ( emitted ) { if ( ! emitted . exit ) { let node = emitted . node , sourceCode = context . getSourceCode ( ) ; if ( allVariableDeclarations [ node . name ] && sourceCode . getParent ( node ) . type !== \"VariableDeclarator\" ) { delete allVariableDeclarations [ node . name ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set cursor to point to first visibility in order of vis . array . For each function Fi inside contract if Fi s vis is same as that pointed by cursor ignore func . If not check the pos in the order of Fi s vis . If ahead simply move cursor forward to Fi s vis . s position in array . If behind report func . [CODESPLIT] function inspectFunctionsOfContract ( emitted ) { if ( emitted . exit ) { return ; } const { node } = emitted , { body } = node ; let cursor = 0 ; // Filter out non-function nodes body . filter ( child => { return [ \"FunctionDeclaration\" , \"ConstructorDeclaration\" ] . includes ( child . type ) ; } ) . forEach ( funcNode => { // Return if the function is ignored or in the correct order. if ( ( context . options && isIgnored ( funcNode , node , context . options [ 0 ] . ignore ) ) || isFunctionVisibility ( node , funcNode , functionOrder [ cursor ] ) ) { return ; } const funcPosInOrder = findFuncPosInOrder ( node , funcNode ) ; if ( funcPosInOrder > cursor ) { cursor = funcPosInOrder ; return ; } context . report ( { node : funcNode , message : errorMessage } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The InformalParameter nodes ( params ) in modifier declaration should follow the same spacing rules as function declarations [CODESPLIT] function inspectModifierDeclaration ( emitted ) { let node = emitted . node ; if ( emitted . exit ) { return ; } //If parameters are specified, ensure appropriate spacing surrounding commas let params = node . params ; if ( params && params . length > 1 ) { params . slice ( 0 , - 1 ) . forEach ( function ( arg ) { sourceCode . getNextChar ( arg ) !== \",\" && context . report ( { node : arg , location : { column : sourceCode . getEndingColumn ( arg ) + 1 } , message : \"All arguments (except the last one) must be immediately followed by a comma.\" } ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "same could potentially be applied to FunctionDeclaration [CODESPLIT] function inspectCallExpression ( emitted ) { let node = emitted . node , callArgs = node . arguments ; if ( emitted . exit ) { return ; } let nodeCode = sourceCode . getText ( node ) ; //for a 0-argument call, ensure that name is followed by '()' if ( ! callArgs . length ) { for ( let i = nodeCode . length ; i > 0 ; i -- ) { if ( nodeCode [ i ] === \")\" && nodeCode [ i - 1 ] === \"(\" ) { return ; } if ( / [\\s\\(\\)] / . test ( nodeCode [ i ] ) ) { break ; } } return context . report ( { node : node , message : \"\\\"\" + nodeCode + \"\\\": \" + \"A call without arguments should have brackets without any whitespace between them, like 'functionName ()'.\" } ) ; } let lastCallArg = callArgs . slice ( - 1 ) [ 0 ] ; //if call spans over multiple lines (due to too many arguments), below rules don't apply if ( sourceCode . getLine ( node ) !== sourceCode . getEndingLine ( lastCallArg ) ) { return ; } let charBeforeFirstArg = sourceCode . getPrevChar ( callArgs [ 0 ] ) , charAfterLastCallArg = sourceCode . getNextChar ( lastCallArg ) ; ( callArgs [ 0 ] . type !== \"NameValueAssignment\" && charBeforeFirstArg !== \"(\" ) && context . report ( { node : callArgs [ 0 ] , location : { column : sourceCode . getColumn ( callArgs [ 0 ] ) - 1 } , message : \"'\" + node . callee . name + \"': The first argument must not be preceded by any whitespace or comments (only '(').\" } ) ; ( lastCallArg . type !== \"NameValueAssignment\" && charAfterLastCallArg !== \")\" ) && context . report ( { node : callArgs [ 0 ] , location : { column : sourceCode . getEndingColumn ( lastCallArg ) + 1 } , message : \"'\" + node . callee . name + \"': The last argument must not be succeeded by any whitespace or comments (only ')').\" } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This executes only when we re leaving the Program node . At that time we check whether the missing pragma on top error has already been reported or not . If not we proceed to report it here . This happens when there are no pragma statements in the entire file . If there is one ( but not on top of file ) it gets reported by inspectPragmaStatement () . NOTE : A Pragma dir must exist at absolute top even before pragma experimental . [CODESPLIT] function inspectProgram ( emitted ) { let node = emitted . node , body = node . body ; if ( ! emitted . exit || missingNodeOnTopErrorReported ) { return ; } ( body . length > 0 ) && ( body [ 0 ] . type !== \"PragmaStatement\" ) && context . report ( { node : node , message : \"No Pragma directive found at the top of file.\" } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Experimental pragmas if they exist must be above everything EXCEPT pragma solidity & other experimental pragmas . [CODESPLIT] function inspectExperimentalPragmaStatement ( emitted ) { if ( emitted . exit ) { return ; } const { node } = emitted , nodesAllowedAbove = [ \"ExperimentalPragmaStatement\" , \"PragmaStatement\" ] , programNode = context . getSourceCode ( ) . getParent ( node ) ; for ( let childNode of programNode . body ) { // If we've reached this exp. pragma while traversing body, it means its position is fine. if ( node . start === childNode . start ) { return ; } // We found the first node not allowed above experimental pragma, report and exit. const pragmaCode = context . getSourceCode ( ) . getText ( node ) ; if ( nodesAllowedAbove . indexOf ( childNode . type ) < 0 ) { const errObject = { node , fix ( fixer ) { return [ fixer . remove ( node ) , fixer . insertTextBefore ( childNode , ` ${ pragmaCode } ${ EOL } ` ) ] ; } , message : \"Experimental Pragma must precede everything except Solidity Pragma.\" } ; return context . report ( errObject ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply fixes to source code depending on whichever errors can be fixed . [CODESPLIT] function ( sourceCode , errorMessages ) { let fixedSourceCode = \"\" , fixes = [ ] , fixesApplied = [ ] , remainingMessages = [ ] ; let cursor = Number . NEGATIVE_INFINITY ; function attemptFix ( fix ) { let start = fix . range [ 0 ] , end = fix . range [ 1 ] ; // If this fix overlaps with the previous one or has negaive range, return. // Note that when cursor === start, its NOT an overlap since when source code in range // [i, j] is being edited, the code covered is actually from i to j-1. if ( cursor > start || start > end ) { return false ; } fixedSourceCode += sourceCode . slice ( Math . max ( 0 , cursor ) , Math . max ( 0 , start ) ) ; fixedSourceCode += fix . text ; cursor = end ; return true ; } // Segregate errors that can be fixed from those that can't for sure. errorMessages . forEach ( function ( msg ) { if ( msg . fix ) { // If msg.fix is an Array of fix packets, merge them into a single fix packet. try { msg . fix = mergeFixes ( msg . fix , sourceCode ) ; } catch ( e ) { throw new Error ( \"An error occured while applying fix of rule \\\"\" + msg . ruleName + \"\\\" for error \\\"\" + msg . message + \"\\\": \" + e . message ) ; } return fixes . push ( msg ) ; } remainingMessages . push ( msg ) ; } ) ; // Fixes will be applied in top-down approach. The fix that arrives first (line-wise, followed by column-wise) // gets applied first. But if current fix is applied successfully & the next one overlaps the current one, // then the next one is simply skipped. Hence, it is NOT guranteed that all fixes will be applied. fixes . sort ( compareMessagesByFixRange ) . forEach ( function ( msg ) { if ( attemptFix ( msg . fix ) ) { return fixesApplied . push ( msg ) ; } remainingMessages . push ( msg ) ; } ) ; fixedSourceCode += sourceCode . slice ( Math . max ( 0 , cursor ) ) ; remainingMessages . sort ( compareMessagesByLocation ) ; return { fixesApplied : fixesApplied , fixedSourceCode : fixedSourceCode , remainingErrorMessages : remainingMessages } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This func will receive either empty str ( len = 0 ) str with N Spaces ( N > = 1 ) or N Tabs ( N > = 1 ) [CODESPLIT] function getIndentDescription ( indentStyle , level ) { // If either user has specified 0 indent or we're at level 0 (start), totalIndent becomes 0. const totalIndent = indentStyle . length * level , s = totalIndent > 1 ? \"s\" : \"\" ; // If style is that there should be no indent for any level OR we're at base level if ( totalIndent === 0 ) { return \"0 whitespace\" ; } if ( indentStyle [ 0 ] === \" \" ) { return ` ${ totalIndent } ${ s } ` ; } // If above 2 are bypassed, indent style must be tab(s) return ` ${ totalIndent } ${ s } ` ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure NO indentation exists before top - level declarations ( contract library ) [CODESPLIT] function inspectProgram ( emitted ) { let node = emitted . node ; if ( emitted . exit ) { return ; } function inspectProgramChild ( programChild ) { //if node's code starts at index 0, getPrevChar() returns null (meaning no errors), so change it to '\\n' let prevChar = sourceCode . getPrevChar ( programChild ) || \"\\n\" , childEndingLine = sourceCode . getEndingLine ( programChild ) , childEndingLineText = sourceCode . getTextOnLine ( childEndingLine ) ; function report ( messageText ) { context . report ( { node : programChild , message : ( programChild . type . replace ( \"Statement\" , \"\" ) . toLowerCase ( ) + ( programChild . name ? ( \" '\" + programChild . name + \"'\" ) : \" statement\" ) + \": \" + messageText ) } ) ; } if ( prevChar !== \"\\n\" ) { //either indentation exists, or some other character - both are not allowed if ( / \\s / . test ( prevChar ) ) { report ( \"There should be no indentation before top-level declaration.\" ) ; } else { report ( \"There should be no character(s) before top-level declaration.\" ) ; } } //if node starts and ends on different lines and its last line starts with a whitespace or multiline/natspec comment, report if ( sourceCode . getLine ( programChild ) !== childEndingLine && / ^(\\s+)|(\\/\\*[^*\\/]*\\*\\/) / . test ( childEndingLineText ) ) { context . report ( { node : programChild , location : { line : childEndingLine , column : 0 } , message : \"Line shouln't have any indentation or comments at the beginning.\" } ) ; } } node . body . forEach ( inspectProgramChild ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure level 1 indentation before all immediate children of top - level declarations [CODESPLIT] function inspectTopLevelDeclaration ( emitted ) { let body = emitted . node . body || [ ] , levelOneIndentRegExp = new RegExp ( \"^\\\\n\" + BASE_INDENTATION_STYLE + \"$\" ) , endingLineRegExp = new RegExp ( \"^\" + BASE_INDENTATION_STYLE + \"(\\\\S| \\\\*)$\" ) , //either a non-whitespace character or 1 extra whitespace followed by * (closing of multi-line comment) endingLineExtraIndentRegExp = new RegExp ( \"^\" + BASE_INDENTATION_STYLE . repeat ( 2 ) + \"(\\\\S| \\\\*)$\" ) ; if ( emitted . exit ) { return ; } function inspectChild ( child ) { let prevChars = sourceCode . getPrevChars ( child , BASE_INDENTATION_STYLE . length + 1 ) , endingLineNum = sourceCode . getEndingLine ( child ) ; //if the start of node doesn't follow correct indentation if ( ! levelOneIndentRegExp . test ( prevChars ) ) { context . report ( { node : child , message : ` ${ BASE_INDENTATION_STYLE_DESC } ` } ) ; } // If the node starts & ends on same line, exit. if ( sourceCode . getLine ( child ) === endingLineNum ) { return ; } // If node starts & ends on diff lines, the ending line must also follow correct indentation. // Exception to this is an abstract function whose declaration spans over multiple lines. Eg- // function foo() //     payable //     returns (uint, string); if ( child . type === \"FunctionDeclaration\" && child . is_abstract ) { if ( ! endingLineExtraIndentRegExp . test ( sourceCode . getTextOnLine ( endingLineNum ) . slice ( 0 , BASE_INDENTATION_STYLE . repeat ( 2 ) . length + 1 ) ) ) { context . report ( { node : child , location : { line : endingLineNum , column : 0 } , message : ` ${ BASE_INDENTATION_STYLE_DESC } ` } ) ; } return ; } if ( ! endingLineRegExp . test ( sourceCode . getTextOnLine ( endingLineNum ) . slice ( 0 , BASE_INDENTATION_STYLE . length + 1 ) ) ) { context . report ( { node : child , location : { line : endingLineNum , column : 0 } , message : ` ${ BASE_INDENTATION_STYLE_DESC } ` } ) ; } } body . forEach ( inspectChild ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure 1 extra indentation inside Block than before it [CODESPLIT] function inspectBlockStatement ( emitted ) { let node = emitted . node ; //if the complete block resides on the same line, no need to check for indentation if ( emitted . exit || ( sourceCode . getLine ( node ) === sourceCode . getEndingLine ( node ) ) ) { return ; } let parent = sourceCode . getParent ( node ) , parentDeclarationLine = sourceCode . getLine ( parent ) , parentDeclarationLineText = sourceCode . getTextOnLine ( parentDeclarationLine ) , currentIndent , currentIndentLevel ; function inspectBlockItem ( blockIndent , blockIndentDesc , blockItem ) { let prevChars = sourceCode . getPrevChars ( blockItem , blockIndent . length + 1 ) , endingLineNum = sourceCode . getEndingLine ( blockItem ) , endingLineRegExp = new RegExp ( \"^\" + blockIndent + \"(\" + BASE_INDENTATION_STYLE + \")?\\\\S.*$\" ) ; if ( prevChars !== ( \"\\n\" + blockIndent ) ) { context . report ( { node : blockItem , message : ` ${ blockIndentDesc } ` } ) ; } /**\n\t\t\t\t * If the block item spans over multiple lines, make sure the ending line also follows the indent rule\n\t\t\t\t * An exception to this is the if-else statements when they don't have BlockStatement as their body\n\t\t\t\t * eg-\n\t\t\t\t * if (a)\n\t\t\t\t *     foo();\n\t\t\t\t * else\n\t\t\t\t *     bar();\n\t\t\t\t *\n\t\t\t\t * Another exception is chaining.\n\t\t\t\t * eg-\n\t\t\t\t * function() {\n\t\t\t\t *   myObject\n\t\t\t\t *     .funcA()\n\t\t\t\t *     .funcB()\n\t\t\t\t *     [0];\n\t\t\t\t * }\n\t\t\t\t * Ending line has 1 extra indentation but this is acceptable.\n\t\t\t\t */ if ( blockItem . type !== \"IfStatement\" && sourceCode . getLine ( blockItem ) !== endingLineNum && ! endingLineRegExp . test ( sourceCode . getTextOnLine ( endingLineNum ) ) ) { context . report ( { node : blockItem , location : { line : endingLineNum , column : 0 } , message : ` ${ blockIndentDesc } ` } ) ; } } currentIndent = parentDeclarationLineText . slice ( 0 , parentDeclarationLineText . indexOf ( parentDeclarationLineText . trim ( ) ) ) ; //in case of no match, match() returns null. Return [] instead to avoid crash currentIndentLevel = ( currentIndent . match ( BASE_INDENTATION_STYLE_REGEXP_GLOBAL ) || [ ] ) . length ; //ensure that there is only whitespace of correct level before the block's parent's code if ( getIndentString ( BASE_INDENTATION_STYLE , currentIndentLevel ) !== currentIndent ) { return ; //exit now, we can' proceed further unless this is fixed } //indentation of items inside block should be 1 level greater than that of parent const blockIndent = getIndentString ( BASE_INDENTATION_STYLE , currentIndentLevel + 1 ) ; const blockIndentDesc = getIndentDescription ( BASE_INDENTATION_STYLE , currentIndentLevel + 1 ) ; node . body . forEach ( inspectBlockItem . bind ( null , blockIndent , blockIndentDesc ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "function params ( if on multiple lines ) [CODESPLIT] function inspectFunctionDeclaration ( emitted ) { let node = emitted . node , params = node . params || [ ] ; let startLine = sourceCode . getLine ( node ) , lastArgLine = params . length ? sourceCode . getEndingLine ( params . slice ( - 1 ) [ 0 ] ) : startLine , functionDeclarationLineText , currentIndent , currentIndentLevel ; function inspectParam ( paramIndent , paramIndentDesc , param ) { let indentRegExp = new RegExp ( \"^\" + paramIndent + \"[^\\\\s(\\/\\*)]\" ) , paramLineText = sourceCode . getTextOnLine ( sourceCode . getLine ( param ) ) ; //parameter declaration must be preceded by only correct level of indentation & no comments ! indentRegExp . test ( paramLineText ) && context . report ( { node : param , message : ` ${ paramIndentDesc } ` } ) ; } // If declaration args start & end on same line, exit now if ( emitted . exit || startLine === lastArgLine ) { return ; } functionDeclarationLineText = sourceCode . getTextOnLine ( startLine ) ; currentIndent = functionDeclarationLineText . slice ( 0 , functionDeclarationLineText . indexOf ( functionDeclarationLineText . trim ( ) ) ) ; currentIndentLevel = ( currentIndent . match ( BASE_INDENTATION_STYLE_REGEXP_GLOBAL ) || [ ] ) . length ; //ensure that there is only whitespace of correct level on the line containing parameter if ( getIndentString ( BASE_INDENTATION_STYLE , currentIndentLevel ) !== currentIndent ) { return ; //exit now, we can' proceed further unless this is fixed } const paramIndent = getIndentString ( BASE_INDENTATION_STYLE , currentIndentLevel + 1 ) ; const paramIndentDesc = getIndentDescription ( BASE_INDENTATION_STYLE , currentIndentLevel + 1 ) ; params . forEach ( inspectParam . bind ( null , paramIndent , paramIndentDesc ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive function . -- elopio - 20180421 [CODESPLIT] function checkNodes ( nodes ) { if ( ! Array . isArray ( nodes ) ) { nodes = [ nodes ] ; } nodes . forEach ( node => { let lineNumber = sourceCode . getLine ( node ) - 1 ; if ( lineNumber > lastLine && lines [ lineNumber ] . length > maxLineLength ) { context . report ( { node , message : ` ${ maxLineLength } ` } ) ; lastLine = lineNumber ; } checkNodes ( node . body || [ ] ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function to retrieve the source code text being linted . Returns the complete source code if no node specified [CODESPLIT] function ( node , beforeCount , afterCount ) { let sourceCodeText = this . text ; if ( node ) { if ( astUtils . isASTNode ( node ) ) { return this . text . slice ( Math . max ( 0 , node . start - ( Math . abs ( beforeCount ) || 0 ) ) , node . end + ( Math . abs ( afterCount ) || 0 ) ) ; } throw new Error ( \"Invalid Node object\" ) ; } return sourceCodeText ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the entire string between 2 nodes - ranging from prevNode . end to currentNode . start ( exclusive ) [CODESPLIT] function ( prevNode , currentNode ) { if ( prevNode && astUtils . isASTNode ( prevNode ) && currentNode && astUtils . isASTNode ( currentNode ) && prevNode . start <= currentNode . start ) { return this . text . slice ( prevNode . end , currentNode . start ) ; } throw new Error ( \"Invalid argument for one or both nodes\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the complete text on line lineNumber ( excluding the EOL ) [CODESPLIT] function ( lineNumber ) { // Call getLines() just to ensure that this.sourceCodeTextLines property is set this . getLines ( ) ; if ( lineNumber && typeof lineNumber === \"number\" && parseInt ( lineNumber ) === lineNumber && //ensure that argument is an INTEGER lineNumber >= 1 && lineNumber <= this . sourceCodeTextLines . length ) { return this . sourceCodeTextLines [ lineNumber - 1 ] ; } throw new Error ( ` ${ lineNumber } ` ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "statement like var x = 10 doesn t come under AssignmentExpression so needs to be checked separately [CODESPLIT] function inspectVariableDeclaration ( emitted ) { let node = emitted . node , code = sourceCode . getText ( node ) ; if ( emitted . exit ) { return ; } //if a particular character is '=', check its left and right for single space for ( let i = 2 ; i < code . length ; i ++ ) { if ( code [ i ] === \"=\" ) { ( ! / ^[^\\/\\s] $ / . test ( code . slice ( i - 2 , i ) ) ) && context . report ( { node : node , message : \"There should be only a single space between assignment operator '=' and its left side.\" } ) ; ( ! / ^ [^\\/\\s]$ / . test ( code . slice ( i + 1 , i + 3 ) ) ) && context . report ( { node : node , message : \"There should be only a single space between assignment operator '=' and its right side.\" } ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "context object Constructor to set read - only properties and provide additional functionality to the rules using it [CODESPLIT] function RuleContext ( ruleName , ruleDesc , ruleMeta , Solium ) { let contextObject = this ; // Set contect attribute 'options' iff options were provided. ruleDesc . options && Object . assign ( contextObject , { options : ruleDesc . options } ) ; //set read-only properties of the context object Object . defineProperties ( contextObject , { name : { value : ruleName , writable : false //though the default is false anyway, I think its better to express your intention clearly } , meta : { value : ruleDesc , writable : false } } ) ; //inherit all Solium methods which are of relevance to the rule INHERITABLE_METHODS . forEach ( function ( methodName ) { contextObject [ methodName ] = function ( s , z , a , b , o ) { //every method will receive 5 arguments tops return Solium [ methodName ] . call ( Solium , s , z , a , b , o ) ; } ; } ) ; /**\n     * wrapper around Solium.report () which adds some additional information to the error object\n     * @param {Object} error An object describing the lint error, sent by the rule currently running\n     */ contextObject . report = function ( error ) { if ( ! isErrObjectValid ( error ) ) { throw new Error ( ` ${ ruleName } ${ EOL } ${ util . inspect ( isErrObjectValid . errors ) } ` ) ; } Object . assign ( error , { ruleName : ruleName , ruleMeta : ruleMeta , type : contextObject . meta . type } ) ; Solium . report ( error ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a ruleset name determine whether its a core set or a sharable config and load the rule config accordingly . [CODESPLIT] function resolveUpstream ( upstream ) { let coreRulesetRegExp = / ^solium:[a-z_]+$ / ; // Determine whether upstream is a solium core ruleset or a sharable config. if ( coreRulesetRegExp . test ( upstream ) ) { try { return require ( \"../../config/rulesets/solium-\" + upstream . split ( \":\" ) [ 1 ] ) . rules ; } catch ( e ) { throw new Error ( \"\\\"\" + upstream + \"\\\" is not a core ruleset.\" ) ; } } // If flow reaches here, it means upstream is a sharable config. let configName = constants . SOLIUM_SHARABLE_CONFIG_PREFIX + upstream , config ; try { config = require ( configName ) ; } catch ( e ) { if ( e . code === \"MODULE_NOT_FOUND\" ) { throw new Error ( \"The sharable config \\\"\" + configName + \"\\\" is not installed. \" + \"If Solium is installed globally, install the config globally using \" + \"\\\"npm install -g \" + configName + \"\\\". Else install locally using \" + \"\\\"npm install --save-dev \" + configName + \"\\\".\" ) ; } throw new Error ( \"The sharable config \\\"\" + configName + \"\\\" could not be loaded: \" + e . message ) ; } if ( isAValidSharableConfig ( config ) ) { return config . rules ; } throw new Error ( \"Invalid sharable config \\\"\" + configName + \"\\\". AJV message:\\n\" + util . inspect ( isAValidSharableConfig . errors ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create provided plugin s default rule configuration [CODESPLIT] function resolvePluginConfig ( name , plugin ) { let config = { } ; Object . keys ( plugin . rules ) . forEach ( function ( ruleName ) { config [ name + \"/\" + ruleName ] = plugin . rules [ ruleName ] . meta . docs . type ; } ) ; return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load rule definitions ( rule objects ) from Solium s core rule directory & from pre - installed linter plugins . [CODESPLIT] function load ( listOfRules ) { let ruleDefs = { } ; listOfRules . forEach ( function ( name ) { // If the rule is part of a plugin, first load the plugin assuming that it has already been installed // in the same scope as Solium (global/project). Then return the appropriate rule from that plugin. if ( name . indexOf ( \"/\" ) > - 1 ) { let parts = name . split ( \"/\" ) , pluginName = constants . SOLIUM_PLUGIN_PREFIX + parts [ 0 ] , ruleName = parts [ 1 ] , plugin ; try { plugin = require ( pluginName ) ; } catch ( e ) { throw new Error ( \"Unable to load Plugin \\\"\" + pluginName + \"\\\".\" ) ; } // No need to verify whether this rule's implementation exists & is valid or not. // That is done at a later stage in solium.js itself using rule-inspector. // TODO: Examine \"peerDependencies\" of the plugin to ensure its compatible with current version of Solium. return ruleDefs [ name ] = plugin . rules [ ruleName ] ; } // If we're here, it means the rule is just a regular core rule :) let ruleFile = path . join ( constants . SOLIUM_CORE_RULES_DIRPATH , name ) ; try { ruleDefs [ name ] = require ( ruleFile ) ; } catch ( e ) { throw new Error ( \"Unable to read \" + ruleFile ) ; } } ) ; return ruleDefs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronously write the passed configuration to the file whose absolute path is SOLIUMRC_FILENAME_ABSOLUTE [CODESPLIT] function writeConfigFile ( config ) { try { fs . writeFileSync ( SOLIUMRC_FILENAME_ABSOLUTE , JSON . stringify ( config , null , 2 ) ) ; } catch ( e ) { errorReporter . reportFatal ( ` ${ SOLIUMRC_FILENAME_ABSOLUTE } ${ EOL } ${ e . message } ` ) ; process . exit ( errorCodes . WRITE_FAILED ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy data from cli - utils / . default - solium - ignore to ( newly created ) . soliumignore in user s root directory [CODESPLIT] function createDefaultSoliumIgnore ( ) { try { fs . writeFileSync ( SOLIUMIGNORE_FILENAME_ABSOLUTE , fs . readFileSync ( DEFAULT_SOLIUMIGNORE_PATH ) ) ; } catch ( e ) { errorReporter . reportFatal ( ` ${ SOLIUMIGNORE_FILENAME_ABSOLUTE } ${ EOL } ${ e . message } ` ) ; process . exit ( errorCodes . WRITE_FAILED ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lint a source code string based on user settings . If autofix is enabled write the fixed code back to file . [CODESPLIT] function lintString ( sourceCode , userConfig , errorReporter , fileName ) { let lintErrors , fixesApplied ; try { if ( userConfig . options . autofix || userConfig . options . autofixDryrun ) { let result = solium . lintAndFix ( sourceCode , userConfig ) ; lintErrors = result . errorMessages ; if ( userConfig . options . autofix ) { applyFixes ( fileName , result ) ; fixesApplied = result . fixesApplied ; } else { errorReporter . reportDiff ( fileName , sourceCode , result . fixedSourceCode , result . fixesApplied . length ) ; } } else { lintErrors = solium . lint ( sourceCode , userConfig ) ; } } catch ( e ) { // Don't abort in case of a parse error, just report it as a normal lint issue. if ( e . name !== \"SyntaxError\" ) { const messageOrStackrace = userConfig . options . debug ? e . stack : e . message ; errorReporter . reportFatal ( ` ${ fileName } ${ EOL } ${ messageOrStackrace } ` ) ; process . exit ( errorCodes . ERRORS_FOUND ) ; } lintErrors = [ { ruleName : \"\" , type : \"error\" , message : ` ${ e . found } ` , line : e . location . start . line , column : e . location . start . column } ] ; } // If any lint/internal errors/warnings exist, report them lintErrors . length && errorReporter . report ( fileName , sourceCode , lintErrors , fixesApplied ) ; return lintErrors . reduce ( function ( numOfErrors , err ) { return err . type === \"error\" ? numOfErrors + 1 : numOfErrors ; } , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lint a file based on user settings [CODESPLIT] function lintFile ( fileName , userConfig , errorReporter ) { let sourceCode ; try { sourceCode = fs . readFileSync ( fileName , \"utf8\" ) ; } catch ( e ) { errorReporter . reportFatal ( \"Unable to read \" + fileName + \": \" + e . message ) ; process . exit ( errorCodes . FILE_NOT_FOUND ) ; } return lintString ( sourceCode , userConfig , errorReporter , fileName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function that calls Solium object s linter based on user settings . If not given we lint the entire directory s ( and sub - directories ) solidity files . [CODESPLIT] function lint ( userConfig , input , ignore , errorReporter ) { let filesToLint , errorCount ; //If filename is provided, lint it. Otherwise, lint over current directory & sub-directories if ( input . file ) { if ( ! fsUtils . isFile ( input . file ) ) { errorReporter . reportFatal ( ` ${ input . file } ` ) ; process . exit ( errorCodes . INVALID_PARAMS ) ; } filesToLint = [ input . file ] ; } else if ( input . dir ) { if ( ! fsUtils . isDirectory ( input . dir ) ) { errorReporter . reportFatal ( ` ${ input . dir } ` ) ; process . exit ( errorCodes . INVALID_PARAMS ) ; } filesToLint = traverse ( input . dir , ignore ) ; } if ( filesToLint ) { errorCount = sum ( filesToLint . map ( function ( file , index ) { userConfig . options . returnInternalIssues = ( index === 0 ) ; return lintFile ( file , userConfig , errorReporter ) ; } ) ) ; } else if ( input . stdin ) { // This only works on *nix. Need to fix to enable stdin input in windows. let sourceCode = fs . readFileSync ( \"/dev/stdin\" , \"utf-8\" ) ; userConfig . options . returnInternalIssues = true ; errorCount = lintString ( sourceCode , userConfig , errorReporter , \"[stdin]\" ) ; } else { errorReporter . reportFatal ( \"Must specify input for linter using --file, --dir or --stdin\" ) ; process . exit ( errorCodes . INVALID_PARAMS ) ; } errorReporter . finalize && errorReporter . finalize ( ) ; return errorCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function responsible for defining all the available commandline options & version information [CODESPLIT] function createCliOptions ( cliObject ) { function collect ( val , memo ) { memo . push ( val ) ; return memo ; } cliObject . version ( ` ${ version } ` ) . description ( \"Linter to find & fix style and security issues in Solidity smart contracts.\" ) . usage ( \"[options] <keyword>\" ) . option ( \"-i, --init\" , \"Create default rule configuration files\" ) . option ( \"-f, --file [filepath::String]\" , \"Solidity file to lint\" ) . option ( \"-d, --dir [dirpath::String]\" , \"Directory containing Solidity files to lint\" ) . option ( \"-R, --reporter [name::String]\" , \"Format to report lint issues in (pretty | gcc)\" , \"pretty\" ) . option ( \"-c, --config [filepath::String]\" , \"Path to the .soliumrc configuration file\" ) . option ( \"-, --stdin\" , \"Read input file from stdin\" ) . option ( \"--fix\" , \"Fix Lint issues where possible\" ) . option ( \"--fix-dry-run\" , \"Output fix diff without applying it\" ) . option ( \"--debug\" , \"Display debug information\" ) . option ( \"--watch\" , \"Watch for file changes\" ) . option ( \"--hot\" , \"(Deprecated) Same as --watch\" ) . option ( \"--no-soliumignore\" , \"Do not look for .soliumignore file\" ) . option ( \"--no-soliumrc\" , \"Do not look for soliumrc configuration file\" ) . option ( \"--rule [rule]\" , \"Rule to execute. This overrides the specified rule's configuration in soliumrc if present\" , collect , [ ] ) . option ( \"--plugin [plugin]\" , \"Plugin to execute. This overrides the specified plugin's configuration in soliumrc if present\" , collect , [ ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Entry point to the CLI reponsible for initiating linting process based on command - line arguments [CODESPLIT] function execute ( programArgs ) { let userConfig = { } , ignore , errorReporter ; createCliOptions ( cli ) ; programArgs . length === 2 ? cli . help ( ) : cli . parse ( programArgs ) ; if ( cli . init ) { return setupDefaultUserConfig ( ) ; } try { errorReporter = getErrorReporter ( cli . reporter ) ; } catch ( e ) { process . stderr . write ( ` ${ e . message } ${ EOL } ` ) ; process . exit ( errorCodes . INVALID_PARAMS ) ; } if ( cli . soliumrc ) { /**\n         * If cli.config option is NOT specified, then resort to .soliumrc in current dir.\n         * Else,\n         *   If path is absolute, assign as-it-is.\n         *   Else (relative pathing) join path with current dir.\n         */ const soliumrcAbsPath = cli . config ? ( path . isAbsolute ( cli . config ) ? cli . config : path . join ( CWD , cli . config ) ) : SOLIUMRC_FILENAME_ABSOLUTE ; try { userConfig = require ( soliumrcAbsPath ) ; } catch ( e ) { // Check if soliumrc file exists. If yes, then the file is in an invalid format. if ( fs . existsSync ( soliumrcAbsPath ) ) { errorReporter . reportFatal ( ` ${ SOLIUMRC_FILENAME } ${ e . message } ` ) ; } else { if ( cli . config ) { errorReporter . reportFatal ( ` ${ soliumrcAbsPath } ` ) ; } else { errorReporter . reportFatal ( ` ${ SOLIUMRC_FILENAME } ` ) ; } } process . exit ( errorCodes . NO_SOLIUMRC ) ; } } //if custom rules' file is set, make sure we have its absolute path if ( userConfig [ \"custom-rules-filename\" ] && ! path . isAbsolute ( userConfig [ \"custom-rules-filename\" ] ) ) { userConfig [ \"custom-rules-filename\" ] = path . join ( CWD , userConfig [ \"custom-rules-filename\" ] ) ; } // Pass cli arguments that modify the behaviour of upstream functions. userConfig . options = { autofix : Boolean ( cli . fix ) , autofixDryrun : Boolean ( cli . fixDryRun ) , debug : Boolean ( cli . debug ) } ; if ( userConfig . options . autofixDryrun ) { if ( userConfig . options . autofix ) { return errorReporter . reportFatal ( \"Cannot use both --fix and --fix-dry-run\" ) ; } if ( cli . reporter != \"pretty\" ) { return errorReporter . reportFatal ( \"Option --fix-dry-run is only supported with pretty reporter\" ) ; } } userConfig . plugins = userConfig . plugins || [ ] ; userConfig . rules = userConfig . rules || { } ; for ( const plugin of cli . plugin ) { userConfig . plugins . push ( plugin ) ; } for ( const rule of cli . rule ) { // If no \":\" was found, it means only the rule's name was specified. // Treat it as an error and adopt its default configuration options. if ( ! rule . includes ( \":\" ) ) { userConfig . rules [ rule ] = \"error\" ; continue ; } let [ key , value ] = rule . split ( \":\" ) . map ( i => i . trim ( ) ) ; try { value = JSON . parse ( value ) ; } catch ( e ) { errorReporter . reportFatal ( ` ${ rule } ${ e . message } ` ) ; process . exit ( errorCodes . INVALID_PARAMS ) ; } userConfig . rules [ key ] = value ; } //get all files & folders to ignore from .soliumignore if ( cli . soliumignore ) { try { ignore = fs . readFileSync ( SOLIUMIGNORE_FILENAME_ABSOLUTE , \"utf8\" ) . split ( EOL ) ; } catch ( e ) { if ( e . code === \"ENOENT\" ) { errorReporter . reportInternal ( \"No '.soliumignore' found. Use --no-soliumignore to make this warning go away.\" ) ; } else { errorReporter . reportInternal ( ` ${ e . message } ` ) ; } } } if ( cli . hot ) { // --hot is equivalent to --watch in functionality, is a legacy option cli . watch = true ; } if ( cli . watch ) { if ( cli . stdin ) { return errorReporter . reportFatal ( \"Cannot watch files when reading from stdin\" ) ; } if ( cli . fix ) { return errorReporter . reportFatal ( \"Automatic code formatting is not supported in watch mode.\" ) ; } } let errorCount = lint ( userConfig , { file : cli . file , dir : cli . dir , stdin : cli . stdin } , ignore , errorReporter ) ; if ( cli . watch ) { let spy = chokidar . watch ( CWD ) ; spy . on ( \"change\" , function ( ) { console . log ( \"\\x1Bc\" ) ; // clear the console console . log ( ` ${ EOL } ` ) ; lint ( userConfig , { file : cli . file , dir : cli . dir } , ignore , errorReporter ) ; //lint on subsequent changes (hot) console . log ( ` ${ EOL } ` ) ; } ) ; } else if ( errorCount > 0 ) { process . exit ( errorCodes . ERRORS_FOUND ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the options object supplied is valid according to the schema passed . [CODESPLIT] function ( options , listItemsSchema ) { let validateOptionsList = SchemaValidator . compile ( { type : \"array\" , minItems : listItemsSchema . length , additionalItems : false , items : listItemsSchema } ) ; return validateOptionsList ( options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find index of the first visibility modifier in declaration . Find the first non - VM before this first VM found above . If non - VM found report the VM . [CODESPLIT] function inspectFD ( emitted ) { const { node } = emitted , visibilityModifiers = [ \"public\" , \"external\" , \"internal\" , \"private\" ] ; const modifiers = ( node . modifiers || [ ] ) , firstVisibilityModifierIndex = modifiers . findIndex ( m => visibilityModifiers . includes ( m . name ) ) ; // If no visibility modifiers exist in function declaration, exit now if ( emitted . exit || firstVisibilityModifierIndex === - 1 ) { return ; } const firstNonVisModifBeforeFirstVisModif = modifiers . slice ( 0 , firstVisibilityModifierIndex ) . find ( m => ! visibilityModifiers . includes ( m . name ) ) ; // TODO: Add fix() for this rule if ( firstNonVisModifBeforeFirstVisModif ) { const issue = { node : modifiers [ firstVisibilityModifierIndex ] , message : ` ${ modifiers [ firstVisibilityModifierIndex ] . name } ` } ; context . report ( issue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "function params ( if on multiple lines ) [CODESPLIT] function inspectFunctionDeclaration ( emitted ) { let node = emitted . node , params = node . params || [ ] ; let startLine = sourceCode . getLine ( node ) , lastArgLine = params . length ? sourceCode . getEndingLine ( params . slice ( - 1 ) [ 0 ] ) : startLine ; if ( emitted . exit ) { return ; } if ( startLine === lastArgLine ) { if ( params . length > MAX_IN_SINGLE_LINE ) { context . report ( { node : node , message : \"In case of more than \" + MAX_IN_SINGLE_LINE + \" parameters, drop each into its own line.\" } ) ; } return ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the provided literal is in Hex Notation [CODESPLIT] function isHex ( literal ) { let reg = / ^[0-9a-f]+$ / i ; //test for '0x' separately because hex notation should not be a part of the standard RegExp if ( literal . slice ( 0 , 2 ) !== \"0x\" ) { return false ; } return reg . test ( literal . slice ( 2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Soundfont object [CODESPLIT] function Soundfont ( ctx , nameToUrl ) { console . warn ( 'new Soundfont() is deprected' ) console . log ( 'Please use Soundfont.instrument() instead of new Soundfont().instrument()' ) if ( ! ( this instanceof Soundfont ) ) return new Soundfont ( ctx ) this . nameToUrl = nameToUrl || Soundfont . nameToUrl this . ctx = ctx this . instruments = { } this . promises = [ ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Load the buffers of a given instrument name . It returns a promise that resolves to a hash with midi note numbers as keys and audio buffers as values . [CODESPLIT] function loadBuffers ( ac , name , options ) { console . warn ( 'Soundfont.loadBuffers is deprecate.' ) console . log ( 'Use Soundfont.instrument(..) and get buffers properties from the result.' ) return Soundfont . instrument ( ac , name , options ) . then ( function ( inst ) { return inst . buffers } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a function that plays an oscillator [CODESPLIT] function oscillatorPlayer ( ctx , defaultOptions ) { defaultOptions = defaultOptions || { } return function ( note , time , duration , options ) { console . warn ( 'The oscillator player is deprecated.' ) console . log ( 'Starting with version 0.9.0 you will have to wait until the soundfont is loaded to play sounds.' ) var midi = note > 0 && note < 129 ? + note : parser . midi ( note ) var freq = midi ? parser . midiToFreq ( midi , 440 ) : null if ( ! freq ) return duration = duration || 0.2 options = options || { } var destination = options . destination || defaultOptions . destination || ctx . destination var vcoType = options . vcoType || defaultOptions . vcoType || 'sine' var gain = options . gain || defaultOptions . gain || 0.4 var vco = ctx . createOscillator ( ) vco . type = vcoType vco . frequency . value = freq /* VCA */ var vca = ctx . createGain ( ) vca . gain . value = gain /* Connections */ vco . connect ( vca ) vca . connect ( destination ) vco . start ( time ) if ( duration > 0 ) vco . stop ( time + duration ) return vco } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load a soundfont instrument . It returns a promise that resolves to a instrument object . [CODESPLIT] function instrument ( ac , name , options ) { if ( arguments . length === 1 ) return function ( n , o ) { return instrument ( ac , n , o ) } var opts = options || { } var isUrl = opts . isSoundfontURL || isSoundfontURL var toUrl = opts . nameToUrl || nameToUrl var url = isUrl ( name ) ? name : toUrl ( name , opts . soundfont , opts . format ) return load ( ac , url , { only : opts . only || opts . notes } ) . then ( function ( buffers ) { var p = player ( ac , buffers , opts ) . connect ( opts . destination ? opts . destination : ac . destination ) p . url = url p . name = name return p } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given an instrument name returns a URL to to the Benjamin Gleitzman s package of [ pre - rendered sound fonts ] ( https : // github . com / gleitz / midi - js - soundfonts ) [CODESPLIT] function nameToUrl ( name , sf , format ) { format = format === 'ogg' ? format : 'mp3' sf = sf === 'FluidR3_GM' ? sf : 'MusyngKite' return 'https://gleitz.github.io/midi-js-soundfonts/' + sf + '/' + name + '-' + format + '.js' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks for lib using ldconfig if present or searching SYSTEM_PATHS otherwise . [CODESPLIT] function hasSystemLib ( lib ) { var libName = 'lib' + lib + '.+(so|dylib)' var libNameRegex = new RegExp ( libName ) // Try using ldconfig on linux systems if ( hasLdconfig ( ) ) { try { if ( childProcess . execSync ( 'ldconfig -p 2>/dev/null | grep -E \"' + libName + '\"' ) . length ) { return true } } catch ( err ) { // noop -- proceed to other search methods } } // Try checking common library locations return SYSTEM_PATHS . some ( function ( systemPath ) { try { var dirListing = fs . readdirSync ( systemPath ) return dirListing . some ( function ( file ) { return libNameRegex . test ( file ) } ) } catch ( err ) { return false } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks for ldconfig on the path and / sbin [CODESPLIT] function hasLdconfig ( ) { try { // Add /sbin to path as ldconfig is located there on some systems -- e.g. // Debian (and it can still be used by unprivileged users): childProcess . execSync ( 'export PATH=\"$PATH:/sbin\"' ) process . env . PATH = '...' // execSync throws on nonzero exit childProcess . execSync ( 'hash ldconfig 2>/dev/null' ) return true } catch ( err ) { return false } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper function to convert a callback to a Promise . [CODESPLIT] async function thenify ( fn ) { return await new Promise ( function ( resolve , reject ) { function callback ( err , res ) { if ( err ) return reject ( err ) ; return resolve ( res ) ; } fn ( callback ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Estimates spent working hours based on commit dates [CODESPLIT] function startWatching ( opts ) { var chokidarOpts = createChokidarOpts ( opts ) ; var watcher = chokidar . watch ( opts . patterns , chokidarOpts ) ; var throttledRun = _ . throttle ( run , opts . throttle ) ; var debouncedRun = _ . debounce ( throttledRun , opts . debounce ) ; watcher . on ( 'all' , function ( event , path ) { var description = EVENT_DESCRIPTIONS [ event ] + ':' ; if ( opts . verbose ) { console . error ( description , path ) ; } else { if ( ! opts . silent ) { console . log ( event + ':' + path ) ; } } // XXX: commands might be still run concurrently if ( opts . command ) { debouncedRun ( opts . command . replace ( / \\{path\\} / ig , path ) . replace ( / \\{event\\} / ig , event ) ) ; } } ) ; watcher . on ( 'error' , function ( error ) { console . error ( 'Error:' , error ) ; console . error ( error . stack ) ; } ) ; watcher . once ( 'ready' , function ( ) { var list = opts . patterns . join ( '\", \"' ) ; if ( ! opts . silent ) { console . error ( 'Watching' , '\"' + list + '\" ..' ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes string or array of strings [CODESPLIT] function _resolveIgnoreOpt ( ignoreOpt ) { if ( ! ignoreOpt ) { return ignoreOpt ; } var ignores = ! _ . isArray ( ignoreOpt ) ? [ ignoreOpt ] : ignoreOpt ; return _ . map ( ignores , function ( ignore ) { var isRegex = ignore [ 0 ] === '/' && ignore [ ignore . length - 1 ] === '/' ; if ( isRegex ) { // Convert user input to regex object var match = ignore . match ( new RegExp ( '^/(.*)/(.*?)$' ) ) ; return new RegExp ( match [ 1 ] , match [ 2 ] ) ; } return ignore ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "XXX : Wrapping tos to a promise is a bit wrong abstraction . Maybe RX suits better? [CODESPLIT] function run ( cmd , opts ) { if ( ! SHELL_PATH ) { // If we cannot resolve shell, better to just crash throw new Error ( '$SHELL environment variable is not set.' ) ; } opts = _ . merge ( { pipe : true , cwd : undefined , callback : function ( child ) { // Since we return promise, we need to provide // this callback if one wants to access the child // process reference // Called immediately after successful child process // spawn } } , opts ) ; return new Promise ( function ( resolve , reject ) { var child ; try { child = childProcess . spawn ( SHELL_PATH , [ EXECUTE_OPTION , cmd ] , { cwd : opts . cwd , stdio : opts . pipe ? 'inherit' : null } ) ; } catch ( e ) { return Promise . reject ( e ) ; } opts . callback ( child ) ; function errorHandler ( err ) { child . removeListener ( 'close' , closeHandler ) ; reject ( err ) ; } function closeHandler ( exitCode ) { child . removeListener ( 'error' , errorHandler ) ; resolve ( exitCode ) ; } child . once ( 'error' , errorHandler ) ; child . once ( 'close' , closeHandler ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Require a prop to not be empty [CODESPLIT] function requireProp ( props , propName , componentName ) { return isEmpty ( props [ propName ] ) ? new Error ( ` \\` ${ propName } \\` \\` ${ componentName } \\` ` ) : null }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accept any number in the 0 = > 1 range [CODESPLIT] function _0to1 ( props , propName , componentName ) { if ( isEmpty ( props [ propName ] ) ) { return null } if ( typeof props [ propName ] === 'number' && props [ propName ] >= 0 && props [ propName ] <= 1 ) { return null } return new Error ( ` \\` ${ propName } \\` \\` ${ componentName } \\` ` ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The thread - loader parallelizes code compilation useful with babel since it transpiles both application javascript and node_modules javascript [CODESPLIT] function babel ( options = { } ) { return ( context , { addLoader } ) => addLoader ( { // setting `test` defaults here, in case there is no `context.match` data test : / \\.(js|jsx)$ / , use : [ { loader : 'thread-loader' , options : { // Keep workers alive for more effective watch mode ... ( process . env . NODE_ENV === 'development' && { poolTimeout : Infinity } ) , } , } , { loader : 'babel-loader' , options : Object . assign ( babelLoaderOptions , options ) , } , ] , ... context . match , } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the css and puts it in the <head > [CODESPLIT] function extractCss ( ) { return ( context , { addLoader } ) => addLoader ( { test : / \\.css$ / , use : [ { loader : MiniCssExtractPlugin . loader , } , ] , ... context . match , } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Images smaller than 10kb are loaded as a base64 encoded url instead of file url [CODESPLIT] function imageLoader ( ) { return ( context , { addLoader } ) => addLoader ( { test : / \\.(gif|ico|jpg|jpeg|png|webp)$ / , loader : 'url-loader' , options : { limit : 10000 , name : fileNameTemplate , } , } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse . csv files with PapaParse and return it in a JSON format [CODESPLIT] function csvLoader ( ) { return ( context , { addLoader } ) => addLoader ( { test : / \\.csv$ / , loader : 'csv-loader' , options : { dynamicTyping : true , header : true , skipEmptyLines : true , } , } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows you to use two kinds of imports for SVG : import logoUrl from . / logo . svg ; gives you the URL . import { ReactComponent as Logo } from . / logo . svg ; gives you a component . [CODESPLIT] function reactSvgLoader ( ) { return ( context , { addLoader } ) => addLoader ( { test : / \\.svg$ / , issuer : { test : / \\.(js|jsx|ts|tsx)$ / , } , use : [ // TODO this is probably not needed // { //   loader: 'babel-loader', //   options: babelLoaderOptions, // }, { loader : '@svgr/webpack' , options : { svgProps : { fill : 'currentColor' , } , titleProp : true , svgoConfig : { multipass : true , pretty : process . env . NODE_ENV === 'development' , indent : 2 , plugins : [ { sortAttrs : true } , { removeViewBox : false } , { removeDimensions : true } , { convertColors : { currentColor : true } } , { cleanupIDs : { minify : false } } , ] , } , } , } , { loader : 'url-loader' , options : { limit : 10000 , name : fileNameTemplate , } , } , ] , } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Url - loader for svgs in css [CODESPLIT] function cssSvgLoader ( ) { return ( context , { addLoader } ) => addLoader ( { // This needs to be different form the reactSvgLoader, otherwise it will merge test : / (.*)\\.svg$ / , issuer : { test : / \\.css$ / , } , loader : 'url-loader' , options : { limit : 10000 , name : fileNameTemplate , } , } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add entryPoint at beginning of entry array [CODESPLIT] function prependEntry ( entry ) { const blockFunction = ( context , util ) => { if ( ! context . entriesToPrepend ) context . entriesToPrepend = [ ] context . entriesToPrepend . unshift ( entry ) return config => config } return Object . assign ( blockFunction , { post : prependEntryPostHook , } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the production build and print the deployment instructions . [CODESPLIT] function build ( ) { log . info ( ` ` ) const compiler = createWebpackCompiler ( ( ) => { log . ok ( ` ${ chalk . cyan ( relativeAppBuildPath ) } ` ) } , ( ) => { log . err ( ` ` ) process . exit ( 2 ) } ) return new Promise ( ( resolve , reject ) => { compiler . run ( ( err , stats ) => { if ( err ) { return reject ( err ) } return resolve ( stats ) } ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * The webpack compiler is a low - level interface to Webpack that lets us listen to some events and provide our own custom messages . [CODESPLIT] function createWebpackCompiler ( onFirstReadyCallback = ( ) => { } , onError = ( ) => { } ) { let compiler try { const config = readWebpackConfig ( ) compiler = webpack ( config ) } catch ( err ) { log . err ( ` \\n ${ err . message || err } ` ) process . exit ( 1 ) } const useTypeScript = fs . existsSync ( ` ${ appDir } ` ) // You have changed a file, bundle is now \"invalidated\", and Webpack is recompiling a bundle. compiler . hooks . invalid . tap ( 'invalid' , filePath => { const filePathRelative = path . relative ( appDir , filePath ) console . log ( ) log . info ( ` ${ chalk . cyan ( filePathRelative ) } ` ) } ) let isFirstCompile = true let tsMessagesPromise // used to wait for the typechecking let tsMessagesResolver // used to trigger the messages after the typechecking if ( useTypeScript ) { // reset the promise compiler . hooks . beforeCompile . tap ( 'beforeCompile' , ( ) => { tsMessagesPromise = new Promise ( resolve => { tsMessagesResolver = msgs => resolve ( msgs ) } ) } ) // trigger the rest of done function ForkTsCheckerWebpackPlugin . getCompilerHooks ( compiler ) . receive . tap ( 'afterTypeScriptCheck' , ( diagnostics , lints ) => { const allMsgs = [ ... diagnostics , ... lints ] const format = message => ` ${ message . file } \\n ${ typescriptFormatter ( message , true ) } ` tsMessagesResolver ( { errors : allMsgs . filter ( msg => msg . severity === 'error' ) . map ( format ) , warnings : allMsgs . filter ( msg => msg . severity === 'warning' ) . map ( format ) , } ) } ) } // Webpack has finished recompiling the bundle (whether or not you have warnings or errors) compiler . hooks . done . tap ( 'done' , async stats => { const statsJson = stats . toJson ( { all : false , warnings : true , errors : true , timings : true , } ) if ( useTypeScript && statsJson . errors . length === 0 ) { // push typescript errors and warnings const messages = await tsMessagesPromise statsJson . errors . push ( ... messages . errors ) statsJson . warnings . push ( ... messages . warnings ) // Push errors and warnings into compilation result // to show them after page refresh triggered by user. stats . compilation . errors . push ( ... messages . errors ) stats . compilation . warnings . push ( ... messages . warnings ) // if (messages.errors.length > 0) { //   devSocket.errors(messages.errors); // } else if (messages.warnings.length > 0) { //   devSocket.warnings(messages.warnings); // } } const messages = formatWebpackMessages ( statsJson ) const time = prettyMs ( statsJson . time ) const isSuccessful = messages . errors . length + messages . warnings . length === 0 if ( isSuccessful ) { log . ok ( ` ${ chalk . cyan ( time ) } ` ) } else if ( messages . errors . length > 0 ) { log . err ( 'Errors in compiling:' ) // Only log the first error. Others are often indicative // of the same problem, but confuse the reader with noise console . log ( listLine ( messages . errors [ 0 ] , chalk . red ) ) onError ( ) } else if ( messages . warnings . length > 0 ) { log . warn ( ` ${ chalk . cyan ( time ) } ` ) messages . warnings . forEach ( message => { console . log ( listLine ( message , chalk . yellow ) ) } ) } // If the first time compiles, also with warnings, // call the onFirstReadyCallback if ( isFirstCompile && messages . errors . length === 0 ) { onFirstReadyCallback ( ) isFirstCompile = false } } ) return compiler }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper that recursively merges two data objects together . [CODESPLIT] function mergeData ( to , from ) { if ( ! from ) { return to } var key , toVal , fromVal ; var keys = Object . keys ( from ) ; for ( var i = 0 ; i < keys . length ; i ++ ) { key = keys [ i ] ; toVal = to [ key ] ; fromVal = from [ key ] ; if ( ! hasOwn ( to , key ) ) { set ( to , key , fromVal ) ; } else if ( toVal !== fromVal && isPlainObject ( toVal ) && isPlainObject ( fromVal ) ) { mergeData ( toVal , fromVal ) ; } } return to }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap a function so that if any code inside triggers state change the changes are queued using a ( macro ) task instead of a microtask . [CODESPLIT] function withMacroTask ( fn ) { return fn . _withTask || ( fn . _withTask = function ( ) { useMacroTask = true ; try { return fn . apply ( null , arguments ) } finally { useMacroTask = false ; } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function transformNode ( el , options ) { var warn = options . warn || baseWarn ; var staticClass = getAndRemoveAttr ( el , 'class' ) ; if ( staticClass ) { var res = parseText ( staticClass , options . delimiters ) ; if ( res ) { warn ( \"class=\\\"\" + staticClass + \"\\\": \" + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class=\"{{ val }}\">, use <div :class=\"val\">.' ) ; } } if ( staticClass ) { el . staticClass = JSON . stringify ( staticClass ) ; } var classBinding = getBindingAttr ( el , 'class' , false /* getStatic */ ) ; if ( classBinding ) { el . classBinding = classBinding ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function transformNode$1 ( el , options ) { var warn = options . warn || baseWarn ; var staticStyle = getAndRemoveAttr ( el , 'style' ) ; if ( staticStyle ) { /* istanbul ignore if */ { var res = parseText ( staticStyle , options . delimiters ) ; if ( res ) { warn ( \"style=\\\"\" + staticStyle + \"\\\": \" + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style=\"{{ val }}\">, use <div :style=\"val\">.' ) ; } } el . staticStyle = JSON . stringify ( parseStyleText ( staticStyle ) ) ; } var styleBinding = getBindingAttr ( el , 'style' , false /* getStatic */ ) ; if ( styleBinding ) { el . styleBinding = styleBinding ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if value is a plain object that is an object created by the Object constructor or one with a [[ Prototype ]] of null . [CODESPLIT] function isPlainObject ( value ) { if ( ! isObjectLike_1 ( value ) || _baseGetTag ( value ) != objectTag ) { return false ; } var proto = _getPrototype ( value ) ; if ( proto === null ) { return true ; } var Ctor = hasOwnProperty$1 . call ( proto , 'constructor' ) && proto . constructor ; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString . call ( Ctor ) == objectCtorString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // github . com / vuejs / vue / blob / dev / src / core / util / props . js#L177 [CODESPLIT] function getType ( fn ) { var type = fn !== null && fn !== undefined ? fn . type ? fn . type : fn : null ; var match = type && type . toString ( ) . match ( FN_MATCH_REGEXP ) ; return match && match [ 1 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a def method to the object returning a new object with passed in argument as default property [CODESPLIT] function withDefault ( type ) { return Object . defineProperty ( type , 'def' , { value : function value ( def ) { if ( def === undefined && ! this . default ) { return this ; } if ( ! isFunction ( def ) && ! validateType ( this , def ) ) { warn ( this . _vueTypes_name + \" - invalid default value: \\\"\" + def + \"\\\"\" , def ) ; return this ; } if ( isArray ( def ) ) { this . default = function ( ) { return [ ] . concat ( def ) ; } ; } else if ( isPlainObject_1 ( def ) ) { this . default = function ( ) { return Object . assign ( { } , def ) ; } ; } else { this . default = def ; } return this ; } , enumerable : false , writable : false } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a isRequired getter returning a new object with required : true key - value [CODESPLIT] function withRequired ( type ) { return Object . defineProperty ( type , 'isRequired' , { get : function get ( ) { this . required = true ; return this ; } , enumerable : false } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a validate method useful to set the prop validator function . [CODESPLIT] function withValidate ( type ) { return Object . defineProperty ( type , 'validate' , { value : function value ( fn ) { this . validator = fn . bind ( this ) ; return this ; } , enumerable : false } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds isRequired and def modifiers to an object [CODESPLIT] function toType ( name , obj , validateFn ) { if ( validateFn === void 0 ) { validateFn = false ; } Object . defineProperty ( obj , '_vueTypes_name' , { enumerable : false , writable : false , value : name } ) ; withDefault ( withRequired ( obj ) ) ; if ( validateFn ) { withValidate ( obj ) ; } if ( isFunction ( obj . validator ) ) { obj . validator = obj . validator . bind ( obj ) ; } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates a given value against a prop type object [CODESPLIT] function validateType ( type , value , silent ) { if ( silent === void 0 ) { silent = false ; } var typeToCheck = type ; var valid = true ; var expectedType ; if ( ! isPlainObject_1 ( type ) ) { typeToCheck = { type : type } ; } var namePrefix = typeToCheck . _vueTypes_name ? typeToCheck . _vueTypes_name + ' - ' : '' ; if ( hasOwn . call ( typeToCheck , 'type' ) && typeToCheck . type !== null ) { if ( isArray ( typeToCheck . type ) ) { valid = typeToCheck . type . some ( function ( type ) { return validateType ( type , value , true ) ; } ) ; expectedType = typeToCheck . type . map ( function ( type ) { return getType ( type ) ; } ) . join ( ' or ' ) ; } else { expectedType = getType ( typeToCheck ) ; if ( expectedType === 'Array' ) { valid = isArray ( value ) ; } else if ( expectedType === 'Object' ) { valid = isPlainObject_1 ( value ) ; } else if ( expectedType === 'String' || expectedType === 'Number' || expectedType === 'Boolean' || expectedType === 'Function' ) { valid = getNativeType ( value ) === expectedType ; } else { valid = value instanceof typeToCheck . type ; } } } if ( ! valid ) { silent === false && warn ( namePrefix + \"value \\\"\" + value + \"\\\" should be of type \\\"\" + expectedType + \"\\\"\" ) ; return false ; } if ( hasOwn . call ( typeToCheck , 'validator' ) && isFunction ( typeToCheck . validator ) ) { // swallow warn var oldWarn ; if ( silent ) { oldWarn = warn ; warn = noop ; } valid = typeToCheck . validator ( value ) ; oldWarn && ( warn = oldWarn ) ; if ( ! valid && silent === false ) warn ( namePrefix + \"custom validation failed\" ) ; return valid ; } return valid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the infamous substitute [CODESPLIT] function CustomEvent ( type , eventInitDict ) { /*jshint eqnull:true */ var event = document . createEvent ( eventName ) ; if ( typeof type != 'string' ) { throw new Error ( 'An event name must be provided' ) ; } if ( eventName == 'Event' ) { event . initCustomEvent = initCustomEvent ; } if ( eventInitDict == null ) { eventInitDict = defaultInitDict ; } event . initCustomEvent ( type , eventInitDict . bubbles , eventInitDict . cancelable , eventInitDict . detail ) ; return event ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "attached at runtime [CODESPLIT] function initCustomEvent ( type , bubbles , cancelable , detail ) { /*jshint validthis:true*/ this . initEvent ( type , bubbles , cancelable ) ; this . detail = detail ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #interface - eventtarget [CODESPLIT] function createEventListener ( type , callback , options ) { function eventListener ( e ) { if ( eventListener . once ) { e . currentTarget . removeEventListener ( e . type , callback , eventListener ) ; eventListener . removed = true ; } if ( eventListener . passive ) { e . preventDefault = createEventListener . preventDefault ; } if ( typeof eventListener . callback === 'function' ) { /* jshint validthis: true */ eventListener . callback . call ( this , e ) ; } else if ( eventListener . callback ) { eventListener . callback . handleEvent ( e ) ; } if ( eventListener . passive ) { delete e . preventDefault ; } } eventListener . type = type ; eventListener . callback = callback ; eventListener . capture = ! ! options . capture ; eventListener . passive = ! ! options . passive ; eventListener . once = ! ! options . once ; // currently pointless but specs say to use it, so ... eventListener . removed = false ; return eventListener ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all events set by this instance during runtime [CODESPLIT] function cleanUpRuntimeEvents ( ) { // Remove all touch events added during 'onDown' as well. document . removeEventListener ( 'touchmove' , onMove , getPassiveSupported ( ) ? { passive : false } : false ) ; document . removeEventListener ( 'touchend' , onUp ) ; document . removeEventListener ( 'touchcancel' , stopTracking ) ; document . removeEventListener ( 'mousemove' , onMove , getPassiveSupported ( ) ? { passive : false } : false ) ; document . removeEventListener ( 'mouseup' , onUp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all required runtime events [CODESPLIT] function addRuntimeEvents ( ) { cleanUpRuntimeEvents ( ) ; // @see https://developers.google.com/web/updates/2017/01/scrolling-intervention document . addEventListener ( 'touchmove' , onMove , getPassiveSupported ( ) ? { passive : false } : false ) ; document . addEventListener ( 'touchend' , onUp ) ; document . addEventListener ( 'touchcancel' , stopTracking ) ; document . addEventListener ( 'mousemove' , onMove , getPassiveSupported ( ) ? { passive : false } : false ) ; document . addEventListener ( 'mouseup' , onUp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a custom normalized event object from touch and mouse events [CODESPLIT] function normalizeEvent ( ev ) { if ( ev . type === 'touchmove' || ev . type === 'touchstart' || ev . type === 'touchend' ) { var touch = ev . targetTouches [ 0 ] || ev . changedTouches [ 0 ] ; return { x : touch . clientX , y : touch . clientY , id : touch . identifier } ; } else { // mouse events return { x : ev . clientX , y : ev . clientY , id : null } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes movement tracking [CODESPLIT] function onDown ( ev ) { var event = normalizeEvent ( ev ) ; if ( ! pointerActive && ! paused ) { pointerActive = true ; decelerating = false ; pointerId = event . id ; pointerLastX = pointerCurrentX = event . x ; pointerLastY = pointerCurrentY = event . y ; trackingPoints = [ ] ; addTrackingPoint ( pointerLastX , pointerLastY ) ; addRuntimeEvents ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles move events [CODESPLIT] function onMove ( ev ) { ev . preventDefault ( ) ; var event = normalizeEvent ( ev ) ; if ( pointerActive && event . id === pointerId ) { pointerCurrentX = event . x ; pointerCurrentY = event . y ; addTrackingPoint ( pointerLastX , pointerLastY ) ; requestTick ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles up / end events [CODESPLIT] function onUp ( ev ) { var event = normalizeEvent ( ev ) ; if ( pointerActive && event . id === pointerId ) { stopTracking ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Records movement for the last 100ms [CODESPLIT] function addTrackingPoint ( x , y ) { var time = Date . now ( ) ; while ( trackingPoints . length > 0 ) { if ( time - trackingPoints [ 0 ] . time <= 100 ) { break ; } trackingPoints . shift ( ) ; } trackingPoints . push ( { x : x , y : y , time : time } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate new values call update function [CODESPLIT] function updateAndRender ( ) { var pointerChangeX = pointerCurrentX - pointerLastX ; var pointerChangeY = pointerCurrentY - pointerLastY ; targetX += pointerChangeX * multiplier ; targetY += pointerChangeY * multiplier ; if ( bounce ) { var diff = checkBounds ( ) ; if ( diff . x !== 0 ) { targetX -= pointerChangeX * dragOutOfBoundsMultiplier ( diff . x ) * multiplier ; } if ( diff . y !== 0 ) { targetY -= pointerChangeY * dragOutOfBoundsMultiplier ( diff . y ) * multiplier ; } } else { checkBounds ( true ) ; } callUpdateCallback ( ) ; pointerLastX = pointerCurrentX ; pointerLastY = pointerCurrentY ; ticking = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize animation of values coming to a stop [CODESPLIT] function startDecelAnim ( ) { var firstPoint = trackingPoints [ 0 ] ; var lastPoint = trackingPoints [ trackingPoints . length - 1 ] ; var xOffset = lastPoint . x - firstPoint . x ; var yOffset = lastPoint . y - firstPoint . y ; var timeOffset = lastPoint . time - firstPoint . time ; var D = timeOffset / 15 / multiplier ; decVelX = xOffset / D || 0 ; // prevent NaN decVelY = yOffset / D || 0 ; var diff = checkBounds ( ) ; if ( Math . abs ( decVelX ) > 1 || Math . abs ( decVelY ) > 1 || ! diff . inBounds ) { decelerating = true ; requestAnimFrame ( stepDecelAnim ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Animates values slowing down [CODESPLIT] function stepDecelAnim ( ) { if ( ! decelerating ) { return ; } decVelX *= friction ; decVelY *= friction ; targetX += decVelX ; targetY += decVelY ; var diff = checkBounds ( ) ; if ( Math . abs ( decVelX ) > stopThreshold || Math . abs ( decVelY ) > stopThreshold || ! diff . inBounds ) { if ( bounce ) { var reboundAdjust = 2.5 ; if ( diff . x !== 0 ) { if ( diff . x * decVelX <= 0 ) { decVelX += diff . x * bounceDeceleration ; } else { var adjust = diff . x > 0 ? reboundAdjust : - reboundAdjust ; decVelX = ( diff . x + adjust ) * bounceAcceleration ; } } if ( diff . y !== 0 ) { if ( diff . y * decVelY <= 0 ) { decVelY += diff . y * bounceDeceleration ; } else { var adjust = diff . y > 0 ? reboundAdjust : - reboundAdjust ; decVelY = ( diff . y + adjust ) * bounceAcceleration ; } } } else { if ( diff . x !== 0 ) { if ( diff . x > 0 ) { targetX = boundXmin ; } else { targetX = boundXmax ; } decVelX = 0 ; } if ( diff . y !== 0 ) { if ( diff . y > 0 ) { targetY = boundYmin ; } else { targetY = boundYmax ; } decVelY = 0 ; } } callUpdateCallback ( ) ; requestAnimFrame ( stepDecelAnim ) ; } else { decelerating = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine position relative to bounds [CODESPLIT] function checkBounds ( restrict ) { var xDiff = 0 ; var yDiff = 0 ; if ( boundXmin !== undefined && targetX < boundXmin ) { xDiff = boundXmin - targetX ; } else if ( boundXmax !== undefined && targetX > boundXmax ) { xDiff = boundXmax - targetX ; } if ( boundYmin !== undefined && targetY < boundYmin ) { yDiff = boundYmin - targetY ; } else if ( boundYmax !== undefined && targetY > boundYmax ) { yDiff = boundYmax - targetY ; } if ( restrict ) { if ( xDiff !== 0 ) { targetX = ( xDiff > 0 ) ? boundXmin : boundXmax ; } if ( yDiff !== 0 ) { targetY = ( yDiff > 0 ) ? boundYmin : boundYmax ; } } return { x : xDiff , y : yDiff , inBounds : xDiff === 0 && yDiff === 0 } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Borrowing from underscorejs https : // github . com / jashkenas / underscore [CODESPLIT] function values ( obj ) { var keys = Object . keys ( obj ) ; var length = keys . length ; var vals = new Array ( length ) ; for ( var i = 0 ; i < length ; i ++ ) { vals [ i ] = obj [ keys [ i ] ] ; } return vals ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The default is to save screenshots to the root of your project even though there is a screenshots path in the config object above! ... so we need a function that returns the correct path for storing our screenshots . While we re at it we are adding some meta - data to the filename specifically the Platform / Browser where the test was run and the test ( file ) name . [CODESPLIT] function imgpath ( browser ) { var a = browser . options . desiredCapabilities ; var meta = [ a . platform ] ; meta . push ( a . browserName ? a . browserName : 'any' ) ; meta . push ( a . version ? a . version : 'any' ) ; meta . push ( a . name ) ; // this is the test filename so always exists. var metadata = meta . join ( '~' ) . toLowerCase ( ) . replace ( /   / g , '' ) ; return SCREENSHOT_PATH + metadata + '_' + padLeft ( FILECOUNT ++ ) + '_' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This route returns the editor page as HTML [CODESPLIT] function ( req , res , next ) { var filePath = req . originalUrl . replace ( '/abe/editor' , '' ) if ( filePath === '' || filePath === '/' ) { filePath = null } if ( filePath != null && path . extname ( filePath ) != ` ${ config . files . templates . extension } ` && path . extname ( filePath ) != '.json' ) { next ( ) return } if ( filePath != null ) { var testXSS = xss ( filePath , { whiteList : [ ] , stripIgnoreTag : true } ) if ( testXSS !== filePath ) { filePath = testXSS } } abeExtend . hooks . instance . trigger ( 'beforeRoute' , req , res , next ) if ( typeof res . _header !== 'undefined' && res . _header !== null ) return var isHome = true var jsonPath = null var template = null var fileName = null var folderPath = null var EditorVariables = { user : res . user , slugs : Manager . instance . getSlugs ( ) , express : { res : res , req : req } , filename : fileName , folderPath : folderPath , abeUrl : '/abe/editor/' , isHome : isHome , config : config , Locales : coreUtils . locales . instance . i18n , abeVersion : pkg . version } let p = new Promise ( resolve => { if ( filePath != null ) { fileName = path . basename ( filePath ) folderPath = path . dirname ( filePath ) EditorVariables . isHome = false EditorVariables . isEditor = true var filePathTest = cmsData . revision . getDocumentRevision ( filePath ) if ( typeof filePathTest !== 'undefined' && filePathTest !== null ) { jsonPath = filePathTest . path template = filePathTest . abe_meta . template } if ( jsonPath === null || ! coreUtils . file . exist ( jsonPath ) ) { res . redirect ( '/abe/editor' ) return } var json = { } if ( coreUtils . file . exist ( jsonPath ) ) { json = cmsData . file . get ( jsonPath , 'utf8' ) } var text = cmsTemplates . template . getTemplate ( template , json ) cmsEditor . editor . create ( text , json ) . then ( result => { resolve ( result ) } ) . catch ( function ( e ) { console . error ( e ) } ) } else { resolve ( { json : { } , manager : { } } ) } } ) . catch ( function ( e ) { console . error ( e ) // \"oh, no!\" } ) p . then ( obj => { var precontribs = Manager . instance . getPrecontribution ( ) var promises = [ ] EditorVariables . resultPrecontrib = [ ] if ( precontribs != null ) { Array . prototype . forEach . call ( precontribs , precontrib => { var p = cmsEditor . editor . create ( precontrib , obj . json , true ) . then ( resultPrecontrib => { EditorVariables . resultPrecontrib . push ( resultPrecontrib ) } ) . catch ( function ( e ) { console . error ( e ) } ) promises . push ( p ) } ) Promise . all ( promises ) . then ( ( ) => { renderAbeAdmin ( EditorVariables , obj , filePath , isHome , template ) } ) . catch ( function ( e ) { console . error ( 'get-main.js getDataList' , e . stack ) } ) } } ) . catch ( e => { console . log ( 'error' , e ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stringify () and serizlier () from https : // github . com / moll / json - stringify - safe [CODESPLIT] function stringify ( obj , replacer , spaces , cycleReplacer ) { if ( typeof replacer !== 'function' ) { replacer = null ; } return JSON . stringify ( obj , serializer ( replacer , cycleReplacer ) , spaces ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ie10以及以下，对某些样式支持有问题，需要降级 [CODESPLIT] function getIEVersion ( ) { var agent = navigator . userAgent var reg = / MSIE\\s?(\\d+)(?:\\.(\\d+))? / i var matches = agent . match ( reg ) if ( matches != null ) { return { major : matches [ 1 ] , minor : matches [ 2 ] } } return { major : '-1' , minor : '-1' } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get all components dirs [CODESPLIT] function initCompDirs ( ) { var compRoot = path . resolve ( process . cwd ( ) , 'src/components' ) , compReg = / ^[A-Z]\\w+$ / ; //['Button', 'Select'] compDirs = fs . readdirSync ( compRoot ) . filter ( function ( filename ) { return compReg . test ( filename ) } ) return compDirs }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a log to a file [CODESPLIT] function appendLogToFileStream ( fileName , newLog , headerLineCount ) { const filePath = path . join ( __dirname , '../../' , fileName ) const oldChangelog = grunt . file . read ( filePath ) . toString ( ) . split ( '\\n' ) ; let wStr = fs . createWriteStream ( filePath ) /** lines used by the default header */ let logHeader = oldChangelog . slice ( 0 , headerLineCount ) ; /** previous changelog entries */ let prevLogs = oldChangelog . slice ( headerLineCount ) ; var s = new Readable ; s . pipe ( wStr ) ; s . push ( logHeader . join ( '\\n' ) + '\\n' ) ; s . push ( newLog ) ; s . push ( prevLogs . join ( '\\n' ) ) ; s . push ( null ) ; // indicates end-of-file basically - the end of the stream) return wStr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "maximum bit length of any code [CODESPLIT] function InfTree ( ) { var that = this ; var hn ; // hufts used in space var v ; // work area for huft_build var c ; // bit length count table var r ; // table entry for structure assignment var u ; // table stack var x ; // bit offsets, then code stack function huft_build ( b , // code lengths in bits (all assumed <= // BMAX) bindex , n , // number of codes (assumed <= 288) s , // number of simple-valued codes (0..s-1) d , // list of base values for non-simple codes e , // list of extra bits for non-simple codes t , // result: starting table m , // maximum lookup bits, returns actual hp , // space for trees hn , // hufts used in space v // working area: values in order of bit length ) { // Given a list of code lengths and a maximum table size, make a set of // tables to decode that set of codes. Return Z_OK on success, // Z_BUF_ERROR // if the given code set is incomplete (the tables are still built in // this // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set // of // lengths), or Z_MEM_ERROR if not enough memory. var a ; // counter for codes of length k var f ; // i repeats in table every f entries var g ; // maximum code length var h ; // table level var i ; // counter, current code var j ; // counter var k ; // number of bits in current code var l ; // bits per table (returned in m) var mask ; // (1 << w) - 1, to avoid cc -O bug on HP var p ; // pointer into c[], b[], or v[] var q ; // points to current table var w ; // bits before this table == (l * h) var xp ; // pointer into x var y ; // number of dummy codes added var z ; // number of entries in current table // Generate counts for each bit length p = 0 ; i = n ; do { c [ b [ bindex + p ] ] ++ ; p ++ ; i -- ; // assume all entries <= BMAX } while ( i !== 0 ) ; if ( c [ 0 ] == n ) { // null input--all zero length codes t [ 0 ] = - 1 ; m [ 0 ] = 0 ; return Z_OK ; } // Find minimum and maximum length, bound *m by those l = m [ 0 ] ; for ( j = 1 ; j <= BMAX ; j ++ ) if ( c [ j ] !== 0 ) break ; k = j ; // minimum code length if ( l < j ) { l = j ; } for ( i = BMAX ; i !== 0 ; i -- ) { if ( c [ i ] !== 0 ) break ; } g = i ; // maximum code length if ( l > i ) { l = i ; } m [ 0 ] = l ; // Adjust last length count to fill out codes, if needed for ( y = 1 << j ; j < i ; j ++ , y <<= 1 ) { if ( ( y -= c [ j ] ) < 0 ) { return Z_DATA_ERROR ; } } if ( ( y -= c [ i ] ) < 0 ) { return Z_DATA_ERROR ; } c [ i ] += y ; // Generate starting offsets into the value table for each length x [ 1 ] = j = 0 ; p = 1 ; xp = 2 ; while ( -- i !== 0 ) { // note that i == g from above x [ xp ] = ( j += c [ p ] ) ; xp ++ ; p ++ ; } // Make a table of values in order of bit lengths i = 0 ; p = 0 ; do { if ( ( j = b [ bindex + p ] ) !== 0 ) { v [ x [ j ] ++ ] = i ; } p ++ ; } while ( ++ i < n ) ; n = x [ g ] ; // set n to length of v // Generate the Huffman codes and for each, make the table entries x [ 0 ] = i = 0 ; // first Huffman code is zero p = 0 ; // grab values in bit order h = - 1 ; // no tables yet--level -1 w = - l ; // bits decoded == (l * h) u [ 0 ] = 0 ; // just to keep compilers happy q = 0 ; // ditto z = 0 ; // ditto // go through the bit lengths (k already is bits in shortest code) for ( ; k <= g ; k ++ ) { a = c [ k ] ; while ( a -- !== 0 ) { // here i is the Huffman code of length k bits for value *p // make tables up to required level while ( k > w + l ) { h ++ ; w += l ; // previous table always l bits // compute minimum size table less than or equal to l bits z = g - w ; z = ( z > l ) ? l : z ; // table size upper limit if ( ( f = 1 << ( j = k - w ) ) > a + 1 ) { // try a k-w bit table // too few codes for // k-w bit table f -= a + 1 ; // deduct codes from patterns left xp = k ; if ( j < z ) { while ( ++ j < z ) { // try smaller tables up to z bits if ( ( f <<= 1 ) <= c [ ++ xp ] ) break ; // enough codes to use up j bits f -= c [ xp ] ; // else deduct codes from patterns } } } z = 1 << j ; // table entries for j-bit table // allocate new table if ( hn [ 0 ] + z > MANY ) { // (note: doesn't matter for fixed) return Z_DATA_ERROR ; // overflow of MANY } u [ h ] = q = /* hp+ */ hn [ 0 ] ; // DEBUG hn [ 0 ] += z ; // connect to last table, if there is one if ( h !== 0 ) { x [ h ] = i ; // save pattern for backing up r [ 0 ] = /* (byte) */ j ; // bits in this table r [ 1 ] = /* (byte) */ l ; // bits to dump before this table j = i >>> ( w - l ) ; r [ 2 ] = /* (int) */ ( q - u [ h - 1 ] - j ) ; // offset to this table hp . set ( r , ( u [ h - 1 ] + j ) * 3 ) ; // to // last // table } else { t [ 0 ] = q ; // first table is returned result } } // set up table entry in r r [ 1 ] = /* (byte) */ ( k - w ) ; if ( p >= n ) { r [ 0 ] = 128 + 64 ; // out of values--invalid code } else if ( v [ p ] < s ) { r [ 0 ] = /* (byte) */ ( v [ p ] < 256 ? 0 : 32 + 64 ) ; // 256 is // end-of-block r [ 2 ] = v [ p ++ ] ; // simple code is just the value } else { r [ 0 ] = /* (byte) */ ( e [ v [ p ] - s ] + 16 + 64 ) ; // non-simple--look // up in lists r [ 2 ] = d [ v [ p ++ ] - s ] ; } // fill code-like entries with r f = 1 << ( k - w ) ; for ( j = i >>> w ; j < z ; j += f ) { hp . set ( r , ( q + j ) * 3 ) ; } // backwards increment the k-bit code i for ( j = 1 << ( k - 1 ) ; ( i & j ) !== 0 ; j >>>= 1 ) { i ^= j ; } i ^= j ; // backup over finished tables mask = ( 1 << w ) - 1 ; // needed on HP, cc -O bug while ( ( i & mask ) != x [ h ] ) { h -- ; // don't need to update q w -= l ; mask = ( 1 << w ) - 1 ; } } } // Return Z_BUF_ERROR if we were given an incomplete table return y !== 0 && g != 1 ? Z_BUF_ERROR : Z_OK ; } function initWorkArea ( vsize ) { var i ; if ( ! hn ) { hn = [ ] ; // []; //new Array(1); v = [ ] ; // new Array(vsize); c = new Int32Array ( BMAX + 1 ) ; // new Array(BMAX + 1); r = [ ] ; // new Array(3); u = new Int32Array ( BMAX ) ; // new Array(BMAX); x = new Int32Array ( BMAX + 1 ) ; // new Array(BMAX + 1); } if ( v . length < vsize ) { v = [ ] ; // new Array(vsize); } for ( i = 0 ; i < vsize ; i ++ ) { v [ i ] = 0 ; } for ( i = 0 ; i < BMAX + 1 ; i ++ ) { c [ i ] = 0 ; } for ( i = 0 ; i < 3 ; i ++ ) { r [ i ] = 0 ; } // for(int i=0; i<BMAX; i++){u[i]=0;} u . set ( c . subarray ( 0 , BMAX ) , 0 ) ; // for(int i=0; i<BMAX+1; i++){x[i]=0;} x . set ( c . subarray ( 0 , BMAX + 1 ) , 0 ) ; } that . inflate_trees_bits = function ( c , // 19 code lengths bb , // bits tree desired/actual depth tb , // bits tree result hp , // space for trees z // for messages ) { var result ; initWorkArea ( 19 ) ; hn [ 0 ] = 0 ; result = huft_build ( c , 0 , 19 , 19 , null , null , tb , bb , hp , hn , v ) ; if ( result == Z_DATA_ERROR ) { z . msg = \"oversubscribed dynamic bit lengths tree\" ; } else if ( result == Z_BUF_ERROR || bb [ 0 ] === 0 ) { z . msg = \"incomplete dynamic bit lengths tree\" ; result = Z_DATA_ERROR ; } return result ; } ; that . inflate_trees_dynamic = function ( nl , // number of literal/length codes nd , // number of distance codes c , // that many (total) code lengths bl , // literal desired/actual bit depth bd , // distance desired/actual bit depth tl , // literal/length tree result td , // distance tree result hp , // space for trees z // for messages ) { var result ; // build literal/length tree initWorkArea ( 288 ) ; hn [ 0 ] = 0 ; result = huft_build ( c , 0 , nl , 257 , cplens , cplext , tl , bl , hp , hn , v ) ; if ( result != Z_OK || bl [ 0 ] === 0 ) { if ( result == Z_DATA_ERROR ) { z . msg = \"oversubscribed literal/length tree\" ; } else if ( result != Z_MEM_ERROR ) { z . msg = \"incomplete literal/length tree\" ; result = Z_DATA_ERROR ; } return result ; } // build distance tree initWorkArea ( 288 ) ; result = huft_build ( c , nl , nd , 0 , cpdist , cpdext , td , bd , hp , hn , v ) ; if ( result != Z_OK || ( bd [ 0 ] === 0 && nl > 257 ) ) { if ( result == Z_DATA_ERROR ) { z . msg = \"oversubscribed distance tree\" ; } else if ( result == Z_BUF_ERROR ) { z . msg = \"incomplete distance tree\" ; result = Z_DATA_ERROR ; } else if ( result != Z_MEM_ERROR ) { z . msg = \"empty distance tree with lengths\" ; result = Z_DATA_ERROR ; } return result ; } return Z_OK ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "x : got error [CODESPLIT] function InfCodes ( ) { var that = this ; var mode ; // current inflate_codes mode // mode dependent information var len = 0 ; var tree ; // pointer into tree var tree_index = 0 ; var need = 0 ; // bits needed var lit = 0 ; // if EXT or COPY, where and how much var get = 0 ; // bits to get for extra var dist = 0 ; // distance back to copy from var lbits = 0 ; // ltree bits decoded per branch var dbits = 0 ; // dtree bits decoder per branch var ltree ; // literal/length/eob tree var ltree_index = 0 ; // literal/length/eob tree var dtree ; // distance tree var dtree_index = 0 ; // distance tree // Called with number of bytes left to write in window at least 258 // (the maximum string length) and number of input bytes available // at least ten. The ten bytes are six bytes for the longest length/ // distance pair plus four bytes for overloading the bit buffer. function inflate_fast ( bl , bd , tl , tl_index , td , td_index , s , z ) { var t ; // temporary pointer var tp ; // temporary pointer var tp_index ; // temporary pointer var e ; // extra bits or operation var b ; // bit buffer var k ; // bits in bit buffer var p ; // input data pointer var n ; // bytes available there var q ; // output window write pointer var m ; // bytes to end of window or read pointer var ml ; // mask for literal/length tree var md ; // mask for distance tree var c ; // bytes to copy var d ; // distance back to copy from var r ; // copy source pointer var tp_index_t_3 ; // (tp_index+t)*3 // load input, output, bit values p = z . next_in_index ; n = z . avail_in ; b = s . bitb ; k = s . bitk ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; // initialize masks ml = inflate_mask [ bl ] ; md = inflate_mask [ bd ] ; // do until not enough input or output space for fast loop do { // assume called with m >= 258 && n >= 10 // get literal/length code while ( k < ( 20 ) ) { // max bits for literal/length code n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } t = b & ml ; tp = tl ; tp_index = tl_index ; tp_index_t_3 = ( tp_index + t ) * 3 ; if ( ( e = tp [ tp_index_t_3 ] ) === 0 ) { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; s . window [ q ++ ] = /* (byte) */ tp [ tp_index_t_3 + 2 ] ; m -- ; continue ; } do { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; if ( ( e & 16 ) !== 0 ) { e &= 15 ; c = tp [ tp_index_t_3 + 2 ] + ( /* (int) */ b & inflate_mask [ e ] ) ; b >>= e ; k -= e ; // decode distance base of block to copy while ( k < ( 15 ) ) { // max bits for distance code n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } t = b & md ; tp = td ; tp_index = td_index ; tp_index_t_3 = ( tp_index + t ) * 3 ; e = tp [ tp_index_t_3 ] ; do { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; if ( ( e & 16 ) !== 0 ) { // get extra bits to add to distance base e &= 15 ; while ( k < ( e ) ) { // get extra bits (up to 13) n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } d = tp [ tp_index_t_3 + 2 ] + ( b & inflate_mask [ e ] ) ; b >>= ( e ) ; k -= ( e ) ; // do the copy m -= c ; if ( q >= d ) { // offset before dest // just copy r = q - d ; if ( q - r > 0 && 2 > ( q - r ) ) { s . window [ q ++ ] = s . window [ r ++ ] ; // minimum // count is // three, s . window [ q ++ ] = s . window [ r ++ ] ; // so unroll // loop a // little c -= 2 ; } else { s . window . set ( s . window . subarray ( r , r + 2 ) , q ) ; q += 2 ; r += 2 ; c -= 2 ; } } else { // else offset after destination r = q - d ; do { r += s . end ; // force pointer in window } while ( r < 0 ) ; // covers invalid distances e = s . end - r ; if ( c > e ) { // if source crosses, c -= e ; // wrapped copy if ( q - r > 0 && e > ( q - r ) ) { do { s . window [ q ++ ] = s . window [ r ++ ] ; } while ( -- e !== 0 ) ; } else { s . window . set ( s . window . subarray ( r , r + e ) , q ) ; q += e ; r += e ; e = 0 ; } r = 0 ; // copy rest from start of window } } // copy all or what's left if ( q - r > 0 && c > ( q - r ) ) { do { s . window [ q ++ ] = s . window [ r ++ ] ; } while ( -- c !== 0 ) ; } else { s . window . set ( s . window . subarray ( r , r + c ) , q ) ; q += c ; r += c ; c = 0 ; } break ; } else if ( ( e & 64 ) === 0 ) { t += tp [ tp_index_t_3 + 2 ] ; t += ( b & inflate_mask [ e ] ) ; tp_index_t_3 = ( tp_index + t ) * 3 ; e = tp [ tp_index_t_3 ] ; } else { z . msg = \"invalid distance code\" ; c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_DATA_ERROR ; } } while ( true ) ; break ; } if ( ( e & 64 ) === 0 ) { t += tp [ tp_index_t_3 + 2 ] ; t += ( b & inflate_mask [ e ] ) ; tp_index_t_3 = ( tp_index + t ) * 3 ; if ( ( e = tp [ tp_index_t_3 ] ) === 0 ) { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; s . window [ q ++ ] = /* (byte) */ tp [ tp_index_t_3 + 2 ] ; m -- ; break ; } } else if ( ( e & 32 ) !== 0 ) { c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_STREAM_END ; } else { z . msg = \"invalid literal/length code\" ; c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_DATA_ERROR ; } } while ( true ) ; } while ( m >= 258 && n >= 10 ) ; // not enough input or output--restore pointers and return c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_OK ; } that . init = function ( bl , bd , tl , tl_index , td , td_index ) { mode = START ; lbits = /* (byte) */ bl ; dbits = /* (byte) */ bd ; ltree = tl ; ltree_index = tl_index ; dtree = td ; dtree_index = td_index ; tree = null ; } ; that . proc = function ( s , z , r ) { var j ; // temporary storage var tindex ; // temporary pointer var e ; // extra bits or operation var b = 0 ; // bit buffer var k = 0 ; // bits in bit buffer var p = 0 ; // input data pointer var n ; // bytes available there var q ; // output window write pointer var m ; // bytes to end of window or read pointer var f ; // pointer to copy strings from // copy input/output information to locals (UPDATE macro restores) p = z . next_in_index ; n = z . avail_in ; b = s . bitb ; k = s . bitk ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; // process input and output based on current state while ( true ) { switch ( mode ) { // waiting for \"i:\"=input, \"o:\"=output, \"x:\"=nothing case START : // x: set up for LEN if ( m >= 258 && n >= 10 ) { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; r = inflate_fast ( lbits , dbits , ltree , ltree_index , dtree , dtree_index , s , z ) ; p = z . next_in_index ; n = z . avail_in ; b = s . bitb ; k = s . bitk ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; if ( r != Z_OK ) { mode = r == Z_STREAM_END ? WASH : BADCODE ; break ; } } need = lbits ; tree = ltree ; tree_index = ltree_index ; mode = LEN ; /* falls through */ case LEN : // i: get length/literal/eob next j = need ; while ( k < ( j ) ) { if ( n !== 0 ) r = Z_OK ; else { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } tindex = ( tree_index + ( b & inflate_mask [ j ] ) ) * 3 ; b >>>= ( tree [ tindex + 1 ] ) ; k -= ( tree [ tindex + 1 ] ) ; e = tree [ tindex ] ; if ( e === 0 ) { // literal lit = tree [ tindex + 2 ] ; mode = LIT ; break ; } if ( ( e & 16 ) !== 0 ) { // length get = e & 15 ; len = tree [ tindex + 2 ] ; mode = LENEXT ; break ; } if ( ( e & 64 ) === 0 ) { // next table need = e ; tree_index = tindex / 3 + tree [ tindex + 2 ] ; break ; } if ( ( e & 32 ) !== 0 ) { // end of block mode = WASH ; break ; } mode = BADCODE ; // invalid code z . msg = \"invalid literal/length code\" ; r = Z_DATA_ERROR ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; case LENEXT : // i: getting length extra (have base) j = get ; while ( k < ( j ) ) { if ( n !== 0 ) r = Z_OK ; else { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } len += ( b & inflate_mask [ j ] ) ; b >>= j ; k -= j ; need = dbits ; tree = dtree ; tree_index = dtree_index ; mode = DIST ; /* falls through */ case DIST : // i: get distance next j = need ; while ( k < ( j ) ) { if ( n !== 0 ) r = Z_OK ; else { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } tindex = ( tree_index + ( b & inflate_mask [ j ] ) ) * 3 ; b >>= tree [ tindex + 1 ] ; k -= tree [ tindex + 1 ] ; e = ( tree [ tindex ] ) ; if ( ( e & 16 ) !== 0 ) { // distance get = e & 15 ; dist = tree [ tindex + 2 ] ; mode = DISTEXT ; break ; } if ( ( e & 64 ) === 0 ) { // next table need = e ; tree_index = tindex / 3 + tree [ tindex + 2 ] ; break ; } mode = BADCODE ; // invalid code z . msg = \"invalid distance code\" ; r = Z_DATA_ERROR ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; case DISTEXT : // i: getting distance extra j = get ; while ( k < ( j ) ) { if ( n !== 0 ) r = Z_OK ; else { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } dist += ( b & inflate_mask [ j ] ) ; b >>= j ; k -= j ; mode = COPY ; /* falls through */ case COPY : // o: copying bytes in window, waiting for space f = q - dist ; while ( f < 0 ) { // modulo window size-\"while\" instead f += s . end ; // of \"if\" handles invalid distances } while ( len !== 0 ) { if ( m === 0 ) { if ( q == s . end && s . read !== 0 ) { q = 0 ; m = q < s . read ? s . read - q - 1 : s . end - q ; } if ( m === 0 ) { s . write = q ; r = s . inflate_flush ( z , r ) ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; if ( q == s . end && s . read !== 0 ) { q = 0 ; m = q < s . read ? s . read - q - 1 : s . end - q ; } if ( m === 0 ) { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } } } s . window [ q ++ ] = s . window [ f ++ ] ; m -- ; if ( f == s . end ) f = 0 ; len -- ; } mode = START ; break ; case LIT : // o: got literal, waiting for output space if ( m === 0 ) { if ( q == s . end && s . read !== 0 ) { q = 0 ; m = q < s . read ? s . read - q - 1 : s . end - q ; } if ( m === 0 ) { s . write = q ; r = s . inflate_flush ( z , r ) ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; if ( q == s . end && s . read !== 0 ) { q = 0 ; m = q < s . read ? s . read - q - 1 : s . end - q ; } if ( m === 0 ) { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } } } r = Z_OK ; s . window [ q ++ ] = /* (byte) */ lit ; m -- ; mode = START ; break ; case WASH : // o: got eob, possibly more output if ( k > 7 ) { // return unused byte, if any k -= 8 ; n ++ ; p -- ; // can always return one } s . write = q ; r = s . inflate_flush ( z , r ) ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; if ( s . read != s . write ) { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } mode = END ; /* falls through */ case END : r = Z_STREAM_END ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; case BADCODE : // x: got error r = Z_DATA_ERROR ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; default : r = Z_STREAM_ERROR ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } } } ; that . free = function ( ) { // ZFREE(z, c); } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called with number of bytes left to write in window at least 258 ( the maximum string length ) and number of input bytes available at least ten . The ten bytes are six bytes for the longest length / distance pair plus four bytes for overloading the bit buffer . [CODESPLIT] function inflate_fast ( bl , bd , tl , tl_index , td , td_index , s , z ) { var t ; // temporary pointer var tp ; // temporary pointer var tp_index ; // temporary pointer var e ; // extra bits or operation var b ; // bit buffer var k ; // bits in bit buffer var p ; // input data pointer var n ; // bytes available there var q ; // output window write pointer var m ; // bytes to end of window or read pointer var ml ; // mask for literal/length tree var md ; // mask for distance tree var c ; // bytes to copy var d ; // distance back to copy from var r ; // copy source pointer var tp_index_t_3 ; // (tp_index+t)*3 // load input, output, bit values p = z . next_in_index ; n = z . avail_in ; b = s . bitb ; k = s . bitk ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; // initialize masks ml = inflate_mask [ bl ] ; md = inflate_mask [ bd ] ; // do until not enough input or output space for fast loop do { // assume called with m >= 258 && n >= 10 // get literal/length code while ( k < ( 20 ) ) { // max bits for literal/length code n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } t = b & ml ; tp = tl ; tp_index = tl_index ; tp_index_t_3 = ( tp_index + t ) * 3 ; if ( ( e = tp [ tp_index_t_3 ] ) === 0 ) { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; s . window [ q ++ ] = /* (byte) */ tp [ tp_index_t_3 + 2 ] ; m -- ; continue ; } do { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; if ( ( e & 16 ) !== 0 ) { e &= 15 ; c = tp [ tp_index_t_3 + 2 ] + ( /* (int) */ b & inflate_mask [ e ] ) ; b >>= e ; k -= e ; // decode distance base of block to copy while ( k < ( 15 ) ) { // max bits for distance code n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } t = b & md ; tp = td ; tp_index = td_index ; tp_index_t_3 = ( tp_index + t ) * 3 ; e = tp [ tp_index_t_3 ] ; do { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; if ( ( e & 16 ) !== 0 ) { // get extra bits to add to distance base e &= 15 ; while ( k < ( e ) ) { // get extra bits (up to 13) n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } d = tp [ tp_index_t_3 + 2 ] + ( b & inflate_mask [ e ] ) ; b >>= ( e ) ; k -= ( e ) ; // do the copy m -= c ; if ( q >= d ) { // offset before dest // just copy r = q - d ; if ( q - r > 0 && 2 > ( q - r ) ) { s . window [ q ++ ] = s . window [ r ++ ] ; // minimum // count is // three, s . window [ q ++ ] = s . window [ r ++ ] ; // so unroll // loop a // little c -= 2 ; } else { s . window . set ( s . window . subarray ( r , r + 2 ) , q ) ; q += 2 ; r += 2 ; c -= 2 ; } } else { // else offset after destination r = q - d ; do { r += s . end ; // force pointer in window } while ( r < 0 ) ; // covers invalid distances e = s . end - r ; if ( c > e ) { // if source crosses, c -= e ; // wrapped copy if ( q - r > 0 && e > ( q - r ) ) { do { s . window [ q ++ ] = s . window [ r ++ ] ; } while ( -- e !== 0 ) ; } else { s . window . set ( s . window . subarray ( r , r + e ) , q ) ; q += e ; r += e ; e = 0 ; } r = 0 ; // copy rest from start of window } } // copy all or what's left if ( q - r > 0 && c > ( q - r ) ) { do { s . window [ q ++ ] = s . window [ r ++ ] ; } while ( -- c !== 0 ) ; } else { s . window . set ( s . window . subarray ( r , r + c ) , q ) ; q += c ; r += c ; c = 0 ; } break ; } else if ( ( e & 64 ) === 0 ) { t += tp [ tp_index_t_3 + 2 ] ; t += ( b & inflate_mask [ e ] ) ; tp_index_t_3 = ( tp_index + t ) * 3 ; e = tp [ tp_index_t_3 ] ; } else { z . msg = \"invalid distance code\" ; c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_DATA_ERROR ; } } while ( true ) ; break ; } if ( ( e & 64 ) === 0 ) { t += tp [ tp_index_t_3 + 2 ] ; t += ( b & inflate_mask [ e ] ) ; tp_index_t_3 = ( tp_index + t ) * 3 ; if ( ( e = tp [ tp_index_t_3 ] ) === 0 ) { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; s . window [ q ++ ] = /* (byte) */ tp [ tp_index_t_3 + 2 ] ; m -- ; break ; } } else if ( ( e & 32 ) !== 0 ) { c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_STREAM_END ; } else { z . msg = \"invalid literal/length code\" ; c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_DATA_ERROR ; } } while ( true ) ; } while ( m >= 258 && n >= 10 ) ; // not enough input or output--restore pointers and return c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_OK ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inflater [CODESPLIT] function Inflater ( ) { var that = this ; var z = new ZStream ( ) ; var bufsize = 512 ; var flush = Z_NO_FLUSH ; var buf = new Uint8Array ( bufsize ) ; var nomoreinput = false ; z . inflateInit ( ) ; z . next_out = buf ; that . append = function ( data , onprogress ) { var err , buffers = [ ] , lastIndex = 0 , bufferIndex = 0 , bufferSize = 0 , array ; if ( data . length === 0 ) return ; z . next_in_index = 0 ; z . next_in = data ; z . avail_in = data . length ; do { z . next_out_index = 0 ; z . avail_out = bufsize ; if ( ( z . avail_in === 0 ) && ( ! nomoreinput ) ) { // if buffer is empty and more input is available, refill it z . next_in_index = 0 ; nomoreinput = true ; } err = z . inflate ( flush ) ; if ( nomoreinput && ( err === Z_BUF_ERROR ) ) { if ( z . avail_in !== 0 ) throw new Error ( \"inflating: bad input\" ) ; } else if ( err !== Z_OK && err !== Z_STREAM_END ) throw new Error ( \"inflating: \" + z . msg ) ; if ( ( nomoreinput || err === Z_STREAM_END ) && ( z . avail_in === data . length ) ) throw new Error ( \"inflating: bad input\" ) ; if ( z . next_out_index ) if ( z . next_out_index === bufsize ) buffers . push ( new Uint8Array ( buf ) ) ; else buffers . push ( new Uint8Array ( buf . subarray ( 0 , z . next_out_index ) ) ) ; bufferSize += z . next_out_index ; if ( onprogress && z . next_in_index > 0 && z . next_in_index != lastIndex ) { onprogress ( z . next_in_index ) ; lastIndex = z . next_in_index ; } } while ( z . avail_in > 0 || z . avail_out === 0 ) ; array = new Uint8Array ( bufferSize ) ; buffers . forEach ( function ( chunk ) { array . set ( chunk , bufferIndex ) ; bufferIndex += chunk . length ; } ) ; return array ; } ; that . flush = function ( ) { z . inflateEnd ( ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "inflate / deflate core functions [CODESPLIT] function launchWorkerProcess ( worker , initialMessage , reader , writer , offset , size , onprogress , onend , onreaderror , onwriteerror ) { var chunkIndex = 0 , index , outputSize , sn = initialMessage . sn , crc ; function onflush ( ) { worker . removeEventListener ( 'message' , onmessage , false ) ; onend ( outputSize , crc ) ; } function onmessage ( event ) { var message = event . data , data = message . data , err = message . error ; if ( err ) { err . toString = function ( ) { return 'Error: ' + this . message ; } ; onreaderror ( err ) ; return ; } if ( message . sn !== sn ) return ; if ( typeof message . codecTime === 'number' ) worker . codecTime += message . codecTime ; // should be before onflush() if ( typeof message . crcTime === 'number' ) worker . crcTime += message . crcTime ; switch ( message . type ) { case 'append' : if ( data ) { outputSize += data . length ; writer . writeUint8Array ( data , function ( ) { step ( ) ; } , onwriteerror ) ; } else step ( ) ; break ; case 'flush' : crc = message . crc ; if ( data ) { outputSize += data . length ; writer . writeUint8Array ( data , function ( ) { onflush ( ) ; } , onwriteerror ) ; } else onflush ( ) ; break ; case 'progress' : if ( onprogress ) onprogress ( index + message . loaded , size ) ; break ; case 'importScripts' : //no need to handle here case 'newTask' : case 'echo' : break ; default : console . warn ( 'zip.js:launchWorkerProcess: unknown message: ' , message ) ; } } function step ( ) { index = chunkIndex * CHUNK_SIZE ; // use `<=` instead of `<`, because `size` may be 0. if ( index <= size ) { reader . readUint8Array ( offset + index , Math . min ( CHUNK_SIZE , size - index ) , function ( array ) { if ( onprogress ) onprogress ( index , size ) ; var msg = index === 0 ? initialMessage : { sn : sn } ; msg . type = 'append' ; msg . data = array ; // posting a message with transferables will fail on IE10 try { worker . postMessage ( msg , [ array . buffer ] ) ; } catch ( ex ) { worker . postMessage ( msg ) ; // retry without transferables } chunkIndex ++ ; } , onreaderror ) ; } else { worker . postMessage ( { sn : sn , type : 'flush' } ) ; } } outputSize = 0 ; worker . addEventListener ( 'message' , onmessage , false ) ; step ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ZipReader [CODESPLIT] function decodeASCII ( str ) { var i , out = \"\" , charCode , extendedASCII = [ '\\u00C7' , '\\u00FC' , '\\u00E9' , '\\u00E2' , '\\u00E4' , '\\u00E0' , '\\u00E5' , '\\u00E7' , '\\u00EA' , '\\u00EB' , '\\u00E8' , '\\u00EF' , '\\u00EE' , '\\u00EC' , '\\u00C4' , '\\u00C5' , '\\u00C9' , '\\u00E6' , '\\u00C6' , '\\u00F4' , '\\u00F6' , '\\u00F2' , '\\u00FB' , '\\u00F9' , '\\u00FF' , '\\u00D6' , '\\u00DC' , '\\u00F8' , '\\u00A3' , '\\u00D8' , '\\u00D7' , '\\u0192' , '\\u00E1' , '\\u00ED' , '\\u00F3' , '\\u00FA' , '\\u00F1' , '\\u00D1' , '\\u00AA' , '\\u00BA' , '\\u00BF' , '\\u00AE' , '\\u00AC' , '\\u00BD' , '\\u00BC' , '\\u00A1' , '\\u00AB' , '\\u00BB' , '_' , '_' , '_' , '\\u00A6' , '\\u00A6' , '\\u00C1' , '\\u00C2' , '\\u00C0' , '\\u00A9' , '\\u00A6' , '\\u00A6' , '+' , '+' , '\\u00A2' , '\\u00A5' , '+' , '+' , '-' , '-' , '+' , '-' , '+' , '\\u00E3' , '\\u00C3' , '+' , '+' , '-' , '-' , '\\u00A6' , '-' , '+' , '\\u00A4' , '\\u00F0' , '\\u00D0' , '\\u00CA' , '\\u00CB' , '\\u00C8' , 'i' , '\\u00CD' , '\\u00CE' , '\\u00CF' , '+' , '+' , '_' , '_' , '\\u00A6' , '\\u00CC' , '_' , '\\u00D3' , '\\u00DF' , '\\u00D4' , '\\u00D2' , '\\u00F5' , '\\u00D5' , '\\u00B5' , '\\u00FE' , '\\u00DE' , '\\u00DA' , '\\u00DB' , '\\u00D9' , '\\u00FD' , '\\u00DD' , '\\u00AF' , '\\u00B4' , '\\u00AD' , '\\u00B1' , '_' , '\\u00BE' , '\\u00B6' , '\\u00A7' , '\\u00F7' , '\\u00B8' , '\\u00B0' , '\\u00A8' , '\\u00B7' , '\\u00B9' , '\\u00B3' , '\\u00B2' , '_' , ' ' ] ; for ( i = 0 ; i < str . length ; i ++ ) { charCode = str . charCodeAt ( i ) & 0xFF ; if ( charCode > 127 ) out += extendedASCII [ charCode - 128 ] ; else out += String . fromCharCode ( charCode ) ; } return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "seek last length bytes of file for EOCDR [CODESPLIT] function doSeek ( length , eocdrNotFoundCallback ) { reader . readUint8Array ( reader . size - length , length , function ( bytes ) { for ( var i = bytes . length - EOCDR_MIN ; i >= 0 ; i -- ) { if ( bytes [ i ] === 0x50 && bytes [ i + 1 ] === 0x4b && bytes [ i + 2 ] === 0x05 && bytes [ i + 3 ] === 0x06 ) { eocdrCallback ( new DataView ( bytes . buffer , i , EOCDR_MIN ) ) ; return ; } } eocdrNotFoundCallback ( ) ; } , function ( ) { onerror ( ERR_READ ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@class CardJs [CODESPLIT] function CardJs ( elem ) { this . elem = jQuery ( elem ) ; this . captureName = this . elem . data ( \"capture-name\" ) ? this . elem . data ( \"capture-name\" ) : false ; this . iconColour = this . elem . data ( \"icon-colour\" ) ? this . elem . data ( \"icon-colour\" ) : false ; this . stripe = this . elem . data ( \"stripe\" ) ? this . elem . data ( \"stripe\" ) : false ; if ( this . stripe ) { this . captureName = false ; } // Initialise this . initCardNumberInput ( ) ; this . initNameInput ( ) ; this . initExpiryMonthInput ( ) ; this . initExpiryYearInput ( ) ; this . initCvcInput ( ) ; this . elem . empty ( ) ; // Setup display this . setupCardNumberInput ( ) ; this . setupNameInput ( ) ; this . setupExpiryInput ( ) ; this . setupCvcInput ( ) ; // Set icon colour if ( this . iconColour ) { this . setIconColour ( this . iconColour ) ; } // --- --- --- --- --- --- --- --- --- --- this . refreshCreditCardTypeIcon ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "console . log ( ! -------------- Starting Test options . name ) ; data . push ( { name : Starting test + options . name } ) ; [CODESPLIT] function ( err , inData ) { //console.log(\"!--------------  Checking Results\", options.name, \"Error: \", err, \"Data:\", inData); var passed = true ; if ( err ) { console . log ( \"!------------ Error\" , err . toString ( ) ) ; data . push ( { name : options . name + \" test failed with: \" , css : 'one' } ) ; data . push ( { name : \"  \" + err . toString ( ) , css : 'one' } ) ; return callback ( false ) ; } if ( ! inData || inData . length !== options . results . length ) { console . dir ( inData ) ; console . log ( \"!----------- No Data\" ) ; data . push ( { name : options . name + \" test failed with different results length\" , css : 'one' } ) ; return callback ( false ) ; } if ( inData . length === 0 ) { console . log ( \"!-------- No Data Returned\" ) ; return callback ( passed ) ; } //console.log(\"!------------ Data Returned\", inData.length, inData); for ( var i = 0 ; i < inData . length ; i ++ ) { var result = checkRowOfData ( inData [ i ] , options . results [ i ] ) ; if ( ! result . status ) { passed = false ; data . push ( { name : options . name + \" test failed on row: \" + i + \", field: \" + result . field , css : 'one' } ) ; console . log ( \"$$$$$ Failure:\" , inData [ i ] , options . results [ i ] , typeof inData [ i ] [ result . field ] , typeof options . results [ i ] [ result . field ] ) ; break ; } } callback ( passed ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* Parses a Row of data into a JS Array ( as Native ) [CODESPLIT] function DBGetRowArrayNative ( cursor ) { //noinspection JSUnresolvedFunction let count = cursor . getColumnCount ( ) ; let results = [ ] ; for ( let i = 0 ; i < count ; i ++ ) { const type = cursor . getType ( i ) ; switch ( type ) { case 0 : // NULL results . push ( null ) ; break ; case 1 : // Integer //noinspection JSUnresolvedFunction results . push ( cursor . getLong ( i ) ) ; break ; case 2 : // Float //noinspection JSUnresolvedFunction results . push ( cursor . getFloat ( i ) ) ; break ; case 3 : // String //noinspection JSUnresolvedFunction results . push ( cursor . getString ( i ) ) ; break ; case 4 : // Blob // noinspection JSCheckFunctionSignatures results . push ( cursor . getBlob ( i ) ) ; break ; default : throw new Error ( 'SQLITE - Unknown Field Type ' + type ) ; } } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* Parses a Row of data into a JS Array ( as String ) [CODESPLIT] function DBGetRowArrayString ( cursor ) { //noinspection JSUnresolvedFunction let count = cursor . getColumnCount ( ) ; let results = [ ] ; for ( let i = 0 ; i < count ; i ++ ) { const type = cursor . getType ( i ) ; switch ( type ) { case 0 : // NULL results . push ( null ) ; break ; case 1 : // Integer //noinspection JSUnresolvedFunction results . push ( cursor . getString ( i ) ) ; break ; case 2 : // Float //noinspection JSUnresolvedFunction results . push ( cursor . getString ( i ) ) ; break ; case 3 : // String //noinspection JSUnresolvedFunction results . push ( cursor . getString ( i ) ) ; break ; case 4 : // Blob // noinspection JSCheckFunctionSignatures results . push ( cursor . getBlob ( i ) ) ; break ; default : throw new Error ( 'SQLITE - Unknown Field Type ' + type ) ; } } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* Parses a Row of data into a JS Object ( as String ) [CODESPLIT] function DBGetRowObjectString ( cursor ) { //noinspection JSUnresolvedFunction const count = cursor . getColumnCount ( ) ; let results = { } ; for ( let i = 0 ; i < count ; i ++ ) { const type = cursor . getType ( i ) ; //noinspection JSUnresolvedFunction const name = cursor . getColumnName ( i ) ; switch ( type ) { case 0 : // NULL results [ name ] = null ; break ; case 1 : // Integer //noinspection JSUnresolvedFunction results [ name ] = cursor . getString ( i ) ; break ; case 2 : // Float //noinspection JSUnresolvedFunction results [ name ] = cursor . getString ( i ) ; break ; case 3 : // String //noinspection JSUnresolvedFunction results [ name ] = cursor . getString ( i ) ; break ; case 4 : // Blob // noinspection JSCheckFunctionSignatures results [ name ] = cursor . getBlob ( i ) ; break ; default : throw new Error ( 'SQLITE - Unknown Field Type ' + type ) ; } } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* Database Constructor [CODESPLIT] function Database ( dbname , options , callback ) { if ( ! this instanceof Database ) { // jshint ignore:line //noinspection JSValidateTypes return new Database ( dbname , options , callback ) ; } this . _isOpen = false ; this . _resultType = Database . RESULTSASARRAY ; this . _valuesType = Database . VALUESARENATIVE ; if ( typeof options === 'function' ) { callback = options ; //noinspection JSUnusedAssignment options = { } ; } else { //noinspection JSUnusedAssignment options = options || { } ; } //noinspection JSUnresolvedVariable if ( options && options . multithreading && typeof global . Worker === 'function' ) { // We don't want this passed into the worker; to try and start another worker (which would fail). delete options . multithreading ; if ( ! Database . HAS_COMMERCIAL ) { throw new Error ( \"Commercial only feature; see http://nativescript.tools/product/10\" ) ; } return new Database . _multiSQL ( dbname , options , callback ) ; } // Check to see if it has a path, or if it is a relative dbname // dbname = \"\" - Temporary Database // dbname = \":memory:\" = memory database if ( dbname !== \"\" && dbname !== \":memory:\" ) { //var pkgName = appModule.android.context.getPackageName(); //noinspection JSUnresolvedFunction dbname = _getContext ( ) . getDatabasePath ( dbname ) . getAbsolutePath ( ) . toString ( ) ; let path = dbname . substr ( 0 , dbname . lastIndexOf ( '/' ) + 1 ) ; // Create \"databases\" folder if it is missing.  This causes issues on Emulators if it is missing // So we create it if it is missing try { //noinspection JSUnresolvedFunction,JSUnresolvedVariable let javaFile = new java . io . File ( path ) ; if ( ! javaFile . exists ( ) ) { //noinspection JSUnresolvedFunction javaFile . mkdirs ( ) ; //noinspection JSUnresolvedFunction javaFile . setReadable ( true ) ; //noinspection JSUnresolvedFunction javaFile . setWritable ( true ) ; } } catch ( err ) { console . info ( \"SQLITE.CONSTRUCTOR - Creating DB Folder Error\" , err ) ; } } const self = this ; return new Promise ( function ( resolve , reject ) { try { let flags = 0 ; if ( typeof options . androidFlags !== 'undefined' ) { flags = options . androidFlags ; } self . _db = self . _openDatabase ( dbname , flags , options , _getContext ( ) ) ; } catch ( err ) { console . error ( \"SQLITE.CONSTRUCTOR -  Open DB Error\" , err ) ; if ( callback ) { callback ( err , null ) ; } reject ( err ) ; return ; } self . _isOpen = true ; let doneCnt = _DatabasePluginInits . length , doneHandled = 0 ; const done = function ( err ) { if ( err ) { doneHandled = doneCnt ; // We don't want any more triggers after this if ( callback ) { callback ( err , null ) ; } reject ( err ) ; return ; } doneHandled ++ ; if ( doneHandled === doneCnt ) { if ( callback ) { callback ( null , self ) ; } resolve ( self ) ; } } ; if ( doneCnt ) { try { for ( let i = 0 ; i < doneCnt ; i ++ ) { _DatabasePluginInits [ i ] . call ( self , options , done ) ; } } catch ( err ) { done ( err ) ; } } else { if ( callback ) { callback ( null , self ) ; } resolve ( self ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* Converts a string to a UTF - 8 char array and wraps it in an adopted pointer ( which is GC managed and kept alive until it s referenced by a variable ) . The reason for doing it is that iOS runtime marshals JS string arguments via temporary buffers which are deallocated immediately after the call returns . In some cases however we need them to stay alive for subsequent native calls because otherwise attempts to read the freed memory may lead to unpredictable app crashes . E . g . sqlite3_step function happens to use the stored char * passed as dbname to sqlite3_open_v2 . [CODESPLIT] function toCharPtr ( str ) { const objcStr = NSString . stringWithString ( str ) ; const bufferSize = strlen ( objcStr . UTF8String ) + 1 ; const buffer = interop . alloc ( bufferSize ) ; objcStr . getCStringMaxLengthEncoding ( buffer , bufferSize , NSUTF8StringEncoding ) ; return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* Creates a Cursor Tracking Statement for reading result sets [CODESPLIT] function CursorStatement ( statement , resultType , valuesType ) { this . statement = statement ; this . resultType = resultType ; this . valuesType = valuesType ; this . built = false ; this . columns = [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "noinspection JSValidateJSDoc * Database Constructor [CODESPLIT] function Database ( dbname , options , callback ) { if ( ! this instanceof Database ) { // jshint ignore:line //noinspection JSValidateTypes return new Database ( dbname , options , callback ) ; } this . _isOpen = false ; this . _resultType = Database . RESULTSASARRAY ; this . _valuesType = Database . VALUESARENATIVE ; if ( typeof options === 'function' ) { callback = options ; options = { } ; } else { options = options || { } ; } if ( options && options . multithreading && typeof global . Worker === 'function' ) { delete options . multithreading ; if ( ! Database . HAS_COMMERCIAL ) { throw new Error ( \"Commercial only feature; see http://nativescript.tools/product/10\" ) ; } return new Database . _multiSQL ( dbname , options , callback ) ; } // Check to see if it has a path, or if it is a relative dbname // DBNAME = \"\" - is a Temporary Database // DBNAME = \":memory:\" - is a Memory only database if ( dbname !== \"\" && dbname !== \":memory:\" ) { let path ; if ( dbname . indexOf ( '/' ) === - 1 ) { // noinspection JSUnresolvedVariable, JSUnresolvedFunction path = fs . knownFolders . documents ( ) . path ; dbname = path + '/' + dbname ; } else { path = dbname . substr ( 0 , dbname . lastIndexOf ( '/' ) + 1 ) ; } // Create \"databases\" folder if it is missing.  This causes issues on Emulators if it is missing // So we create it if it is missing try { // noinspection JSUnresolvedVariable if ( ! fs . File . exists ( path ) ) { //noinspection JSUnresolvedFunction const fileManager = iosProperty ( NSFileManager , NSFileManager . defaultManager ) ; //noinspection JSUnresolvedFunction if ( ! fileManager . createDirectoryAtPathWithIntermediateDirectoriesAttributesError ( path , true , null , null ) ) { console . warn ( \"SQLITE.CONSTRUCTOR - Creating DB Folder Error\" ) ; } } } catch ( err ) { console . warn ( \"SQLITE.CONSTRUCTOR - Creating DB Folder Error\" , err ) ; } } this . _dbnamePtr = toCharPtr ( dbname ) ; const self = this ; //noinspection JSUnresolvedFunction return new Promise ( function ( resolve , reject ) { let error ; try { let flags = 0 ; if ( typeof options . iosFlags !== 'undefined' ) { flags = options . iosFlags ; } self . _db = new interop . Reference ( ) ; if ( options && options . readOnly ) { // SQLITE_OPEN_FULLMUTEX = 65536, SQLITE_OPEN_READONLY = 1 ---- 1 | 65536 = 65537 error = sqlite3_open_v2 ( self . _dbnamePtr , self . _db , 65537 | flags , null ) ; } else { // SQLITE_OPEN_FULLMUTEX = 65536, SQLITE_OPEN_CREATE = 4, SQLITE_OPEN_READWRITE = 2 --- 4 | 2 | 65536 = 65542 error = sqlite3_open_v2 ( self . _dbnamePtr , self . _db , 65542 | flags , null ) ; } self . _db = self . _db . value ; } catch ( err ) { if ( callback ) { callback ( err , null ) ; } reject ( err ) ; return ; } if ( error ) { if ( callback ) { callback ( error , null ) ; } reject ( error ) ; return ; } self . _isOpen = true ; let doneCnt = _DatabasePluginInits . length , doneHandled = 0 ; const done = function ( err ) { if ( err ) { doneHandled = doneCnt ; // We don't want any more triggers after this if ( callback ) { callback ( err , null ) ; } reject ( err ) ; return ; } doneHandled ++ ; if ( doneHandled === doneCnt ) { if ( callback ) { callback ( null , self ) ; } resolve ( self ) ; } } ; if ( doneCnt ) { try { for ( let i = 0 ; i < doneCnt ; i ++ ) { _DatabasePluginInits [ i ] . call ( self , options , done ) ; } } catch ( err ) { done ( err ) ; } } else { if ( callback ) { callback ( null , self ) ; } resolve ( self ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an object representing a CronJob [CODESPLIT] function CronJob ( sandbox , job ) { /**\n     * @property name - The name of the cron job\n     * @property schedule - The cron schedule of the job\n     * @property next_scheduled_at - The next time this job is scheduled\n     */ assign ( this , job ) ; /**\n     * @property claims - The claims embedded in the Webtask's token\n     */ if ( job . token ) { this . claims = Decode ( job . token ) ; } else { this . claims = { jtn : job . name , ten : this . container , } ; } /**\n     * @property sandbox - The {@see Sandbox} instance used to create this Webtask instance\n     */ this . sandbox = sandbox ; /**\n     * @property url - The public url that can be used to invoke webtask that the cron job runs\n     */ Object . defineProperty ( this , 'url' , { enumerable : true , get : function ( ) { return this . sandbox . url + '/api/run/' + this . container + '/' + this . name ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an object representing a user s webtask . io credentials [CODESPLIT] function Sandbox ( options ) { var securityVersion = 'v1' ; this . url = options . url ; this . container = options . container ; this . token = options . token ; this . onBeforeRequest = [ ] . concat ( options . onBeforeRequest ) . filter ( hook => typeof hook === 'function' ) ; try { var typ = Decode ( options . token , { header : true } ) . typ ; if ( typ && typ . toLowerCase ( ) === 'jwt' ) { securityVersion = 'v2' ; } } catch ( _ ) { // Ignore jwt decoding failures and assume v1 opaque token } this . securityVersion = securityVersion ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an object representing a Webtask [CODESPLIT] function Webtask ( sandbox , token , options ) { if ( ! options ) options = { } ; if ( sandbox . securityVersion === 'v1' ) { try { /**\n             * @property claims - The claims embedded in the Webtask's token\n             */ this . claims = Decode ( token ) ; /**\n             * @property token - The token associated with this webtask\n             */ this . token = token ; } catch ( _ ) { throw new Error ( 'token must be a valid JWT' ) ; } } if ( sandbox . securityVersion === 'v2' ) { if ( typeof options . name !== 'string' ) { throw new Error ( 'name must be a valid string' ) ; } this . claims = { jtn : options . name , ten : options . container || sandbox . container , } } /**\n     * @property sandbox - The {@see Sandbox} instance used to create this Webtask instance\n     */ this . sandbox = sandbox ; /**\n     * @property meta - The metadata associated with this webtask\n     */ this . meta = options . meta || { } ; /**\n     * @property secrets - The secrets associated with this webtask if `decrypt=true`\n     */ this . secrets = options . secrets ; /**\n     * @property code - The code associated with this webtask if `fetch_code=true`\n     */ this . code = options . code ; /**\n     * @property container - The container name in which the webtask will run\n     */ Object . defineProperty ( this , 'container' , { enumerable : true , get : function ( ) { return options . container || this . sandbox . container ; } } ) ; /**\n     * @property url - The public url that can be used to invoke this webtask\n     */ Object . defineProperty ( this , 'url' , { enumerable : true , get : function ( ) { var url = options . webtask_url ; if ( ! url ) { if ( this . claims . host ) { var surl = Url . parse ( this . sandbox . url ) ; url = surl . protocol + '//' + this . claims . host + ( surl . port ? ( ':' + surl . port ) : '' ) + '/' + this . sandbox . container ; } else { url = this . sandbox . url + '/api/run/' + this . sandbox . container ; } if ( this . claims . jtn ) url += '/' + this . claims . jtn ; else url += '?key=' + this . token ; } return url ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "********************************************************************************************** * CcZnp Class ** ********************************************************************************************** [CODESPLIT] function CcZnp ( ) { EventEmitter . call ( this ) ; var self = this ; this . MT = MT ; // export constant this . _init = false ; this . _resetting = false ; this . _sp = null ; this . _unpi = null ; this . _spinLock = false ; this . _txQueue = [ ] ; this . on ( '_ready' , function ( ) { self . _init = true ; self . emit ( 'ready' ) ; } ) ; this . _innerListeners = { spOpen : function ( ) { debug ( 'The serialport ' + self . _sp . path + ' is opened.' ) ; self . emit ( '_ready' ) ; } , spErr : function ( err ) { self . _sp . close ( ) ; } , spClose : function ( ) { debug ( 'The serialport ' + self . _sp . path + ' is closed.' ) ; self . _txQueue = null ; self . _txQueue = [ ] ; self . _sp = null ; self . _unpi = null ; self . _init = false ; self . emit ( 'close' ) ; } , parseMtIncomingData : function ( result ) { self . _parseMtIncomingData ( result ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "********************************************************************************************** * ZpiObject Class ** * 1 . Provides command framer ( SREQ ) ** * 2 . Provides parser ( SRSP AREQ ) ** ********************************************************************************************** [CODESPLIT] function ZpiObject ( subsys , cmd , args ) { // args is optional, and can be an array or a value-object if given var subsystem = zmeta . Subsys . get ( subsys ) , command , reqParams ; this . type = undefined ; // string after assgined this . subsys = undefined ; // string after assigned this . cmd = undefined ; // string after assigned this . cmdId = undefined ; // number after assigned this . args = undefined ; // array after assigned: [ { name, type, value }, ... ] if ( ! subsystem ) throw new Error ( 'Unrecognized subsystem' ) ; this . subsys = subsystem . key ; command = zmeta [ this . subsys ] . get ( cmd ) ; if ( ! command ) throw new Error ( 'Unrecognized command' ) ; this . cmd = command . key ; this . cmdId = command . value ; this . type = zmeta . getType ( this . subsys , this . cmd ) ; if ( ! this . type ) throw new Error ( 'Unrecognized type' ) ; // if args is given, this is for REQ transmission // otherwise, maybe just for parsing RSP packet if ( args ) reqParams = zmeta . getReqParams ( this . subsys , this . cmd ) ; // [ { name, type }, ... ] if ( reqParams ) { if ( Array . isArray ( args ) ) { // arg: { name, type } -> { name, type, value } reqParams . forEach ( function ( arg , idx ) { arg . value = args [ idx ] ; } ) ; } else if ( typeof args === 'object' ) { reqParams . forEach ( function ( arg , idx ) { if ( ! args . hasOwnProperty ( arg . name ) ) throw new Error ( 'The argument object has incorrect properties' ) ; else arg . value = args [ arg . name ] ; } ) ; } this . args = reqParams ; // [ { name, type, value }, ... ] } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates to this class should also be applied to the the ES6 version in es6 - wrapped - promise . js . [CODESPLIT] function wrappedPromise ( executor ) { if ( ! ( this instanceof wrappedPromise ) ) { return Promise ( executor ) ; } if ( typeof executor !== 'function' ) { return new Promise ( executor ) ; } var context , args ; var promise = new Promise ( wrappedExecutor ) ; promise . __proto__ = wrappedPromise . prototype ; try { executor . apply ( context , args ) ; } catch ( err ) { args [ 1 ] ( err ) ; } return promise ; function wrappedExecutor ( resolve , reject ) { context = this ; args = [ wrappedResolve , wrappedReject ] ; // These wrappers create a function that can be passed a function and an argument to // call as a continuation from the resolve or reject. function wrappedResolve ( val ) { ensureAslWrapper ( promise , false ) ; return resolve ( val ) ; } function wrappedReject ( val ) { ensureAslWrapper ( promise , false ) ; return reject ( val ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wrap callbacks ( success error ) so that the callbacks will be called as a continuations of the resolve or reject call using the __asl_wrapper created above . [CODESPLIT] function bind ( fn ) { if ( typeof fn !== 'function' ) return fn ; return wrapCallback ( function ( val ) { var result = ( promise . __asl_wrapper || propagateAslWrapper ) ( this , fn , val , next ) ; if ( result . error ) { throw result . errorVal } else { return result . returnVal } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simple helper function that s probably faster than using Array filter methods and can be inlined . [CODESPLIT] function union ( dest , added ) { var destLength = dest . length ; var addedLength = added . length ; var returned = [ ] ; if ( destLength === 0 && addedLength === 0 ) return returned ; for ( var j = 0 ; j < destLength ; j ++ ) returned [ j ] = dest [ j ] ; if ( addedLength === 0 ) return returned ; for ( var i = 0 ; i < addedLength ; i ++ ) { var missing = true ; for ( j = 0 ; j < destLength ; j ++ ) { if ( dest [ j ] . uid === added [ i ] . uid ) { missing = false ; break ; } } if ( missing ) returned . push ( added [ i ] ) ; } return returned ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for performance in the case where there are no handlers just the listener [CODESPLIT] function simpleWrap ( original , list , length ) { inAsyncTick = true ; for ( var i = 0 ; i < length ; ++ i ) { var listener = list [ i ] ; if ( listener . create ) listener . create ( listener . data ) ; } inAsyncTick = false ; // still need to make sure nested async calls are made in the context // of the listeners active at their creation return function ( ) { listenerStack . push ( listeners ) ; listeners = union ( list , listeners ) ; var returned = original . apply ( this , arguments ) ; listeners = listenerStack . pop ( ) ; return returned ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called each time an asynchronous function that s been monkeypatched in index . js is called . If there are no listeners return the function unwrapped . If there are any asyncListeners and any of them have callbacks pass them off to asyncWrap for later use otherwise just call the listener . [CODESPLIT] function wrapCallback ( original ) { var length = listeners . length ; // no context to capture, so avoid closure creation if ( length === 0 ) return original ; // capture the active listeners as of when the wrapped function was called var list = listeners . slice ( ) ; for ( var i = 0 ; i < length ; ++ i ) { if ( list [ i ] . flags > 0 ) return asyncWrap ( original , list , length ) ; } return simpleWrap ( original , list , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the largest file in the given directory optionally performing a recursive search . [CODESPLIT] function ( dir , options , internal ) { // Parse arguments. options = options || largest . options ; // Get all file stats in parallel. return fs . readdirAsync ( dir ) . then ( function ( files ) { var paths = _ . map ( files , function ( file ) { return path . join ( dir , file ) ; } ) ; return Promise . all ( _ . map ( paths , function ( path ) { return fs . statAsync ( path ) ; } ) ) . then ( function ( stats ) { return [ paths , stats ] ; } ) ; } ) // Build up a list of possible candidates, recursing into subfolders if requested. . spread ( function ( paths , stats ) { return Promise . all ( _ . map ( stats , function ( stat , i ) { if ( stat . isFile ( ) ) return Promise . resolve ( { path : paths [ i ] , size : stat . size , searched : 1 } ) ; return options . recurse ? largest ( paths [ i ] , options , true ) : Promise . resolve ( null ) ; } ) ) ; } ) // Choose the best candidate. . then ( function ( candidates ) { return _ ( candidates ) . compact ( ) . reduce ( function ( best , cand ) { if ( cand . size > best . size ) var temp = cand , cand = best , best = temp ; best . searched += cand . searched ; return best ; } ) ; } ) // Add a preview if requested (but skip if this is an internal step in a recursive search). . then ( function ( result ) { if ( result && options . preview && ! internal ) { var fd_ ; return fs . openAsync ( result . path , 'r' ) . then ( function ( fd ) { fd_ = fd ; var buffer = new Buffer ( 40 ) ; return fs . readAsync ( fd , buffer , 0 , 40 , 0 ) ; } ) . spread ( function ( bytesRead , buffer ) { result . preview = buffer . toString ( 'utf-8' , 0 , bytesRead ) ; return fs . closeAsync ( fd_ ) ; } ) . then ( function ( ) { return result ; } ) ; } else { return result ; // Return without adding preview. } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function for creating a specific variant of the async function . [CODESPLIT] function makeAsyncFunc ( config ) { // Validate the specified configuration config . validate ( ) ; // Create an async function tailored to the given options. var result = function async ( bodyFunc ) { // Create a semaphore for limiting top-level concurrency, if specified in options. var semaphore = config . maxConcurrency ? new Semaphore ( config . maxConcurrency ) : Semaphore . unlimited ; // Choose and run the appropriate function factory based on whether the result should be iterable. var makeFunc = config . isIterable ? makeAsyncIterator : makeAsyncNonIterator ; var result = makeFunc ( bodyFunc , config , semaphore ) ; // Ensure the suspendable function's arity matches that of the function it wraps. var arity = bodyFunc . length ; if ( config . acceptsCallback ) ++ arity ; result = makeFuncWithArity ( result , arity ) ; return result ; } ; // Add the mod() function, and return the result. result . mod = makeModFunc ( config ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function for creating iterable suspendable functions . [CODESPLIT] function makeAsyncIterator ( bodyFunc , config , semaphore ) { // Return a function that returns an iterator. return function iterable ( ) { // Capture the initial arguments used to start the iterator, as an array. var startupArgs = new Array ( arguments . length + 1 ) ; // Reserve 0th arg for the yield function.  for ( var i = 0 , len = arguments . length ; i < len ; ++ i ) startupArgs [ i + 1 ] = arguments [ i ] ; // Create a yield() function tailored for this iterator. var yield_ = function ( expr ) { // Ensure this function is executing inside a fiber. if ( ! Fiber . current ) { throw new Error ( 'await functions, yield functions, and value-returning suspendable ' + 'functions may only be called from inside a suspendable function. ' ) ; } // Notify waiters of the next result, then suspend the iterator. if ( runContext . callback ) runContext . callback ( null , { value : expr , done : false } ) ; if ( runContext . resolver ) runContext . resolver . resolve ( { value : expr , done : false } ) ; Fiber . yield ( ) ; } ; // Insert the yield function as the first argument when starting the iterator. startupArgs [ 0 ] = yield_ ; // Create the iterator. var runContext = new RunContext ( bodyFunc , this , startupArgs ) ; var iterator = new AsyncIterator ( runContext , semaphore , config . returnValue , config . acceptsCallback ) ; // Wrap the given bodyFunc to properly complete the iteration. runContext . wrapped = function ( ) { var len = arguments . length , args = new Array ( len ) ; for ( var i = 0 ; i < len ; ++ i ) args [ i ] = arguments [ i ] ; bodyFunc . apply ( this , args ) ; iterator . destroy ( ) ; return { done : true } ; } ; // Return the iterator. return iterator ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a yield () function tailored for this iterator . [CODESPLIT] function ( expr ) { // Ensure this function is executing inside a fiber. if ( ! Fiber . current ) { throw new Error ( 'await functions, yield functions, and value-returning suspendable ' + 'functions may only be called from inside a suspendable function. ' ) ; } // Notify waiters of the next result, then suspend the iterator. if ( runContext . callback ) runContext . callback ( null , { value : expr , done : false } ) ; if ( runContext . resolver ) runContext . resolver . resolve ( { value : expr , done : false } ) ; Fiber . yield ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function for creating non - iterable suspendable functions . [CODESPLIT] function makeAsyncNonIterator ( bodyFunc , config , semaphore ) { // Return a function that executes fn in a fiber and returns a promise of fn's result. return function nonIterable ( ) { // Get all the arguments passed in, as an array. var argsAsArray = new Array ( arguments . length ) ; for ( var i = 0 ; i < argsAsArray . length ; ++ i ) argsAsArray [ i ] = arguments [ i ] ; // Remove concurrency restrictions for nested calls, to avoid race conditions. if ( FiberMgr . isExecutingInFiber ( ) ) this . _semaphore = Semaphore . unlimited ; // Configure the run context. var runContext = new RunContext ( bodyFunc , this , argsAsArray , function ( ) { return semaphore . leave ( ) ; } ) ; if ( config . returnValue !== Config . NONE ) { var resolver = defer ( ) ; runContext . resolver = resolver ; } if ( config . acceptsCallback && argsAsArray . length && _ . isFunction ( argsAsArray [ argsAsArray . length - 1 ] ) ) { var callback = argsAsArray . pop ( ) ; runContext . callback = callback ; } // Execute bodyFunc to completion in a coroutine. For thunks, this is a lazy operation. if ( config . returnValue === Config . THUNK ) { var thunk = function ( done ) { if ( done ) resolver . promise . then ( function ( val ) { return done ( null , val ) ; } , function ( err ) { return done ( err ) ; } ) ; semaphore . enter ( function ( ) { return FiberMgr . create ( ) . run ( runContext ) ; } ) ; } ; } else { semaphore . enter ( function ( ) { return FiberMgr . create ( ) . run ( runContext ) ; } ) ; } // Return the appropriate value. switch ( config . returnValue ) { case Config . PROMISE : return resolver . promise ; case Config . THUNK : return thunk ; case Config . RESULT : return await ( resolver . promise ) ; case Config . NONE : return ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a function that directly proxies the given function whilst reporting the given arity . [CODESPLIT] function makeFuncWithArity ( fn , arity ) { // Need to handle each arity individually, but the body never changes. switch ( arity ) { case 0 : return function f0 ( ) { var i , l = arguments . length , r = new Array ( l ) ; for ( i = 0 ; i < l ; ++ i ) r [ i ] = arguments [ i ] ; return fn . apply ( this , r ) ; } ; case 1 : return function f1 ( a ) { var i , l = arguments . length , r = new Array ( l ) ; for ( i = 0 ; i < l ; ++ i ) r [ i ] = arguments [ i ] ; return fn . apply ( this , r ) ; } ; case 2 : return function f2 ( a , b ) { var i , l = arguments . length , r = new Array ( l ) ; for ( i = 0 ; i < l ; ++ i ) r [ i ] = arguments [ i ] ; return fn . apply ( this , r ) ; } ; case 3 : return function f3 ( a , b , c ) { var i , l = arguments . length , r = new Array ( l ) ; for ( i = 0 ; i < l ; ++ i ) r [ i ] = arguments [ i ] ; return fn . apply ( this , r ) ; } ; case 4 : return function f4 ( a , b , c , d ) { var i , l = arguments . length , r = new Array ( l ) ; for ( i = 0 ; i < l ; ++ i ) r [ i ] = arguments [ i ] ; return fn . apply ( this , r ) ; } ; case 5 : return function f5 ( a , b , c , d , e ) { var i , l = arguments . length , r = new Array ( l ) ; for ( i = 0 ; i < l ; ++ i ) r [ i ] = arguments [ i ] ; return fn . apply ( this , r ) ; } ; case 6 : return function f6 ( a , b , c , d , e , f ) { var i , l = arguments . length , r = new Array ( l ) ; for ( i = 0 ; i < l ; ++ i ) r [ i ] = arguments [ i ] ; return fn . apply ( this , r ) ; } ; case 7 : return function f7 ( a , b , c , d , e , f , g ) { var i , l = arguments . length , r = new Array ( l ) ; for ( i = 0 ; i < l ; ++ i ) r [ i ] = arguments [ i ] ; return fn . apply ( this , r ) ; } ; case 8 : return function f8 ( a , b , c , d , e , f , g , h ) { var i , l = arguments . length , r = new Array ( l ) ; for ( i = 0 ; i < l ; ++ i ) r [ i ] = arguments [ i ] ; return fn . apply ( this , r ) ; } ; case 9 : return function f9 ( a , b , c , d , e , f , g , h , _i ) { var i , l = arguments . length , r = new Array ( l ) ; for ( i = 0 ; i < l ; ++ i ) r [ i ] = arguments [ i ] ; return fn . apply ( this , r ) ; } ; default : return fn ; // Bail out if arity is crazy high. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The runInFiber () function provides the prolog / epilog wrapper code for running a function inside a fiber . The runInFiber () function accepts a RunContext instance and calls the wrapped function specified there . The final return / throw value of the wrapped function is used to notify the promise resolver and / or callback specified in the RunContext . This function must take all its information in a single argument because it is called via Fiber#run () which accepts one argument . NB : Since try / catch / finally prevents V8 optimisations the function is split into several parts . [CODESPLIT] function runInFiber ( runCtx ) { try { tryBlock ( runCtx ) ; } catch ( err ) { catchBlock ( runCtx , err ) ; } finally { finallyBlock ( runCtx ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The following functionality prevents memory leaks in node - fibers by actively managing Fiber . poolSize . For more information see https : // github . com / laverdet / node - fibers / issues / 169 . [CODESPLIT] function adjustFiberCount ( delta ) { activeFiberCount += delta ; if ( activeFiberCount >= fiberPoolSize ) { fiberPoolSize += 100 ; Fiber . poolSize = fiberPoolSize ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function for creating a specific variant of the await () function . [CODESPLIT] function makeAwaitFunc ( variant ) { // Return an await function tailored to the given options. switch ( variant ) { case 'in' : return getExtraInfo ( traverseInPlace ) ; case 'top' : return function ( n ) { return getExtraInfo ( traverseInPlace , n ) ; } ; default : return getExtraInfo ( traverseClone ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper function for makeAwaitFunc () . [CODESPLIT] function getExtraInfo ( traverse , topN ) { return function await ( ) { // Ensure this function is executing inside a fiber. if ( ! Fiber . current ) { throw new Error ( 'await functions, yield functions, and value-returning suspendable ' + 'functions may only be called from inside a suspendable function. ' ) ; } // Parse argument(s). If not a single argument, treat it like an array was passed in. if ( arguments . length === 1 ) { var expr = arguments [ 0 ] ; } else { expr = new Array ( arguments . length ) ; for ( var i = 0 ; i < arguments . length ; ++ i ) expr [ i ] = arguments [ i ] ; traverse = traverseInPlace ; } // Handle each supported 'awaitable' appropriately... var fiber = Fiber . current ; if ( expr && _ . isFunction ( expr . then ) ) { // A promise: resume the coroutine with the resolved value, or throw the rejection value into it. // NB: ensure the handlers return null to avoid bluebird 3.x warning 'a promise was created in a //     handler but none were returned from it'. This occurs if the next resumption of the suspendable //     function (i.e. in the client's code) creates a bluebird 3.x promise and then awaits it. expr . then ( function ( val ) { return ( fiber . run ( val ) , fiber = null ) ; } , function ( err ) { return ( fiber . throwInto ( err ) , fiber = null ) ; } ) ; } else if ( _ . isFunction ( expr ) ) { // A thunk: resume the coroutine with the callback value, or throw the errback value into it. expr ( function ( err , val ) { if ( err ) fiber . throwInto ( err ) ; else fiber . run ( val ) ; fiber = null ; } ) ; } else if ( _ . isArray ( expr ) || _ . isPlainObject ( expr ) ) { // An array or plain object: resume the coroutine with a deep clone of the array/object, // where all contained promises and thunks have been replaced by their resolved values. // NB: ensure handlers return null (see similar comment above). var trackedPromises = [ ] ; expr = traverse ( expr , trackAndReplaceWithResolvedValue ( trackedPromises ) ) ; if ( ! topN ) { Promise . all ( trackedPromises ) . then ( function ( val ) { return ( fiber . run ( expr ) , fiber = null ) ; } , function ( err ) { return ( fiber . throwInto ( err ) , fiber = null ) ; } ) ; } else { Promise . some ( trackedPromises , topN ) . then ( function ( val ) { return ( fiber . run ( val ) , fiber = null ) ; } , function ( err ) { return ( fiber . throwInto ( err ) , fiber = null ) ; } ) ; } } else { // Anything else: resume the coroutine immediately with the value. setImmediate ( function ( ) { fiber . run ( expr ) ; fiber = null ; } ) ; } // Suspend the current fiber until the one of the above handlers resumes it again. return Fiber . yield ( ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In - place ( ie non - cloning ) object traversal . [CODESPLIT] function traverseInPlace ( o , visitor ) { if ( _ . isArray ( o ) ) { var len = o . length ; for ( var i = 0 ; i < len ; ++ i ) { traverseInPlace ( o [ i ] , visitor ) ; visitor ( o , i ) ; } } else if ( _ . isPlainObject ( o ) ) { for ( var key in o ) { if ( ! o . hasOwnProperty ( key ) ) continue ; traverseInPlace ( o [ key ] , visitor ) ; visitor ( o , key ) ; } } return o ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Object traversal with cloning . [CODESPLIT] function traverseClone ( o , visitor ) { var result ; if ( _ . isArray ( o ) ) { var len = o . length ; result = new Array ( len ) ; for ( var i = 0 ; i < len ; ++ i ) { result [ i ] = traverseClone ( o [ i ] , visitor ) ; visitor ( result , i ) ; } } else if ( _ . isPlainObject ( o ) ) { result = { } ; for ( var key in o ) { if ( o . hasOwnProperty ( key ) ) { result [ key ] = traverseClone ( o [ key ] , visitor ) ; visitor ( result , key ) ; } } } else { result = o ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a thunk to a promise . [CODESPLIT] function thunkToPromise ( thunk ) { return new Promise ( function ( resolve , reject ) { var callback = function ( err , val ) { return ( err ? reject ( err ) : resolve ( val ) ) ; } ; thunk ( callback ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of files in the given directory . [CODESPLIT] function ( dir ) { var files = fs . readdirSync ( dir ) ; // Get all file stats in parallel. var paths = _ . map ( files , function ( file ) { return path . join ( dir , file ) ; } ) ; var stats = _ . map ( paths , function ( path ) { return fs . statSync ( path ) ; } ) ; // Count the files. return _ . filter ( stats , function ( stat ) { return stat . isFile ( ) ; } ) . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cb ( er parsed raw response ) [CODESPLIT] function requestDone ( method , where , cb ) { return function ( er , response , data ) { if ( er ) return cb ( er ) var urlObj = url . parse ( where ) if ( urlObj . auth ) urlObj . auth = '***' this . log . http ( response . statusCode , url . format ( urlObj ) ) if ( Buffer . isBuffer ( data ) ) { data = data . toString ( ) } var parsed if ( data && typeof data === 'string' && response . statusCode !== 304 ) { try { parsed = JSON . parse ( data ) } catch ( ex ) { ex . message += '\\n' + data this . log . verbose ( 'bad json' , data ) this . log . error ( 'registry' , 'error parsing json' ) return cb ( ex , null , data , response ) } } else if ( data ) { parsed = data data = JSON . stringify ( parsed ) } // expect data with any error codes if ( ! data && response . statusCode >= 400 ) { var code = response . statusCode return cb ( makeError ( code + ' ' + STATUS_CODES [ code ] , null , code ) , null , data , response ) } er = null if ( parsed && response . headers . etag ) { parsed . _etag = response . headers . etag } if ( parsed && response . headers [ 'last-modified' ] ) { parsed . _lastModified = response . headers [ 'last-modified' ] } // for the search endpoint, the 'error' property can be an object if ( ( parsed && parsed . error && typeof parsed . error !== 'object' ) || response . statusCode >= 400 ) { var w = url . parse ( where ) . pathname . substr ( 1 ) var name if ( ! w . match ( / ^- / ) ) { w = w . split ( '/' ) var index = w . indexOf ( '_rewrite' ) if ( index === - 1 ) { index = w . length - 1 } else { index ++ } name = decodeURIComponent ( w [ index ] ) } if ( ! parsed . error ) { if ( response . statusCode === 401 && response . headers [ 'www-authenticate' ] ) { const auth = response . headers [ 'www-authenticate' ] . split ( / ,\\s* / ) . map ( s => s . toLowerCase ( ) ) if ( auth . indexOf ( 'ipaddress' ) !== - 1 ) { er = makeError ( 'Login is not allowed from your IP address' , name , response . statusCode , 'EAUTHIP' ) } else if ( auth . indexOf ( 'otp' ) !== - 1 ) { er = makeError ( 'OTP required for this operation' , name , response . statusCode , 'EOTP' ) } else { er = makeError ( 'Unable to authenticate, need: ' + response . headers [ 'www-authenticate' ] , name , response . statusCode , 'EAUTHUNKNOWN' ) } } else { const msg = parsed . message ? ': ' + parsed . message : '' er = makeError ( 'Registry returned ' + response . statusCode + ' for ' + method + ' on ' + where + msg , name , response . statusCode ) } } else if ( name && parsed . error === 'not_found' ) { er = makeError ( '404 Not Found: ' + name , name , response . statusCode ) } else if ( name && parsed . error === 'User not found' ) { er = makeError ( 'User not found. Check `npm whoami` and make sure you have a NPM account.' , name , response . statusCode ) } else { er = makeError ( parsed . error + ' ' + ( parsed . reason || '' ) + ': ' + ( name || w ) , name , response . statusCode ) } } return cb ( er , parsed , data , response ) } . bind ( this ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This is meant to be overridden in specific implementations if you want specialized behavior for metadata ( i . e . caching ) . [CODESPLIT] function get ( uri , params , cb ) { assert ( typeof uri === 'string' , 'must pass registry URI to get' ) assert ( params && typeof params === 'object' , 'must pass params to get' ) assert ( typeof cb === 'function' , 'must pass callback to get' ) var parsed = url . parse ( uri ) assert ( parsed . protocol === 'http:' || parsed . protocol === 'https:' , 'must have a URL that starts with http: or https:' ) this . request ( uri , params , cb ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy the settings synonyms and rules of the source index to the target index [CODESPLIT] async function scopedCopyIndex ( client , sourceIndex , targetIndex ) { const { taskID } = await client . copyIndex ( sourceIndex . indexName , targetIndex . indexName , [ 'settings' , 'synonyms' , 'rules' ] ) ; return targetIndex . waitTask ( taskID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "moves the source index to the target index [CODESPLIT] async function moveIndex ( client , sourceIndex , targetIndex ) { const { taskID } = await client . moveIndex ( sourceIndex . indexName , targetIndex . indexName ) ; return targetIndex . waitTask ( taskID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does an Algolia index exist already [CODESPLIT] async function indexExists ( index ) { try { const { nbHits } = await index . search ( ) ; return nbHits > 0 ; } catch ( e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hotfix the Gatsby reporter to allow setting status ( not supported everywhere ) [CODESPLIT] function setStatus ( activity , status ) { if ( activity && activity . setStatus ) { activity . setStatus ( status ) ; } else { console . log ( 'Algolia:' , status ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the given module . [CODESPLIT] function loadModule ( moduleName ) { var module = modules [ moduleName ] ; if ( module !== undefined ) { return module ; } // This uses a switch for static require analysis switch ( moduleName ) { case 'charset' : module = require ( './lib/charset' ) ; break ; case 'encoding' : module = require ( './lib/encoding' ) ; break ; case 'language' : module = require ( './lib/language' ) ; break ; case 'mediaType' : module = require ( './lib/mediaType' ) ; break ; default : throw new Error ( 'Cannot find module \\'' + moduleName + '\\'' ) ; } // Store to prevent invoking require() modules [ moduleName ] = module ; return module ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the Accept - Language header . [CODESPLIT] function parseAcceptLanguage ( accept ) { var accepts = accept . split ( ',' ) ; for ( var i = 0 , j = 0 ; i < accepts . length ; i ++ ) { var language = parseLanguage ( accepts [ i ] . trim ( ) , i ) ; if ( language ) { accepts [ j ++ ] = language ; } } // trim accepts accepts . length = j ; return accepts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a language from the Accept - Language header . [CODESPLIT] function parseLanguage ( str , i ) { var match = simpleLanguageRegExp . exec ( str ) ; if ( ! match ) return null ; var prefix = match [ 1 ] , suffix = match [ 2 ] , full = prefix ; if ( suffix ) full += \"-\" + suffix ; var q = 1 ; if ( match [ 3 ] ) { var params = match [ 3 ] . split ( ';' ) for ( var j = 0 ; j < params . length ; j ++ ) { var p = params [ j ] . split ( '=' ) ; if ( p [ 0 ] === 'q' ) q = parseFloat ( p [ 1 ] ) ; } } return { prefix : prefix , suffix : suffix , q : q , i : i , full : full } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the priority of a language . [CODESPLIT] function getLanguagePriority ( language , accepted , index ) { var priority = { o : - 1 , q : 0 , s : 0 } ; for ( var i = 0 ; i < accepted . length ; i ++ ) { var spec = specify ( language , accepted [ i ] , index ) ; if ( spec && ( priority . s - spec . s || priority . q - spec . q || priority . o - spec . o ) < 0 ) { priority = spec ; } } return priority ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the specificity of the language . [CODESPLIT] function specify ( language , spec , index ) { var p = parseLanguage ( language ) if ( ! p ) return null ; var s = 0 ; if ( spec . full . toLowerCase ( ) === p . full . toLowerCase ( ) ) { s |= 4 ; } else if ( spec . prefix . toLowerCase ( ) === p . full . toLowerCase ( ) ) { s |= 2 ; } else if ( spec . full . toLowerCase ( ) === p . prefix . toLowerCase ( ) ) { s |= 1 ; } else if ( spec . full !== '*' ) { return null } return { i : index , o : spec . i , q : spec . q , s : s } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the preferred languages from an Accept - Language header . [CODESPLIT] function preferredLanguages ( accept , provided ) { // RFC 2616 sec 14.4: no header = * var accepts = parseAcceptLanguage ( accept === undefined ? '*' : accept || '' ) ; if ( ! provided ) { // sorted list of all languages return accepts . filter ( isQuality ) . sort ( compareSpecs ) . map ( getFullLanguage ) ; } var priorities = provided . map ( function getPriority ( type , index ) { return getLanguagePriority ( type , accepts , index ) ; } ) ; // sorted list of accepted languages return priorities . filter ( isQuality ) . sort ( compareSpecs ) . map ( function getLanguage ( priority ) { return provided [ priorities . indexOf ( priority ) ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare two specs . [CODESPLIT] function compareSpecs ( a , b ) { return ( b . q - a . q ) || ( b . s - a . s ) || ( a . o - b . o ) || ( a . i - b . i ) || 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the Accept - Charset header . [CODESPLIT] function parseAcceptCharset ( accept ) { var accepts = accept . split ( ',' ) ; for ( var i = 0 , j = 0 ; i < accepts . length ; i ++ ) { var charset = parseCharset ( accepts [ i ] . trim ( ) , i ) ; if ( charset ) { accepts [ j ++ ] = charset ; } } // trim accepts accepts . length = j ; return accepts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a charset from the Accept - Charset header . [CODESPLIT] function parseCharset ( str , i ) { var match = simpleCharsetRegExp . exec ( str ) ; if ( ! match ) return null ; var charset = match [ 1 ] ; var q = 1 ; if ( match [ 2 ] ) { var params = match [ 2 ] . split ( ';' ) for ( var j = 0 ; j < params . length ; j ++ ) { var p = params [ j ] . trim ( ) . split ( '=' ) ; if ( p [ 0 ] === 'q' ) { q = parseFloat ( p [ 1 ] ) ; break ; } } } return { charset : charset , q : q , i : i } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the priority of a charset . [CODESPLIT] function getCharsetPriority ( charset , accepted , index ) { var priority = { o : - 1 , q : 0 , s : 0 } ; for ( var i = 0 ; i < accepted . length ; i ++ ) { var spec = specify ( charset , accepted [ i ] , index ) ; if ( spec && ( priority . s - spec . s || priority . q - spec . q || priority . o - spec . o ) < 0 ) { priority = spec ; } } return priority ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the specificity of the charset . [CODESPLIT] function specify ( charset , spec , index ) { var s = 0 ; if ( spec . charset . toLowerCase ( ) === charset . toLowerCase ( ) ) { s |= 1 ; } else if ( spec . charset !== '*' ) { return null } return { i : index , o : spec . i , q : spec . q , s : s } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the preferred charsets from an Accept - Charset header . [CODESPLIT] function preferredCharsets ( accept , provided ) { // RFC 2616 sec 14.2: no header = * var accepts = parseAcceptCharset ( accept === undefined ? '*' : accept || '' ) ; if ( ! provided ) { // sorted list of all charsets return accepts . filter ( isQuality ) . sort ( compareSpecs ) . map ( getFullCharset ) ; } var priorities = provided . map ( function getPriority ( type , index ) { return getCharsetPriority ( type , accepts , index ) ; } ) ; // sorted list of accepted charsets return priorities . filter ( isQuality ) . sort ( compareSpecs ) . map ( function getCharset ( priority ) { return provided [ priorities . indexOf ( priority ) ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an encoding from the Accept - Encoding header . [CODESPLIT] function parseEncoding ( str , i ) { var match = simpleEncodingRegExp . exec ( str ) ; if ( ! match ) return null ; var encoding = match [ 1 ] ; var q = 1 ; if ( match [ 2 ] ) { var params = match [ 2 ] . split ( ';' ) ; for ( var j = 0 ; j < params . length ; j ++ ) { var p = params [ j ] . trim ( ) . split ( '=' ) ; if ( p [ 0 ] === 'q' ) { q = parseFloat ( p [ 1 ] ) ; break ; } } } return { encoding : encoding , q : q , i : i } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the priority of an encoding . [CODESPLIT] function getEncodingPriority ( encoding , accepted , index ) { var priority = { o : - 1 , q : 0 , s : 0 } ; for ( var i = 0 ; i < accepted . length ; i ++ ) { var spec = specify ( encoding , accepted [ i ] , index ) ; if ( spec && ( priority . s - spec . s || priority . q - spec . q || priority . o - spec . o ) < 0 ) { priority = spec ; } } return priority ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the preferred encodings from an Accept - Encoding header . [CODESPLIT] function preferredEncodings ( accept , provided ) { var accepts = parseAcceptEncoding ( accept || '' ) ; if ( ! provided ) { // sorted list of all encodings return accepts . filter ( isQuality ) . sort ( compareSpecs ) . map ( getFullEncoding ) ; } var priorities = provided . map ( function getPriority ( type , index ) { return getEncodingPriority ( type , accepts , index ) ; } ) ; // sorted list of accepted encodings return priorities . filter ( isQuality ) . sort ( compareSpecs ) . map ( function getEncoding ( priority ) { return provided [ priorities . indexOf ( priority ) ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the Accept header . [CODESPLIT] function parseAccept ( accept ) { var accepts = splitMediaTypes ( accept ) ; for ( var i = 0 , j = 0 ; i < accepts . length ; i ++ ) { var mediaType = parseMediaType ( accepts [ i ] . trim ( ) , i ) ; if ( mediaType ) { accepts [ j ++ ] = mediaType ; } } // trim accepts accepts . length = j ; return accepts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a media type from the Accept header . [CODESPLIT] function parseMediaType ( str , i ) { var match = simpleMediaTypeRegExp . exec ( str ) ; if ( ! match ) return null ; var params = Object . create ( null ) ; var q = 1 ; var subtype = match [ 2 ] ; var type = match [ 1 ] ; if ( match [ 3 ] ) { var kvps = splitParameters ( match [ 3 ] ) . map ( splitKeyValuePair ) ; for ( var j = 0 ; j < kvps . length ; j ++ ) { var pair = kvps [ j ] ; var key = pair [ 0 ] . toLowerCase ( ) ; var val = pair [ 1 ] ; // get the value, unwrapping quotes var value = val && val [ 0 ] === '\"' && val [ val . length - 1 ] === '\"' ? val . substr ( 1 , val . length - 2 ) : val ; if ( key === 'q' ) { q = parseFloat ( value ) ; break ; } // store parameter params [ key ] = value ; } } return { type : type , subtype : subtype , params : params , q : q , i : i } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the priority of a media type . [CODESPLIT] function getMediaTypePriority ( type , accepted , index ) { var priority = { o : - 1 , q : 0 , s : 0 } ; for ( var i = 0 ; i < accepted . length ; i ++ ) { var spec = specify ( type , accepted [ i ] , index ) ; if ( spec && ( priority . s - spec . s || priority . q - spec . q || priority . o - spec . o ) < 0 ) { priority = spec ; } } return priority ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the specificity of the media type . [CODESPLIT] function specify ( type , spec , index ) { var p = parseMediaType ( type ) ; var s = 0 ; if ( ! p ) { return null ; } if ( spec . type . toLowerCase ( ) == p . type . toLowerCase ( ) ) { s |= 4 } else if ( spec . type != '*' ) { return null ; } if ( spec . subtype . toLowerCase ( ) == p . subtype . toLowerCase ( ) ) { s |= 2 } else if ( spec . subtype != '*' ) { return null ; } var keys = Object . keys ( spec . params ) ; if ( keys . length > 0 ) { if ( keys . every ( function ( k ) { return spec . params [ k ] == '*' || ( spec . params [ k ] || '' ) . toLowerCase ( ) == ( p . params [ k ] || '' ) . toLowerCase ( ) ; } ) ) { s |= 1 } else { return null } } return { i : index , o : spec . i , q : spec . q , s : s , } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the preferred media types from an Accept header . [CODESPLIT] function preferredMediaTypes ( accept , provided ) { // RFC 2616 sec 14.2: no header = */* var accepts = parseAccept ( accept === undefined ? '*/*' : accept || '' ) ; if ( ! provided ) { // sorted list of all types return accepts . filter ( isQuality ) . sort ( compareSpecs ) . map ( getFullType ) ; } var priorities = provided . map ( function getPriority ( type , index ) { return getMediaTypePriority ( type , accepts , index ) ; } ) ; // sorted list of accepted types return priorities . filter ( isQuality ) . sort ( compareSpecs ) . map ( function getType ( priority ) { return provided [ priorities . indexOf ( priority ) ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Count the number of quotes in a string . [CODESPLIT] function quoteCount ( string ) { var count = 0 ; var index = 0 ; while ( ( index = string . indexOf ( '\"' , index ) ) !== - 1 ) { count ++ ; index ++ ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split a key value pair . [CODESPLIT] function splitKeyValuePair ( str ) { var index = str . indexOf ( '=' ) ; var key ; var val ; if ( index === - 1 ) { key = str ; } else { key = str . substr ( 0 , index ) ; val = str . substr ( index + 1 ) ; } return [ key , val ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split an Accept header into media types . [CODESPLIT] function splitMediaTypes ( accept ) { var accepts = accept . split ( ',' ) ; for ( var i = 1 , j = 0 ; i < accepts . length ; i ++ ) { if ( quoteCount ( accepts [ j ] ) % 2 == 0 ) { accepts [ ++ j ] = accepts [ i ] ; } else { accepts [ j ] += ',' + accepts [ i ] ; } } // trim accepts accepts . length = j + 1 ; return accepts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split a string of parameters . [CODESPLIT] function splitParameters ( str ) { var parameters = str . split ( ';' ) ; for ( var i = 1 , j = 0 ; i < parameters . length ; i ++ ) { if ( quoteCount ( parameters [ j ] ) % 2 == 0 ) { parameters [ ++ j ] = parameters [ i ] ; } else { parameters [ j ] += ';' + parameters [ i ] ; } } // trim parameters parameters . length = j + 1 ; for ( var i = 0 ; i < parameters . length ; i ++ ) { parameters [ i ] = parameters [ i ] . trim ( ) ; } return parameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function ( ) { this . seq ( ) . obj ( this . key ( 'version' ) . use ( Version ) , this . key ( 'privateKeyAlgorithm' ) . use ( AlgorithmIdentifier ) , this . key ( 'privateKey' ) . octstr ( ) , this . key ( 'attributes' ) . optional ( ) . any ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function ( ) { this . seq ( ) . obj ( this . key ( 'version' ) . use ( Version ) , this . key ( 'privateKey' ) . octstr ( ) , this . key ( 'parameters' ) . explicit ( 0 ) . optional ( ) . any ( ) , this . key ( 'publicKey' ) . explicit ( 1 ) . optional ( ) . bitstr ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function ( ) { this . seq ( ) . obj ( this . key ( 'version' ) . use ( Version ) , this . key ( 'modulus' ) . int ( ) , this . key ( 'publicExponent' ) . int ( ) , this . key ( 'privateExponent' ) . int ( ) , this . key ( 'prime1' ) . int ( ) , this . key ( 'prime2' ) . int ( ) , this . key ( 'exponent1' ) . int ( ) , this . key ( 'exponent2' ) . int ( ) , this . key ( 'coefficient' ) . int ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------- // Constructor Module // ---------------------------------------------------------------------------- // ////////////////////////////////////////////////////////////////////////////// [CODESPLIT] function Module ( process , name , path , base , size ) { // Auto instantiate the Module if ( ! ( this instanceof Module ) ) { return new Module ( process , name , path , base , size ) ; } // Check for any arguments if ( process === undefined ) { this . _valid = false ; this . _name = \"\" ; this . _path = \"\" ; this . _base = 0 ; this . _size = 0 ; this . _proc = robot . Process ( ) ; this . _segments = null ; return ; } // Verify that args are valid if ( typeof name === \"string\" && typeof path === \"string\" && typeof base === \"number\" && typeof size === \"number\" && process instanceof robot . Process ) { this . _valid = true ; this . _name = name ; this . _path = path ; this . _base = base ; this . _size = size ; this . _proc = process ; this . _segments = null ; return ; } throw new TypeError ( \"Invalid arguments\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------- // Constructor Hash // ---------------------------------------------------------------------------- // ////////////////////////////////////////////////////////////////////////////// [CODESPLIT] function Hash ( data ) { // Auto instantiate the Hash if ( ! ( this instanceof Hash ) ) return new Hash ( data ) ; this . result = 0 ; if ( data !== undefined ) this . append ( data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////// [CODESPLIT] function ( details ) { console . warn ( mColors . yellow . bold ( \"WARNING: robot-js precompiled binaries could \" + \"not be downloaded, an attempt to compile them\" + \" manually will be made. For more information,\" + \" please visit http://getrobot.net/docs/node.html.\" + \" Details: \" + details ) ) ; try { // Delete target binary mFS . unlinkSync ( TARGET ) ; } catch ( e ) { } process . exitCode = 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////// [CODESPLIT] function ( details ) { console . error ( mColors . red . bold ( \"ERROR: robot-js precompiled binaries could not \" + \"be verified. This could be a result of a man-in\" + \"-the-middle attack. If you want to continue \" + \"anyway, use the following command to disable\" + \" verification: 'npm config set robot-js:verify \" + \"false'. Details: \" + details ) ) ; try { // Delete target binary mFS . unlinkSync ( TARGET ) ; } catch ( e ) { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////// [CODESPLIT] function ( url , success , failure ) { // Attempt to get the URL var req = mHTTP . get ( url ) ; // Whenever a response is received req . on ( \"response\" , function ( res ) { // Check if response is OK if ( res . statusCode === 200 ) success ( res ) ; // Some unexpected response else failure ( \"bad response\" + \" (\" + res . statusCode + \") \" + res . statusMessage ) ; } ) ; // Whenever an error is thrown req . on ( \"error\" , function ( err ) { failure ( err . message ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------- // Constructor Size // ---------------------------------------------------------------------------- // ////////////////////////////////////////////////////////////////////////////// [CODESPLIT] function Size ( aw , ah ) { // Auto instantiate the Size if ( ! ( this instanceof Size ) ) return new Size ( aw , ah ) ; var s = Size . normalize ( aw , ah ) ; this . w = s . w ; this . h = s . h ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------- // Constructor Screen // ---------------------------------------------------------------------------- // ////////////////////////////////////////////////////////////////////////////// [CODESPLIT] function Screen ( bounds , usable ) { // Auto instantiate the Screen if ( ! ( this instanceof Screen ) ) return new Screen ( bounds , usable ) ; // Check if using defaults if ( bounds === undefined && usable === undefined ) { this . _bounds = robot . Bounds ( ) ; this . _usable = robot . Bounds ( ) ; return ; } // Check if assigning bounds values if ( bounds instanceof robot . Bounds && usable instanceof robot . Bounds ) { this . _bounds = bounds ; this . _usable = usable ; return ; } throw new TypeError ( \"Invalid arguments\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------- // Region Memory // ---------------------------------------------------------------------------- // ////////////////////////////////////////////////////////////////////////////// [CODESPLIT] function Region ( ) { // Auto instantiate the Region if ( ! ( this instanceof Region ) ) return new Region ( ) ; this . valid = false ; this . bound = false ; this . start = 0 ; this . stop = 0 ; this . size = 0 ; this . readable = false ; this . writable = false ; this . executable = false ; this . access = 0 ; this . private = false ; this . guarded = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads configuration while ensuring sounce - map is enabled [CODESPLIT] function loadWebpackConfig ( ) { var webpackConfig = require ( './webpack.config.js' ) ; webpackConfig . devtool = 'inline-source-map' ; webpackConfig . module . preLoaders = [ { test : / \\.jsx?$ / , include : path . resolve ( 'lib' ) , loader : 'isparta' } ] ; return webpackConfig ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assigns values to an object creating keys in keyPath if they don t exist yet . [CODESPLIT] function assign ( obj , keyPath , value ) { const lastKeyIndex = keyPath . length - 1 for ( let i = 0 ; i < lastKeyIndex ; ++ i ) { const key = keyPath [ i ] if ( ! ( key in obj ) ) obj [ key ] = { } obj = obj [ key ] } obj [ keyPath [ lastKeyIndex ] ] = value }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "transforms the selectedValues from store into the X - Search - Filters string for analytics [CODESPLIT] function getFilterString ( selectedValues ) { if ( selectedValues && Object . keys ( selectedValues ) . length ) { return Object // take all selectedValues . entries ( selectedValues ) // filter out filter components having some value . filter ( ( [ , componentValues ] ) => filterComponents . includes ( componentValues . componentType ) // in case of an array filter out empty array values as well && ( ( componentValues . value && componentValues . value . length ) // also consider range values in the shape { start, end } || componentValues . value . start || componentValues . value . end ) ) // parse each filter value . map ( ( [ componentId , componentValues ] ) => parseFilterValue ( componentId , componentValues ) ) // return as a string separated with comma . join ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates a function on the given page . [CODESPLIT] function evaluatePage ( page , fn ) { var args = Array . prototype . slice . call ( arguments , 2 ) ; return this . ready . then ( function ( ) { var stack ; page = page || this . page ; var res = HorsemanPromise . fromCallback ( function ( done ) { // Wrap fn to be able to catch exceptions and reject Promise stack = HorsemanPromise . reject ( new Error ( 'See next line' ) ) ; return page . evaluate ( function evaluatePage ( fnstr , args ) { try { var fn ; eval ( 'fn = ' + fnstr ) ; var res = fn . apply ( this , args ) ; // Call fn with args return { res : res } ; } catch ( err ) { return { err : err , iserr : err instanceof Error } ; } } , fn . toString ( ) , args , done ) ; } ) . then ( function handleErrback ( args ) { return stack . catch ( function ( err ) { if ( args . err ) { if ( args . iserr ) { var stack = err . stack . split ( '\\n' ) . slice ( 1 ) ; // Append Node stack to Phantom stack args . err . stack += '\\n' + stack . join ( '\\n' ) ; } return HorsemanPromise . reject ( args . err ) ; } return args . res ; } ) ; } ) ; stack . catch ( function ( ) { } ) ; return res ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits for a function to evaluate to a given value on the given page [CODESPLIT] function waitForPage ( page , optsOrFn ) { var self = this ; var args , value , fname , timeout = self . options . timeout , fn ; if ( typeof optsOrFn === \"function\" ) { fn = optsOrFn ; args = Array . prototype . slice . call ( arguments ) ; value = args . pop ( ) ; fname = fn . name || '<anonymous>' ; } else if ( typeof optsOrFn === \"object\" ) { fn = optsOrFn . fn ; args = [ page , fn ] . concat ( optsOrFn . args || [ ] ) ; value = optsOrFn . value ; fname = fn . name || '<anonymous>' ; if ( optsOrFn . timeout ) { timeout = optsOrFn . timeout ; } } debug . apply ( debug , [ '.waitFor()' , fname ] . concat ( args . slice ( 2 ) ) ) ; return this . ready . then ( function ( ) { return new HorsemanPromise ( function ( resolve , reject ) { var start = Date . now ( ) ; var checkInterval = setInterval ( function waitForCheck ( ) { var _page = page || self . page ; var diff = Date . now ( ) - start ; if ( diff > timeout ) { clearInterval ( checkInterval ) ; debug ( '.waitFor() timed out' ) ; if ( typeof _page . onTimeout === 'function' ) { _page . onTimeout ( 'waitFor' ) ; } reject ( new TimeoutError ( 'timeout during .waitFor() after ' + diff + ' ms' ) ) ; } else { return evaluatePage . apply ( self , args ) . tap ( function ( res ) { debugv ( '.waitFor() iteration' , fname , res , diff , self . id ) ; } ) . then ( function ( res ) { if ( res === value ) { debug ( '.waitFor() completed successfully' ) ; clearInterval ( checkInterval ) ; resolve ( ) ; } } ) . catch ( function ( err ) { clearInterval ( checkInterval ) ; reject ( err ) ; } ) ; } } , self . options . interval ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Horseman . [CODESPLIT] function Horseman ( options ) { this . ready = false ; if ( ! ( this instanceof Horseman ) ) { return new Horseman ( options ) ; } this . options = defaults ( clone ( options ) || { } , DEFAULTS ) ; this . id = ++ instanceId ; debug ( '.setup() creating phantom instance %s' , this . id ) ; var phantomOptions = { 'load-images' : this . options . loadImages , 'ssl-protocol' : this . options . sslProtocol } ; if ( typeof this . options . ignoreSSLErrors !== 'undefined' ) { phantomOptions [ 'ignore-ssl-errors' ] = this . options . ignoreSSLErrors ; } if ( typeof this . options . webSecurity !== 'undefined' ) { phantomOptions [ 'web-security' ] = this . options . webSecurity ; } if ( typeof this . options . proxy !== 'undefined' ) { phantomOptions . proxy = this . options . proxy ; } if ( typeof this . options . proxyType !== 'undefined' ) { phantomOptions [ 'proxy-type' ] = this . options . proxyType ; } if ( typeof this . options . proxyAuth !== 'undefined' ) { phantomOptions [ 'proxy-auth' ] = this . options . proxyAuth ; } if ( typeof this . options . diskCache !== 'undefined' ) { phantomOptions [ 'disk-cache' ] = this . options . diskCache ; } if ( typeof this . options . diskCachePath !== 'undefined' ) { phantomOptions [ 'disk-cache-path' ] = this . options . diskCachePath ; } if ( typeof this . options . cookiesFile !== 'undefined' ) { phantomOptions [ 'cookies-file' ] = this . options . cookiesFile ; } if ( this . options . debugPort ) { phantomOptions [ 'remote-debugger-port' ] = this . options . debugPort ; phantomOptions [ 'remote-debugger-autorun' ] = 'no' ; if ( this . options . debugAutorun !== false ) { phantomOptions [ 'remote-debugger-autorun' ] = 'yes' ; } } Object . keys ( this . options . phantomOptions || { } ) . forEach ( function ( key ) { if ( typeof phantomOptions [ key ] !== 'undefined' ) { debug ( 'Horseman option ' + key + ' overridden by phantomOptions' ) ; } phantomOptions [ key ] = this . options . phantomOptions [ key ] ; } . bind ( this ) ) ; var instantiationOptions = { parameters : phantomOptions } ; if ( typeof this . options . phantomPath !== 'undefined' ) { instantiationOptions [ 'path' ] = this . options . phantomPath ; } // Store the url that was requested for the current url this . targetUrl = null ; // Store the HTTP status code for resources requested. this . responses = { } ; this . tabs = [ ] ; this . onTabCreated = noop ; this . onTabClosed = noop ; this . ready = prepare ( this , instantiationOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do any javascript injection on the page TODO : Consolidate into one page . evaluate? [CODESPLIT] function loadFinishedSetup ( status ) { var args = arguments ; self . pageCnt ++ ; debug ( 'phantomjs onLoadFinished triggered' , status , self . pageCnt ) ; return self . ready = HorsemanPromise . try ( function checkStatus ( ) { if ( status !== 'success' ) { var err = new Error ( 'Failed to load url' ) ; return HorsemanPromise . reject ( err ) ; } } ) . then ( function injectJQuery ( ) { if ( ! self . options . injectJquery ) { return ; } return HorsemanPromise . fromCallback ( function hasJQuery ( done ) { return page . evaluate ( function hasJQuery ( ) { return ( typeof window . jQuery !== 'undefined' ) ; } , done ) ; } ) . then ( function ( hasJquery ) { if ( hasJquery ) { debug ( 'jQuery not injected - already exists on page' ) ; return ; } var jQueryLocation = path . join ( __dirname , '../files/jquery-2.1.1.min.js' ) ; return HorsemanPromise . fromCallback ( function ( done ) { return page . injectJs ( jQueryLocation , done ) ; } ) . tap ( function ( successful ) { if ( ! successful ) { var err = new Error ( 'jQuery injection failed' ) ; return HorsemanPromise . reject ( err ) ; } debug ( 'injected jQuery' ) ; } ) ; } ) ; } ) . then ( function injectBluebird ( ) { var inject = self . options . injectBluebird ; if ( ! inject ) { return ; } return HorsemanPromise . fromCallback ( function hasPromise ( done ) { return page . evaluate ( function hasPromise ( ) { return ( typeof window . Promise !== 'undefined' ) ; } , done ) ; } ) . then ( function ( hasPromise ) { if ( hasPromise && inject !== 'bluebird' ) { debug ( 'bluebird not injected - ' + 'Promise already exists on page' ) ; return ; } var bbLoc = 'bluebird/js/browser/bluebird' + ( self . options . bluebirdDebug ? '' : '.min' ) + '.js' ; return HorsemanPromise . fromCallback ( function ( done ) { return page . injectJs ( require . resolve ( bbLoc ) , done ) ; } ) . tap ( function ( successful ) { if ( ! successful ) { var err = new Error ( 'bluebird injection failed' ) ; return HorsemanPromise . reject ( err ) ; } debug ( 'injected bluebird' ) ; } ) ; } ) . then ( function configBluebird ( ) { return HorsemanPromise . fromCallback ( function ( done ) { return page . evaluate ( function configBluebird ( noConflict , debug ) { if ( debug ) { // TODO: Turn on warnings in bluebird 3 Promise . longStackTraces ( ) ; } if ( noConflict ) { window . Bluebird = Promise . noConflict ( ) ; } } , inject === 'bluebird' , self . options . bluebirdDebug , done ) ; } ) ; } ) ; } ) . then ( function initWindow ( ) { return HorsemanPromise . fromCallback ( function ( done ) { return page . evaluate ( function initWindow ( ) { window . __horseman = { } ; } , done ) ; } ) ; } ) . then ( function finishLoad ( ) { if ( page . onLoadFinished2 ) { return page . onLoadFinished2 . apply ( page , args ) ; } } ) . bind ( self ) . asCallback ( page . loadDone ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helpers here get image colors [CODESPLIT] function getColors ( image , cb ) { var data = [ ] ; var img = createImage ( image ) ; var promise = new Promise ( function ( resolve ) { img . onload = function ( ) { var canvas = document . createElement ( 'canvas' ) ; canvas . width = img . width ; canvas . height = img . height ; canvas . getContext ( '2d' ) . drawImage ( img , 0 , 0 , img . width , img . height ) ; var ctx = canvas . getContext ( '2d' ) ; var imageData = ctx . getImageData ( 0 , 0 , img . width , 1 ) . data ; for ( var i = 0 ; i < img . width ; i ++ ) { data . push ( [ imageData [ i * 4 ] / 255 , imageData [ i * 4 + 1 ] / 255 , imageData [ i * 4 + 2 ] / 255 ] ) ; } resolve ( data ) ; } ; } ) ; return promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create colormap by rotating cubehelix [CODESPLIT] function createCubehelix ( steps , opts ) { var data = [ ] ; for ( var i = 0 ; i < steps ; i ++ ) { data . push ( cubehelix . rgb ( i / steps , opts ) . map ( ( v ) => v / 255 ) ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return imagedata from colormap [CODESPLIT] function toImageData ( colors ) { return colors . map ( ( color ) => color . map ( ( v ) => v * 255 ) . concat ( 255 ) ) . reduce ( ( prev , curr ) => prev . concat ( curr ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return interpolated imagedata with only each [CODESPLIT] function compress ( colors , factor ) { var data = [ ] ; var len = ( colors . length ) / factor ; var step = ( colors . length - 1 ) / len ; for ( var i = 0 ; i < colors . length ; i += step ) { data . push ( colors [ i | 0 ] ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert imagedata to colormap JSON [CODESPLIT] function toColormap ( data ) { var stops = [ ] ; for ( var i = 0 ; i < data . length ; i ++ ) { stops . push ( { index : Math . round ( i * 100 / ( data . length - 1 ) ) / 100 , rgb : data [ i ] . map ( ( v ) => Math . round ( v * 255 ) ) } ) ; } return stops ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a canvas with the image / colordata preview [CODESPLIT] function show ( pixels , title ) { if ( typeof pixels === 'string' ) { var img = createImage ( pixels ) ; img . style . height = '40px' ; img . style . width = '100%' ; title && img . setAttribute ( 'title' , title ) ; document . body . appendChild ( img ) ; return ; } var canvas = document . createElement ( 'canvas' ) ; var w = ( pixels . length / 4 ) | 0 ; canvas . width = w ; canvas . height = 1 ; canvas . style . height = '40px' ; canvas . style . width = '100%' ; var ctx = canvas . getContext ( '2d' ) ; var imageData = ctx . createImageData ( w , 1 ) ; imageData . data . set ( pixels ) ; ctx . putImageData ( imageData , 0 , 0 ) ; title && canvas . setAttribute ( 'title' , title ) ; document . body . appendChild ( canvas ) ; document . body . appendChild ( document . createElement ( 'br' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Thanks jQuery! [CODESPLIT] function ( ) { var prop = 'pageYOffset' , method = 'scrollTop' ; return win ? ( prop in win ) ? win [ prop ] : win . document . documentElement [ method ] : win . document . body [ method ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Tricky code to work with hidden elements like tabs . Note : This code is based on jquery . actual plugin . https : // github . com / dreamerslab / jquery . actual [CODESPLIT] function getRealWidth ( element ) { var width = 0 ; var $target = element ; var css_class = 'hidden_element' ; $target = $target . clone ( ) . attr ( 'class' , css_class ) . appendTo ( 'body' ) ; width = $target . width ( true ) ; $target . remove ( ) ; return width ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this is essentially the update sugar function from daleharvey / pouchdb#1388 the diffFun tells us what delta to apply to the doc . it either returns the doc or false if it doesn t need to do an update after all [CODESPLIT] function upsertInner ( db , docId , diffFun ) { if ( typeof docId !== 'string' ) { return PouchPromise . reject ( new Error ( 'doc id is required' ) ) ; } return db . get ( docId ) . catch ( function ( err ) { /* istanbul ignore next */ if ( err . status !== 404 ) { throw err ; } return { } ; } ) . then ( function ( doc ) { // the user might change the _rev, so save it for posterity var docRev = doc . _rev ; var newDoc = diffFun ( doc ) ; if ( ! newDoc ) { // if the diffFun returns falsy, we short-circuit as // an optimization return { updated : false , rev : docRev , id : docId } ; } // users aren't allowed to modify these values, // so reset them here newDoc . _id = docId ; newDoc . _rev = docRev ; return tryAndPut ( db , newDoc , diffFun ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this can throw exceptions callers responsibility [CODESPLIT] function startDownload ( src , storageFile ) { var uri = Windows . Foundation . Uri ( src ) ; var downloader = new Windows . Networking . BackgroundTransfer . BackgroundDownloader ( ) ; var download = downloader . createDownload ( uri , storageFile ) ; return download . startAsync ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ContentSync constructor . [CODESPLIT] function ( options ) { this . _handlers = { 'progress' : [ ] , 'cancel' : [ ] , 'error' : [ ] , 'complete' : [ ] } ; // require options parameter if ( typeof options === 'undefined' ) { throw new Error ( 'The options argument is required.' ) ; } // require options.src parameter if ( typeof options . src === 'undefined' && options . type !== \"local\" ) { throw new Error ( 'The options.src argument is required for merge replace types.' ) ; } // require options.id parameter if ( typeof options . id === 'undefined' ) { throw new Error ( 'The options.id argument is required.' ) ; } // define synchronization strategy // //     replace: This is the normal behavior. Existing content is replaced //              completely by the imported content, i.e. is overridden or //              deleted accordingly. //     merge:   Existing content is not modified, i.e. only new content is //              added and none is deleted or modified. //     local:   Existing content is not modified, i.e. only new content is //              added and none is deleted or modified. // if ( typeof options . type === 'undefined' ) { options . type = 'replace' ; } if ( typeof options . headers === 'undefined' ) { options . headers = null ; } if ( typeof options . copyCordovaAssets === 'undefined' ) { options . copyCordovaAssets = false ; } if ( typeof options . copyRootApp === 'undefined' ) { options . copyRootApp = false ; } if ( typeof options . timeout === 'undefined' ) { options . timeout = 15.0 ; } if ( typeof options . trustHost === 'undefined' ) { options . trustHost = false ; } if ( typeof options . manifest === 'undefined' ) { options . manifest = \"\" ; } if ( typeof options . validateSrc === 'undefined' ) { options . validateSrc = true ; } // store the options to this object instance this . options = options ; // triggered on update and completion var that = this ; var success = function ( result ) { if ( result && typeof result . progress !== 'undefined' ) { that . emit ( 'progress' , result ) ; } else if ( result && typeof result . localPath !== 'undefined' ) { that . emit ( 'complete' , result ) ; } } ; // triggered on error var fail = function ( msg ) { var e = ( typeof msg === 'string' ) ? new Error ( msg ) : msg ; that . emit ( 'error' , e ) ; } ; // wait at least one process tick to allow event subscriptions setTimeout ( function ( ) { exec ( success , fail , 'Sync' , 'sync' , [ options . src , options . id , options . type , options . headers , options . copyCordovaAssets , options . copyRootApp , options . timeout , options . trustHost , options . manifest , options . validateSrc ] ) ; } , 10 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unzip [CODESPLIT] function ( fileUrl , dirUrl , callback , progressCallback ) { var win = function ( result ) { if ( result && result . progress ) { if ( progressCallback ) { progressCallback ( result ) ; } } else if ( callback ) { callback ( 0 ) ; } } ; var fail = function ( result ) { if ( callback ) { callback ( - 1 ) ; } } ; exec ( win , fail , 'Zip' , 'unzip' , [ fileUrl , dirUrl ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Download [CODESPLIT] function ( url , headers , cb ) { var callback = ( typeof headers == \"function\" ? headers : cb ) ; exec ( callback , callback , 'Sync' , 'download' , [ url , null , headers ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create consumer or publisher RabbitMQ channel [CODESPLIT] function createAppChannel ( app , key ) { assert ( ~ [ 'consumerChannel' , 'publisherChannel' ] . indexOf ( key ) , 'Channel key must be \"consumerChannel\" or \"publisherChannel\"' ) assert ( app . connection , 'Cannot create a channel without a connection' ) assert ( ! app [ key ] , 'Channel \"' + key + '\" already exists' ) return co ( function * ( ) { const channel = app [ key ] = yield app . connection . createChannel ( ) channel . __coworkersCloseHandler = module . exports . closeHandler . bind ( null , app , key ) channel . __coworkersErrorHandler = module . exports . errorHandler . bind ( null , app , key ) channel . once ( 'close' , channel . __coworkersCloseHandler ) channel . once ( 'error' , channel . __coworkersErrorHandler ) app . emit ( 'channel:create' , channel ) // attach special event to determine if a message has been confirmed // this event is handled in context.js if ( key === 'consumerChannel' ) { if ( app . prefetchOpts ) { channel . prefetch ( app . prefetchOpts . count , app . prefetchOpts . global ) } wrap ( channel , [ 'ack' , 'nack' ] , function ( fn , args ) { const message = args [ 0 ] assert ( ! message . messageAcked , 'Messages cannot be acked/nacked more than once (will close channel)' ) const ret = fn . apply ( this , args ) message . messageAcked = true return ret } ) } return channel } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "channel error handler [CODESPLIT] function errorHandler ( app , key , err ) { // delete app key delete app [ key ] // log and adjust err message const msg = ` ${ key } ${ err . message } ` debug ( msg , err ) err . message = msg // throw the error throw err }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a RabbitMQ connection [CODESPLIT] function createAppConnection ( app , url , socketOptions ) { assert ( ! app . connection , 'Cannot create connection if it already exists' ) return co ( function * ( ) { const conn = app . connection = yield amqplib . connect ( url , socketOptions ) conn . __coworkersCloseHandler = module . exports . closeHandler . bind ( null , app ) conn . __coworkersErrorHandler = module . exports . errorHandler . bind ( null , app ) conn . once ( 'close' , conn . __coworkersCloseHandler ) conn . once ( 'error' , conn . __coworkersErrorHandler ) app . emit ( 'connection:create' , conn ) return conn } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "connection error handler [CODESPLIT] function errorHandler ( app , err ) { delete app . connection // log and adjust err message const msg = ` ${ err . message } ` debug ( msg , err ) err . message = msg // throw the error throw err }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Respond utility [CODESPLIT] function respond ( ) { const context = this const consumeOpts = context . consumeOpts const channel = context . consumerChannel let method let args const methods = [ 'ack' , 'nack' , 'ackAll' , 'nackAll' , 'reject' ] method = methods . find ( function ( method ) { if ( context [ method ] ) { args = context [ method ] return true } } ) if ( method ) { args = values ( pick ( args , [ 'allUpTo' , 'requeue' ] ) ) if ( method === 'ack' || method === 'nack' ) { args . unshift ( context . message ) } channel [ method ] . apply ( channel , args ) } else if ( ! consumeOpts . noAck ) { // if queue is expecting an acknowledgement emit err let err = new NoAckError ( 'Message completed middlewares w/out any acknowledgement' ) Context . onerror ( context , err ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new Application inherits from EventEmitter [CODESPLIT] function Application ( options ) { if ( ! ( this instanceof Application ) ) return new Application ( options ) EventEmitter . call ( this ) // options defaults const env = getEnv ( ) const COWORKERS_CLUSTER = env . COWORKERS_CLUSTER const COWORKERS_QUEUE = env . COWORKERS_QUEUE const COWORKERS_QUEUE_WORKER_NUM = env . COWORKERS_QUEUE_WORKER_NUM || 1 options = options || { } // hack: instanceof check while avoiding rabbitmq-schema dep (for now) if ( options . constructor . name === 'Schema' ) { options = { schema : options } } defaults ( options , { cluster : COWORKERS_CLUSTER , queueName : COWORKERS_QUEUE , queueWorkerNum : COWORKERS_QUEUE_WORKER_NUM } ) defaults ( options , { cluster : true } ) // set options on app this . schema = options . schema this . queueName = options . queueName this . queueWorkerNum = options . queueWorkerNum // validate options if ( options . cluster && cluster . isMaster ) { this . clusterManager = new ClusterManager ( this ) if ( exists ( options . queueName ) ) { console . warn ( 'warn: \"queueName\" is not required when clustering is enabled' ) } } else { assert ( exists ( options . queueName ) , '\"queueName\" is required for consumer processes' ) } // app properties this . context = { } this . middlewares = [ ] this . queueMiddlewares = { // <queueName>: [middlewares...] } Object . defineProperty ( this , 'queueNames' , { get ( ) { return Object . keys ( this . queueMiddlewares ) } } ) /*\n  this.connection = <amqplibConnection>\n  this.consumerChannel = <amqplibChannel>\n  this.publisherChannel = <amqplibChannel>\n  this.consumerTags = [...]\n  */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start consuming message from app s queues [CODESPLIT] function assertAndConsumeAppQueue ( app , queueName ) { return co ( function * ( ) { const queue = app . queueMiddlewares [ queueName ] const queueOpts = queue . queueOpts const consumeOpts = queue . consumeOpts const handler = app . messageHandler ( queueName ) yield app . consumerChannel . assertQueue ( queueName , queueOpts ) return yield app . consumerChannel . consume ( queueName , handler , consumeOpts ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取焦点起始坐标 [CODESPLIT] function getSelection ( el ) { var start = 0 , end = 0 , normalizedValue , range , textInputRange , len , endRange ; if ( typeof el . selectionStart == \"number\" && typeof el . selectionEnd == \"number\" ) { start = el . selectionStart ; end = el . selectionEnd ; } else { range = document . selection . createRange ( ) ; if ( range && range . parentElement ( ) == el ) { len = el . value . length ; normalizedValue = el . value . replace ( / \\r\\n / g , \"\\n\" ) ; // Create a working TextRange that lives only in the input textInputRange = el . createTextRange ( ) ; textInputRange . moveToBookmark ( range . getBookmark ( ) ) ; // Check if the start and end of the selection are at the very end // of the input, since moveStart/moveEnd doesn't return what we want // in those cases endRange = el . createTextRange ( ) ; endRange . collapse ( false ) ; if ( textInputRange . compareEndPoints ( \"StartToEnd\" , endRange ) > - 1 ) { start = end = len ; } else { start = - textInputRange . moveStart ( \"character\" , - len ) ; start += normalizedValue . slice ( 0 , start ) . split ( \"\\n\" ) . length - 1 ; if ( textInputRange . compareEndPoints ( \"EndToEnd\" , endRange ) > - 1 ) { end = len ; } else { end = - textInputRange . moveEnd ( \"character\" , - len ) ; end += normalizedValue . slice ( 0 , end ) . split ( \"\\n\" ) . length - 1 ; } } } } return { start : start , end : end } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a given string to the matching sharding function . [CODESPLIT] function parseShardFun ( str /* : string */ ) /* : ShardV1 */ { str = str . trim ( ) if ( str . length === 0 ) { throw new Error ( 'empty shard string' ) } if ( ! str . startsWith ( PREFIX ) ) { throw new Error ( ` ${ str } ` ) } const parts = str . slice ( PREFIX . length ) . split ( '/' ) const version = parts [ 0 ] if ( version !== 'v1' ) { throw new Error ( ` ${ version } ` ) } const name = parts [ 1 ] if ( ! parts [ 2 ] ) { throw new Error ( 'missing param' ) } const param = parseInt ( parts [ 2 ] , 10 ) switch ( name ) { case 'prefix' : return new Prefix ( param ) case 'suffix' : return new Suffix ( param ) case 'next-to-last' : return new NextToLast ( param ) default : throw new Error ( ` ${ name } ` ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@description Updates existing dom to match a new dom . [CODESPLIT] function setDOM ( oldNode , newNode ) { // Ensure a realish dom node is provided. assert ( oldNode && oldNode . nodeType , 'You must provide a valid node to update.' ) // Alias document element with document. if ( oldNode . nodeType === DOCUMENT_TYPE ) oldNode = oldNode . documentElement // Document Fragments don't have attributes, so no need to look at checksums, ignored, attributes, or node replacement. if ( newNode . nodeType === DOCUMENT_FRAGMENT_TYPE ) { // Simply update all children (and subchildren). setChildNodes ( oldNode , newNode ) } else { // Otherwise we diff the entire old node. setNode ( oldNode , typeof newNode === 'string' // If a string was provided we will parse it as dom. ? parseHTML ( newNode , oldNode . nodeName ) : newNode ) } // Trigger mount events on initial set. if ( ! oldNode [ NODE_MOUNTED ] ) { oldNode [ NODE_MOUNTED ] = true mount ( oldNode ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private @description Updates a specific htmlNode and does whatever it takes to convert it to another one . [CODESPLIT] function setNode ( oldNode , newNode ) { if ( oldNode . nodeType === newNode . nodeType ) { // Handle regular element node updates. if ( oldNode . nodeType === ELEMENT_TYPE ) { // Checks if nodes are equal before diffing. if ( isEqualNode ( oldNode , newNode ) ) return // Update all children (and subchildren). setChildNodes ( oldNode , newNode ) // Update the elements attributes / tagName. if ( oldNode . nodeName === newNode . nodeName ) { // If we have the same nodename then we can directly update the attributes. setAttributes ( oldNode . attributes , newNode . attributes ) } else { // Otherwise clone the new node to use as the existing node. var newPrev = newNode . cloneNode ( ) // Copy over all existing children from the original node. while ( oldNode . firstChild ) newPrev . appendChild ( oldNode . firstChild ) // Replace the original node with the new one with the right tag. oldNode . parentNode . replaceChild ( newPrev , oldNode ) } } else { // Handle other types of node updates (text/comments/etc). // If both are the same type of node we can update directly. if ( oldNode . nodeValue !== newNode . nodeValue ) { oldNode . nodeValue = newNode . nodeValue } } } else { // we have to replace the node. oldNode . parentNode . replaceChild ( newNode , dismount ( oldNode ) ) mount ( newNode ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private @description Utility that will update one list of attributes to match another . [CODESPLIT] function setAttributes ( oldAttributes , newAttributes ) { var i , a , b , ns , name // Remove old attributes. for ( i = oldAttributes . length ; i -- ; ) { a = oldAttributes [ i ] ns = a . namespaceURI name = a . localName b = newAttributes . getNamedItemNS ( ns , name ) if ( ! b ) oldAttributes . removeNamedItemNS ( ns , name ) } // Set new attributes. for ( i = newAttributes . length ; i -- ; ) { a = newAttributes [ i ] ns = a . namespaceURI name = a . localName b = oldAttributes . getNamedItemNS ( ns , name ) if ( ! b ) { // Add a new attribute. newAttributes . removeNamedItemNS ( ns , name ) oldAttributes . setNamedItemNS ( a ) } else if ( b . value !== a . value ) { // Update existing attribute. b . value = a . value } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private @description Utility that will nodes childern to match another nodes children . [CODESPLIT] function setChildNodes ( oldParent , newParent ) { var checkOld , oldKey , checkNew , newKey , foundNode , keyedNodes var oldNode = oldParent . firstChild var newNode = newParent . firstChild var extra = 0 // Extract keyed nodes from previous children and keep track of total count. while ( oldNode ) { extra ++ checkOld = oldNode oldKey = getKey ( checkOld ) oldNode = oldNode . nextSibling if ( oldKey ) { if ( ! keyedNodes ) keyedNodes = { } keyedNodes [ oldKey ] = checkOld } } // Loop over new nodes and perform updates. oldNode = oldParent . firstChild while ( newNode ) { extra -- checkNew = newNode newNode = newNode . nextSibling if ( keyedNodes && ( newKey = getKey ( checkNew ) ) && ( foundNode = keyedNodes [ newKey ] ) ) { delete keyedNodes [ newKey ] // If we have a key and it existed before we move the previous node to the new position if needed and diff it. if ( foundNode !== oldNode ) { oldParent . insertBefore ( foundNode , oldNode ) } else { oldNode = oldNode . nextSibling } setNode ( foundNode , checkNew ) } else if ( oldNode ) { checkOld = oldNode oldNode = oldNode . nextSibling if ( getKey ( checkOld ) ) { // If the old child had a key we skip over it until the end. oldParent . insertBefore ( checkNew , checkOld ) mount ( checkNew ) } else { // Otherwise we diff the two non-keyed nodes. setNode ( checkOld , checkNew ) } } else { // Finally if there was no old node we add the new node. oldParent . appendChild ( checkNew ) mount ( checkNew ) } } // Remove old keyed nodes. for ( oldKey in keyedNodes ) { extra -- oldParent . removeChild ( dismount ( keyedNodes [ oldKey ] ) ) } // If we have any remaining unkeyed nodes remove them from the end. while ( -- extra >= 0 ) { oldParent . removeChild ( dismount ( oldParent . lastChild ) ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private @description Utility to try to pull a key out of an element . Uses data - key if possible and falls back to id . [CODESPLIT] function getKey ( node ) { if ( node . nodeType !== ELEMENT_TYPE ) return var key = node . getAttribute ( setDOM . KEY ) || node . id if ( key ) return KEY_PREFIX + key }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if nodes are equal using the following by checking if they are both ignored have the same checksum or have the same contents . [CODESPLIT] function isEqualNode ( a , b ) { return ( // Check if both nodes are ignored. ( isIgnored ( a ) && isIgnored ( b ) ) || // Check if both nodes have the same checksum. ( getCheckSum ( a ) === getCheckSum ( b ) ) || // Fall back to native isEqualNode check. a . isEqualNode ( b ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively trigger an event for a node and it s children . Only emits events for keyed nodes . [CODESPLIT] function dispatch ( node , type ) { // Trigger event for this element if it has a key. if ( getKey ( node ) ) { var ev = document . createEvent ( 'Event' ) var prop = { value : node } ev . initEvent ( type , false , false ) Object . defineProperty ( ev , 'target' , prop ) Object . defineProperty ( ev , 'srcElement' , prop ) node . dispatchEvent ( ev ) } // Dispatch to all children. var child = node . firstChild while ( child ) child = dispatch ( child , type ) . nextSibling return node }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "join this signaling server network [CODESPLIT] function join ( socket , multiaddr , pub , cb ) { const log = socket . log = config . log . bind ( config . log , '[' + socket . id + ']' ) if ( getConfig ( ) . strictMultiaddr && ! util . validateMa ( multiaddr ) ) { joinsTotal . inc ( ) joinsFailureTotal . inc ( ) return cb ( 'Invalid multiaddr' ) } if ( getConfig ( ) . cryptoChallenge ) { if ( ! pub . length ) { joinsTotal . inc ( ) joinsFailureTotal . inc ( ) return cb ( 'Crypto Challenge required but no Id provided' ) } if ( ! nonces [ socket . id ] ) { nonces [ socket . id ] = { } } if ( nonces [ socket . id ] [ multiaddr ] ) { log ( 'response cryptoChallenge' , multiaddr ) nonces [ socket . id ] [ multiaddr ] . key . verify ( Buffer . from ( nonces [ socket . id ] [ multiaddr ] . nonce ) , Buffer . from ( pub , 'hex' ) , ( err , ok ) => { if ( err || ! ok ) { joinsTotal . inc ( ) joinsFailureTotal . inc ( ) } if ( err ) { return cb ( 'Crypto error' ) } // the errors NEED to be a string otherwise JSON.stringify() turns them into {} if ( ! ok ) { return cb ( 'Signature Invalid' ) } joinFinalize ( socket , multiaddr , cb ) } ) } else { joinsTotal . inc ( ) const addr = multiaddr . split ( 'ipfs/' ) . pop ( ) log ( 'do cryptoChallenge' , multiaddr , addr ) util . getIdAndValidate ( pub , addr , ( err , key ) => { if ( err ) { joinsFailureTotal . inc ( ) ; return cb ( err ) } const nonce = uuid ( ) + uuid ( ) socket . once ( 'disconnect' , ( ) => { delete nonces [ socket . id ] } ) nonces [ socket . id ] [ multiaddr ] = { nonce : nonce , key : key } cb ( null , nonce ) } ) } } else { joinsTotal . inc ( ) joinFinalize ( socket , multiaddr , cb ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve a ( local ) json - schema - [CODESPLIT] function ( reference , options ) { reference = reference . trim ( ) if ( reference . lastIndexOf ( '#' , 0 ) < 0 ) { console . warn ( 'Remote references not supported yet. Reference must start with \"#\" (but was ' + reference + ')' ) return { } } var components = reference . split ( '#' ) // var url = components[0] var hash = components [ 1 ] var hashParts = hash . split ( '/' ) // TODO : Download remote json from url if url not empty var current = options . data . root hashParts . forEach ( function ( hashPart ) { // Traverse schema from root along the path if ( hashPart . trim ( ) . length > 0 ) { if ( typeof current === 'undefined' ) { throw new Error ( \"Reference '\" + reference + \"' cannot be resolved. '\" + hashPart + \"' is undefined.\" ) } current = current [ hashPart ] } } ) return current }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a descriptive string for a datatype [CODESPLIT] function dataType ( value ) { if ( ! value ) return null if ( value [ 'anyOf' ] || value [ 'allOf' ] || value [ 'oneOf' ] ) { return '' } if ( ! value . type ) { return 'object' } if ( value . type === 'array' ) { return dataType ( value . items || { } ) + '[]' } return value . type }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Connect to a server and establish a STOMP session . [CODESPLIT] function connect ( ) { const args = normalizeConnectArgs ( arguments ) ; const options = { host : 'localhost' , port : 61613 , timeout : 3000 , connectHeaders : { } , ... args [ 0 ] } ; const connectListener = args [ 1 ] ; let client = null ; let socket = null ; let timeout = null ; let originalSocketDestroy = null ; const cleanup = function ( ) { if ( timeout ) { clearTimeout ( timeout ) ; } client . removeListener ( 'error' , onError ) ; client . removeListener ( 'connect' , onConnected ) ; } ; const onError = function ( error ) { cleanup ( ) ; error . connectArgs = options ; if ( typeof connectListener === 'function' ) { connectListener ( error ) ; } } ; const onConnected = function ( ) { if ( originalSocketDestroy ) { socket . destroy = originalSocketDestroy ; } cleanup ( ) ; client . emit ( 'socket-connect' ) ; const connectOpts = Object . assign ( { host : options . host } , options . connectHeaders ) ; client . connect ( connectOpts , connectListener ) ; } ; let transportConnect = net . connect ; if ( 'connect' in options ) { transportConnect = options . connect ; } else { if ( 'ssl' in options ) { if ( typeof options . ssl === 'boolean' ) { if ( options . ssl === true ) { transportConnect = tls . connect ; } } else { if ( options . ssl !== void 0 ) { throw new Error ( 'expected ssl property to have boolean value' ) ; } } } } socket = transportConnect ( options , onConnected ) ; if ( options . timeout > 0 ) { timeout = setTimeout ( function ( ) { client . destroy ( client . createTransportError ( 'connect timed out' ) ) ; } , options . timeout ) ; originalSocketDestroy = socket . destroy ; socket . destroy = function ( ) { clearTimeout ( timeout ) ; socket . destroy = originalSocketDestroy ; originalSocketDestroy . apply ( socket , arguments ) ; } ; } client = new Client ( socket , options ) ; client . on ( 'error' , onError ) ; return client ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * jslint node : true indent : 2 unused : true maxlen : 80 camelcase : true esversion : 9 [CODESPLIT] function parseServerUri ( uri ) { const comps = uri . match ( / ^\\s*((\\w+):\\/\\/)?(([^:]+):([^@]+)@)?([\\w-.]+)(:(\\d+))?\\s*$ / ) ; if ( ! comps ) { throw new Error ( 'could not parse server uri \\'' + uri + '\\'' ) ; } const scheme = comps [ 2 ] ; const login = comps [ 4 ] ; const passcode = comps [ 5 ] ; const hostname = comps [ 6 ] ; const port = comps [ 8 ] ; const server = { host : hostname , connectHeaders : { } } ; if ( scheme !== void 0 ) { server . ssl = scheme === 'ssl' || scheme === 'stomp+ssl' ; } if ( port !== void 0 ) { server . port = parseInt ( port , 10 ) ; } if ( login !== void 0 ) { server . connectHeaders . login = login ; } if ( passcode !== void 0 ) { server . connectHeaders . passcode = passcode ; } if ( scheme === 'unix' || hostname [ 0 ] === '/' ) { if ( port !== void 0 ) { throw new Error ( 'invalid server uri \\'' + uri + '\\'' ) ; } server . path = hostname ; server . ssl = false ; } return server ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * jslint node : true indent : 2 unused : true maxlen : 80 camelcase : true esversion : 9 [CODESPLIT] function getAddressInfo ( args ) { let info ; if ( typeof args . connect === 'function' && typeof args . connect . getAddressInfo === 'function' ) { info = args . connect . getAddressInfo ( args ) ; } const hasPath = typeof args . path === 'string' ; const hasHost = typeof args . host === 'string' ; const hasPort = ! isNaN ( args . port ) ; const hasSSL = args . ssl === true ; const hasConnectHeaders = typeof args . connectHeaders === 'object' ; const login = hasConnectHeaders && args . connectHeaders . login ; const hasHostHeader = hasConnectHeaders && typeof args . connectHeaders . host === 'string' && args . connectHeaders . host . length > 0 ; let transport ; if ( hasHost ) { transport = hasSSL ? 'ssl' : 'tcp' ; } else if ( hasPath ) { transport = 'unix' ; } let pseudoUri = 'stomp+' + transport + '://' ; if ( login ) { pseudoUri += login + '@' ; } let transportPath = '' ; if ( hasHost ) { transportPath += args . host ; } else if ( hasPath ) { transportPath += args . path ; } if ( hasHost && hasPort ) { transportPath += ':' + args . port ; } pseudoUri += transportPath ; if ( hasHostHeader ) { pseudoUri += '/' + args . connectHeaders . host ; } return Object . assign ( { connectArgs : args , transport : transport , transportPath : transportPath , path : args . path , host : args . host , port : args . port , pseudoUri : pseudoUri } , info || { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler [CODESPLIT] function ( err , images ) { var alert = $ ( '<div class=\"alert alert-dismissable fade show\">' ) ; alert . append ( '<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>' ) ; if ( err ) { alert . addClass ( 'alert-danger' ) ; alert . append ( '<p class=\"mb-0\"><strong>Error:</strong> ' + err . message + '</p>' ) ; } else { alert . addClass ( 'alert-success' ) ; alert . append ( '<p><strong>Success:</strong></p>' ) ; images . forEach ( function ( image , index ) { var text = image . width + 'x' + image . height + ', ' + image . bpp + 'bit' ; var url = URL . createObjectURL ( new Blob ( [ image . buffer ] , { type : mime } ) ) ; alert . append ( '<p class=\"mb-' + ( index === images . length - 1 ? 0 : 3 ) + '\"><a href=\"' + url + '\" target=\"_blank\"><img src=\"' + url + '\" /> ' + text + '</a></p>' ) ; } ) ; } alert . prependTo ( '#demos-parse-results' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * To re - render suite we need to change object reference because of shallow data comparing [CODESPLIT] function forceUpdateSuiteData ( suites , test ) { const id = getSuiteId ( test ) ; suites [ id ] = cloneDeep ( suites [ id ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get private data . [CODESPLIT] function pd ( event ) { const retv = privateData . get ( event ) ; console . assert ( retv != null , \"'this' is expected an Event object, but got\" , event ) ; return retv }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dom . spec . whatwg . org / #set - the - canceled - flag [CODESPLIT] function setCancelFlag ( data ) { if ( data . passiveListener != null ) { if ( typeof console !== \"undefined\" && typeof console . error === \"function\" ) { console . error ( \"Unable to preventDefault inside passive event listener invocation.\" , data . passiveListener ) ; } return } if ( ! data . event . cancelable ) { return } data . canceled = true ; if ( typeof data . event . preventDefault === \"function\" ) { data . event . preventDefault ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the property descriptor to redirect a given property . [CODESPLIT] function defineRedirectDescriptor ( key ) { return { get ( ) { return pd ( this ) . event [ key ] } , set ( value ) { pd ( this ) . event [ key ] = value ; } , configurable : true , enumerable : true , } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the property descriptor to call a given method property . [CODESPLIT] function defineCallDescriptor ( key ) { return { value ( ) { const event = pd ( this ) . event ; return event [ key ] . apply ( event , arguments ) } , configurable : true , enumerable : true , } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define new wrapper class . [CODESPLIT] function defineWrapper ( BaseEvent , proto ) { const keys = Object . keys ( proto ) ; if ( keys . length === 0 ) { return BaseEvent } /** CustomEvent */ function CustomEvent ( eventTarget , event ) { BaseEvent . call ( this , eventTarget , event ) ; } CustomEvent . prototype = Object . create ( BaseEvent . prototype , { constructor : { value : CustomEvent , configurable : true , writable : true } , } ) ; // Define accessors. for ( let i = 0 ; i < keys . length ; ++ i ) { const key = keys [ i ] ; if ( ! ( key in BaseEvent . prototype ) ) { const descriptor = Object . getOwnPropertyDescriptor ( proto , key ) ; const isFunc = typeof descriptor . value === \"function\" ; Object . defineProperty ( CustomEvent . prototype , key , isFunc ? defineCallDescriptor ( key ) : defineRedirectDescriptor ( key ) ) ; } } return CustomEvent }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the wrapper class of a given prototype . [CODESPLIT] function getWrapper ( proto ) { if ( proto == null || proto === Object . prototype ) { return Event } let wrapper = wrappers . get ( proto ) ; if ( wrapper == null ) { wrapper = defineWrapper ( getWrapper ( Object . getPrototypeOf ( proto ) ) , proto ) ; wrappers . set ( proto , wrapper ) ; } return wrapper }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap a given event to management a dispatching . [CODESPLIT] function wrapEvent ( eventTarget , event ) { const Wrapper = getWrapper ( Object . getPrototypeOf ( event ) ) ; return new Wrapper ( eventTarget , event ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get listeners . [CODESPLIT] function getListeners ( eventTarget ) { const listeners = listenersMap . get ( eventTarget ) ; if ( listeners == null ) { throw new TypeError ( \"'this' is expected an EventTarget object, but got another value.\" ) } return listeners }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the property descriptor for the event attribute of a given event . [CODESPLIT] function defineEventAttributeDescriptor ( eventName ) { return { get ( ) { const listeners = getListeners ( this ) ; let node = listeners . get ( eventName ) ; while ( node != null ) { if ( node . listenerType === ATTRIBUTE ) { return node . listener } node = node . next ; } return null } , set ( listener ) { if ( typeof listener !== \"function\" && ! isObject ( listener ) ) { listener = null ; // eslint-disable-line no-param-reassign } const listeners = getListeners ( this ) ; // Traverse to the tail while removing old value. let prev = null ; let node = listeners . get ( eventName ) ; while ( node != null ) { if ( node . listenerType === ATTRIBUTE ) { // Remove old value. if ( prev !== null ) { prev . next = node . next ; } else if ( node . next !== null ) { listeners . set ( eventName , node . next ) ; } else { listeners . delete ( eventName ) ; } } else { prev = node ; } node = node . next ; } // Add new value. if ( listener !== null ) { const newNode = { listener , listenerType : ATTRIBUTE , passive : false , once : false , next : null , } ; if ( prev === null ) { listeners . set ( eventName , newNode ) ; } else { prev . next = newNode ; } } } , configurable : true , enumerable : true , } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define a custom EventTarget with event attributes . [CODESPLIT] function defineCustomEventTarget ( eventNames ) { /** CustomEventTarget */ function CustomEventTarget ( ) { EventTarget . call ( this ) ; } CustomEventTarget . prototype = Object . create ( EventTarget . prototype , { constructor : { value : CustomEventTarget , configurable : true , writable : true , } , } ) ; for ( let i = 0 ; i < eventNames . length ; ++ i ) { defineEventAttribute ( CustomEventTarget . prototype , eventNames [ i ] ) ; } return CustomEventTarget }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "EventTarget . [CODESPLIT] function EventTarget ( ) { /*eslint-disable consistent-return */ if ( this instanceof EventTarget ) { listenersMap . set ( this , new Map ( ) ) ; return } if ( arguments . length === 1 && Array . isArray ( arguments [ 0 ] ) ) { return defineCustomEventTarget ( arguments [ 0 ] ) } if ( arguments . length > 0 ) { const types = new Array ( arguments . length ) ; for ( let i = 0 ; i < arguments . length ; ++ i ) { types [ i ] = arguments [ i ] ; } return defineCustomEventTarget ( types ) } throw new TypeError ( \"Cannot call a class as a function\" ) /*eslint-enable consistent-return */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform upload to qiniu [CODESPLIT] function ( fileName , retrying ) { let file = assets [ fileName ] || { } ; let key = path . posix . join ( uploadPath , fileName ) ; let putPolicy = new qiniu . rs . PutPolicy ( { scope : bucket + ':' + key } ) ; let uploadToken = putPolicy . uploadToken ( mac ) ; let formUploader = new qiniu . form_up . FormUploader ( qiniuConfig ) ; let putExtra = new qiniu . form_up . PutExtra ( ) ; return new Promise ( ( resolve ) => { let begin = Date . now ( ) ; formUploader . putFile ( uploadToken , key , file . existsAt , putExtra , function ( err , body ) { // handle upload error if ( err ) { // eslint-disable-next-line no-console console . log ( ` ${ fileName } ${ err . message || err . name || err . stack } ` ) ; if ( ! ~ retryFiles . indexOf ( fileName ) ) retryFiles . push ( fileName ) ; } else { uploadedFiles ++ ; } spinner . text = tip ( uploadedFiles , retryFiles . length , totalFiles , retrying ) ; body . duration = Date . now ( ) - begin ; resolve ( body ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retry all failed files one by one [CODESPLIT] function ( err ) { if ( err ) { // eslint-disable-next-line no-console console . log ( '\\n' ) ; return Promise . reject ( err ) ; } if ( retryFilesCountDown < 0 ) retryFilesCountDown = 0 ; // Get batch files let _files = retryFiles . splice ( 0 , batch <= retryFilesCountDown ? batch : retryFilesCountDown ) ; retryFilesCountDown = retryFilesCountDown - _files . length ; if ( _files . length ) { return Promise . all ( _files . map ( file => performUpload ( file , true ) ) ) . then ( ( ) => retryFailedFiles ( ) , retryFailedFiles ) ; } else { if ( retryFiles . length ) { return Promise . reject ( new Error ( 'File uploaded failed' ) ) ; } else { return Promise . resolve ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Touch support [CODESPLIT] function ( ev ) { var cts , i , nextPointers if ( ! ev . defaultPrevented ) { if ( _preventDefault ) { ev . preventDefault ( ) } nextPointers = utils . clone ( _currPointers ) // See [2] cts = ev . changedTouches for ( i = 0 ; i < cts . length ; i += 1 ) { nextPointers [ cts [ i ] . identifier ] = [ cts [ i ] . pageX , cts [ i ] . pageY ] } if ( ! _started ) { _started = true _handlers . start ( nextPointers ) } _currPointers = nextPointers } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mouse support No hover support . [CODESPLIT] function ( ev ) { var nextPointers if ( ! ev . defaultPrevented ) { if ( _preventDefault ) { ev . preventDefault ( ) } if ( ! _mouseDown ) { _mouseDown = true nextPointers = utils . clone ( _currPointers ) // See [2] nextPointers [ 'mouse' ] = [ ev . pageX , ev . pageY ] if ( ! _started ) { _started = true _handlers . start ( nextPointers ) } _currPointers = nextPointers } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor [CODESPLIT] function ( space ) { // Parameters //   space //     a Space, optional, default to null. AbstractRectangle . call ( this ) // This is the DOM container. Populated in mount(). this . _el = null // Mapping from AbstractNode#id to HTMLElement // Every HTMLElement created by the view is stored here. this . _elements = { } // Mapping from AbstractNode#id to a map from an event name to a handler fn. // Event handlers of every rendered AbstractNode are stored here. this . _handlers = { } // Mapping from an event name to a handler fn. // Handlers for the view's events like 'added'. Populated in mount(). this . _viewHandlers = { } // View is now ready to be added onto the space. // Note that this implicitly sets //   this._parent = space // Therefore, to access the space, call this.getParent() or this._parent if ( typeof space === 'object' ) { // Test if valid space if ( ! ( space instanceof Space ) ) { throw new Error ( 'Parent of a View must be a Space.' ) } this . setParent ( space ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Convert from Select2 view - model to Angular view - model . [CODESPLIT] function ( select2_data ) { var model ; if ( opts . simple_tags ) { model = [ ] ; angular . forEach ( select2_data , function ( value , index ) { model . push ( value . id ) ; } ) ; } else { model = select2_data ; } return model ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Convert from Angular view - model to Select2 view - model . [CODESPLIT] function ( angular_data ) { var model = [ ] ; if ( ! angular_data ) { return model ; } if ( opts . simple_tags ) { model = [ ] ; angular . forEach ( angular_data , function ( value , index ) { model . push ( { 'id' : value , 'text' : value } ) ; } ) ; } else { model = angular_data ; } return model ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new Teamcity reporter for the browser . [CODESPLIT] function teamcity ( runner ) { Base . call ( this , runner ) ; var stats = this . stats ; var flowId = document . title || new Date ( ) . getTime ( ) ; runner . on ( 'suite' , function ( suite ) { if ( suite . root ) return ; suite . startDate = new Date ( ) ; log ( '##teamcity[testSuiteStarted name=\\'' + escape ( suite . title ) + '\\' flowId=\\'' + flowId + '\\']' ) ; } ) ; runner . on ( 'test' , function ( test ) { log ( '##teamcity[testStarted name=\\'' + escape ( test . title ) + '\\' flowId=\\'' + flowId + '\\'  captureStandardOutput=\\'true\\']' ) ; } ) ; runner . on ( 'fail' , function ( test , err ) { log ( '##teamcity[testFailed name=\\'' + escape ( test . title ) + '\\' flowId=\\'' + flowId + '\\' message=\\'' + escape ( err . message ) + '\\' captureStandardOutput=\\'true\\' details=\\'' + escape ( err . stack ) + '\\']' ) ; } ) ; runner . on ( 'pending' , function ( test ) { log ( '##teamcity[testIgnored name=\\'' + escape ( test . title ) + '\\' flowId=\\'' + flowId + '\\' message=\\'pending\\']' ) ; } ) ; runner . on ( 'test end' , function ( test ) { log ( '##teamcity[testFinished name=\\'' + escape ( test . title ) + '\\' flowId=\\'' + flowId + '\\' duration=\\'' + test . duration + '\\']' ) ; } ) ; runner . on ( 'suite end' , function ( suite ) { if ( suite . root ) return ; log ( '##teamcity[testSuiteFinished name=\\'' + escape ( suite . title ) + '\\' duration=\\'' + ( new Date ( ) - suite . startDate ) + '\\' flowId=\\'' + flowId + '\\']' ) ; } ) ; runner . on ( 'end' , function ( ) { log ( '##teamcity[testSuiteFinished name=\\'mocha.suite\\' duration=\\'' + stats . duration + '\\' flowId=\\'' + flowId + '\\']' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new Teamcity reporter . [CODESPLIT] function Teamcity ( runner , options ) { options = options || { } ; const reporterOptions = options . reporterOptions || { } ; let flowId , useStdError , recordHookFailures ; ( reporterOptions . flowId ) ? flowId = reporterOptions . flowId : flowId = process . env [ 'MOCHA_TEAMCITY_FLOWID' ] || processPID ; ( reporterOptions . useStdError ) ? useStdError = reporterOptions . useStdError : useStdError = process . env [ 'USE_STD_ERROR' ] ; ( reporterOptions . recordHookFailures ) ? recordHookFailures = reporterOptions . recordHookFailures : recordHookFailures = process . env [ 'RECORD_HOOK_FAILURES' ] ; ( useStdError ) ? useStdError = ( useStdError . toLowerCase ( ) === 'true' ) : useStdError = false ; ( recordHookFailures ) ? recordHookFailures = ( recordHookFailures . toLowerCase ( ) === 'true' ) : recordHookFailures = false ; Base . call ( this , runner ) ; let stats = this . stats ; const topLevelSuite = reporterOptions . topLevelSuite || process . env [ 'MOCHA_TEAMCITY_TOP_LEVEL_SUITE' ] ; runner . on ( 'suite' , function ( suite ) { if ( suite . root ) { if ( topLevelSuite ) { log ( formatString ( SUITE_START , topLevelSuite , flowId ) ) ; } return ; } suite . startDate = new Date ( ) ; log ( formatString ( SUITE_START , suite . title , flowId ) ) ; } ) ; runner . on ( 'test' , function ( test ) { log ( formatString ( TEST_START , test . title , flowId ) ) ; } ) ; runner . on ( 'fail' , function ( test , err ) { if ( useStdError ) { logError ( formatString ( TEST_FAILED , test . title , err . message , err . stack , flowId ) ) ; } else { log ( formatString ( TEST_FAILED , test . title , err . message , err . stack , flowId ) ) ; } } ) ; runner . on ( 'pending' , function ( test ) { log ( formatString ( TEST_IGNORED , test . title , test . title , flowId ) ) ; } ) ; runner . on ( 'test end' , function ( test ) { log ( formatString ( TEST_END , test . title , test . duration , flowId ) ) ; } ) ; runner . on ( 'hook' , function ( test ) { if ( recordHookFailures ) { log ( formatString ( TEST_START , test . title , flowId ) ) ; } } ) ; runner . on ( 'suite end' , function ( suite ) { if ( suite . root ) return ; log ( formatString ( SUITE_END , suite . title , new Date ( ) - suite . startDate , flowId ) ) ; } ) ; runner . on ( 'end' , function ( ) { if ( topLevelSuite ) { log ( formatString ( SUITE_END , topLevelSuite , stats . duration , flowId ) ) ; } log ( formatString ( SUITE_END , 'mocha.suite' , stats . duration , flowId ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Module dependencies . [CODESPLIT] function convert ( integer ) { var str = Number ( integer ) . toString ( 16 ) ; return str . length === 1 ? '0' + str : str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an Extended JSON string constructing the JavaScript value or object described by that string . [CODESPLIT] function parse ( text , options ) { options = Object . assign ( { } , { relaxed : true } , options ) ; // relaxed implies not strict if ( typeof options . relaxed === 'boolean' ) options . strict = ! options . relaxed ; if ( typeof options . strict === 'boolean' ) options . relaxed = ! options . strict ; return JSON . parse ( text , ( key , value ) => deserializeValue ( this , key , value , options ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a BSON document to an Extended JSON string optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified . [CODESPLIT] function stringify ( value , replacer , space , options ) { if ( space != null && typeof space === 'object' ) ( options = space ) , ( space = 0 ) ; if ( replacer != null && typeof replacer === 'object' ) ( options = replacer ) , ( replacer = null ) , ( space = 0 ) ; options = Object . assign ( { } , { relaxed : true } , options ) ; const doc = Array . isArray ( value ) ? serializeArray ( value , options ) : serializeDocument ( value , options ) ; return JSON . stringify ( doc , replacer , space ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes an object to an Extended JSON string and reparse it as a JavaScript object . [CODESPLIT] function serialize ( bson , options ) { options = options || { } ; return JSON . parse ( stringify ( bson , options ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserializes an Extended JSON object into a plain JavaScript object with native / BSON types [CODESPLIT] function deserialize ( ejson , options ) { options = options || { } ; return parse ( JSON . stringify ( ejson ) , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A * Facade * is an object meant for creating convience wrappers around objects . When developing integrations you probably want to look at its subclasses such as { @link Track } or { @link Identify } rather than this general - purpose class . [CODESPLIT] function Facade ( obj , opts ) { opts = opts || { } ; if ( ! ( 'clone' in opts ) ) opts . clone = true ; if ( opts . clone ) obj = clone ( obj ) ; if ( ! ( 'traverse' in opts ) ) opts . traverse = true ; if ( ! ( 'timestamp' in obj ) ) obj . timestamp = new Date ( ) ; else obj . timestamp = newDate ( obj . timestamp ) ; if ( opts . traverse ) traverse ( obj ) ; this . opts = opts ; this . obj = obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make functions that will define virtual modules [CODESPLIT] function makeDefineVirtualModule ( loader , load , addDep , args ) { function namer ( loadName ) { var baseName = loadName . substr ( 0 , loadName . indexOf ( \"!\" ) ) ; return function ( part , plugin ) { return baseName + \"-\" + part + ( plugin ? ( \".\" + plugin ) : \"\" ) ; } ; } function addresser ( loadAddress ) { return function ( part , plugin ) { var base = loadAddress + \".\" + part ; return base + ( plugin ? ( \".\" + plugin ) : \"\" ) ; } ; } var name = namer ( load . name ) ; var address = addresser ( load . address ) ; // A function for disposing of modules during live-reload var disposeModule = function ( moduleName ) { if ( loader . has ( moduleName ) ) loader [ \"delete\" ] ( moduleName ) ; } ; if ( loader . liveReloadInstalled || loader . has ( \"live-reload\" ) ) { loader . import ( \"live-reload\" , { name : module . id } ) . then ( function ( reload ) { disposeModule = reload . disposeModule || disposeModule ; } ) ; } return function ( defn ) { if ( defn . condition ) { if ( defn . arg ) { // viewModel args . push ( defn . arg ) ; } var moduleName = typeof defn . name === \"function\" ? defn . name ( name ) : name ( defn . name ) ; var moduleAddress = typeof defn . address === \"function\" ? defn . address ( address ) : address ( defn . address ) ; // from=\"something.js\" if ( defn . from ) { addDep ( defn . from , false ) ; } else if ( defn . getLoad ) { var moduleSource = defn . source ( ) ; return defn . getLoad ( moduleName ) . then ( function ( newLoad ) { moduleName = newLoad . name || moduleName ; // For live-reload disposeModule ( moduleName ) ; loader . define ( moduleName , moduleSource , { metadata : newLoad . metadata , address : moduleAddress } ) ; addDep ( moduleName ) ; } ) ; } else if ( defn . source ) { addDep ( moduleName ) ; if ( loader . has ( moduleName ) ) loader [ \"delete\" ] ( moduleName ) ; if ( typeof defn . source !== \"string\" ) { return Promise . resolve ( defn . source ) . then ( function ( source ) { loader . define ( moduleName , source , { address : address ( defn . name ) , metadata : defn . metadata } ) ; } ) ; } return loader . define ( moduleName , defn . source , { address : address ( defn . name ) } ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "!steal - remove - start [CODESPLIT] function getFilename ( name ) { var hash = name . indexOf ( '#' ) ; var bang = name . indexOf ( '!' ) ; return name . slice ( hash < bang ? ( hash + 1 ) : 0 , bang ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "!steal - remove - end [CODESPLIT] function translate ( load ) { var filename ; //!steal-remove-start filename = getFilename ( load . name ) ; //!steal-remove-end var localLoader = this . localLoader || this , result = parse ( load . source ) , tagName = result . tagName , texts = result . texts , types = result . types , froms = result . froms , normalize = function ( str ) { return localLoader . normalize ( str , module . id ) ; } , deps = [ normalize ( \"can-component\" ) ] , ases = [ \"Component\" ] , addDep = function ( depName , isVirtual ) { deps . push ( depName ) ; if ( isVirtual !== false ) load . metadata . virtualDeps . push ( depName ) ; } , stylePromise , templatePromise ; load . metadata . virtualDeps = [ ] ; var defineVirtualModule = makeDefineVirtualModule ( localLoader , load , addDep , ases ) ; // Define the template templatePromise = defineVirtualModule ( { condition : froms . template || froms . view || result . intermediate . length , arg : \"view\" , name : \"view\" , from : froms . template || froms . view , source : templateDefine ( result , normalize , filename ) , metadata : { originalSource : load . source , importSpecifiers : getImportSpecifiers ( result ) } } ) ; // Define the ViewModel defineVirtualModule ( { condition : froms [ \"view-model\" ] || texts [ \"view-model\" ] , arg : \"ViewModel\" , name : \"view-model\" , from : froms [ \"view-model\" ] , source : texts [ \"view-model\" ] } ) ; // Define events defineVirtualModule ( { condition : froms . events || texts . events , arg : \"events\" , name : \"events\" , from : froms . events , source : texts . events } ) ; // Define helpers defineVirtualModule ( { condition : froms . helpers || texts . helpers , arg : \"helpers\" , name : \"helpers\" , from : froms . helpers , source : texts . helpers } ) ; // Define simple-helpers defineVirtualModule ( { condition : froms [ \"simple-helpers\" ] || texts [ \"simple-helpers\" ] , arg : \"simpleHelpers\" , name : \"simple-helpers\" , from : froms [ \"simple-helpers\" ] , source : texts [ \"simple-helpers\" ] } ) ; // Define the styles stylePromise = defineVirtualModule ( { condition : froms . style || texts . style , name : function ( name ) { return name ( \"style\" , types . style || \"css\" ) + \"!\" } , address : function ( address ) { return address ( \"style\" , types . style ) ; } , source : function ( ) { var styleText = texts . style ; if ( types . style === \"less\" ) { var styleText = tagName + \" {\\n\" + texts . style + \"}\\n\" ; } return styleText ; } , getLoad : function ( styleName ) { var styleLoad = { } ; var normalizePromise = localLoader . normalize ( styleName , load . name ) ; var locatePromise = normalizePromise . then ( function ( name ) { styleName = name ; styleLoad = { name : name , metadata : { } } ; return localLoader . locate ( styleLoad ) ; } ) ; return locatePromise . then ( function ( ) { return { name : styleName , metadata : styleLoad . metadata } ; } ) ; } } ) || Promise . resolve ( ) ; return Promise . all ( [ stylePromise , templatePromise ] ) . then ( function ( ) { return Promise . all ( deps ) ; } ) . then ( function ( deps ) { return \"def\" + \"ine(\" + JSON . stringify ( deps ) + \", function(\" + ases . join ( \", \" ) + \"){\\n\" + \"\\tvar __interop = function(m){if(m && m['default']) {return m['default'];}else if(m) return m;};\\n\\n\" + \"\\tvar ViewModel = __interop(typeof ViewModel !== 'undefined' ? ViewModel : undefined);\\n\" + \"\\tvar ComponentConstructor = Component.extend({\\n\" + \"\\t\\ttag: '\" + tagName + \"',\\n\" + \"\\t\\tview: __interop(typeof view !== 'undefined' ? view : undefined),\\n\" + \"\\t\\tViewModel: ViewModel,\\n\" + \"\\t\\tevents: __interop(typeof events !== 'undefined' ? events : undefined),\\n\" + \"\\t\\thelpers: __interop(typeof helpers !== 'undefined' ? helpers : undefined),\\n\" + \"\\t\\tsimpleHelpers: __interop(typeof simpleHelpers !== 'undefined' ? simpleHelpers : undefined),\\n\" + \"\\t\\tleakScope: \" + result . leakScope + \"\\n\" + \"\\t});\\n\\n\" + \"\\treturn {\\n\" + \"\\t\\tComponent: ComponentConstructor,\\n\" + \"\\t\\tViewModel: ViewModel,\\n\" + \"\\t\\tdefault: ComponentConstructor\\n\" + \"\\t};\\n\" + \"});\" ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "!steal - remove - end [CODESPLIT] function ( depName , isVirtual ) { deps . push ( depName ) ; if ( isVirtual !== false ) load . metadata . virtualDeps . push ( depName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor [CODESPLIT] function MIDIFile ( buffer , strictMode ) { var track ; var curIndex ; var i ; var j ; // If not buffer given, creating a new MIDI file if ( ! buffer ) { // Creating the content this . header = new MIDIFileHeader ( ) ; this . tracks = [ new MIDIFileTrack ( ) ] ; // if a buffer is provided, parsing him } else { buffer = ensureArrayBuffer ( buffer ) ; // Minimum MIDI file size is a headerChunk size (14bytes) // and an empty track (8+3bytes) if ( 25 > buffer . byteLength ) { throw new Error ( 'A buffer of a valid MIDI file must have, at least, a' + ' size of 25bytes.' ) ; } // Reading header this . header = new MIDIFileHeader ( buffer , strictMode ) ; this . tracks = [ ] ; curIndex = MIDIFileHeader . HEADER_LENGTH ; // Reading tracks for ( i = 0 , j = this . header . getTracksCount ( ) ; i < j ; i ++ ) { // Testing the buffer length if ( strictMode && curIndex >= buffer . byteLength - 1 ) { throw new Error ( \"Couldn't find datas corresponding to the track #\" + i + '.' ) ; } // Creating the track object track = new MIDIFileTrack ( buffer , curIndex , strictMode ) ; this . tracks . push ( track ) ; // Updating index to the track end curIndex += track . getTrackLength ( ) + 8 ; } // Testing integrity : curIndex should be at the end of the buffer if ( strictMode && curIndex !== buffer . byteLength ) { throw new Error ( 'It seems that the buffer contains too much datas.' ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "MIDIFileTrack : Read and edit a MIDI track chunk in a given ArrayBuffer [CODESPLIT] function MIDIFileTrack ( buffer , start ) { let a ; let trackLength ; // no buffer, creating him if ( ! buffer ) { a = new Uint8Array ( 12 ) ; // Adding the empty track header (MTrk) a [ 0 ] = 0x4d ; a [ 1 ] = 0x54 ; a [ 2 ] = 0x72 ; a [ 3 ] = 0x6b ; // Adding the empty track size (4) a [ 4 ] = 0x00 ; a [ 5 ] = 0x00 ; a [ 6 ] = 0x00 ; a [ 7 ] = 0x04 ; // Adding the track end event a [ 8 ] = 0x00 ; a [ 9 ] = 0xff ; a [ 10 ] = 0x2f ; a [ 11 ] = 0x00 ; // Saving the buffer this . datas = new DataView ( a . buffer , 0 , MIDIFileTrack . HDR_LENGTH + 4 ) ; // parsing the given buffer } else { if ( ! ( buffer instanceof ArrayBuffer ) ) { throw new Error ( 'Invalid buffer received.' ) ; } // Buffer length must size at least like an  empty track (8+3bytes) if ( 12 > buffer . byteLength - start ) { throw new Error ( 'Invalid MIDIFileTrack (0x' + start . toString ( 16 ) + ') :' + ' Buffer length must size at least 12bytes' ) ; } // Creating a temporary view to read the track header this . datas = new DataView ( buffer , start , MIDIFileTrack . HDR_LENGTH ) ; // Reading MIDI track header chunk if ( ! ( 'M' === String . fromCharCode ( this . datas . getUint8 ( 0 ) ) && 'T' === String . fromCharCode ( this . datas . getUint8 ( 1 ) ) && 'r' === String . fromCharCode ( this . datas . getUint8 ( 2 ) ) && 'k' === String . fromCharCode ( this . datas . getUint8 ( 3 ) ) ) ) { throw new Error ( 'Invalid MIDIFileTrack (0x' + start . toString ( 16 ) + ') :' + ' MTrk prefix not found' ) ; } // Reading the track length trackLength = this . getTrackLength ( ) ; if ( buffer . byteLength - start < trackLength ) { throw new Error ( 'Invalid MIDIFileTrack (0x' + start . toString ( 16 ) + ') :' + ' The track size exceed the buffer length.' ) ; } // Creating the final DataView this . datas = new DataView ( buffer , start , MIDIFileTrack . HDR_LENGTH + trackLength ) ; // Trying to find the end of track event if ( ! ( 0xff === this . datas . getUint8 ( MIDIFileTrack . HDR_LENGTH + ( trackLength - 3 ) ) && 0x2f === this . datas . getUint8 ( MIDIFileTrack . HDR_LENGTH + ( trackLength - 2 ) ) && 0x00 === this . datas . getUint8 ( MIDIFileTrack . HDR_LENGTH + ( trackLength - 1 ) ) ) ) { throw new Error ( 'Invalid MIDIFileTrack (0x' + start . toString ( 16 ) + ') :' + ' No track end event found at the expected index' + ' (' + ( MIDIFileTrack . HDR_LENGTH + ( trackLength - 1 ) ) . toString ( 16 ) + ').' ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match protocols using semver ~ matching . [CODESPLIT] function matchSemver ( myProtocol , senderProtocol , callback ) { const mps = myProtocol . split ( '/' ) const sps = senderProtocol . split ( '/' ) const myName = mps [ 1 ] const myVersion = mps [ 2 ] const senderName = sps [ 1 ] const senderVersion = sps [ 2 ] if ( myName !== senderName ) { return callback ( null , false ) } // does my protocol satisfy the sender? const valid = semver . satisfies ( myVersion , '~' + senderVersion ) callback ( null , valid ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prefixes a message with a varint TODO this is a pull - stream creep ( pull stream to add a byte? ) [CODESPLIT] function encode ( msg , callback ) { pull ( values ( Buffer . isBuffer ( msg ) ? [ msg ] : [ Buffer . from ( msg ) ] ) , pullLP . encode ( ) , collect ( ( err , encoded ) => { if ( err ) { return callback ( err ) } callback ( null , encoded [ 0 ] ) } ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match protocols exactly . [CODESPLIT] function matchExact ( myProtocol , senderProtocol , callback ) { const result = myProtocol === senderProtocol callback ( null , result ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Diff two arrays . [CODESPLIT] function diffArrays ( arr1 , arr2 ) { if ( ! Array . isArray ( arr1 ) || ! Array . isArray ( arr2 ) ) { return true ; } if ( arr1 . length !== arr2 . length ) { return true ; } for ( var i = 0 , len = arr1 . length ; i < len ; i ++ ) { if ( arr1 [ i ] !== arr2 [ i ] ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turn the rules for a sourceType into a human - readable string [CODESPLIT] function getSourceRuleString ( sourceRule ) { function getRuleString ( rule ) { if ( rule . length === 1 ) { return '\"' + rule + '\"' ; } return '(\"' + rule . join ( '\" AND \"' ) + '\")' ; } return sourceRule . map ( getRuleString ) . join ( ' OR ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the arguments for the timeline based on parameter rules [CODESPLIT] function getTimelineArgs ( scope ) { var timelineArgs = { sourceType : scope . sourceType } ; // if this is a valid sourceType... if ( rules . hasOwnProperty ( scope . sourceType ) ) { var sourceRules = rules [ scope . sourceType ] ; var valid = false ; // Loop over the required args for the source for ( var i = 0 , len = sourceRules . length ; i < len ; i ++ ) { var rule = sourceRules [ i ] ; var params = { } ; for ( var j = 0 , ruleLen = rule . length ; j < ruleLen ; j ++ ) { if ( angular . isDefined ( scope [ rule [ j ] ] ) ) { // if the rule is present, add it to the params collection params [ rule [ j ] ] = scope [ rule [ j ] ] ; } } if ( Object . keys ( params ) . length === ruleLen ) { angular . merge ( timelineArgs , params ) ; valid = true ; break ; } } if ( ! valid ) { throw new TimelineArgumentException ( scope . sourceType , 'args: ' + getSourceRuleString ( sourceRules ) ) ; } } else { throw new TimelineArgumentException ( scope . sourceType , 'unknown type' ) ; } return timelineArgs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find method in klass prototype chain [CODESPLIT] function ( method , klass ) { while ( ! ! klass ) { var key = null , pro = klass . prototype ; // find method in current klass Object . keys ( pro ) . some ( function ( name ) { if ( method === pro [ name ] ) { key = name ; return ! 0 ; } } ) ; // method finded in klass if ( key != null ) { return { name : key , klass : klass } ; } klass = klass . supor ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dump files to temporary directory [CODESPLIT] function ( config ) { _logger . info ( 'begin dump files ...' ) ; var map = { } ; [ 'fileInclude' , 'fileExclude' ] . forEach ( function ( name ) { var value = config [ name ] ; if ( ! ! value ) { if ( typeof value === 'string' ) { var reg = new RegExp ( value , 'i' ) ; config [ name ] = function ( file ) { return reg . test ( file ) ; } ; } else if ( ! ! value . test ) { config [ name ] = function ( file ) { return value . test ( file ) ; } } } if ( ! _util . isFunction ( config [ name ] ) ) { var flag = name !== 'fileExclude' ; config [ name ] = function ( file ) { return flag ; } ; } } ) ; ( config . resRoot || '' ) . split ( ',' ) . forEach ( function ( dir ) { if ( ! dir ) { return ; } var ret = _fs . lsfile ( dir , function ( name , file ) { return ! config . fileExclude ( file ) && config . fileInclude ( file ) ; } ) ; ret . forEach ( function ( v ) { map [ v ] = v . replace ( config . webRoot , config . temp ) ; } ) ; } ) ; _logger . debug ( 'package file map -> %j' , map ) ; Object . keys ( map ) . forEach ( function ( src ) { var dst = map [ src ] ; _fs . copy ( src , dst , function ( a ) { _logger . info ( 'copy file %s' , a ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "zip files package [CODESPLIT] function ( config ) { _logger . info ( 'begin zip package ...' ) ; var cmd = [ 'java' , '-jar' , JSON . stringify ( config . zip ) , JSON . stringify ( config . temp ) , JSON . stringify ( config . output ) ] . join ( ' ' ) ; _logger . debug ( 'do command: %s' , cmd ) ; exec ( cmd , function ( error , stdout , stderr ) { if ( error ) { _logger . error ( 'zip package error for reason:\\n%s' , error . stack ) ; process . abort ( ) ; return ; } if ( stdout ) { _logger . info ( stdout ) ; } if ( stderr ) { _logger . error ( stderr ) ; } uploadToServer ( config ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "upload package to web cache server [CODESPLIT] function ( config ) { if ( ! _fs . exist ( config . output ) ) { return abortProcess ( config , 'no package to be uploaded' ) ; } _logger . info ( 'begin build upload form ...' ) ; var form = new FormData ( ) ; var ex = _util . merge ( { version : '0.1' , platform : 'ios&android' } , config . extension ) ; // build form Object . keys ( ex ) . forEach ( function ( name ) { form . append ( name , ex [ name ] ) ; } ) ; form . append ( 'token' , config . token ) ; form . append ( 'resID' , config . appid ) ; form . append ( 'appID' , config . nativeId ) ; form . append ( 'userData' , JSON . stringify ( { domains : config . domains } ) ) ; form . append ( 'zip' , fs . createReadStream ( config . output ) ) ; // submit form _logger . info ( 'begin upload package to web cache server ...' ) ; form . submit ( config . api , function ( err , res ) { if ( err ) { return abortProcess ( config , 'upload failed for reason:\\n%s' , err . stack ) ; } // chunk response data var arr = [ ] ; res . on ( 'data' , function ( chunk ) { arr . push ( chunk ) ; } ) ; // parse response result res . on ( 'end' , function ( ) { var ret = null , txt = arr . join ( '' ) ; try { ret = JSON . parse ( txt ) ; } catch ( ex ) { // result error return abortProcess ( config , '[%s] %s\\n%s' , res . statusCode , txt , ex . stack ) ; } if ( ! ! ret && ret . code == 0 ) { clearTemp ( config ) ; _logger . info ( 'package upload success' ) ; config . ondone ( ) ; } else { return abortProcess ( config , 'package upload failed for reason: [%s] %s' , res . statusCode , txt ) ; } } ) ; res . resume ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "clear temporary infomation [CODESPLIT] function ( config ) { _logger . info ( 'clear temporary directory and files' ) ; _fs . rmdir ( config . temp ) ; _fs . rm ( config . output ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "abort process when error [CODESPLIT] function ( config ) { var args = [ ] . slice . call ( arguments , 0 ) ; clearTemp ( args . shift ( ) ) ; _logger . error . apply ( _logger , args ) ; process . abort ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dump dependency config [CODESPLIT] function ( content ) { var ret , handler = function ( map ) { ret = map ; } , sandbox = { NEJ : { deps : handler , config : handler } } ; // detect dep config try { //eval(content); vm . createContext ( sandbox ) ; vm . runInContext ( content , sandbox ) ; } catch ( ex ) { // ignore } return ret || null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse nej patch [CODESPLIT] function ( patform , deps , func ) { var args = exports . formatARG . apply ( exports , arguments ) ; if ( ! this . patches ) { this . patches = [ ] ; } // illegal patch if ( ! args [ 0 ] ) { return ; } // cache patch config this . patches . push ( { expression : args [ 0 ] , dependency : args [ 1 ] , source : ( args [ 2 ] || '' ) . toString ( ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eval content to dump nej patch [CODESPLIT] function ( content ) { // emulate NEJ patch env var ret = { } , sandbox = { NEJ : { patch : _doPatch . bind ( ret ) } } ; // eval content for nej patch check try { //eval(util.format('(%s)();',content)); vm . createContext ( sandbox ) ; vm . runInContext ( util . format ( '(%s)();' , content ) , sandbox ) ; } catch ( ex ) { // ignore } return ret . patches ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "do nej define [CODESPLIT] function ( uri , deps , func ) { var args = exports . formatARG . apply ( exports , arguments ) ; this . isNEJ = ! 0 ; this . dependency = args [ 1 ] ; this . source = ( args [ 2 ] || '' ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for 2 . 0a< = or 2 . 0a = or 2 . 0a > = [CODESPLIT] function ( result , exp ) { switch ( exp . op ) { case '<' : case '<=' : result . lower = exp ; break ; case '>' : case '>=' : result . upper = exp ; break ; case '=' : case '==' : result . midle = exp ; break ; } delete exp . op ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for < = 2 . 0a or = 2 . 0a or > = 2 . 0a [CODESPLIT] function ( result , exp ) { switch ( exp . op ) { case '<' : case '<=' : // check over write upper var upper = result . upper ; if ( ! upper || exp . value <= upper . value ) { result . upper = exp ; if ( ! ! upper ) { exp . eq = upper . eq && exp . eq ; } } break ; case '>' : case '>=' : // check over write lower var lower = result . lower ; if ( ! lower || exp . value >= lower . value ) { result . lower = exp ; if ( ! ! lower ) { exp . eq = lower . eq && exp . eq ; } } break ; case '=' : case '==' : // check over write lower var midle = result . midle ; if ( ! midle ) { result . midle = exp ; } else if ( midle . value !== exp . value ) { result . dirty = ! 0 ; delete result . midle ; } break ; } delete exp . op ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "format patch [CODESPLIT] function ( name , config ) { var patch = config . patch ; if ( ! patch ) { return ; } // cache patch content if not x.patch.js var content = _io . getFromCache ( patch ) ; if ( ! content ) { var ret = [ _path . uri2key ( patch ) , 'function(x){return x;}' , _path . uri2key ( config . uri ) ] ; _io . cache ( config . patch , util . format ( '%s(%s);' , name , ret . join ( ',' ) ) ) ; } // cache dependency list for x.patch.js if ( ! _dep . get ( patch ) ) { _dep . set ( patch , [ config . uri ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "format plugin [CODESPLIT] function ( name , config , plugins ) { var plugin = config . plugin ; if ( ! plugin ) { return ; } // check plugin content var key = plugin + ':' + config . uri ; if ( _io . getFromCache ( key ) != null ) { return ; } // update plugin content var content = _io . getFromCache ( config . uri ) || '' ; // check content if ( typeof content !== 'string' && _util . isFunction ( content . stringify ) ) { content = content . stringify ( ) ; } // check plugin precessor var func = plugins [ plugin ] ; if ( ! ! func ) { if ( typeof func == 'string' ) { func = plugins [ func ] ; } if ( _util . isFunction ( func ) ) { var ret = func ( { file : config . uri , content : content } ) ; if ( ret != null ) { content = ret ; } } } // cache content after process _io . cache ( key , util . format ( '%s(%s,%s);' , name , _path . uri2key ( key ) , content ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check all html file [CODESPLIT] function ( event ) { if ( event . type == 'script' ) { event . value = this . _checkResInScript ( event . file , event . content , options ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "static resource [CODESPLIT] function ( uri , config ) { // c:/a/b/c.png?a=1 var arr = uri . split ( '?' ) ; var isdir = _fs . isdir ( arr [ 0 ] ) ; // check version only for file if ( config . versionStac && ! isdir ) { if ( ! ! arr [ 1 ] ) { this . emit ( 'warn' , { data : [ uri ] , message : 'static resource %s with error version' } ) ; } else { arr = _io . adjustResource ( arr [ 0 ] , config , function ( src , dst ) { this . emit ( 'debug' , { data : [ src , dst ] , message : 'copy static resource %s to %s' } ) ; } . bind ( this ) ) ; } } // update path arr [ 0 ] = this . _formatURI ( arr [ 0 ] , { fromPage : config . fromPage , pathRoot : config . output , webRoot : config . webRoot , domain : config . rsDomain } ) ; // fix last / for dir if ( isdir && ! / \\/$ / . test ( arr [ 0 ] ) ) { arr [ 0 ] += '/' ; } return arr . join ( '?' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "style resource [CODESPLIT] function ( uri , config ) { config = _util . merge ( config , { domain : config . csDomain } ) ; return this . _formatRSURI ( uri , '.css' , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "script resource [CODESPLIT] function ( uri , config ) { config = _util . merge ( config , { domain : config . jsDomain } ) ; return this . _formatRSURI ( uri , '.js' , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "source map file path [CODESPLIT] function ( uri , config ) { return this . _formatURI ( uri , { fromPage : config . fromPage , pathRoot : config . output , webRoot : config . webRoot } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "manifest file [CODESPLIT] function ( uri , config ) { _io . resource ( 'manifested' , ! 0 ) ; return this . _formatURI ( config . manOutput , { pathRoot : config . output , webRoot : config . webRoot , domain : config . manRoot } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "nej module root [CODESPLIT] function ( uri , config ) { uri = uri . replace ( config . srcRoot , config . outHtmlRoot ) ; return this . _formatURI ( uri , { pathRoot : config . output , webRoot : config . webRoot , domain : config . mdlRoot } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "html path adjust [CODESPLIT] function ( uri , config ) { return uri . replace ( config . srcRoot , config . outHtmlRoot ) . replace ( config . webRoot , '/' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "export klass or api [CODESPLIT] function global ( map ) { Object . keys ( map ) . forEach ( function ( key ) { var file = map [ key ] , arr = file . split ( '#' ) , mdl = require ( './lib/' + arr [ 0 ] + '.js' ) ; // for util/logger#Logger if ( ! ! arr [ 1 ] ) { // for util/logger#level,logger var brr = arr [ 1 ] . split ( ',' ) ; if ( brr . length > 1 ) { var ret = { } ; brr . forEach ( function ( name ) { ret [ name ] = mdl [ name ] ; } ) ; mdl = ret ; } else { mdl = mdl [ brr [ 0 ] ] ; } } exports [ key ] = mdl ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This is a very simple buffer for a predetermined set of events . It is unbounded . It forwards all arguments to any outlet emitter attached with sync () . [CODESPLIT] function ( src , events ) { // By default, we service the default stream events var self = this , streamEvents = [ 'data' , 'end' , 'error' , 'close' , 'fd' , 'drain' , 'pipe' ] ; this . events = events || streamEvents ; this . emitter = src ; this . eventBuffer = [ ] ; this . outlet = null ; this . events . forEach ( function ( name ) { self . emitter . addListener ( name , function ( ) { self . proxyEmit ( name , arguments ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We don t use >>> 0 . We let the values negate . The only use of addition in Murmur uses the result of a multiplication which will be converted to unsigned integer by our 16 - bit at a time multiplication . [CODESPLIT] function fmix32 ( hash ) { hash ^= hash >>> 16 hash = multiply ( hash , 0x85ebca6b ) hash ^= hash >>> 13 hash = multiply ( hash , 0xc2b2ae35 ) hash ^= hash >>> 16 return hash }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "With this unused function we always make sure we have an unsigned integer value but it s not absolutely necessary . We re only interested in the integer value when we perform addition or write the value to our buffer . We do not do this within Murmur s mix function . I m leaving it in place for a benchmark where I can gauge the cost of >>> 0 . [CODESPLIT] function fmix32_pure ( hash ) { hash = ( hash ^ ( hash >>> 16 ) ) >>> 0 hash = multiply ( hash , 0x85ebca6b ) hash = ( hash ^ ( hash >>> 13 ) ) >>> 0 hash = multiply ( hash , 0xc2b2ae35 ) hash = ( hash ^ ( hash >>> 16 ) ) >>> 0 return hash }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO Branch and leaf size can we just sort that out in a call to balance? [CODESPLIT] function Strata ( options ) { this . options = options this . options . comparator = options . comparator || compare this . journalist = new Journalist ( this , options ) this . housekeeper = new Turnstile this . writer = new Turnstile this . _cursors = [ ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define getters & setters . This function is the internal entry point to a lot of functionality . [CODESPLIT] function bindKeys ( scope , obj , def , parentNode , path ) { var meta , key if ( typeof obj !== 'object' || obj === null ) throw new TypeError ( 'Invalid type of value \"' + obj + '\", object expected.' ) Object . defineProperty ( obj , memoizedObjectKey , { value : { } , configurable : true } ) Object . defineProperty ( obj , metaKey , { value : { } , configurable : true } ) meta = obj [ metaKey ] for ( key in def ) { meta [ key ] = { keyPath : { key : key , root : path . root , target : obj } , activeNodes : [ ] , previousValues : [ ] , // Assign the current marker relevant to this object. This is in case of // arrays of objects. currentMarker : def [ key ] [ markerKey ] , valueIsArray : null } bindKey ( scope , obj , def , key , parentNode ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is an internal function that s used for defining the getters and setters . [CODESPLIT] function bindKey ( scope , obj , def , key , parentNode ) { var memoizedObject = obj [ memoizedObjectKey ] var meta = obj [ metaKey ] [ key ] var branch = def [ key ] var node = branch [ 0 ] var change = ! branch [ hasDefinitionKey ] && branch [ 1 ] var definition = branch [ hasDefinitionKey ] && branch [ 1 ] var mount = branch [ 2 ] var isMarkerLast = branch [ isMarkerLastKey ] // Temporary keys. var keyPath = meta . keyPath var activeNodes = meta . activeNodes var previousValues = meta . previousValues var valueIsArray = meta . valueIsArray // For initialization, call this once. if ( branch [ isBoundToParentKey ] ) parentSetter ( obj [ key ] ) else setter ( obj [ key ] ) Object . defineProperty ( obj , key , { get : getter , set : branch [ isBoundToParentKey ] ? parentSetter : setter , enumerable : true , configurable : true } ) function getter ( ) { return memoizedObject [ key ] } // Special case for binding same node as parent. function parentSetter ( x ) { var previousValue = memoizedObject [ key ] var returnValue // Optimistically set the memoized value, so it persists even if an error // occurs after this point. memoizedObject [ key ] = x // Check for no-op. if ( x === previousValue ) return x // Need to qualify this check for non-empty value. if ( definition && x !== null && x !== void 0 ) bindKeys ( scope , x , definition , parentNode , keyPath ) else if ( change ) { returnValue = change ( parentNode , x , previousValue === void 0 ? null : previousValue , keyPath ) if ( returnValue !== void 0 ) changeValue ( parentNode , returnValue , branch [ replaceAttributeKey ] ) } return x } function setter ( x ) { var value , marker , currentNode var a , b , i , j // Optimistically set the memoized value, so it persists even if an error // occurs after this point. memoizedObject [ key ] = x valueIsArray = meta . valueIsArray = Array . isArray ( x ) value = valueIsArray ? x : [ x ] for ( i = 0 , j = Math . max ( previousValues . length , value . length ) ; i < j ; i ++ ) { a = value [ i ] b = previousValues [ i ] currentNode = ! a || a !== b ? replaceNode ( a , b , i ) : null marker = meta . currentMarker if ( currentNode ) if ( isMarkerLast ) { marker . parentNode . appendChild ( currentNode ) marker . parentNode . appendChild ( marker ) } else marker . parentNode . insertBefore ( currentNode , getNextNode ( i + 1 , activeNodes ) || marker ) } // Reset length to current values, implicitly deleting indices and // allowing for garbage collection. if ( value . length !== previousValues . length ) previousValues . length = activeNodes . length = value . length // Assign array mutator methods if we get an array. if ( valueIsArray ) { // Some mutators such as `sort`, `reverse`, `fill`, `copyWithin` are // not present here. That is because they trigger the array index // setter functions by assigning on them internally. // These mutators may alter length. value . pop = pop value . push = push value . shift = shift value . unshift = unshift value . splice = splice // Handle array index assignment. for ( i = 0 , j = value . length ; i < j ; i ++ ) defineIndex ( value , i ) } return x } function defineIndex ( array , i ) { var value = array [ i ] Object . defineProperty ( array , i , { get : function ( ) { return value } , set : function ( x ) { var a , b , marker , currentNode value = x a = array [ i ] b = previousValues [ i ] if ( a !== b ) currentNode = replaceNode ( a , b , i ) marker = meta . currentMarker if ( currentNode ) if ( isMarkerLast ) { marker . parentNode . appendChild ( currentNode ) marker . parentNode . appendChild ( marker ) } else marker . parentNode . insertBefore ( currentNode , getNextNode ( i + 1 , activeNodes ) || marker ) } , enumerable : true , configurable : true } ) } function removeNode ( value , previousValue , i ) { var marker = meta . currentMarker var activeNode = activeNodes [ i ] var returnValue delete previousValues [ i ] if ( activeNode ) { delete activeNodes [ i ] if ( valueIsArray ) keyPath . index = i else delete keyPath . index if ( change ) returnValue = change ( activeNode , null , previousValue , keyPath ) else if ( definition && mount ) { keyPath . target = previousValue returnValue = mount ( activeNode , null , previousValue , keyPath ) } // If a change or mount function returns the retain element symbol, // skip removing the element from the DOM. if ( returnValue !== retainElementKey ) marker . parentNode . removeChild ( activeNode ) } } // The return value of this function is a Node to be added, otherwise null. function replaceNode ( value , previousValue , i ) { var activeNode = activeNodes [ i ] var currentNode = node var returnValue // Cast values to null if undefined. if ( value === void 0 ) value = null if ( previousValue === void 0 ) previousValue = null // If value is null, just remove the Node. if ( value === null ) { removeNode ( null , previousValue , i ) return null } if ( valueIsArray ) keyPath . index = i else delete keyPath . index previousValues [ i ] = value if ( definition ) { if ( activeNode ) removeNode ( value , previousValue , i ) currentNode = processNodes ( scope , node , definition ) keyPath . target = valueIsArray ? value [ i ] : value bindKeys ( scope , value , definition , currentNode , keyPath ) if ( mount ) { keyPath . target = value mount ( currentNode , value , null , keyPath ) } } else { currentNode = activeNode || node . cloneNode ( true ) if ( change ) { returnValue = change ( currentNode , value , previousValue , keyPath ) if ( returnValue !== void 0 ) changeValue ( currentNode , returnValue , branch [ replaceAttributeKey ] ) } else { // Add default update behavior. Note that this event does not get // removed, since it is assumed that it will be garbage collected. if ( previousValue === null && ~ updateTags . indexOf ( currentNode . tagName ) ) currentNode . addEventListener ( 'input' , updateChange ( branch [ replaceAttributeKey ] , keyPath , key ) ) changeValue ( currentNode , value , branch [ replaceAttributeKey ] ) } // Do not actually add an element to the DOM if it's only a change // between non-empty values. if ( activeNode ) return null } activeNodes [ i ] = currentNode return currentNode } // Below are optimized array mutator methods. They have to exist within // this closure. Note that the native implementations of these methods do // not trigger setter functions on array indices. function pop ( ) { var i = this . length - 1 var previousValue = previousValues [ i ] var value = Array . prototype . pop . call ( this ) removeNode ( null , previousValue , i ) previousValues . length = activeNodes . length = this . length return value } function push ( ) { var i = this . length var j = i + arguments . length var marker , currentNode // Passing arguments to apply is fine. var value = Array . prototype . push . apply ( this , arguments ) for ( j = i + arguments . length ; i < j ; i ++ ) { currentNode = replaceNode ( this [ i ] , null , i ) marker = meta . currentMarker if ( currentNode ) if ( isMarkerLast ) { marker . parentNode . appendChild ( currentNode ) marker . parentNode . appendChild ( marker ) } else marker . parentNode . insertBefore ( currentNode , marker ) defineIndex ( this , i ) } return value } function shift ( ) { removeNode ( null , previousValues [ 0 ] , 0 ) Array . prototype . shift . call ( previousValues ) Array . prototype . shift . call ( activeNodes ) return Array . prototype . shift . call ( this ) } function unshift ( ) { var i = this . length var j , k , marker , currentNode // Passing arguments to apply is fine. var value = Array . prototype . unshift . apply ( this , arguments ) Array . prototype . unshift . apply ( previousValues , arguments ) Array . prototype . unshift . apply ( activeNodes , Array ( k ) ) for ( j = 0 , k = arguments . length ; j < k ; j ++ ) { currentNode = replaceNode ( arguments [ j ] , null , j ) marker = meta . currentMarker if ( currentNode ) if ( isMarkerLast ) { marker . parentNode . appendChild ( currentNode ) marker . parentNode . appendChild ( marker ) } else marker . parentNode . insertBefore ( currentNode , getNextNode ( arguments . length , activeNodes ) || marker ) } for ( j = i + arguments . length ; i < j ; i ++ ) defineIndex ( this , i ) return value } function splice ( start , count ) { var insert = [ ] var i , j , k , value , marker , currentNode , shouldAppend for ( i = start , j = start + count ; i < j ; i ++ ) removeNode ( null , previousValues [ i ] , i ) for ( i = 2 , j = arguments . length ; i < j ; i ++ ) insert . push ( arguments [ i ] ) // Passing arguments to apply is fine. Array . prototype . splice . apply ( previousValues , arguments ) // In this case, avoid setting new values. Array . prototype . splice . apply ( activeNodes , [ start , count ] . concat ( Array ( insert . length ) ) ) value = Array . prototype . splice . apply ( this , arguments ) shouldAppend = start - count >= this . length - 1 for ( i = start + insert . length - 1 , j = start ; i >= j ; i -- ) { currentNode = replaceNode ( insert [ i - start ] , null , i ) marker = meta . currentMarker if ( currentNode ) if ( isMarkerLast && shouldAppend ) { marker . parentNode . appendChild ( currentNode ) marker . parentNode . appendChild ( marker ) } else marker . parentNode . insertBefore ( currentNode , getNextNode ( start + insert . length , activeNodes ) || marker ) } k = insert . length - count if ( k < 0 ) previousValues . length = activeNodes . length = this . length else if ( k > 0 ) for ( i = this . length - k , j = this . length ; i < j ; i ++ ) defineIndex ( this , i ) return value } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Special case for binding same node as parent . [CODESPLIT] function parentSetter ( x ) { var previousValue = memoizedObject [ key ] var returnValue // Optimistically set the memoized value, so it persists even if an error // occurs after this point. memoizedObject [ key ] = x // Check for no-op. if ( x === previousValue ) return x // Need to qualify this check for non-empty value. if ( definition && x !== null && x !== void 0 ) bindKeys ( scope , x , definition , parentNode , keyPath ) else if ( change ) { returnValue = change ( parentNode , x , previousValue === void 0 ? null : previousValue , keyPath ) if ( returnValue !== void 0 ) changeValue ( parentNode , returnValue , branch [ replaceAttributeKey ] ) } return x }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The return value of this function is a Node to be added otherwise null . [CODESPLIT] function replaceNode ( value , previousValue , i ) { var activeNode = activeNodes [ i ] var currentNode = node var returnValue // Cast values to null if undefined. if ( value === void 0 ) value = null if ( previousValue === void 0 ) previousValue = null // If value is null, just remove the Node. if ( value === null ) { removeNode ( null , previousValue , i ) return null } if ( valueIsArray ) keyPath . index = i else delete keyPath . index previousValues [ i ] = value if ( definition ) { if ( activeNode ) removeNode ( value , previousValue , i ) currentNode = processNodes ( scope , node , definition ) keyPath . target = valueIsArray ? value [ i ] : value bindKeys ( scope , value , definition , currentNode , keyPath ) if ( mount ) { keyPath . target = value mount ( currentNode , value , null , keyPath ) } } else { currentNode = activeNode || node . cloneNode ( true ) if ( change ) { returnValue = change ( currentNode , value , previousValue , keyPath ) if ( returnValue !== void 0 ) changeValue ( currentNode , returnValue , branch [ replaceAttributeKey ] ) } else { // Add default update behavior. Note that this event does not get // removed, since it is assumed that it will be garbage collected. if ( previousValue === null && ~ updateTags . indexOf ( currentNode . tagName ) ) currentNode . addEventListener ( 'input' , updateChange ( branch [ replaceAttributeKey ] , keyPath , key ) ) changeValue ( currentNode , value , branch [ replaceAttributeKey ] ) } // Do not actually add an element to the DOM if it's only a change // between non-empty values. if ( activeNode ) return null } activeNodes [ i ] = currentNode return currentNode }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Below are optimized array mutator methods . They have to exist within this closure . Note that the native implementations of these methods do not trigger setter functions on array indices . [CODESPLIT] function pop ( ) { var i = this . length - 1 var previousValue = previousValues [ i ] var value = Array . prototype . pop . call ( this ) removeNode ( null , previousValue , i ) previousValues . length = activeNodes . length = this . length return value }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Default behavior when a return value is given for a change function . [CODESPLIT] function changeValue ( node , value , attribute ) { var firstChild switch ( attribute ) { case 'textContent' : firstChild = node . firstChild if ( firstChild && ! firstChild . nextSibling && firstChild . nodeType === TEXT_NODE ) firstChild . textContent = value else node . textContent = value break case 'checked' : node . checked = Boolean ( value ) break case 'value' : // Prevent some misbehavior in certain browsers when setting a value to // itself, i.e. text caret not in the correct position. if ( node . value !== value ) node . value = value break default : break } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find next node in a potentially sparse array . [CODESPLIT] function getNextNode ( index , activeNodes ) { var i , j , nextNode for ( i = index , j = activeNodes . length ; i < j ; i ++ ) if ( activeNodes [ i ] ) { nextNode = activeNodes [ i ] break } return nextNode }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal event listener to update data on input change . [CODESPLIT] function updateChange ( targetKey , path , key ) { var target = path . target var index = path . index var replaceKey = key if ( typeof index === 'number' ) { target = target [ key ] replaceKey = index } return function handleChange ( event ) { target [ replaceKey ] = event . target [ targetKey ] } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind an object to the DOM . [CODESPLIT] function simulacra ( obj , def , matchNode ) { var document = this ? this . document : window . document var Node = this ? this . Node : window . Node var node , query // Before continuing, check if required features are present. featureCheck ( this || window , features ) if ( obj === null || typeof obj !== 'object' || isArray ( obj ) ) throw new TypeError ( 'First argument must be a singular object.' ) if ( ! isArray ( def ) ) throw new TypeError ( 'Second argument must be an array.' ) if ( typeof def [ 0 ] === 'string' ) { query = def [ 0 ] def [ 0 ] = document . querySelector ( query ) if ( ! def [ 0 ] ) throw new Error ( 'Top-level Node \"' + query + '\" could not be found in the document.' ) } else if ( ! ( def [ 0 ] instanceof Node ) ) throw new TypeError ( 'The first position of the top-level must be either a Node or a CSS ' + 'selector string.' ) if ( ! def [ isProcessedKey ] ) { // Auto-detect template tag. if ( 'content' in def [ 0 ] ) def [ 0 ] = def [ 0 ] . content def [ 0 ] = def [ 0 ] . cloneNode ( true ) cleanNode ( this , def [ 0 ] ) ensureNodes ( def [ 0 ] , def [ 1 ] ) setProperties ( def ) } node = processNodes ( this , def [ 0 ] , def [ 1 ] ) bindKeys ( this , obj , def [ 1 ] , node , { root : obj } ) if ( matchNode ) { rehydrate ( this , obj , def [ 1 ] , node , matchNode ) return matchNode } return node }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function to mutate string selectors into Nodes and validate that they are allowed . [CODESPLIT] function ensureNodes ( parentNode , def ) { var adjacentNodes = [ ] var i , j , key , query , branch , boundNode , matchedNodes var adjacentNode , adjacentKey if ( typeof def !== 'object' ) throw new TypeError ( 'The second position must be an object.' ) for ( key in def ) { branch = def [ key ] // Change function or definition object bound to parent. if ( typeof branch === 'function' || ( typeof branch === 'object' && branch !== null && ! Array . isArray ( branch ) ) ) def [ key ] = branch = [ parentNode , branch ] // Cast CSS selector string to array. else if ( typeof branch === 'string' ) def [ key ] = branch = [ branch ] else if ( ! Array . isArray ( branch ) ) throw new TypeError ( 'The binding on key \"' + key + '\" is invalid.' ) // Dereference CSS selector string to actual DOM element. if ( typeof branch [ 0 ] === 'string' ) { query = branch [ 0 ] // Match all nodes for the selector, pick the first and remove the rest. matchedNodes = parentNode . querySelectorAll ( query ) if ( ! matchedNodes . length ) throw new Error ( 'An element for selector \"' + query + '\" was not found.' ) for ( i = 1 , j = matchedNodes . length ; i < j ; i ++ ) matchedNodes [ i ] . parentNode . removeChild ( matchedNodes [ i ] ) branch [ 0 ] = matchedNodes [ 0 ] } else if ( ! branch [ 0 ] ) throw new TypeError ( 'The first position on key \"' + key + '\" must be a CSS selector string.' ) // Auto-detect template tag. if ( 'content' in branch [ 0 ] ) branch [ 0 ] = branch [ 0 ] . content boundNode = branch [ 0 ] if ( typeof branch [ 1 ] === 'object' && branch [ 1 ] !== null ) { Object . defineProperty ( branch , hasDefinitionKey , { value : true } ) if ( branch [ 2 ] && typeof branch [ 2 ] !== 'function' ) throw new TypeError ( 'The third position on key \"' + key + '\" must be a function.' ) } else if ( branch [ 1 ] && typeof branch [ 1 ] !== 'function' ) throw new TypeError ( 'The second position on key \"' + key + '\" must be an object or a function.' ) // Special case for binding to parent node. if ( parentNode === boundNode ) { Object . defineProperty ( branch , isBoundToParentKey , { value : true } ) if ( branch [ hasDefinitionKey ] ) ensureNodes ( boundNode , branch [ 1 ] ) else if ( typeof branch [ 1 ] === 'function' ) setReplaceAttribute ( branch , boundNode ) else console . warn ( // eslint-disable-line 'A change function was not defined on the key \"' + key + '\".' ) setProperties ( branch ) continue } adjacentNodes . push ( [ key , boundNode ] ) if ( ! parentNode . contains ( boundNode ) ) throw new Error ( 'The bound DOM element must be either ' + 'contained in or equal to the element in its parent binding.' ) if ( branch [ hasDefinitionKey ] ) { ensureNodes ( boundNode , branch [ 1 ] ) setProperties ( branch ) continue } setReplaceAttribute ( branch , boundNode ) setProperties ( branch ) } // Need to loop again to invalidate containment in adjacent nodes, after the // adjacent nodes are found. for ( key in def ) { boundNode = def [ key ] [ 0 ] for ( i = 0 , j = adjacentNodes . length ; i < j ; i ++ ) { adjacentKey = adjacentNodes [ i ] [ 0 ] adjacentNode = adjacentNodes [ i ] [ 1 ] if ( adjacentNode . contains ( boundNode ) && adjacentKey !== key ) throw new Error ( 'The element for key \"' + key + '\" is contained in the ' + 'element for the adjacent key \"' + adjacentKey + '\".' ) } } setProperties ( def ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function to strip empty text nodes . [CODESPLIT] function cleanNode ( scope , node ) { // A constant for showing text nodes. var showText = 0x00000004 var document = scope ? scope . document : window . document var treeWalker = document . createTreeWalker ( node , showText , processNodes . acceptNode , false ) var textNode while ( treeWalker . nextNode ( ) ) { textNode = treeWalker . currentNode textNode . textContent = textNode . textContent . trim ( ) } node . normalize ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function to remove bound nodes and replace them with markers . [CODESPLIT] function processNodes ( scope , node , def ) { var document = scope ? scope . document : window . document var key , branch , result , mirrorNode , parent , marker , indices var i , j , treeWalker , orderedKeys result = def [ templateKey ] if ( ! result ) { node = node . cloneNode ( true ) indices = [ ] matchNodes ( scope , node , def ) orderedKeys = Object . keys ( def ) . sort ( function ( a , b ) { var nodeA = def [ a ] [ 0 ] [ matchedNodeKey ] var nodeB = def [ b ] [ 0 ] [ matchedNodeKey ] if ( nodeA && nodeB ) return nodeA . index - nodeB . index return 0 } ) for ( i = 0 ; i < orderedKeys . length ; i ++ ) { key = orderedKeys [ i ] branch = def [ key ] if ( branch [ isBoundToParentKey ] ) continue result = branch [ 0 ] [ matchedNodeKey ] indices . push ( result . index ) mirrorNode = result . node parent = mirrorNode . parentNode // This value is memoized so that `appendChild` can be used instead of // `insertBefore`, which is a performance optimization. if ( mirrorNode . nextElementSibling === null ) branch [ isMarkerLastKey ] = true if ( processNodes . useCommentNode ) { marker = parent . insertBefore ( document . createComment ( ' end \"' + key + '\" ' ) , mirrorNode ) parent . insertBefore ( document . createComment ( ' begin \"' + key + '\" ' ) , marker ) } else marker = parent . insertBefore ( document . createTextNode ( '' ) , mirrorNode ) branch [ markerKey ] = marker parent . removeChild ( mirrorNode ) } Object . defineProperty ( def , templateKey , { value : { node : node . cloneNode ( true ) , indices : indices } } ) } else { node = result . node . cloneNode ( true ) indices = result . indices i = 0 j = 0 treeWalker = document . createTreeWalker ( node , showAll , acceptNode , false ) for ( key in def ) { branch = def [ key ] if ( branch [ isBoundToParentKey ] ) continue while ( treeWalker . nextNode ( ) ) { if ( i === indices [ j ] ) { branch [ markerKey ] = treeWalker . currentNode i ++ break } i ++ } j ++ } } return node }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function to find and set matching DOM nodes on cloned nodes . [CODESPLIT] function matchNodes ( scope , node , def ) { var document = scope ? scope . document : window . document var treeWalker = document . createTreeWalker ( node , showAll , acceptNode , false ) var nodes = [ ] var i , j , key , currentNode , childWalker var nodeIndex = 0 // This offset is a bit tricky, it's used to determine the index of the // marker in the processed node, which depends on whether comment nodes // are used and the count of child nodes. var offset = processNodes . useCommentNode ? 1 : 0 for ( key in def ) nodes . push ( def [ key ] [ 0 ] ) while ( treeWalker . nextNode ( ) && nodes . length ) { for ( i = 0 , j = nodes . length ; i < j ; i ++ ) { currentNode = nodes [ i ] if ( treeWalker . currentNode . isEqualNode ( currentNode ) ) { Object . defineProperty ( currentNode , matchedNodeKey , { value : { index : nodeIndex + offset , node : treeWalker . currentNode } } ) if ( processNodes . useCommentNode ) offset ++ childWalker = document . createTreeWalker ( currentNode , showAll , acceptNode , false ) while ( childWalker . nextNode ( ) ) offset -- nodes . splice ( i , 1 ) break } } nodeIndex ++ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rehydration of existing DOM nodes by recursively checking equality . [CODESPLIT] function rehydrate ( scope , obj , def , node , matchNode ) { var document = scope ? scope . document : window . document var key , branch , x , value , change , definition , mount , keyPath var meta , valueIsArray , activeNodes , index , treeWalker , currentNode for ( key in def ) { branch = def [ key ] meta = obj [ metaKey ] [ key ] change = ! branch [ hasDefinitionKey ] && branch [ 1 ] definition = branch [ hasDefinitionKey ] && branch [ 1 ] mount = branch [ 2 ] keyPath = meta . keyPath if ( branch [ isBoundToParentKey ] ) { x = obj [ key ] if ( definition && x !== null && x !== void 0 ) bindKeys ( scope , x , definition , matchNode , keyPath ) else if ( change ) change ( matchNode , x , null , keyPath ) continue } activeNodes = meta . activeNodes if ( ! activeNodes . length ) continue valueIsArray = meta . valueIsArray x = valueIsArray ? obj [ key ] : [ obj [ key ] ] index = 0 treeWalker = document . createTreeWalker ( matchNode , whatToShow , acceptNode , false ) while ( index < activeNodes . length && treeWalker . nextNode ( ) ) { currentNode = activeNodes [ index ] if ( treeWalker . currentNode . isEqualNode ( currentNode ) ) { activeNodes . splice ( index , 1 , treeWalker . currentNode ) value = x [ index ] if ( valueIsArray ) keyPath . index = index else delete keyPath . index if ( definition ) { rehydrate ( scope , value , definition , currentNode , treeWalker . currentNode ) if ( mount ) { keyPath . target = value mount ( treeWalker . currentNode , value , null , keyPath ) } } else if ( change ) change ( treeWalker . currentNode , value , null , keyPath ) index ++ } } if ( index !== activeNodes . length ) throw new Error ( 'Matching nodes could not be found on key \"' + key + '\", expected ' + activeNodes . length + ', found ' + index + '.' ) // Rehydrate marker node. currentNode = treeWalker . currentNode // Try to re-use comment node. if ( processNodes . useCommentNode && currentNode . nextSibling !== null && currentNode . nextSibling . nodeType === COMMENT_NODE ) branch [ markerKey ] = currentNode . nextSibling else branch [ markerKey ] = currentNode . parentNode . insertBefore ( document . createTextNode ( '' ) , currentNode . nextSibling ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function for rendering strings . The benchmark to beat is plain old string concatenation and for loops . Although this won t be faster it should work with more or less the same functionality as the DOM version . [CODESPLIT] function render ( obj , def , html ) { var i , nodes , handler , parser , element , elementPrototype // If given bindings with a root node, pick only the binding keys. if ( Array . isArray ( def ) ) def = def [ 1 ] // Generating the render function is processing intensive. Skip if possible. if ( renderFnKey in def ) return def [ renderFnKey ] ( obj ) // Callback API looks weird. This is actually synchronous, not asynchronous. handler = new htmlParser . DomHandler ( function ( error , result ) { if ( error ) throw error nodes = result } , handlerOptions ) parser = new htmlParser . Parser ( handler ) parser . write ( html ) parser . end ( ) for ( i = nodes . length ; i -- ; ) if ( nodes [ i ] . type === 'tag' ) { element = nodes [ i ] break } if ( ! element ) throw new Error ( 'No element found!' ) elementPrototype = Object . getPrototypeOf ( element ) Element . prototype = elementPrototype Object . defineProperties ( elementPrototype , elementExtension ) processDefinition ( def , nodes ) def [ renderFnKey ] = makeRender ( def , nodes ) return def [ renderFnKey ] ( obj ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if capabilities are available or throw an error . [CODESPLIT] function featureCheck ( globalScope , features ) { var i , j , k , l , feature , path for ( i = 0 , j = features . length ; i < j ; i ++ ) { path = features [ i ] if ( typeof path [ 0 ] === 'string' ) { feature = globalScope for ( k = 0 , l = path . length ; k < l ; k ++ ) { if ( ! ( path [ k ] in feature ) ) throw new Error ( 'Missing ' + path . slice ( 0 , k + 1 ) . join ( '.' ) + ' feature which is required.' ) feature = feature [ path [ k ] ] } } else { feature = path [ 0 ] for ( k = 1 , l = path . length ; k < l ; k ++ ) { if ( k > 1 ) feature = feature [ path [ k ] ] if ( typeof feature === 'undefined' ) throw new Error ( 'Missing ' + path [ 0 ] . name + path . slice ( 1 , k + 1 ) . join ( '.' ) + ' feature which is required.' ) } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create String from BEM entitys [CODESPLIT] function bemNames ( entitys , delimiters ) { var resultString = '' ; var names = entitys || { mods : { } , mixin : '' } ; var delims = _extends ( { ns : '' , el : '__' , mod : '--' , modVal : '-' } , delimiters ) ; var mixin = isString ( names . mixin ) ? ' ' + names . mixin : '' ; if ( ! names . block ) return '' ; resultString = delims . ns ? delims . ns + names . block : names . block ; if ( names . el ) resultString += delims . el + names . el ; if ( isPObject ( names . mods ) ) { resultString += Object . keys ( names . mods ) . reduce ( function ( prev , name ) { var val = names . mods [ name ] ; /* eslint-disable no-param-reassign */ if ( val === true ) { prev += ' ' + resultString + delims . mod + name ; } else if ( isString ( val ) || isNumber ( val ) ) { prev += ' ' + resultString + delims . mod + name + delims . modVal + names . mods [ name ] ; } /* eslint-enable no-param-reassign */ return prev ; } , '' ) ; } return resultString + mixin ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "const { blue } = require ( . / log . js ) [CODESPLIT] function write ( dest , code ) { return new Promise ( function ( resolve , reject ) { fs . writeFile ( dest , code , function ( err ) { if ( err ) return reject ( err ) // console.log(blue(dest) + ' ' + getSize(code)) resolve ( code ) } ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges an array of configs [CODESPLIT] function deepMergeConfigs ( configs , options ) { return merge . all ( configs . filter ( config => config ) , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads a file from GitHub [CODESPLIT] async function loadYaml ( context , params ) { try { const response = await context . github . repos . getContents ( params ) ; return parseConfig ( response . data . content ) ; } catch ( e ) { if ( e . code === 404 ) { return null ; } throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes parameters for the repository specified in base [CODESPLIT] function getBaseParams ( params , base ) { if ( typeof base !== 'string' ) { throw new Error ( ` ${ BASE_KEY } ` ) ; } const match = base . match ( BASE_REGEX ) ; if ( match == null ) { throw new Error ( ` ${ BASE_KEY } ${ base } ` ) ; } return { owner : match [ 1 ] || params . owner , repo : match [ 2 ] , path : match [ 3 ] || params . path , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the specified config file from the context s repository [CODESPLIT] async function getConfig ( context , fileName , defaultConfig , deepMergeOptions ) { const filePath = path . posix . join ( CONFIG_PATH , fileName ) ; const params = context . repo ( { path : filePath , } ) ; const config = await loadYaml ( context , params ) ; let baseRepo ; if ( config == null ) { baseRepo = DEFAULT_BASE ; } else if ( config != null && BASE_KEY in config ) { baseRepo = config [ BASE_KEY ] ; delete config [ BASE_KEY ] ; } let baseConfig ; if ( baseRepo ) { const baseParams = getBaseParams ( params , baseRepo ) ; baseConfig = await loadYaml ( context , baseParams ) ; } if ( config == null && baseConfig == null && ! defaultConfig ) { return null ; } return deepMergeConfigs ( [ defaultConfig , baseConfig , config ] , deepMergeOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a property on an object preserving its enumerability . This function assumes that the property is already writable . [CODESPLIT] function defineProperty ( obj , name , value ) { var enumerable = ! ! obj [ name ] && obj . propertyIsEnumerable ( name ) Object . defineProperty ( obj , name , { configurable : true , enumerable : enumerable , writable : true , value : value } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Keep initialization idempotent . [CODESPLIT] function shimmer ( options ) { if ( options && options . logger ) { if ( ! isFunction ( options . logger ) ) logger ( \"new logger isn't a function, not replacing\" ) else logger = options . logger } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "inject manifest html fragment into page code [CODESPLIT] function injectManifest ( data ) { let manifestHtml = ` ${ hexo . config . pwa . manifest . path } ` ; if ( data . indexOf ( manifestHtml ) === - 1 ) { data = data . replace ( '<head>' , manifestHtml ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "inject service worker registion fragment into page code [CODESPLIT] function injectSWRegister ( data ) { let swHtml = ` ${ compiledSWRegTpl } ` ; if ( data . indexOf ( compiledSWRegTpl ) === - 1 ) { data = data . replace ( '</body>' , swHtml ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "inject async load page js fragment [CODESPLIT] function injectAsyncLoadPageJS ( data ) { let injectHtml = ` ${ asyncLoadPageJSTpl } ` ; if ( data . indexOf ( injectHtml ) === - 1 ) { data = data . replace ( '</head>' , injectHtml ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attach a react compiler . [CODESPLIT] function rehype2react ( options ) { var settings = options || { } ; var createElement = settings . createElement ; var components = settings . components || { } ; this . Compiler = compiler ; /* Compile HAST to React. */ function compiler ( node ) { if ( node . type === 'root' ) { if ( node . children . length === 1 && node . children [ 0 ] . type === 'element' ) { node = node . children [ 0 ] ; } else { node = { type : 'element' , tagName : 'div' , properties : node . properties || { } , children : node . children } ; } } return toH ( h , tableCellStyle ( node ) , settings . prefix ) ; } /* Wrap `createElement` to pass components in. */ function h ( name , props , children ) { var component = has ( components , name ) ? components [ name ] : name ; return createElement ( component , props , children ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Compile HAST to React . [CODESPLIT] function compiler ( node ) { if ( node . type === 'root' ) { if ( node . children . length === 1 && node . children [ 0 ] . type === 'element' ) { node = node . children [ 0 ] ; } else { node = { type : 'element' , tagName : 'div' , properties : node . properties || { } , children : node . children } ; } } return toH ( h , tableCellStyle ( node ) , settings . prefix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Wrap createElement to pass components in . [CODESPLIT] function h ( name , props , children ) { var component = has ( components , name ) ? components [ name ] : name ; return createElement ( component , props , children ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Promise wrapper for exec execFile [CODESPLIT] function doExec ( method , args ) { var cp ; var cpPromise = new ChildProcessPromise ( ) ; var reject = cpPromise . _cpReject ; var resolve = cpPromise . _cpResolve ; var finalArgs = slice . call ( args , 0 ) ; finalArgs . push ( callback ) ; cp = child_process [ method ] . apply ( child_process , finalArgs ) ; function callback ( err , stdout , stderr ) { if ( err ) { var commandStr = args [ 0 ] + ( Array . isArray ( args [ 1 ] ) ? ( ' ' + args [ 1 ] . join ( ' ' ) ) : '' ) ; err . message += ' `' + commandStr + '` (exited with error code ' + err . code + ')' ; err . stdout = stdout ; err . stderr = stderr ; var cpError = new ChildProcessError ( err . message , err . code , child_process , stdout , stderr ) ; reject ( cpError ) ; } else { resolve ( { childProcess : cp , stdout : stdout , stderr : stderr } ) ; } } cpPromise . childProcess = cp ; return cpPromise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "spawn as Promised [CODESPLIT] function doSpawn ( method , command , args , options ) { var result = { } ; var cp ; var cpPromise = new ChildProcessPromise ( ) ; var reject = cpPromise . _cpReject ; var resolve = cpPromise . _cpResolve ; var successfulExitCodes = ( options && options . successfulExitCodes ) || [ 0 ] ; cp = method ( command , args , options ) ; // Don't return the whole Buffered result by default. var captureStdout = false ; var captureStderr = false ; var capture = options && options . capture ; if ( capture ) { for ( var i = 0 , len = capture . length ; i < len ; i ++ ) { var cur = capture [ i ] ; if ( cur === 'stdout' ) { captureStdout = true ; } else if ( cur === 'stderr' ) { captureStderr = true ; } } } result . childProcess = cp ; if ( captureStdout ) { result . stdout = '' ; cp . stdout . on ( 'data' , function ( data ) { result . stdout += data ; } ) ; } if ( captureStderr ) { result . stderr = '' ; cp . stderr . on ( 'data' , function ( data ) { result . stderr += data ; } ) ; } cp . on ( 'error' , reject ) ; cp . on ( 'close' , function ( code ) { if ( successfulExitCodes . indexOf ( code ) === - 1 ) { var commandStr = command + ( args . length ? ( ' ' + args . join ( ' ' ) ) : '' ) ; var message = '`' + commandStr + '` failed with code ' + code ; var err = new ChildProcessError ( message , code , cp ) ; if ( captureStderr ) { err . stderr = result . stderr . toString ( ) ; } if ( captureStdout ) { err . stdout = result . stdout . toString ( ) ; } reject ( err ) ; } else { result . code = code ; resolve ( result ) ; } } ) ; cpPromise . childProcess = cp ; return cpPromise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the slopes of the tangents ( Hermite - type interpolation ) based on the following paper : Steffen M . 1990 . A Simple Method for Monotonic Interpolation in One Dimension . Astronomy and Astrophysics Vol . 239 NO . NOV ( II ) P . 443 1990 . [CODESPLIT] function slope3 ( that , x2 , y2 ) { var h0 = that . _x1 - that . _x0 , h1 = x2 - that . _x1 , s0 = ( that . _y1 - that . _y0 ) / ( h0 || h1 < 0 && - 0 ) , s1 = ( y2 - that . _y1 ) / ( h1 || h0 < 0 && - 0 ) , p = ( s0 * h1 + s1 * h0 ) / ( h0 + h1 ) ; return ( sign ( s0 ) + sign ( s1 ) ) * Math . min ( Math . abs ( s0 ) , Math . abs ( s1 ) , 0.5 * Math . abs ( p ) ) || 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate a one - sided slope . [CODESPLIT] function slope2 ( that , t ) { var h = that . _x1 - that . _x0 ; return h ? ( 3 * ( that . _y1 - that . _y0 ) / h - t ) / 2 : t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "According to https : // en . wikipedia . org / wiki / Cubic_Hermite_spline#Representations you can express cubic Hermite interpolation in terms of cubic Bézier curves with respect to the four values p0 p0 + m0 / 3 p1 - m1 / 3 p1 . [CODESPLIT] function point ( that , t0 , t1 ) { var x0 = that . _x0 , y0 = that . _y0 , x1 = that . _x1 , y1 = that . _y1 , dx = ( x1 - x0 ) / 3 ; that . _context . bezierCurveTo ( x0 + dx , y0 + dx * t0 , x1 - dx , y1 - dx * t1 , x1 , y1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether a property name is a writeable attribute . [CODESPLIT] function shouldSetAttribute ( name , value ) { if ( isReservedProp ( name ) ) { return false ; } if ( name . length > 2 && ( name [ 0 ] === 'o' || name [ 0 ] === 'O' ) && ( name [ 1 ] === 'n' || name [ 1 ] === 'N' ) ) { return false ; } if ( value === null ) { return true ; } switch ( typeof value ) { case 'boolean' : return shouldAttributeAcceptBooleanValue ( name ) ; case 'undefined' : case 'number' : case 'string' : case 'object' : return true ; default : // function, symbol return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates markup for a property . [CODESPLIT] function createMarkupForProperty ( name , value ) { var propertyInfo = getPropertyInfo ( name ) ; if ( propertyInfo ) { if ( shouldIgnoreValue ( propertyInfo , value ) ) { return '' ; } var attributeName = propertyInfo . attributeName ; if ( propertyInfo . hasBooleanValue || propertyInfo . hasOverloadedBooleanValue && value === true ) { return attributeName + '=\"\"' ; } else if ( typeof value !== 'boolean' || shouldAttributeAcceptBooleanValue ( name ) ) { return attributeName + '=' + quoteAttributeValueForBrowser ( value ) ; } } else if ( shouldSetAttribute ( name , value ) ) { if ( value == null ) { return '' ; } return name + '=' + quoteAttributeValueForBrowser ( value ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render a ReactElement to its initial HTML . This should only be used on the server . See https : // reactjs . org / docs / react - dom - server . html#rendertostring [CODESPLIT] function renderToString ( element ) { var renderer = new ReactDOMServerRenderer$1 ( element , false ) ; var markup = renderer . read ( Infinity ) ; return markup ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Similar to renderToString except this doesn t create extra DOM attributes such as data - react - id that React uses internally . See https : // reactjs . org / docs / react - dom - server . html#rendertostaticmarkup [CODESPLIT] function renderToStaticMarkup ( element ) { var renderer = new ReactDOMServerRenderer$1 ( element , true ) ; var markup = renderer . read ( Infinity ) ; return markup ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Traps top - level events by using event bubbling . [CODESPLIT] function trapBubbledEvent ( topLevelType , handlerBaseName , element ) { if ( ! element ) { return null ; } return EventListener . listen ( element , handlerBaseName , dispatchEvent . bind ( null , topLevelType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { start end } where start is the character / codepoint index of ( anchorNode anchorOffset ) within the textContent of outerNode and end is the index of ( focusNode focusOffset ) . [CODESPLIT] function getModernOffsetsFromPoints ( outerNode , anchorNode , anchorOffset , focusNode$$1 , focusOffset ) { var length = 0 ; var start = - 1 ; var end = - 1 ; var indexWithinAnchor = 0 ; var indexWithinFocus = 0 ; var node = outerNode ; var parentNode = null ; outer : while ( true ) { var next = null ; while ( true ) { if ( node === anchorNode && ( anchorOffset === 0 || node . nodeType === TEXT_NODE ) ) { start = length + anchorOffset ; } if ( node === focusNode$$1 && ( focusOffset === 0 || node . nodeType === TEXT_NODE ) ) { end = length + focusOffset ; } if ( node . nodeType === TEXT_NODE ) { length += node . nodeValue . length ; } if ( ( next = node . firstChild ) === null ) { break ; } // Moving from `node` to its first child `next`. parentNode = node ; node = next ; } while ( true ) { if ( node === outerNode ) { // If `outerNode` has children, this is always the second time visiting // it. If it has no children, this is still the first loop, and the only // valid selection is anchorNode and focusNode both equal to this node // and both offsets 0, in which case we will have handled above. break outer ; } if ( parentNode === anchorNode && ++ indexWithinAnchor === anchorOffset ) { start = length ; } if ( parentNode === focusNode$$1 && ++ indexWithinFocus === focusOffset ) { end = length ; } if ( ( next = node . nextSibling ) !== null ) { break ; } node = parentNode ; parentNode = node . parentNode ; } // Moving from `node` to its next sibling `next`. node = next ; } if ( start === - 1 || end === - 1 ) { // This should never happen. (Would happen if the anchor/focus nodes aren't // actually inside the passed-in node.) return null ; } return { start : start , end : end } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Singly linked - list of updates . When an update is scheduled it is added to the queue of the current fiber and the work - in - progress fiber . The two queues are separate but they share a persistent structure . During reconciliation updates are removed from the work - in - progress fiber but they remain on the current fiber . That ensures that if a work - in - progress is aborted the aborted updates are recovered by cloning from current . The work - in - progress queue is always a subset of the current queue . When the tree is committed the work - in - progress becomes the current . [CODESPLIT] function createUpdateQueue ( baseState ) { var queue = { baseState : baseState , expirationTime : NoWork , first : null , last : null , callbackList : null , hasForceUpdate : false , isInitialized : false } ; { queue . isProcessing = false ; } return queue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the mount life - cycles on a previously never rendered instance . [CODESPLIT] function mountClassInstance ( workInProgress , renderExpirationTime ) { var current = workInProgress . alternate ; { checkClassInstance ( workInProgress ) ; } var instance = workInProgress . stateNode ; var state = instance . state || null ; var props = workInProgress . pendingProps ; ! props ? invariant ( false , 'There must be pending props for an initial mount. This error is likely caused by a bug in React. Please file an issue.' ) : void 0 ; var unmaskedContext = getUnmaskedContext ( workInProgress ) ; instance . props = props ; instance . state = workInProgress . memoizedState = state ; instance . refs = emptyObject ; instance . context = getMaskedContext ( workInProgress , unmaskedContext ) ; if ( enableAsyncSubtreeAPI && workInProgress . type != null && workInProgress . type . prototype != null && workInProgress . type . prototype . unstable_isAsyncReactComponent === true ) { workInProgress . internalContextTag |= AsyncUpdates ; } if ( typeof instance . componentWillMount === 'function' ) { callComponentWillMount ( workInProgress , instance ) ; // If we had additional state updates during this life-cycle, let's // process them now. var updateQueue = workInProgress . updateQueue ; if ( updateQueue !== null ) { instance . state = processUpdateQueue ( current , workInProgress , updateQueue , instance , props , renderExpirationTime ) ; } } if ( typeof instance . componentDidMount === 'function' ) { workInProgress . effectTag |= Update ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "User - originating errors ( lifecycles and refs ) should not interrupt deletion so don t let them throw . Host - originating errors should interrupt deletion so it s okay [CODESPLIT] function commitUnmount ( current ) { if ( typeof onCommitUnmount === 'function' ) { onCommitUnmount ( current ) ; } switch ( current . tag ) { case ClassComponent : { safelyDetachRef ( current ) ; var instance = current . stateNode ; if ( typeof instance . componentWillUnmount === 'function' ) { safelyCallComponentWillUnmount ( current , instance ) ; } return ; } case HostComponent : { safelyDetachRef ( current ) ; return ; } case CallComponent : { commitNestedUnmounts ( current . stateNode ) ; return ; } case HostPortal : { // TODO: this is recursive. // We are also not using this parent because // the portal will get pushed immediately. if ( enableMutatingReconciler && mutation ) { unmountHostComponents ( current ) ; } else if ( enablePersistentReconciler && persistence ) { emptyPortalContainer ( current ) ; } return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "requestWork is called by the scheduler whenever a root receives an update . It s up to the renderer to call renderRoot at some point in the future . [CODESPLIT] function requestWork ( root , expirationTime ) { if ( nestedUpdateCount > NESTED_UPDATE_LIMIT ) { invariant ( false , 'Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.' ) ; } // Add the root to the schedule. // Check if this root is already part of the schedule. if ( root . nextScheduledRoot === null ) { // This root is not already scheduled. Add it. root . remainingExpirationTime = expirationTime ; if ( lastScheduledRoot === null ) { firstScheduledRoot = lastScheduledRoot = root ; root . nextScheduledRoot = root ; } else { lastScheduledRoot . nextScheduledRoot = root ; lastScheduledRoot = root ; lastScheduledRoot . nextScheduledRoot = firstScheduledRoot ; } } else { // This root is already scheduled, but its priority may have increased. var remainingExpirationTime = root . remainingExpirationTime ; if ( remainingExpirationTime === NoWork || expirationTime < remainingExpirationTime ) { // Update the priority. root . remainingExpirationTime = expirationTime ; } } if ( isRendering ) { // Prevent reentrancy. Remaining work will be scheduled at the end of // the currently rendering batch. return ; } if ( isBatchingUpdates ) { // Flush work at the end of the batch. if ( isUnbatchingUpdates ) { // ...unless we're inside unbatchedUpdates, in which case we should // flush it now. performWorkOnRoot ( root , Sync ) ; } return ; } // TODO: Get rid of Sync and use current time? if ( expirationTime === Sync ) { performWork ( Sync , null ) ; } else if ( ! isCallbackScheduled ) { isCallbackScheduled = true ; startRequestCallbackTimer ( ) ; scheduleDeferredCallback ( performAsyncWork ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When working on async work the reconciler asks the renderer if it should yield execution . For DOM we implement this with requestIdleCallback . [CODESPLIT] function shouldYield ( ) { if ( deadline === null ) { return false ; } if ( deadline . timeRemaining ( ) > timeHeuristicForUnitOfWork ) { return false ; } deadlineDidExpire = true ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Batching should be implemented at the renderer level not inside the reconciler . [CODESPLIT] function batchedUpdates ( fn , a ) { var previousIsBatchingUpdates = isBatchingUpdates ; isBatchingUpdates = true ; try { return fn ( a ) ; } finally { isBatchingUpdates = previousIsBatchingUpdates ; if ( ! isBatchingUpdates && ! isRendering ) { performWork ( Sync , null ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Batching should be implemented at the renderer level not inside the reconciler . [CODESPLIT] function unbatchedUpdates ( fn ) { if ( isBatchingUpdates && ! isUnbatchingUpdates ) { isUnbatchingUpdates = true ; try { return fn ( ) ; } finally { isUnbatchingUpdates = false ; } } return fn ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Batching should be implemented at the renderer level not within the reconciler . [CODESPLIT] function flushSync ( fn ) { var previousIsBatchingUpdates = isBatchingUpdates ; isBatchingUpdates = true ; try { return syncUpdates ( fn ) ; } finally { isBatchingUpdates = previousIsBatchingUpdates ; ! ! isRendering ? invariant ( false , 'flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.' ) : void 0 ; performWork ( Sync , null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value for a property on a node . [CODESPLIT] function setValueForProperty ( node , name , value ) { var propertyInfo = getPropertyInfo ( name ) ; if ( propertyInfo && shouldSetAttribute ( name , value ) ) { var mutationMethod = propertyInfo . mutationMethod ; if ( mutationMethod ) { mutationMethod ( node , value ) ; } else if ( shouldIgnoreValue ( propertyInfo , value ) ) { deleteValueForProperty ( node , name ) ; return ; } else if ( propertyInfo . mustUseProperty ) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node [ propertyInfo . propertyName ] = value ; } else { var attributeName = propertyInfo . attributeName ; var namespace = propertyInfo . attributeNamespace ; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if ( namespace ) { node . setAttributeNS ( namespace , attributeName , '' + value ) ; } else if ( propertyInfo . hasBooleanValue || propertyInfo . hasOverloadedBooleanValue && value === true ) { node . setAttribute ( attributeName , '' ) ; } else { node . setAttribute ( attributeName , '' + value ) ; } } } else { setValueForAttribute ( node , name , shouldSetAttribute ( name , value ) ? value : null ) ; return ; } { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the value for a property on a node . [CODESPLIT] function deleteValueForProperty ( node , name ) { var propertyInfo = getPropertyInfo ( name ) ; if ( propertyInfo ) { var mutationMethod = propertyInfo . mutationMethod ; if ( mutationMethod ) { mutationMethod ( node , undefined ) ; } else if ( propertyInfo . mustUseProperty ) { var propName = propertyInfo . propertyName ; if ( propertyInfo . hasBooleanValue ) { node [ propName ] = false ; } else { node [ propName ] = '' ; } } else { node . removeAttribute ( propertyInfo . attributeName ) ; } } else { node . removeAttribute ( name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements an <input > host component that allows setting these optional props : checked value defaultChecked and defaultValue . [CODESPLIT] function getHostProps ( element , props ) { var node = element ; var value = props . value ; var checked = props . checked ; var hostProps = _assign ( { // Make sure we set .type before any other properties (setting .value // before .type means .value is lost in IE11 and below) type : undefined , // Make sure we set .step before .value (setting .value before .step // means .value is rounded on mount, based upon step precision) step : undefined , // Make sure we set .min & .max before .value (to ensure proper order // in corner cases such as min or max deriving from value, e.g. Issue #7170) min : undefined , max : undefined } , props , { defaultChecked : undefined , defaultValue : undefined , value : value != null ? value : node . _wrapperState . initialValue , checked : checked != null ? checked : node . _wrapperState . initialChecked } ) ; return hostProps ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply the diff . [CODESPLIT] function updateProperties$1 ( domElement , updatePayload , tag , lastRawProps , nextRawProps ) { var wasCustomComponentTag = isCustomComponent ( tag , lastRawProps ) ; var isCustomComponentTag = isCustomComponent ( tag , nextRawProps ) ; // Apply the diff. updateDOMProperties ( domElement , updatePayload , wasCustomComponentTag , isCustomComponentTag ) ; // TODO: Ensure that an update gets scheduled if any of the special props // changed. switch ( tag ) { case 'input' : // Update the wrapper around inputs *after* updating props. This has to // happen after `updateDOMProperties`. Otherwise HTML5 input validations // raise warnings and prevent the new value from being assigned. updateWrapper ( domElement , nextRawProps ) ; // We also check that we haven't missed a value update, such as a // Radio group shifting the checked value to another named radio input. updateValueIfChanged ( domElement ) ; break ; case 'textarea' : updateWrapper$1 ( domElement , nextRawProps ) ; break ; case 'select' : // <select> value update needs to occur after <option> children // reconciliation postUpdateWrapper ( domElement , nextRawProps ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Base class helpers for the updating state of a component . [CODESPLIT] function PureComponent ( props , context , updater ) { // Duplicated from Component. this . props = props ; this . context = context ; this . refs = emptyObject ; // We initialize the default updater but the real one gets injected by the // renderer. this . updater = updater || ReactNoopUpdateQueue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clone and return a new ReactElement using element as the starting point . See https : // reactjs . org / docs / react - api . html#cloneelement [CODESPLIT] function cloneElement ( element , config , children ) { var propName ; // Original props are copied var props = _assign ( { } , element . props ) ; // Reserved names are extracted var key = element . key ; var ref = element . ref ; // Self is preserved since the owner is preserved. var self = element . _self ; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element . _source ; // Owner will be preserved, unless ref is overridden var owner = element . _owner ; if ( config != null ) { if ( hasValidRef ( config ) ) { // Silently steal the ref from the parent. ref = config . ref ; owner = ReactCurrentOwner . current ; } if ( hasValidKey ( config ) ) { key = '' + config . key ; } // Remaining properties override existing props var defaultProps ; if ( element . type && element . type . defaultProps ) { defaultProps = element . type . defaultProps ; } for ( propName in config ) { if ( hasOwnProperty . call ( config , propName ) && ! RESERVED_PROPS . hasOwnProperty ( propName ) ) { if ( config [ propName ] === undefined && defaultProps !== undefined ) { // Resolve default props props [ propName ] = defaultProps [ propName ] ; } else { props [ propName ] = config [ propName ] ; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments . length - 2 ; if ( childrenLength === 1 ) { props . children = children ; } else if ( childrenLength > 1 ) { var childArray = Array ( childrenLength ) ; for ( var i = 0 ; i < childrenLength ; i ++ ) { childArray [ i ] = arguments [ i + 2 ] ; } props . children = childArray ; } return ReactElement ( element . type , key , ref , self , source , owner , props ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given an element validate that its props follow the propTypes definition provided by the type . [CODESPLIT] function validatePropTypes ( element ) { var componentClass = element . type ; if ( typeof componentClass !== 'function' ) { return ; } var name = componentClass . displayName || componentClass . name ; var propTypes = componentClass . propTypes ; if ( propTypes ) { currentlyValidatingElement = element ; checkPropTypes ( propTypes , element . props , 'prop' , name , getStackAddendum ) ; currentlyValidatingElement = null ; } if ( typeof componentClass . getDefaultProps === 'function' ) { warning ( componentClass . getDefaultProps . isReactClassApproved , 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a fragment validate that it can only be provided with fragment props [CODESPLIT] function validateFragmentProps ( fragment ) { currentlyValidatingElement = fragment ; var _iteratorNormalCompletion = true ; var _didIteratorError = false ; var _iteratorError = undefined ; try { for ( var _iterator = Object . keys ( fragment . props ) [ Symbol . iterator ] ( ) , _step ; ! ( _iteratorNormalCompletion = ( _step = _iterator . next ( ) ) . done ) ; _iteratorNormalCompletion = true ) { var key = _step . value ; if ( ! VALID_FRAGMENT_PROPS . has ( key ) ) { warning ( false , 'Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.%s' , key , getStackAddendum ( ) ) ; break ; } } } catch ( err ) { _didIteratorError = true ; _iteratorError = err ; } finally { try { if ( ! _iteratorNormalCompletion && _iterator [ 'return' ] ) { _iterator [ 'return' ] ( ) ; } } finally { if ( _didIteratorError ) { throw _iteratorError ; } } } if ( fragment . ref !== null ) { warning ( false , 'Invalid attribute `ref` supplied to `React.Fragment`.%s' , getStackAddendum ( ) ) ; } currentlyValidatingElement = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Measures the impact of running a certain script on your system . Monitors the cpu and memory usage of the whole tree of processes generated by the script provided . [CODESPLIT] async function sympact ( code , options ) { if ( typeof code !== 'string' ) { throw new TypeError ( \"The 'code' paramater must a string'\" ) ; } if ( typeof options === 'undefined' ) { options = { } ; } if ( typeof options !== 'object' ) { throw new TypeError ( \"The 'options' paramater must an object'\" ) ; } const interval = options . interval || 125 ; const cwd = options . cwd || path . dirname ( caller ( ) ) ; if ( interval < 1 ) { throw new TypeError ( \"The 'interval' paramater must be greater than 0'\" ) ; } return new Promise ( ( resolve , reject ) => { const slave = new Worker ( code , cwd ) ; const probe = new Profiler ( slave . pid ( ) , interval ) ; slave . on ( 'ready' , async ( ) => { await probe . watch ( ) ; slave . run ( ) ; } ) ; slave . on ( 'after' , async ( start , end ) => { await probe . unwatch ( ) ; slave . kill ( ) ; resolve ( probe . report ( start , end ) ) ; } ) ; slave . on ( 'error' , async err => { await probe . unwatch ( ) ; slave . kill ( ) ; reject ( err ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Abstract class defining the skeleton for the backoff strategies . Accepts an object holding the options for the backoff strategy : * randomisationFactor : The randomisation factor which must be between 0 and 1 where 1 equates to a randomization factor of 100% and 0 to no randomization . * initialDelay : The backoff initial delay in milliseconds . * maxDelay : The backoff maximal delay in milliseconds . [CODESPLIT] function BackoffStrategy ( options ) { options = options || { } ; if ( isDef ( options . initialDelay ) && options . initialDelay < 1 ) { throw new Error ( 'The initial timeout must be greater than 0.' ) ; } else if ( isDef ( options . maxDelay ) && options . maxDelay < 1 ) { throw new Error ( 'The maximal timeout must be greater than 0.' ) ; } this . initialDelay_ = options . initialDelay || 100 ; this . maxDelay_ = options . maxDelay || 10000 ; if ( this . maxDelay_ <= this . initialDelay_ ) { throw new Error ( 'The maximal backoff delay must be ' + 'greater than the initial backoff delay.' ) ; } if ( isDef ( options . randomisationFactor ) && ( options . randomisationFactor < 0 || options . randomisationFactor > 1 ) ) { throw new Error ( 'The randomisation factor must be between 0 and 1.' ) ; } this . randomisationFactor_ = options . randomisationFactor || 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exponential backoff strategy . [CODESPLIT] function ExponentialBackoffStrategy ( options ) { BackoffStrategy . call ( this , options ) ; this . backoffDelay_ = 0 ; this . nextBackoffDelay_ = this . getInitialDelay ( ) ; this . factor_ = ExponentialBackoffStrategy . DEFAULT_FACTOR ; if ( options && options . factor !== undefined ) { precond . checkArgument ( options . factor > 1 , 'Exponential factor should be greater than 1 but got %s.' , options . factor ) ; this . factor_ = options . factor ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A class to hold the state of a backoff operation . Accepts a backoff strategy to generate the backoff delays . [CODESPLIT] function Backoff ( backoffStrategy ) { events . EventEmitter . call ( this ) ; this . backoffStrategy_ = backoffStrategy ; this . maxNumberOfRetry_ = - 1 ; this . backoffNumber_ = 0 ; this . backoffDelay_ = 0 ; this . timeoutID_ = - 1 ; this . handlers = { backoff : this . onBackoff_ . bind ( this ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps a function to be called in a backoff loop . [CODESPLIT] function FunctionCall ( fn , args , callback ) { events . EventEmitter . call ( this ) ; precond . checkIsFunction ( fn , 'Expected fn to be a function.' ) ; precond . checkIsArray ( args , 'Expected args to be an array.' ) ; precond . checkIsFunction ( callback , 'Expected callback to be a function.' ) ; this . function_ = fn ; this . arguments_ = args ; this . callback_ = callback ; this . lastResult_ = [ ] ; this . numRetries_ = 0 ; this . backoff_ = null ; this . strategy_ = null ; this . failAfter_ = - 1 ; this . retryPredicate_ = FunctionCall . DEFAULT_RETRY_PREDICATE_ ; this . state_ = FunctionCall . State_ . PENDING ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Channel constructor . [CODESPLIT] function Channel ( connection , name , options ) { options || ( options = { } ) ; options . capped = true ; // In mongo v <= 2.2 index for _id is not done by default options . autoIndexId = true ; options . size || ( options . size = 1024 * 1024 * 5 ) ; options . strict = false ; this . options = options ; this . connection = connection ; this . closed = false ; this . listening = null ; this . name = name || 'mubsub' ; this . create ( ) . listen ( ) ; this . setMaxListeners ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connection constructor . [CODESPLIT] function Connection ( uri , options ) { var self = this ; options || ( options = { } ) ; options . autoReconnect != null || ( options . autoReconnect = true ) ; // It's a Db instance. if ( uri . collection ) { this . db = uri ; } else { MongoClient . connect ( uri , options , function ( err , db ) { if ( err ) return self . emit ( 'error' , err ) ; self . db = db ; self . emit ( 'connect' , db ) ; db . on ( 'error' , function ( err ) { self . emit ( 'error' , err ) ; } ) ; } ) ; } this . destroyed = false ; this . channels = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "event listener : DOM ready [CODESPLIT] function addLoadEvent ( func ) { 'use strict' ; var oldonload = window . onload ; if ( typeof window . onload !== 'function' ) { window . onload = func ; } else { window . onload = function ( ) { oldonload ( ) ; func ( ) ; } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eslint - disable - next - line no - unused - vars [CODESPLIT] function isTryBody ( path , { stackOffset = 0 } = { } ) { const node = path . getParentNode ( stackOffset - 1 ) const parent = path . getParentNode ( stackOffset ) const grandparent = path . getParentNode ( stackOffset + 1 ) const greatgrandparent = path . getParentNode ( stackOffset + 2 ) if ( parent . type === 'TryStatement' && node === parent . block ) { return true } if ( singleExpressionBlock ( parent ) && grandparent . type === 'TryStatement' && parent === grandparent . block ) { return true } if ( parent . type === 'ExpressionStatement' && singleExpressionBlock ( grandparent ) && greatgrandparent . type === 'TryStatement' && grandparent === greatgrandparent . block ) { return true } return false }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "function handleIfStatementComments ( text precedingNode enclosingNode followingNode comment options ) { [CODESPLIT] function handleIfStatementComments ( text , precedingNode , enclosingNode , followingNode , comment ) { if ( ! enclosingNode || ! ( enclosingNode . type === 'IfStatement' || enclosingNode . type === 'ConditionalExpression' ) || ! followingNode ) { return false } if ( precedingNode === enclosingNode . consequent && followingNode === enclosingNode . alternate ) { // if (precedingNode.type === 'BlockStatement') { //   addTrailingComment(precedingNode, comment) // } else { addDanglingComment ( enclosingNode , comment ) // } return true } return false }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "function parse ( text parsers opts ) { [CODESPLIT] function parse ( text ) { // Inline the require to avoid the module if we don't use it const coffeescript = require ( 'coffeescript' ) const coffeescriptOptions = { ast : true , } const ast = coffeescript . compile ( text , coffeescriptOptions ) // TODO: Any cleanup of the AST? return ast }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make an element draggable . [CODESPLIT] function Draggable ( target , options ) { if ( ! ( this instanceof Draggable ) ) { return new Draggable ( target , options ) ; } var that = this ; //ignore existing instance var instance = draggableCache . get ( target ) ; if ( instance ) { instance . state = 'reset' ; //take over options extend ( instance , options ) ; instance . update ( ) ; return instance ; } else { //get unique id for instance //needed to track event binders that . id = getUid ( ) ; that . _ns = '.draggy_' + that . id ; //save element passed that . element = target ; draggableCache . set ( target , that ) ; } //define state behaviour defineState ( that , 'state' , that . state ) ; //preset handles that . currentHandles = [ ] ; //take over options extend ( that , options ) ; //define handle if ( that . handle === undefined ) { that . handle = that . element ; } //setup droppable if ( that . droppable ) { that . initDroppable ( ) ; } //try to calc out basic limits that . update ( ) ; //go to initial state that . state = 'idle' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "little helpers [CODESPLIT] function q ( str ) { if ( Array . isArray ( str ) ) { return str . map ( q ) . reduce ( function ( prev , curr ) { return prev . concat ( curr ) ; } , [ ] ) ; } else if ( str instanceof HTMLElement ) { return [ str ] ; } else { return [ ] . slice . call ( document . querySelectorAll ( str ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This file is part of the lps . js project released open source under the BSD 3 - Clause license . For more info please see https : // github . com / mauris / lps . js [CODESPLIT] function Functor ( name , args ) { let _name = name ; let _args = args ; let _argsCount = 0 ; let _variableHash = null ; if ( typeof _args === 'undefined' ) { _args = [ ] ; } else { _argsCount = args . length ; } this . getName = function getName ( ) { return _name ; } ; this . getId = function getId ( ) { return _name + '/' + _argsCount ; } ; this . evaluate = function evaluate ( ) { return this . toString ( ) ; } ; this . getGoal = function getGoal ( ) { return this ; } ; this . getArgumentCount = function getArgumentCount ( ) { return _argsCount ; } ; this . getVariables = function getVariables ( ) { return Object . keys ( this . getVariableHash ( ) ) ; } ; this . getVariableHash = function getVariableHash ( existingHash ) { let hash = existingHash ; if ( _variableHash !== null ) { if ( hash === undefined ) { return _variableHash ; } Object . keys ( _variableHash ) . forEach ( ( v ) => { hash [ v ] = true ; } ) ; return hash ; } if ( hash === undefined ) { hash = { } ; } let storedHash = { } ; _args . forEach ( ( arg ) => { arg . getVariableHash ( hash ) ; arg . getVariableHash ( storedHash ) ; } ) ; _variableHash = storedHash ; return hash ; } ; this . isGround = function isGround ( ) { let result = true ; for ( let i = 0 ; i < _argsCount ; i += 1 ) { let arg = _args [ i ] ; if ( ! arg . isGround ( ) ) { result = false ; break ; } } return result ; } ; this . getArguments = function getArguments ( ) { // content of _args is immutable return _args . concat ( ) ; } ; this . substitute = function substitute ( theta ) { let newArgs = _args . map ( ( arg ) => { return arg . substitute ( theta ) ; } ) ; return new Functor ( _name , newArgs ) ; } ; this . toString = function toString ( ) { let result = _name ; if ( _argsCount > 0 ) { result += '(' ; for ( let i = 0 ; i < _argsCount ; i += 1 ) { result += _args [ i ] . toString ( ) ; if ( i < _argsCount - 1 ) { result += ', ' ; } } result += ')' ; } return result ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps conjunctions to a value . [CODESPLIT] function ConjunctionMap ( ) { let _conjunctions = [ ] ; /**\n   * Add a mapping of a conjunction to a value to this map.\n   * @param {Array} conjunction The conjunction to map the value\n   * @param {any} value       The value to be mapped\n   */ this . add = function add ( conjunction , value ) { if ( value === undefined ) { return ; } let map = new LiteralTreeMap ( ) ; conjunction . forEach ( ( conjunct ) => { map . add ( conjunct ) ; } ) ; _conjunctions . push ( [ map . size ( ) , map , value ] ) ; } ; /**\n   * Get the value of a conjunction.\n   * @return {any} Return the value of the conjunction mapped if it exists. Otherwise if the\n   *    conjunction is not mapped then undefined would be returned instead.\n   */ this . get = function get ( conjunction ) { let result ; for ( let i = 0 ; i < _conjunctions . length ; i += 1 ) { let pair = _conjunctions [ i ] ; let containMismatch = false ; if ( conjunction . length !== pair [ 0 ] ) { continue ; } for ( let j = 0 ; j < conjunction . length ; j += 1 ) { let conjunct = conjunction [ j ] ; if ( ! pair [ 1 ] . contains ( conjunct ) ) { containMismatch = true ; break ; } } if ( ! containMismatch ) { result = pair [ 2 ] ; break ; } } return result ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This file is part of the lps . js project released open source under the BSD 3 - Clause license . For more info please see https : // github . com / mauris / lps . js [CODESPLIT] function Profiler ( ) { let _values = { } ; this . reset = function reset ( key ) { _values [ key ] = 0 ; } ; this . increment = function increment ( key ) { if ( _values [ key ] === undefined || typeof _values [ key ] !== 'number' ) { return ; } _values [ key ] += 1 ; } ; this . increaseBy = function increaseBy ( key , value ) { if ( _values [ key ] === undefined || typeof _values [ key ] !== 'number' ) { return ; } _values [ key ] += value ; } ; this . set = function set ( key , value ) { _values [ key ] = value ; } ; this . add = function add ( key , value ) { if ( _values [ key ] === undefined || ! Array . isArray ( _values [ key ] ) ) { return ; } _values [ key ] . push ( value ) ; } ; this . get = function get ( key ) { return _values [ key ] ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort timables into set of earlyConjuncts and laterConjuncts [CODESPLIT] function sortTimables ( conjunction , forTime ) { let earlyConjuncts = [ ] ; let laterConjuncts = [ ] ; let dependentTimeVariables = { } ; // determine the time dependent variables for ( let k = 0 ; k < conjunction . length ; k += 1 ) { let conjunct = conjunction [ k ] ; if ( ! ( conjunct instanceof Timable ) ) { // skip over non-Timables if ( conjunct instanceof Functor && comparisonTerms . indexOf ( conjunct . getId ( ) ) !== - 1 ) { conjunct . getVariables ( ) . forEach ( ( v ) => { dependentTimeVariables [ v ] = true ; } ) ; } continue ; } let conjunctStartTime = conjunct . getStartTime ( ) ; let conjunctEndTime = conjunct . getEndTime ( ) ; if ( conjunctEndTime instanceof Variable ) { let endTimeName = conjunctEndTime . evaluate ( ) ; if ( conjunctStartTime instanceof Value || ( conjunctStartTime instanceof Variable && conjunctStartTime . evaluate ( ) !== endTimeName ) ) { // different start/end times dependentTimeVariables [ endTimeName ] = true ; } } } // sort between early and later for ( let k = 0 ; k < conjunction . length ; k += 1 ) { let conjunct = conjunction [ k ] ; if ( ! ( conjunct instanceof Timable ) ) { if ( laterConjuncts . length > 0 ) { laterConjuncts . push ( conjunct ) ; continue ; } earlyConjuncts . push ( conjunct ) ; continue ; } if ( ! conjunct . isInRange ( forTime ) ) { laterConjuncts . push ( conjunct ) ; continue ; } let conjunctStartTime = conjunct . getStartTime ( ) ; if ( conjunctStartTime instanceof Variable ) { if ( dependentTimeVariables [ conjunctStartTime . evaluate ( ) ] !== undefined ) { laterConjuncts . push ( conjunct ) ; continue ; } } earlyConjuncts . push ( conjunct ) ; } return [ earlyConjuncts , laterConjuncts ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This file is part of the lps . js project released open source under the BSD 3 - Clause license . For more info please see https : // github . com / mauris / lps . js [CODESPLIT] function AstNode ( type , token ) { let _type = type ; let _token = token ; let _children = [ ] ; this . getType = function getType ( ) { return _type ; } ; this . getToken = function getToken ( ) { return _token ; } ; this . getChildren = function getChildren ( ) { return _children ; } ; this . setToken = function setToken ( t ) { _token = t ; } ; this . isLeaf = function isLeaf ( ) { return _children . length === 0 ; } ; this . addChild = function addChild ( childNode ) { _children . push ( childNode ) ; } ; this . print = function print ( nArg ) { let n = nArg ; if ( ! n ) { n = 0 ; } console . log ( ' ' . repeat ( n ) + String ( _type ) + ( _token ? ( ': ' + _token . value ) : '' ) ) ; n += 1 ; _children . forEach ( ( child ) => { child . print ( n ) ; } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct the program arguments predicate [CODESPLIT] function ( programArgs ) { let _programArgs = programArgs ; if ( programArgs === undefined ) { _programArgs = [ ] ; } // map to values _programArgs = _programArgs . map ( arg => new Value ( arg ) ) ; let argsList = new List ( _programArgs ) ; let theta = { List : argsList } ; return programArgsPredicate . substitute ( theta ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a function to update a given program with the given program arguments [CODESPLIT] function createProgramArgsUpdaterFunc ( programArgs ) { return ( program ) => { let programArgsFact = buildProgramArgsPredicate ( programArgs ) ; program . getFacts ( ) . add ( programArgsFact ) ; return Promise . resolve ( program ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A list data representation [CODESPLIT] function List ( head , tail ) { let _head = head ; let _tail = tail ; let _variableHash = null ; if ( tail === undefined ) { // empty list for tail _tail = null ; } /**\n   * Get the head of the list\n   * @return {Array} Return the array representing the head of the list\n   */ this . getHead = function getHead ( ) { return _head . concat ( ) ; } ; /**\n   * Get the tail of the list\n   * @return {Array|List|Variable} Return the tail representation of the list\n   */ this . getTail = function getTail ( ) { return _tail ; } ; /**\n   * Determine if the term is ground\n   * @return {Boolean} Return true if the term is ground, false otherwise.\n   */ this . isGround = function isGround ( ) { if ( _tail !== null ) { return _tail . isGround ( ) ; } for ( let i = 0 ; i < _head . length ; i += 1 ) { if ( ! _head [ i ] . isGround ( ) ) { return false ; } } return true ; } ; /**\n   * Get all unique variables that occur in this term\n   * @return {Array} Return the array of unique variables occuring in this term\n   */ this . getVariables = function getVariables ( ) { return Object . keys ( this . getVariableHash ( ) ) ; } ; this . getVariableHash = function getVariableHash ( existingHash ) { let hash = existingHash ; if ( _variableHash !== null ) { if ( hash === undefined ) { return _variableHash ; } Object . keys ( _variableHash ) . forEach ( ( v ) => { hash [ v ] = true ; } ) ; return hash ; } // if we're writing into existing hash, don't store the hash if ( hash === undefined ) { hash = { } ; } let storedHash = { } ; const processArg = function processArg ( arg ) { arg . getVariableHash ( storedHash ) ; arg . getVariableHash ( hash ) ; } ; _head . forEach ( processArg ) ; if ( _tail instanceof List ) { processArg ( _tail ) ; } else if ( _tail instanceof Variable ) { storedHash [ _tail . evaluate ( ) ] = true ; hash [ _tail . evaluate ( ) ] = true ; } _variableHash = storedHash ; return hash ; } ; /**\n   * Perform a substitution on this term.\n   * @param  {Object} theta The substitution theta\n   * @return {List}       Return the substituted list\n   */ this . substitute = function substitute ( theta ) { let newHead = head . map ( ( element ) => { return element . substitute ( theta ) ; } ) ; let newTail = _tail ; if ( newTail instanceof List || newTail instanceof Variable ) { newTail = newTail . substitute ( theta ) ; } return new List ( newHead , newTail ) ; } ; /**\n   * Create a flat representation of the list. If the tail of the list is a variable,\n   * the empty list is assumed.\n   * @return {Array} Return the flat array representation of the list\n   */ this . flatten = function flatten ( ) { let result = [ ] ; if ( _head . length > 0 ) { result = result . concat ( _head ) ; if ( _tail instanceof List ) { result = result . concat ( _tail . flatten ( ) ) ; } } return result ; } ; /**\n   * Determine if the list is empty\n   * @return {Boolean} Return true if the list is empty, false otherwise.\n   */ this . isEmpty = function isEmpty ( ) { return _head . length === 0 && ( _tail instanceof List && _tail . isEmpty ( ) ) ; } ; /**\n   * Create a string representation of the term\n   * @return {string} Return the string representation of the term\n   */ this . toString = function toString ( ) { let result = '' ; result += '[' ; for ( let j = 0 ; j < _head . length ; j += 1 ) { result += _head [ j ] ; if ( j < _head . length - 1 ) { result += ', ' ; } } if ( _tail !== null && ( ! ( _tail instanceof List ) || ! _tail . isEmpty ( ) ) ) { result += '|' + _tail . toString ( ) ; } result += ']' ; return result ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eslint - disable - next - line no - unused - vars [CODESPLIT] function observeProcessor ( engine , program ) { let result = engine . query ( observeLiteral ) ; result . forEach ( ( r ) => { if ( r . theta . O === undefined || r . theta . ST === undefined || r . theta . ET === undefined ) { // ignoring those undefined ones return ; } let observation = r . theta . O ; let startTime = r . theta . ST ; let endTime = r . theta . ET ; if ( ! ( startTime instanceof Value ) ) { throw new Error ( stringLiterals ( [ 'declarationProcessors' , 'observe' , 'invalidStartTimeValue' ] ) ) ; } if ( ! ( endTime instanceof Value ) ) { throw new Error ( stringLiterals ( [ 'declarationProcessors' , 'observe' , 'invalidEndTimeValue' ] ) ) ; } let sTime = startTime . evaluate ( ) ; let eTime = endTime . evaluate ( ) ; if ( eTime < sTime ) { throw new Error ( stringLiterals ( [ 'declarationProcessors' , 'observe' , 'invalidTimeOrdering' ] ) ) ; } engine . scheduleObservation ( observation , sTime , eTime ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This file is part of the lps . js project released open source under the BSD 3 - Clause license . For more info please see https : // github . com / mauris / lps . js [CODESPLIT] function Manager ( ) { let _events = { } ; this . addListener = function addListener ( event , listener ) { if ( _events [ event ] === undefined ) { _events [ event ] = [ ] ; } _events [ event ] . push ( listener ) ; } ; this . clearListeners = function clearListeners ( event ) { delete _events [ event ] ; } ; this . notify = function notify ( event , sender ) { if ( _events [ event ] === undefined ) { return Promise . resolve ( ) ; } _events [ event ] . forEach ( ( listener ) => { listener ( sender ) ; } ) ; return Promise . resolve ( ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process observations for the current cycle [CODESPLIT] function processCycleObservations ( ) { let activeObservations = new LiteralTreeMap ( ) ; if ( _observations [ _currentTime ] === undefined ) { // no observations for current time return activeObservations ; } let cloneProgram = _program . clone ( ) ; cloneProgram . setExecutedActions ( activeObservations ) ; const nextTime = _currentTime + 1 ; // process observations for the current time _observations [ _currentTime ] . forEach ( ( ob ) => { let action = ob . action ; let tempTreeMap = new LiteralTreeMap ( ) ; tempTreeMap . add ( action ) ; activeObservations . add ( action ) ; let postCloneProgram = cloneProgram . clone ( ) ; let postState = postCloneProgram . getState ( ) ; postCloneProgram . setExecutedActions ( new LiteralTreeMap ( ) ) ; updateStateWithFluentActors ( this , tempTreeMap , postState ) ; postCloneProgram . setState ( postState ) ; // perform pre-check and post-check if ( ! checkConstraintSatisfaction . call ( this , cloneProgram ) || ! checkConstraintSatisfaction . call ( this , postCloneProgram ) ) { // reject the observed event // to keep model true activeObservations . remove ( action ) ; // warning _engineEventManager . notify ( 'warning' , { type : 'observation.reject' , message : stringLiterals ( 'engine.rejectObservationWarning' , action , _currentTime , nextTime ) } ) ; } // if the given observation endTime has not ended // propagate to the next cycle's if ( ob . endTime > nextTime ) { if ( _observations [ nextTime ] === undefined ) { _observations [ nextTime ] = [ ] ; } _observations [ nextTime ] . push ( ob ) ; } } ) ; return activeObservations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Select the appropriate set of actions from the given goal trees such that constraints are not violated for the current cycle . [CODESPLIT] function actionsSelector ( goalTrees ) { const recursiveActionsSelector = ( actionsSoFar , programSoFar , l ) => { if ( l >= goalTrees . length ) { let actions = new LiteralTreeMap ( ) ; actionsSoFar . forEach ( ( map ) => { map . forEach ( ( literal ) => { actions . add ( literal ) ; } ) ; } ) ; return actions ; } let goalTree = goalTrees [ l ] ; let resultSet = null ; goalTree . forEachCandidateActions ( _currentTime , ( candidateActions ) => { let cloneProgram = programSoFar . clone ( ) ; let cloneExecutedActions = cloneProgram . getExecutedActions ( ) ; candidateActions . forEach ( ( a ) => { cloneExecutedActions . add ( a ) ; } ) ; // pre-condition check if ( ! checkConstraintSatisfaction . call ( this , cloneProgram ) ) { return false ; } // post condition checks let clonePostProgram = programSoFar . clone ( ) ; clonePostProgram . setExecutedActions ( new LiteralTreeMap ( ) ) ; let postState = clonePostProgram . getState ( ) ; updateStateWithFluentActors ( this , candidateActions , postState ) ; clonePostProgram . setState ( postState ) ; if ( ! checkConstraintSatisfaction . call ( this , clonePostProgram ) ) { return false ; } resultSet = recursiveActionsSelector ( actionsSoFar . concat ( [ candidateActions ] ) , cloneProgram , l + 1 ) ; return true ; } ) ; if ( resultSet !== null ) { return resultSet ; } return recursiveActionsSelector ( actionsSoFar , programSoFar , l + 1 ) ; } ; return recursiveActionsSelector ( [ ] , _program , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the state transition for a single cycle . [CODESPLIT] function performCycle ( ) { _currentTime += 1 ; let selectedAndExecutedActions = new LiteralTreeMap ( ) ; let executedObservations = new LiteralTreeMap ( ) ; // Step 0 - Updating database let updatedState = _program . getState ( ) . clone ( ) ; updateStateWithFluentActors ( this , _program . getExecutedActions ( ) , updatedState ) ; _program . setState ( updatedState ) ; _nextCycleObservations . forEach ( ( obs ) => { executedObservations . add ( obs ) ; } ) ; _nextCycleActions . forEach ( ( act ) => { selectedAndExecutedActions . add ( act ) ; } ) ; // Step 1 - Processing rules let newFiredGoals = processRules ( this , _program , _currentTime , _profiler ) ; _goals = _goals . concat ( newFiredGoals ) ; // Step 3 - Processing return evaluateGoalTrees ( _currentTime , _goals , _profiler ) . then ( ( newGoals ) => { _goals = newGoals ; // Start preparation for next cycle // reset the set of executed actions _program . setExecutedActions ( new LiteralTreeMap ( ) ) ; _goals . sort ( goalTreeSorter ( _currentTime ) ) ; // select actions from candidate actions return actionsSelector . call ( this , _goals ) ; } ) . then ( ( nextCycleActions ) => { _nextCycleActions = new LiteralTreeMap ( ) ; nextCycleActions . forEach ( ( l ) => { _nextCycleActions . add ( l ) ; } ) ; _nextCycleObservations = new LiteralTreeMap ( ) ; let cycleObservations = processCycleObservations . call ( this ) ; cycleObservations . forEach ( ( observation ) => { nextCycleActions . add ( observation ) ; _nextCycleObservations . add ( observation ) ; } ) ; _program . setExecutedActions ( nextCycleActions ) ; _lastCycleActions = selectedAndExecutedActions ; _lastCycleObservations = executedObservations ; // done with cycle return Promise . resolve ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "converts native arguments object to an array and applies function [CODESPLIT] function applyArgs ( func , thisObj , args ) { return func . apply ( thisObj , Array . prototype . slice . call ( args ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "defines a flow given any number of functions as arguments [CODESPLIT] function define ( ) { var thisFlow = function ( ) { applyArgs ( thisFlow . exec , thisFlow , arguments ) ; } thisFlow . blocks = arguments ; thisFlow . exec = function ( ) { // The flowState is the actual object each step in the flow is applied to. It acts as a // callback to the next function. It also maintains the internal state of each execution // and acts as a place for users to save values between steps of the flow. var flowState = function ( ) { if ( flowState . __frozen ) return ; if ( flowState . __timeoutId ) { clearTimeout ( flowState . __timeoutId ) ; delete flowState . __timeoutId ; } var blockIdx = flowState . __nextBlockIdx ++ ; var block = thisFlow . blocks [ blockIdx ] ; if ( block === undefined ) { return ; } else { applyArgs ( block , flowState , arguments ) ; } } // __nextBlockIdx specifies which function is the next step in the flow. flowState . __nextBlockIdx = 0 ; // __multiCount is incremented every time MULTI is used to createa a multiplexed callback flowState . __multiCount = 0 ; // __multiOutputs accumulates the arguments of each call to callbacks generated by MULTI flowState . __multiOutputs = [ ] ; // REWIND signals that the next call to thisFlow should repeat this step. It allows you // to create serial loops. flowState . REWIND = function ( ) { flowState . __nextBlockIdx -= 1 ; } // MULTI can be used to generate callbacks that must ALL be called before the next step // in the flow is executed. Arguments to those callbacks are accumulated, and an array of // of those arguments objects is sent as the one argument to the next step in the flow. // @param {String} resultId An identifier to get the result of a multi call. flowState . MULTI = function ( resultId ) { flowState . __multiCount += 1 ; return function ( ) { flowState . __multiCount -= 1 ; flowState . __multiOutputs . push ( arguments ) ; if ( resultId ) { var result = arguments . length <= 1 ? arguments [ 0 ] : arguments flowState . __multiOutputs [ resultId ] = result ; } if ( flowState . __multiCount === 0 ) { var multiOutputs = flowState . __multiOutputs ; flowState . __multiOutputs = [ ] ; flowState ( multiOutputs ) ; } } } // TIMEOUT sets a timeout that freezes a flow and calls the provided callback. This // timeout is cleared if the next flow step happens first. flowState . TIMEOUT = function ( milliseconds , timeoutCallback ) { if ( flowState . __timeoutId !== undefined ) { throw new Error ( \"timeout already set for this flow step\" ) ; } flowState . __timeoutId = setTimeout ( function ( ) { flowState . __frozen = true ; timeoutCallback ( ) ; } , milliseconds ) ; } applyArgs ( flowState , this , arguments ) ; } return thisFlow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The flowState is the actual object each step in the flow is applied to . It acts as a callback to the next function . It also maintains the internal state of each execution and acts as a place for users to save values between steps of the flow . [CODESPLIT] function ( ) { if ( flowState . __frozen ) return ; if ( flowState . __timeoutId ) { clearTimeout ( flowState . __timeoutId ) ; delete flowState . __timeoutId ; } var blockIdx = flowState . __nextBlockIdx ++ ; var block = thisFlow . blocks [ blockIdx ] ; if ( block === undefined ) { return ; } else { applyArgs ( block , flowState , arguments ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "defines a flow and evaluates it immediately . The first flow function won t receive any arguments . [CODESPLIT] function exec ( ) { var flow = typeof exports != 'undefined' ? exports : window . flow ; applyArgs ( flow . define , flow , arguments ) ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helper methods [CODESPLIT] function anyError ( results ) { var r , _i , _len ; for ( _i = 0 , _len = results . length ; _i < _len ; _i ++ ) { r = results [ _i ] ; if ( r [ 0 ] ) { return r [ 0 ] ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pads supplied string with character to fill the desired length . [CODESPLIT] function padStart ( str , length , padChar ) { if ( str . length >= length ) { return str ; } else { return padChar . repeat ( length - str . length ) + str ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SM2 elliptic curve [CODESPLIT] function SM2Curve ( params ) { if ( ! ( this instanceof SM2Curve ) ) { return new SM2Curve ( params ) ; } elliptic . curve . short . call ( this , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a point on the curve . Will throw error if ( x y ) is not on curve . [CODESPLIT] function _sm2Point ( x , y , parity ) { if ( x == null ) { return SM2 . point ( ) ; } var pt ; if ( y != null ) { pt = SM2 . point ( x , y ) ; if ( ! SM2 . validate ( pt ) ) { throw 'point is not on curve' ; } } else { var px = new BN ( x , 16 ) . toRed ( SM2 . red ) ; var py = px . redSqr ( ) . redMul ( px ) ; py = py . redIAdd ( px . redMul ( SM2 . a ) ) . redIAdd ( SM2 . b ) . redSqrt ( ) ; if ( ( parity === 'odd' ) != py . fromRed ( ) . isOdd ( ) ) { py = py . redNeg ( ) ; } pt = SM2 . point ( px , py ) ; } return pt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SM2 public and private key pair [CODESPLIT] function SM2KeyPair ( pub , pri ) { if ( ! ( this instanceof SM2KeyPair ) ) { return new SM2KeyPair ( pub , pri ) ; } this . curve = SM2 ; // curve parameter this . pub = null ; // public key, should be a point on the curve this . pri = null ; // private key, should be a integer var validPub = false ; var validPri = false ; if ( pub != null ) { if ( typeof pub === 'string' ) { this . _pubFromString ( pub ) ; } else if ( Array . isArray ( pub ) ) { this . _pubFromBytes ( pub ) ; } else if ( 'x' in pub && pub . x instanceof BN && 'y' in pub && pub . y instanceof BN ) { // pub is already the Point object this . pub = pub ; validPub = true ; } else { throw 'invalid public key' ; } } if ( pri != null ) { if ( typeof pri === 'string' ) { this . pri = new BN ( pri , 16 ) ; } else if ( pri instanceof BN ) { this . pri = pri ; validPri = true ; } else { throw 'invalid private key' ; } // calculate public key if ( this . pub == null ) { this . pub = SM2 . g . mul ( this . pri ) ; } } if ( ! ( validPub && validPri ) && ! this . validate ( ) ) { throw 'invalid key' ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ------------------------------------------------------------------ Constructor : EnoceanUtils () ---------------------------------------------------------------- [CODESPLIT] function ( ) { this . _default_baud_rate = 57600 ; this . _baud_rate = 57600 ; this . _path = '' ; this . _devices = { } ; this . _port = null ; this . _telegram_buffer = null ; this . _gateway = null ; mEventEmitter . call ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "plugin wrapper so streams can pipe to it . [CODESPLIT] function gulpStaticI18n ( options ) { return through . obj ( function ( target , encoding , cb ) { var stream = this ; var build = new StaticI18n ( target , options , stream ) ; build . translate ( cb ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an event to an object and optionally adjust it s scope [CODESPLIT] function ( obj , type , fn , scope ) { scope = scope || obj ; var wrappedFn = function ( e ) { fn . call ( scope , e ) ; } ; obj . addEventListener ( type , wrappedFn , false ) ; cache . push ( [ obj , type , fn , wrappedFn ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an event from an object [CODESPLIT] function ( obj , type , fn ) { var wrappedFn , item , len = cache . length , i ; for ( i = 0 ; i < len ; i ++ ) { item = cache [ i ] ; if ( item [ 0 ] === obj && item [ 1 ] === type && item [ 2 ] === fn ) { wrappedFn = item [ 3 ] ; if ( wrappedFn ) { obj . removeEventListener ( type , wrappedFn , false ) ; cache = cache . slice ( i ) ; return true ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an event to an object and optionally adjust it s scope ( IE ) [CODESPLIT] function ( obj , type , fn , scope ) { scope = scope || obj ; var wrappedFn = function ( ) { var e = window . event ; e . target = e . target || e . srcElement ; e . preventDefault = function ( ) { e . returnValue = false ; } ; fn . call ( scope , e ) ; } ; obj . attachEvent ( 'on' + type , wrappedFn ) ; cache . push ( [ obj , type , fn , wrappedFn ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an event from an object ( IE ) [CODESPLIT] function ( obj , type , fn ) { var wrappedFn , item , len = cache . length , i ; for ( i = 0 ; i < len ; i ++ ) { item = cache [ i ] ; if ( item [ 0 ] === obj && item [ 1 ] === type && item [ 2 ] === fn ) { wrappedFn = item [ 3 ] ; if ( wrappedFn ) { obj . detachEvent ( 'on' + type , wrappedFn ) ; cache = cache . slice ( i ) ; return true ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a view model . [CODESPLIT] function View ( model ) { var wrapper ; this . el = wrapper = document . createElement ( 'div' ) ; this . model = model ; this . isShowing = false ; // HTML wrapper . id = config . name ; config . parent . appendChild ( wrapper ) ; // CSS css . inject ( document . getElementsByTagName ( 'head' ) [ 0 ] , config . styles ) ; // JavaScript events . add ( document , ( 'ontouchstart' in window ) ? 'touchstart' : 'click' , viewevents . click , this ) ; events . add ( document , 'keyup' , viewevents . keyup , this ) ; events . add ( document , 'readystatechange' , viewevents . readystatechange , this ) ; events . add ( window , 'pageshow' , viewevents . pageshow , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new product . [CODESPLIT] function Product ( data ) { data . quantity = parser . quantity ( data . quantity ) ; data . amount = parser . amount ( data . amount ) ; data . href = parser . href ( data . href ) ; this . _data = data ; this . _options = null ; this . _discount = null ; this . _amount = null ; this . _total = null ; Pubsub . call ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders the Mini Cart to the page s DOM . [CODESPLIT] function Cart ( name , duration ) { var data , items , settings , len , i ; this . _items = [ ] ; this . _settings = { bn : constants . BN } ; Pubsub . call ( this ) ; Storage . call ( this , name , duration ) ; if ( ( data = this . load ( ) ) ) { items = data . items ; settings = data . settings ; if ( settings ) { this . _settings = settings ; } if ( items ) { for ( i = 0 , len = items . length ; i < len ; i ++ ) { this . add ( items [ i ] ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Builds the project with ant . Returns a promise . [CODESPLIT] function ( opts ) { // Without our custom_rules.xml, we need to clean before building. var ret = Q ( ) ; if ( ! hasCustomRules ( ) ) { // clean will call check_ant() for us. ret = this . clean ( opts ) ; } var args = this . getArgs ( opts . buildType == 'debug' ? 'debug' : 'release' , opts ) ; return check_reqs . check_ant ( ) . then ( function ( ) { console . log ( 'Executing: ant ' + args . join ( ' ' ) ) ; return spawn ( 'ant' , args ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Builds the project with gradle . Returns a promise . [CODESPLIT] function ( opts ) { var wrapper = path . join ( ROOT , 'gradlew' ) ; var args = this . getArgs ( opts . buildType == 'debug' ? 'debug' : 'release' , opts ) ; return Q ( ) . then ( function ( ) { console . log ( 'Running: ' + wrapper + ' ' + args . join ( ' ' ) ) ; return spawn ( wrapper , args ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "on rejection either retry or throw the error [CODESPLIT] function onRejected ( error ) { attemts_left -= 1 ; if ( attemts_left < 1 ) { throw error ; } console . log ( \"A retried call failed. Retrying \" + attemts_left + \" more time(s).\" ) ; // retry call self again with the same arguments, except attemts_left is now lower var fullArguments = [ attemts_left , promiseFunction ] . concat ( promiseFunctionArguments ) ; return module . exports . retryPromise . apply ( undefined , fullArguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this is the function for full tree / * function collectDependencies ( bowerJson ) { var dependencies = [] ; if ( bowerJson ! = null && bowerJson ! = undefined ) { if ( bowerJson . hasOwnProperty ( dependencies )) { var dependenciesJson = bowerJson . dependencies ; var dependencisKeys = Object . keys ( dependenciesJson ) ; var key ; for ( key in dependencisKeys ) { var dependecyJson = dependenciesJson [ dependencisKeys [ key ]] ; var dependency = createDependency ( dependecyJson ) ; if ( dependency ! = null ) { dependency . children = collectDependencies ( dependecyJson ) ; dependencies . push ( dependency ) ; } } } } return dependencies ; } [CODESPLIT] function collectDependencies ( bowerJson , dependencies ) { if ( bowerJson != null && bowerJson != undefined ) { if ( bowerJson . hasOwnProperty ( \"dependencies\" ) ) { var dependenciesJson = bowerJson . dependencies ; var dependencisKeys = Object . keys ( dependenciesJson ) ; var key ; for ( key in dependencisKeys ) { var dependecyJson = dependenciesJson [ dependencisKeys [ key ] ] ; var dependency = createDependency ( dependecyJson ) ; if ( dependency != null ) { dependencies . push ( dependency ) ; collectDependencies ( dependecyJson , dependencies ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a tree with optional deep paths and create new blobs . Entries is an array of { mode path hash|content } Also deltas can be specified by setting entries . base to the hash of a tree in delta mode entries can be removed by specifying just { path } [CODESPLIT] function createTree ( entries , callback ) { if ( ! callback ) return createTree . bind ( repo , entries ) ; var toDelete = entries . base && entries . filter ( function ( entry ) { return ! entry . mode ; } ) . map ( function ( entry ) { return entry . path ; } ) ; var toCreate = entries . filter ( function ( entry ) { return bodec . isBinary ( entry . content ) ; } ) ; if ( ! toCreate . length ) return next ( ) ; var done = false ; var left = entries . length ; toCreate . forEach ( function ( entry ) { repo . saveAs ( \"blob\" , entry . content , function ( err , hash ) { if ( done ) return ; if ( err ) { done = true ; return callback ( err ) ; } delete entry . content ; entry . hash = hash ; left -- ; if ( ! left ) next ( ) ; } ) ; } ) ; function next ( err ) { if ( err ) return callback ( err ) ; if ( toDelete && toDelete . length ) { return slowUpdateTree ( entries , toDelete , callback ) ; } return fastUpdateTree ( entries , callback ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Github doesn t support deleting entries via the createTree API so we need to manually create those affected trees and modify the request . [CODESPLIT] function slowUpdateTree ( entries , toDelete , callback ) { callback = singleCall ( callback ) ; var root = entries . base ; var left = 0 ; // Calculate trees that need to be re-built and save any provided content. var parents = { } ; toDelete . forEach ( function ( path ) { var parentPath = path . substr ( 0 , path . lastIndexOf ( \"/\" ) ) ; var parent = parents [ parentPath ] || ( parents [ parentPath ] = { add : { } , del : [ ] } ) ; var name = path . substr ( path . lastIndexOf ( \"/\" ) + 1 ) ; parent . del . push ( name ) ; } ) ; var other = entries . filter ( function ( entry ) { if ( ! entry . mode ) return false ; var parentPath = entry . path . substr ( 0 , entry . path . lastIndexOf ( \"/\" ) ) ; var parent = parents [ parentPath ] ; if ( ! parent ) return true ; var name = entry . path . substr ( entry . path . lastIndexOf ( \"/\" ) + 1 ) ; if ( entry . hash ) { parent . add [ name ] = { mode : entry . mode , hash : entry . hash } ; return false ; } left ++ ; repo . saveAs ( \"blob\" , entry . content , function ( err , hash ) { if ( err ) return callback ( err ) ; parent . add [ name ] = { mode : entry . mode , hash : hash } ; if ( ! -- left ) onParents ( ) ; } ) ; return false ; } ) ; if ( ! left ) onParents ( ) ; function onParents ( ) { Object . keys ( parents ) . forEach ( function ( parentPath ) { left ++ ; // TODO: remove this dependency on pathToEntry repo . pathToEntry ( root , parentPath , function ( err , entry ) { if ( err ) return callback ( err ) ; var tree = entry . tree ; var commands = parents [ parentPath ] ; commands . del . forEach ( function ( name ) { delete tree [ name ] ; } ) ; for ( var name in commands . add ) { tree [ name ] = commands . add [ name ] ; } repo . saveAs ( \"tree\" , tree , function ( err , hash , tree ) { if ( err ) return callback ( err ) ; other . push ( { path : parentPath , hash : hash , mode : modes . tree } ) ; if ( ! -- left ) { other . base = entries . base ; if ( other . length === 1 && other [ 0 ] . path === \"\" ) { return callback ( null , hash , tree ) ; } fastUpdateTree ( other , callback ) ; } } ) ; } ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GitHub has a nasty habit of stripping whitespace from messages and losing the timezone . This information is required to make our hashes match up so we guess it by mutating the value till the hash matches . If we re unable to match we will just force the hash when saving to the cache . [CODESPLIT] function fixDate ( type , value , hash ) { if ( type !== \"commit\" && type !== \"tag\" ) return ; // Add up to 3 extra newlines and try all 30-minutes timezone offsets. var clone = JSON . parse ( JSON . stringify ( value ) ) ; for ( var x = 0 ; x < 3 ; x ++ ) { for ( var i = - 720 ; i < 720 ; i += 30 ) { if ( type === \"commit\" ) { clone . author . date . offset = i ; clone . committer . date . offset = i ; } else if ( type === \"tag\" ) { clone . tagger . date . offset = i ; } if ( hash !== hashAs ( type , clone ) ) continue ; // Apply the changes and return. value . message = clone . message ; if ( type === \"commit\" ) { value . author . date . offset = clone . author . date . offset ; value . committer . date . offset = clone . committer . date . offset ; } else if ( type === \"tag\" ) { value . tagger . date . offset = clone . tagger . date . offset ; } return true ; } clone . message += \"\\n\" ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Note on viewbox / width This methods only work when the pixels match the svg units . when the viewbox is changed or width is set they won t return the correct results Returns the global coordinates of a position given for a specific coordinate system [CODESPLIT] function toGlobalCoordinates ( svgdoc : any , elem : any , x : number , y : number ) { var offset = svgdoc . getBoundingClientRect ( ) ; var matrix = elem . getScreenCTM ( ) ; return { x : matrix . a * x + matrix . c * y + matrix . e - offset . left , y : matrix . b * x + matrix . d * y + matrix . f - offset . top } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the angle ( degrees ) given a point . Assumes 0 0 as the center of the circle [CODESPLIT] function getAngleForPoint ( x : number , y : number ) { if ( x == 0 && y == 0 ) return 0 ; const angle = Math . atan ( x / y ) ; let angleDeg = angle * 180 / Math . PI ; //The final value depends on the quadrant const quadrant = getQuadrant ( x , y ) ; if ( quadrant === 1 ) { angleDeg = 90 - angleDeg ; } if ( quadrant === 2 ) { angleDeg = 90 - angleDeg ; } if ( quadrant === 3 ) { angleDeg = 270 - angleDeg ; } if ( quadrant === 4 ) { angleDeg = 270 - angleDeg ; } return angleDeg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms the top / left variables of the rectangle returned by getBoundingClientRect to document based coordinates without the scroll . UPDATE [CODESPLIT] function transformBoundingClientRectToDocument ( box ) { var t ; const scrollX = ( ( ( t = document . documentElement ) || ( t = document . body . parentNode ) ) && typeof t . scrollLeft == \"number\" ? t : document . body ) . scrollLeft ; const scrollY = ( ( ( t = document . documentElement ) || ( t = document . body . parentNode ) ) && typeof t . scrollTop == \"number\" ? t : document . body ) . scrollTop ; //This assumes width == height const ttop = box . top - scrollY ; const tleft = box . left - scrollX ; //info needed to draw line from center to mousepos return { top : ttop , left : tleft , width : box . width , height : box . height } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This method must be called once during initialization . It sets the behaviour of the naked bar in case of one handle . [CODESPLIT] function ( position , handleWidth ) { if ( position === \"stickToSides\" ) { _naked_bar_deltas = { toEndWidth : handleWidth , toBeginLeft : 0 , toBeginWidth : handleWidth } ; } else if ( position === \"middle\" ) { // Position naked end of the bar at the middle value. _naked_bar_deltas = { toEndWidth : handleWidth / 2 , toBeginLeft : handleWidth / 2 , toBeginWidth : handleWidth / 2 } ; } else { throw new Error ( 'unknown position of setNakedBarDelta: ' + position ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Move slider grips to the specified position . This method is designed to run within the user interaction lifecycle . Only call this method if the user has interacted with the sliders actually ... [CODESPLIT] function ( nextLeftGripPositionPx , nextRightGripPositionPx ) { var $this = this ; var draggableAreaLengthPx = _methods . getSliderWidthPx . call ( $this ) - $this . data ( 'left_grip_width' ) ; // // Validate & Move // if ( nextRightGripPositionPx <= draggableAreaLengthPx && nextLeftGripPositionPx >= 0 && nextLeftGripPositionPx <= draggableAreaLengthPx && ( ! $this . data ( 'has_right_grip' ) || nextLeftGripPositionPx <= nextRightGripPositionPx ) ) { var prevMin = $this . data ( 'cur_min' ) , prevMax = $this . data ( 'cur_max' ) ; // note: also stores new cur_min, cur_max _methods . set_position_from_px . call ( $this , nextLeftGripPositionPx , nextRightGripPositionPx ) ; // set the style of the grips according to the highlighted range _methods . refresh_grips_style . call ( $this ) ; _methods . notify_changed_implicit . call ( $this , 'drag_move' , prevMin , prevMax ) ; } return $this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Update aria attributes of the slider based on the current configuration of the slider . [CODESPLIT] function ( ) { var $this = this , settings = $this . data ( 'settings' ) , $leftGrip = $this . find ( settings . left_grip_selector ) ; // // double grips sliders is probably the most common case... // ... also, the values to be set in the two cases are quite // different. // if ( $this . data ( 'has_right_grip' ) ) { var $rightGrip = $this . find ( settings . right_grip_selector ) ; // // grips are mutually binding their max/min values when 2 grips // are present. For example, we should imagine the left grip as // being constrained between [ rangeMin, valueMax ] // $leftGrip . attr ( 'aria-valuemin' , $this . data ( 'range_min' ) ) . attr ( 'aria-valuenow' , methods . get_current_min_value . call ( $this ) ) . attr ( 'aria-valuemax' , methods . get_current_max_value . call ( $this ) ) ; $rightGrip . attr ( 'aria-valuemin' , methods . get_current_min_value . call ( $this ) ) . attr ( 'aria-valuenow' , methods . get_current_max_value . call ( $this ) ) . attr ( 'aria-valuemax' , $this . data ( 'range_max' ) ) ; } else { $leftGrip . attr ( 'aria-valuemin' , $this . data ( 'range_min' ) ) . attr ( 'aria-valuenow' , methods . get_current_min_value . call ( $this ) ) . attr ( 'aria-valuemax' , $this . data ( 'range_max' ) ) ; } return $this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Return the position of the right Grip if it exists or return the current position if not . Even if the right grip doesn t exist its position should be defined as it determines the position of the bar . [CODESPLIT] function ( ) { var $this = this , settings = $this . data ( 'settings' ) ; if ( $this . data ( 'has_right_grip' ) ) { return _methods . getGripPositionPx . call ( $this , $this . find ( settings . right_grip_selector ) ) ; } // default var sliderWidthPx = _methods . getSliderWidthPx . call ( $this ) - $this . data ( 'left_grip_width' ) ; return _methods . rangemap_0_to_n . call ( $this , $this . data ( 'cur_max' ) , sliderWidthPx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Perform binary search to find searchElement into a generic array . It uses a customized compareFunc to perform the comparison between two elements of the array and a getElement function to pick the element from the array ( e . g . in case we want to pick a field of an array of objects ) [CODESPLIT] function ( array , searchElement , getElementFunc , compareFunc ) { var minIndex = 0 ; var maxIndex = array . length - 1 ; var currentIndex ; var currentElement ; while ( minIndex <= maxIndex ) { currentIndex = ( minIndex + maxIndex ) / 2 | 0 ; currentElement = getElementFunc ( array , currentIndex ) ; // lt = -1 (searchElement < currentElement) // eq = 0  // gt = 1  (searchElement > currentElement) var lt_eq_gt = compareFunc ( searchElement , array , currentIndex ) ; if ( lt_eq_gt > 0 ) { minIndex = currentIndex + 1 ; } else if ( lt_eq_gt < 0 ) { maxIndex = currentIndex - 1 ; } else { return currentIndex ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns true if this slider has limit false otherwise . There can be an upper limit and a lower limit for the sliders . The lower / upper limits are values that are out of the slider range but that can be selected by the user when he moves a slider all the way down the minimum and up to the maximum value . [CODESPLIT] function ( ) { var $this = this , lowerLimit = $this . data ( 'lower-limit' ) , upperLimit = $this . data ( 'upper-limit' ) , haveLimits = false ; if ( typeof lowerLimit !== 'undefined' && typeof upperLimit !== 'undefined' ) { haveLimits = true ; } return haveLimits ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This method is called whenever the style of the grips needs to get updated . [CODESPLIT] function ( ) { var $this = this , settings = $this . data ( 'settings' ) ; // Skip refreshing grips style if no hihglight is specified in // construction if ( typeof settings . highlight === 'undefined' ) { return ; } var highlightedRangeMin = $this . data ( 'highlightedRangeMin' ) ; if ( typeof highlightedRangeMin === 'undefined' ) { return ; } var $leftGrip = $this . find ( settings . left_grip_selector ) , $rightGrip = $this . find ( settings . right_grip_selector ) , highlightedRangeMax = $this . data ( 'highlightedRangeMax' ) , curMin = $this . data ( 'cur_min' ) , curMax = $this . data ( 'cur_max' ) , highlightGripClass = settings . highlight . grip_class ; // curmin is within the highlighted range if ( curMin < highlightedRangeMin || curMin > highlightedRangeMax ) { // de-highlight grip $leftGrip . removeClass ( highlightGripClass ) ; } else { // highlight grip $leftGrip . addClass ( highlightGripClass ) ; } // time to highlight right grip if ( curMax < highlightedRangeMin || curMax > highlightedRangeMax ) { // de-highlight grip $rightGrip . removeClass ( highlightGripClass ) ; } else { // highlight grip $rightGrip . addClass ( highlightGripClass ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set left and right handle at the right position on the screen ( pixels ) given the desired position in currency . [CODESPLIT] function ( cur_min , cur_max ) { var $this = this ; //  // We need to understand how much pixels cur_min and cur_max // correspond. // var range_min = $this . data ( 'range_min' ) , range_max = $this . data ( 'range_max' ) ; // // (safety) constrain the cur_min or the cur_max value between the // max/min ranges allowed for this slider. // if ( cur_min < range_min ) { cur_min = range_min ; } if ( cur_min > range_max ) { cur_min = range_max ; } if ( $this . data ( 'has_right_grip' ) ) { if ( cur_max > range_max ) { cur_max = range_max ; } if ( cur_max < range_min ) { cur_max = range_min ; } } else { cur_max = $this . data ( 'cur_max' ) ; } var leftPx = methods . value_to_px . call ( $this , cur_min ) , rightPx = methods . value_to_px . call ( $this , cur_max ) ; _methods . set_handles_at_px . call ( $this , leftPx , rightPx ) ; // save this position $this . data ( 'cur_min' , cur_min ) ; if ( $this . data ( 'has_right_grip' ) ) { $this . data ( 'cur_max' , cur_max ) ; } return $this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the position of the handles at the specified pixel points ( taking the whole slider width as a maximum point ) . [CODESPLIT] function ( leftPx , rightPx ) { var $this = this ; // // we need to find a value from the given value in pixels // // now set the position as requested... _methods . set_handles_at_px . call ( $this , leftPx , rightPx ) ; var valueLeftRight = _methods . getSliderValuesAtPositionPx . call ( $this , leftPx , rightPx ) , leftPxInValue = valueLeftRight [ 0 ] , rightPxInValue = valueLeftRight [ 1 ] ; // ... and save the one we've found. $this . data ( 'cur_min' , leftPxInValue ) ; if ( $this . data ( 'has_right_grip' ) ) { $this . data ( 'cur_max' , rightPxInValue ) ; } return $this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Updates the CSS of grips and bar so that the left grip appears at leftPx and the right grip appears at rightPx . Note : leftPx can be > rightPx . [CODESPLIT] function ( leftPx , rightPx ) { var $this = this ; var settings = $this . data ( 'settings' ) ; var left_grip_selector = settings . left_grip_selector , right_grip_selector = settings . right_grip_selector , value_bar_selector = settings . value_bar_selector ; var handleWidth = $this . data ( 'left_grip_width' ) ; // The left grip $this . find ( left_grip_selector ) . css ( 'left' , leftPx + 'px' ) ; // The right grip $this . find ( right_grip_selector ) . css ( 'left' , rightPx + 'px' ) ; // The value bar if ( $this . data ( 'has_right_grip' ) ) { // If both the grips are there, the value bar must stick to // beginning and the end of the grips.  $this . find ( value_bar_selector ) . css ( 'left' , leftPx + 'px' ) . css ( 'width' , ( rightPx - leftPx + handleWidth ) + 'px' ) ; } else { if ( ! _naked_bar_deltas ) { _methods . populateNakedBarDeltas . call ( $this , leftPx , rightPx , handleWidth ) ; } if ( rightPx > leftPx ) { // The naked end of the bar is on the right of the grip $this . find ( value_bar_selector ) . css ( 'left' , leftPx + 'px' ) . css ( 'width' , rightPx - leftPx + _naked_bar_deltas . toEndWidth + 'px' ) ; } else { // The naked end of the bar is on the left of the grip // NOTE: leftPx and rightPx are to be read swapped here. $this . find ( value_bar_selector ) . css ( 'left' , rightPx + _naked_bar_deltas . toBeginLeft + 'px' ) . css ( 'width' , ( leftPx - rightPx + _naked_bar_deltas . toBeginWidth ) + 'px' ) ; } } return $this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compare search element with current element < 0 search < current 0 equals > 0 search > current [CODESPLIT] function ( search , array , currentIdx ) { // first check if this is our element // this is our element if the search value is: if ( search < array [ currentIdx ] . range ) { // we can have a match or search in the left half if ( currentIdx > 0 ) { if ( search >= array [ currentIdx - 1 ] . range ) { return 0 ; } else { // go left return - 1 ; } } else { return 0 ; } } else { // we must search in the next half return 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Calls the user mouseup callback with the right parameters . Relies on $data ( beforestart_min / max ) in addition to the isLeftGrip parameter . [CODESPLIT] function ( isLeftGrip ) { var $this = this , current_min_value = methods . get_current_min_value . call ( $this ) , current_max_value = methods . get_current_max_value . call ( $this ) , didValuesChange = false ; // check if we changed. if ( ( $this . data ( 'beforestart_min' ) !== current_min_value ) || ( $this . data ( 'beforestart_max' ) !== current_max_value ) ) { // values have changed! didValuesChange = true ; // save the new values $this . data ( 'beforestart_min' , current_min_value ) ; $this . data ( 'beforestart_max' , current_max_value ) ; } var settings = $this . data ( 'settings' ) ; settings . user_mouseup_callback . call ( $this , methods . get_current_min_value . call ( $this ) , methods . get_current_max_value . call ( $this ) , isLeftGrip , didValuesChange ) ; return $this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * NOTE : this method may take the previous min / max value as input . if no arguments are provided the method blindly notifies . [CODESPLIT] function ( cause , prevMin , prevMax ) { var $this = this ; var force = false ; if ( cause === 'init' || cause === 'refresh' ) { force = true ; } var curMin = methods . get_current_min_value . call ( $this ) , curMax = methods . get_current_max_value . call ( $this ) ; if ( ! force ) { prevMin = methods . round_value_according_to_rounding . call ( $this , prevMin ) ; prevMax = methods . round_value_according_to_rounding . call ( $this , prevMax ) ; } if ( force || curMin !== prevMin || curMax !== prevMax ) { _methods . notify_changed_explicit . call ( $this , cause , prevMin , prevMax , curMin , curMax ) ; force = 1 ; } return force ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Maps a value between [ minRange -- maxRange ] into [ 0 -- n ] . The target range will be an integer number . [CODESPLIT] function ( val , n ) { var $this = this ; var rangeMin = $this . data ( 'range_min' ) ; var rangeMax = $this . data ( 'range_max' ) ; if ( val <= rangeMin ) { return 0 ; } if ( val >= rangeMax ) { return n ; } return Math . floor ( ( n * val - n * rangeMin ) / ( rangeMax - rangeMin ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Maps a value between [ 0 -- max ] back into [ minRange -- maxRange ] . The target range can be a floating point number . [CODESPLIT] function ( val , max ) { var $this = this ; var rangeMin = $this . data ( 'range_min' ) ; var rangeMax = $this . data ( 'range_max' ) ; if ( val <= 0 ) { return rangeMin ; } if ( val >= max ) { return rangeMax ; } // // To do this we first map 0 -- max relatively withing [minRange // and maxRange], that is between [0 and (maxRange-minRange)]. // var relativeMapping = ( rangeMax - rangeMin ) * val / max ; // ... then we bring this to the actual value by adding rangeMin. return relativeMapping + rangeMin ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for test removed by Grunt [CODESPLIT] function ( ) { var $this = this ; // remove all data set with .data() $this . removeData ( ) ; // unbind the document as well $ ( document ) . unbind ( 'mousemove.nstSlider' ) . unbind ( 'mouseup.nstSlider' ) ; // unbind events bound to the container element $this . parent ( ) . unbind ( 'mousedown.nstSlider' ) . unbind ( 'touchstart.nstSlider' ) . unbind ( 'touchmove.nstSlider' ) . unbind ( 'touchend.nstSlider' ) ; // unbind events bound to the current element $this . unbind ( 'keydown.nstSlider' ) . unbind ( 'keyup.nstSlider' ) ; return $this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "just call set_position on the current values [CODESPLIT] function ( ) { var $this = this ; // re-set the slider step if specified var lastStepHistogram = $this . data ( 'last_step_histogram' ) ; if ( typeof lastStepHistogram !== 'undefined' ) { methods . set_step_histogram . call ( $this , lastStepHistogram ) ; } // re-center given values _methods . set_position_from_val . call ( $this , methods . get_current_min_value . call ( $this ) , methods . get_current_max_value . call ( $this ) ) ; // re-highlight the range var highlightRangeMin = $this . data ( 'highlightedRangeMin' ) ; if ( typeof highlightRangeMin === 'number' ) { // a highlight range is present, we must update it var highlightRangeMax = $this . data ( 'highlightedRangeMax' ) ; methods . highlight_range . call ( $this , highlightRangeMin , highlightRangeMax ) ; } _methods . notify_changed_implicit . call ( $this , 'refresh' ) ; return $this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This one is the public method called externally . It sets the position and notifies in fact . [CODESPLIT] function ( min , max ) { var $this = this ; var prev_min = $this . data ( 'cur_min' ) , prev_max = $this . data ( 'cur_max' ) ; if ( min > max ) { _methods . set_position_from_val . call ( $this , max , min ) ; } else { _methods . set_position_from_val . call ( $this , min , max ) ; } // set the style of the grips according to the highlighted range _methods . refresh_grips_style . call ( $this ) ; _methods . notify_changed_implicit . call ( $this , 'set_position' , prev_min , prev_max ) ; // this is for the future, therefore \"before the next // interaction starts\" $this . data ( 'beforestart_min' , min ) ; $this . data ( 'beforestart_max' , max ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This tells the slider to increment its step non linearly over the current range based on the histogram on where results are . [CODESPLIT] function ( histogram ) { var $this = this ; $this . data ( 'last_step_histogram' , histogram ) ; if ( typeof histogram === 'undefined' ) { $ . error ( 'got an undefined histogram in set_step_histogram' ) ; _methods . unset_step_histogram . call ( $this ) ; } var sliderWidthPx = _methods . getSliderWidthPx . call ( $this ) - $this . data ( 'left_grip_width' ) , nbuckets = histogram . length ; if ( sliderWidthPx <= 0 ) { // that means the slider is not visible... return ; } // // we need to transform this pdf into a cdf, and use it to obtain // two mappings: pixel to value and value to pixel. // // 1) normalize the pdf to sum to sliderWidthPx first var i ; var histogram_sum = 0 ; for ( i = 0 ; i < nbuckets ; i ++ ) { histogram_sum += histogram [ i ] ; } // // if the sum of the histogram is 0 it means that all is 0 in the  // histogram! (i.e, flat histogram). In this case we already know // what's going to be the answer... // if ( histogram_sum === 0 ) { // ... and the answer is: a linear scale between min_range and // max range! methods . unset_step_histogram . call ( $this ) ; return $this ; } // coefficient for normalization var coeff = parseFloat ( histogram_sum ) / sliderWidthPx ; // go normalize the histogram using this coefficient! for ( i = 0 ; i < nbuckets ; i ++ ) { histogram [ i ] = histogram [ i ] / coeff ; } // 2) now that the histogram is normalized, extract the cumulative // distribution function (CDF). This is an always increasing function // that ranges between 0 and sliderWidthPx; // // We also build the inverted cdf, just the cdf read the other way // around. // var cdf = [ histogram [ 0 ] ] ; // points to pixels for ( i = 1 ; i < nbuckets ; i ++ ) { var cdf_x = cdf [ i - 1 ] + histogram [ i ] ; cdf . push ( cdf_x ) ; } cdf . push ( sliderWidthPx ) ; // the first value here is always min_range as the cdf is supposed // to start from 0 (also first pixel = min_range) var pixel_to_value_lookup = [ $this . data ( 'range_min' ) ] ; var last_filled = 0 ; // we've already filled 0 // now stretch over the rest of the cdf var last_price_for_cdf_bucket = pixel_to_value_lookup [ 0 ] ; var cdf_bucket_count = 0 ; while ( last_filled <= sliderWidthPx ) { // do until all pixels are filled // get next item from cdf var fill_up_to_px = parseInt ( cdf . shift ( ) , 10 ) ; var price_for_cdf_bucket = _methods . inverse_rangemap_0_to_n . call ( $this , cdf_bucket_count + 1 , nbuckets + 1 ) ; cdf_bucket_count ++ ; // how many pixels do we have to fill var fill_tot = fill_up_to_px - last_filled ; // interpolate and fill var diff = price_for_cdf_bucket - last_price_for_cdf_bucket ; for ( i = last_filled ; i < fill_up_to_px ; i ++ ) { var next_price_for_cdf_bucket = last_price_for_cdf_bucket + ( diff * ( i - last_filled + 1 ) / fill_tot ) ; pixel_to_value_lookup . push ( next_price_for_cdf_bucket ) ; last_filled ++ ; last_price_for_cdf_bucket = next_price_for_cdf_bucket ; } if ( last_filled === sliderWidthPx ) { break ; } } pixel_to_value_lookup [ pixel_to_value_lookup . length - 1 ] = $this . data ( 'range_max' ) ; // 3) build lookup functions to extract pixels and values from the // cdf and the inverted cdf. // var pixel_to_value_mapping = function ( pixel ) { return pixel_to_value_lookup [ parseInt ( pixel , 10 ) ] ; } ; var value_to_pixel_mapping = function ( value ) { // // Binary search into the array of pixels, returns always the // rightmost pixel if there is no exact match. // var suggestedPixel = _methods . binarySearch . call ( $this , pixel_to_value_lookup , value , function ( a , i ) { return a [ i ] ; } , // access a value in the array _methods . binarySearchValueToPxCompareFunc ) ; // exact match if ( pixel_to_value_lookup [ suggestedPixel ] === value ) { return suggestedPixel ; } // approx match: we need to check if it's closer to the value // at suggestedPixel or the value at suggestedPixel-1 if ( Math . abs ( pixel_to_value_lookup [ suggestedPixel - 1 ] - value ) < Math . abs ( pixel_to_value_lookup [ suggestedPixel ] - value ) ) { return suggestedPixel - 1 ; } return suggestedPixel ; } ; // // these two functions will be stored and then used internally to // decide what value to display given a certain pixel, and what // pixel to put the slider on given a certain value. // $this . data ( 'pixel_to_value_mapping' , pixel_to_value_mapping ) ; $this . data ( 'value_to_pixel_mapping' , value_to_pixel_mapping ) ; return $this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This method highlights the range of the slider apart from the position of the slider grips . To work well the slider must have background color set to transparent in the CSS or not set . [CODESPLIT] function ( rangeMin , rangeMax ) { var $this = this ; var settings = $this . data ( 'settings' ) ; if ( typeof settings . highlight === \"undefined\" ) { $ . error ( 'you cannot call highlight_range if you haven\\' specified the \"highlight\" parameter in construction!' ) ; } // avoid empty string if ( ! rangeMin ) { rangeMin = 0 ; } if ( ! rangeMax ) { rangeMax = 0 ; } // we need to map rangeMin and rangeMax into pixels. var leftPx = methods . value_to_px . call ( $this , rangeMin ) , rightPx = methods . value_to_px . call ( $this , rangeMax ) , barWidth = rightPx - leftPx + $this . data ( 'left_grip_width' ) ; // set position var $highlightPanel = $this . find ( settings . highlight . panel_selector ) ; $highlightPanel . css ( 'left' , leftPx + \"px\" ) ; $highlightPanel . css ( 'width' , barWidth + \"px\" ) ; // keep the latest highlighted range, because if set_range is called // we must be able to update the highlighting. $this . data ( 'highlightedRangeMin' , rangeMin ) ; $this . data ( 'highlightedRangeMax' , rangeMax ) ; // now decide wether the handler should be highlight _methods . refresh_grips_style . call ( $this ) ; return $this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Sets the increment rounding for the slider see input parameters section for more information . [CODESPLIT] function ( rounding ) { var $this = this ; if ( typeof rounding === 'string' && rounding . indexOf ( '{' ) > - 1 ) { // probably a json string rounding = $ . parseJSON ( rounding ) ; } $this . data ( 'rounding' , rounding ) ; // build an array of roundings and sort it by value to facilitate search // when the range is going to be set. var roundings_array = [ ] ; if ( typeof rounding === 'object' ) { // initial object has the form { value : range } var rounding_value ; for ( rounding_value in rounding ) { // skip_javascript_test if ( rounding . hasOwnProperty ( rounding_value ) ) { var rounding_range = rounding [ rounding_value ] ; roundings_array . push ( { 'range' : rounding_range , 'value' : rounding_value } ) ; } } // now sort it by rounding range roundings_array . sort ( function ( a , b ) { return a . range - b . range ; } ) ; $this . data ( 'rounding_ranges' , roundings_array ) ; } else { $this . removeData ( 'rounding_ranges' ) ; } return $this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This method rounds a given value to the closest integer defined according to the rounding . Examples : rounding : 10 v : 12 . 3 -- > 10 rounding : 1 v : 12 . 3 -- > 12 rounding : 10 v : 12 . 6 -- > 13 [CODESPLIT] function ( v ) { var $this = this ; var rounding = _methods . get_rounding_for_value . call ( $this , v ) ; if ( rounding > 0 ) { // We bring ourselves in a space of unitary roundings. You can // imagine now that sliders range between a certain minimum and  // maximum, and we always increase/decrease of one. var increment = v / rounding ; // This is the proposed value. var increment_int = parseInt ( increment , 10 ) ; // delta is a positive number between 0 and 1 that tells us how // close is the slider to integer + 1 (i.e., the next rounding). // 0 means the grip is exactly on integer // 1 means the grip is on integer + 1. var delta = increment - increment_int ; // now use delta to modify or not the current value. if ( delta > 0.5 ) { increment_int ++ ; } // we now move the  var rounded = increment_int * rounding ; return rounded ; } else { $ . error ( 'rounding must be > 0, got ' + rounding + ' instead' ) ; } return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Utility function . Given a value within the range of the slider converts the value in pixels . If a value_to_pixel_mapping function is defined it will be used otherwise a linear mapping is used for the conversion . [CODESPLIT] function ( value ) { var $this = this , value_to_pixel_mapping_func = $this . data ( 'value_to_pixel_mapping' ) ; // try using non-linear mapping if it's there... if ( typeof value_to_pixel_mapping_func !== 'undefined' ) { return value_to_pixel_mapping_func ( value ) ; } // ... use linear mapping otherwise var w = _methods . getSliderWidthPx . call ( $this ) - $this . data ( 'left_grip_width' ) ; return _methods . rangemap_0_to_n . call ( $this , value , w ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Internal method Example : params ( city { name : Aalst postalcode : 9300 } ) returns city . name = { name } appendToken city . postalcode = { postalcode } [CODESPLIT] function append ( fieldName , props , appendToken ) { var params = '' ; var notFirst = false ; fieldName += '.' ; for ( var key in props ) { var obj = props [ key ] ; if ( notFirst ) params += appendToken ; else notFirst = true ; params += fieldName + key + '={' + key + '}' ; } return params ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Example : remove ( city [ name postalcode ] ) returns city . name city . postalcode [CODESPLIT] function remove ( fieldName , props ) { var removes = '' , notFirst = false , i = props . length ; fieldName += '.' ; while ( i -- ) { if ( notFirst ) { removes += ',' ; } else { notFirst = true ; } removes += fieldName + props [ i ] ; } return removes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a where and set string and a new object with unique propertynames Example : whereSetProperties ( user { userid : 123 firstname : foo } { firstname : bar } ) returns { where : user . userid = { xQ_1 } AND user . firstname = { xQ_2 } set : user . firstname = { xQ_3 } props { xQ_1 : 123 xQ_2 : foo xQ_2 : bar } } [CODESPLIT] function whereSetProperties ( fieldName , oldProps , newProps ) { var prefix = 'xQ_' , whereClause = '' , setClause = '' , notFirst = false , props = { } , i = 0 , obj ; fieldName += '.' ; // Build WHERE for ( var k in oldProps ) { obj = oldProps [ k ] ; if ( notFirst ) whereClause += ' AND ' ; else notFirst = true ; whereClause += fieldName + k + '={' + prefix + ( ++ i ) + '}' ; props [ prefix + i ] = obj ; } notFirst = false ; // Build SET for ( var key in newProps ) { obj = newProps [ key ] ; if ( notFirst ) setClause += ',' ; else notFirst = true ; // Create unique placeholder {xx1} {xx2} ... setClause += fieldName + key + '={' + prefix + ( ++ i ) + '}' ; // Build new properties object props [ prefix + i ] = obj ; } // Return stringified `where` and `set` clause and a new object with unique property names // So there are no name collisions return { where : whereClause , set : setClause , properties : props } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Example : labels ( [ User Student ] ) returns : User : Student [CODESPLIT] function labels ( array ) { var res = '' ; if ( typeof array === 'string' ) { return ':' + array ; } for ( var i = 0 ; i < array . length ; i ++ ) { res += ':' + array [ i ] ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Replace a Node s properties This will replace all existing properties on the node with the new set of attributes . [CODESPLIT] function ( node_id , node_data , callback ) { var that = this ; request . put ( that . url + '/db/data/node/' + node_id + '/properties' ) . set ( this . header ) . send ( that . stringifyValueObjects ( that . replaceNullWithString ( node_data ) ) ) . end ( function ( result ) { switch ( result . statusCode ) { case 204 : callback ( null , true ) ; break ; case 404 : callback ( null , false ) ; break ; default : callback ( new Error ( 'HTTP Error ' + result . statusCode + ' when updating a Node.' ) , null ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * CONSTRAINTS / * Create a uniqueness constraint on a property . Example : createUniquenessConstraint ( User email callback ) ; returns { label : User type : UNIQUENESS property - keys : [ email ] } [CODESPLIT] function ( label , property_key , callback ) { var that = this ; var val = new Validator ( ) ; val . label ( label ) . property ( property_key ) ; if ( val . hasErrors ) { return callback ( val . error ( ) , null ) ; } request . post ( that . url + '/db/data/schema/constraint/' + label + '/uniqueness' ) . set ( this . header ) . send ( { 'property_keys' : [ property_key ] } ) . end ( function ( result ) { switch ( result . statusCode ) { case 200 : callback ( null , result . body ) ; break ; case 409 : callback ( null , false ) ; // Constraint already exists break ; default : callback ( new Error ( 'HTTP Error ' + result . statusCode + ' when creating a uniqueness contraint.' ) , null ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Get Relationships of a Node --------- [CODESPLIT] function ( node_id , options , callback ) { var that = this ; if ( typeof options === 'function' ) { callback = options ; } var url = that . url + '/db/data/node/' + node_id + '/relationships/' ; // Set direction of relationships to retrieve. if ( options . direction && ( options . direction === 'in' || options . direction === 'out' ) ) { url += options . direction ; } else { url += 'all' ; } // Set types of relationships to retrieve. if ( options . types && options . types . length >= 1 ) { url += '/' + encodeURIComponent ( options . types . join ( '&' ) ) ; } request . get ( url ) . set ( this . header ) . end ( function ( result ) { switch ( result . statusCode ) { case 200 : that . addRelationshipIdForArray ( result . body , callback ) ; break ; case 404 : callback ( null , false ) ; break ; default : callback ( new Error ( 'HTTP Error ' + result . statusCode + ' when retrieving relationships for node ' + node_id ) , null ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pokémon Go RPC client . [CODESPLIT] function Client ( options ) { if ( ! ( this instanceof Client ) ) { return new Client ( options ) ; } const self = this ; /*\n     * PUBLIC METHODS\n     */ /**\n      * Sets the specified client option to the given value.\n      * Note that not all options support changes after client initialization.\n      * @param {string} option - Option name\n      * @param {any} value - Option value\n      */ this . setOption = function ( option , value ) { self . options [ option ] = value ; } ; /**\n     * Sets the player's latitude and longitude.\n     * Note that this does not actually update the player location on the server, it only sets\n     * the location to be used in following API calls. To update the location on the server you\n     * need to make an API call.\n     * @param {number|object} latitude - The player's latitude, or an object with parameters\n     * @param {number} longitude - The player's longitude\n     * @param {number} [accuracy=0] - The location accuracy in m\n     * @param {number} [altitude=0] - The player's altitude\n     */ this . setPosition = function ( latitude , longitude , accuracy , altitude ) { if ( typeof latitude === 'object' ) { const pos = latitude ; latitude = pos . latitude ; longitude = pos . longitude ; accuracy = pos . accuracy ; altitude = pos . altitude ; } self . playerLatitude = latitude ; self . playerLongitude = longitude ; self . playerLocationAccuracy = accuracy || 0 ; self . playerAltitude = altitude || 0 ; } ; /**\n     * Performs client initialization and downloads needed settings from the API and hashing server.\n     * @param {boolean} [downloadSettings] - Deprecated, use downloadSettings option instead\n     * @return {Promise} promise\n     */ this . init = function ( downloadSettings ) { // For backwards compatibility only if ( typeof downloadSettings !== 'undefined' ) self . setOption ( 'downloadSettings' , downloadSettings ) ; self . lastMapObjectsCall = 0 ; self . endpoint = INITIAL_ENDPOINT ; // convert app version (5704) to client version (0.57.4) let signatureVersion = '0.' + ( ( + self . options . version ) / 100 ) . toFixed ( 0 ) ; signatureVersion += '.' + ( + self . options . version % 100 ) ; Signature . signature . register ( self , self . options . deviceId ) ; self . signatureBuilder = new Signature . encryption . Builder ( { protos : POGOProtos , version : signatureVersion , } ) ; self . signatureBuilder . encryptAsync = Promise . promisify ( self . signatureBuilder . encrypt , { context : self . signatureBuilder } ) ; let promise = Promise . resolve ( true ) ; if ( self . options . useHashingServer ) { promise = promise . then ( self . initializeHashingServer ) ; } if ( self . options . downloadSettings ) { promise = promise . then ( ( ) => self . downloadSettings ( ) ) . then ( self . processSettingsResponse ) ; } return promise ; } ; /**\n     * Sets batch mode. All further API requests will be held and executed in one RPC call when\n     * {@link #batchCall} is called.\n     * @return {Client} this\n     */ this . batchStart = function ( ) { if ( ! self . batchRequests ) { self . batchRequests = [ ] ; } return self ; } ; /**\n     * Clears the list of batched requests and aborts batch mode.\n     */ this . batchClear = function ( ) { delete self . batchRequests ; } ; /**\n     * Executes any batched requests.\n     * @return {Promise}\n     */ this . batchCall = function ( ) { var p = self . callRPC ( self . batchRequests || [ ] ) ; self . batchClear ( ) ; return p ; } ; /**\n     * Gets rate limit info from the latest signature server request, if applicable.\n     * @return {Object}\n     */ this . getSignatureRateInfo = function ( ) { return self . signatureBuilder . rateInfos ; } ; /*\n     * API CALLS (in order of RequestType enum)\n     */ this . getPlayer = function ( country , language , timezone ) { return self . callOrChain ( { type : RequestType . GET_PLAYER , message : new RequestMessages . GetPlayerMessage ( { player_locale : { country : country , language : language , timezone : timezone } } ) , responseType : Responses . GetPlayerResponse } ) ; } ; this . getInventory = function ( lastTimestamp ) { return self . callOrChain ( { type : RequestType . GET_INVENTORY , message : new RequestMessages . GetInventoryMessage ( { last_timestamp_ms : lastTimestamp } ) , responseType : Responses . GetInventoryResponse } ) ; } ; this . downloadSettings = function ( hash ) { return self . callOrChain ( { type : RequestType . DOWNLOAD_SETTINGS , message : new RequestMessages . DownloadSettingsMessage ( { hash : hash } ) , responseType : Responses . DownloadSettingsResponse } ) ; } ; this . downloadItemTemplates = function ( paginate , pageOffset , pageTimestamp ) { return self . callOrChain ( { type : RequestType . DOWNLOAD_ITEM_TEMPLATES , message : new RequestMessages . DownloadItemTemplatesMessage ( { paginate : paginate , page_offset : pageOffset , page_timestamp : pageTimestamp } ) , responseType : Responses . DownloadItemTemplatesResponse } ) ; } ; this . downloadRemoteConfigVersion = function ( platform , deviceManufacturer , deviceModel , locale , appVersion ) { return self . callOrChain ( { type : RequestType . DOWNLOAD_REMOTE_CONFIG_VERSION , message : new RequestMessages . DownloadRemoteConfigVersionMessage ( { platform : platform , device_manufacturer : deviceManufacturer , device_model : deviceModel , locale : locale , app_version : appVersion } ) , responseType : Responses . DownloadRemoteConfigVersionResponse } ) ; } ; this . registerBackgroundDevice = function ( deviceType , deviceID ) { return self . callOrChain ( { type : RequestType . REGISTER_BACKGROUND_DEVICE , message : new RequestMessages . RegisterBackgroundDeviceMessage ( { device_type : deviceType , device_id : deviceID } ) , responseType : Responses . RegisterBackgroundDeviceResponse } ) ; } ; this . fortSearch = function ( fortID , fortLatitude , fortLongitude ) { return self . callOrChain ( { type : RequestType . FORT_SEARCH , message : new RequestMessages . FortSearchMessage ( { fort_id : fortID , player_latitude : self . playerLatitude , player_longitude : self . playerLongitude , fort_latitude : fortLatitude , fort_longitude : fortLongitude } ) , responseType : Responses . FortSearchResponse } ) ; } ; this . encounter = function ( encounterID , spawnPointID ) { return self . callOrChain ( { type : RequestType . ENCOUNTER , message : new RequestMessages . EncounterMessage ( { encounter_id : encounterID , spawn_point_id : spawnPointID , player_latitude : self . playerLatitude , player_longitude : self . playerLongitude } ) , responseType : Responses . EncounterResponse } ) ; } ; this . catchPokemon = function ( encounterID , pokeballItemID , normalizedReticleSize , spawnPointID , hitPokemon , spinModifier , normalizedHitPosition ) { return self . callOrChain ( { type : RequestType . CATCH_POKEMON , message : new RequestMessages . CatchPokemonMessage ( { encounter_id : encounterID , pokeball : pokeballItemID , normalized_reticle_size : normalizedReticleSize , spawn_point_id : spawnPointID , hit_pokemon : hitPokemon , spin_modifier : spinModifier , normalized_hit_position : normalizedHitPosition } ) , responseType : Responses . CatchPokemonResponse } ) ; } ; this . fortDetails = function ( fortID , fortLatitude , fortLongitude ) { return self . callOrChain ( { type : RequestType . FORT_DETAILS , message : new RequestMessages . FortDetailsMessage ( { fort_id : fortID , latitude : fortLatitude , longitude : fortLongitude } ) , responseType : Responses . FortDetailsResponse } ) ; } ; this . getMapObjects = function ( cellIDs , sinceTimestamps ) { return self . callOrChain ( { type : RequestType . GET_MAP_OBJECTS , message : new RequestMessages . GetMapObjectsMessage ( { cell_id : cellIDs , since_timestamp_ms : sinceTimestamps , latitude : self . playerLatitude , longitude : self . playerLongitude } ) , responseType : Responses . GetMapObjectsResponse } ) ; } ; this . fortDeployPokemon = function ( fortID , pokemonID ) { return self . callOrChain ( { type : RequestType . FORT_DEPLOY_POKEMON , message : new RequestMessages . FortDeployPokemonMessage ( { fort_id : fortID , pokemon_id : pokemonID , player_latitude : self . playerLatitude , player_longitude : self . playerLongitude } ) , responseType : Responses . FortDeployPokemonResponse } ) ; } ; this . fortRecallPokemon = function ( fortID , pokemonID ) { return self . callOrChain ( { type : RequestType . FORT_RECALL_POKEMON , message : new RequestMessages . FortRecallPokemonMessage ( { fort_id : fortID , pokemon_id : pokemonID , player_latitude : self . playerLatitude , player_longitude : self . playerLongitude } ) , responseType : Responses . FortRecallPokemonResponse } ) ; } ; this . releasePokemon = function ( pokemonIDs ) { if ( ! Array . isArray ( pokemonIDs ) ) pokemonIDs = [ pokemonIDs ] ; return self . callOrChain ( { type : RequestType . RELEASE_POKEMON , message : new RequestMessages . ReleasePokemonMessage ( { pokemon_id : pokemonIDs . length === 1 ? pokemonIDs [ 0 ] : undefined , pokemon_ids : pokemonIDs . length > 1 ? pokemonIDs : undefined } ) , responseType : Responses . ReleasePokemonResponse } ) ; } ; this . useItemPotion = function ( itemID , pokemonID ) { return self . callOrChain ( { type : RequestType . USE_ITEM_POTION , message : new RequestMessages . UseItemPotionMessage ( { item_id : itemID , pokemon_id : pokemonID } ) , responseType : Responses . UseItemPotionResponse } ) ; } ; this . useItemCapture = function ( itemID , encounterID , spawnPointID ) { return self . callOrChain ( { type : RequestType . USE_ITEM_CAPTURE , message : new RequestMessages . UseItemCaptureMessage ( { item_id : itemID , encounter_id : encounterID , spawn_point_id : spawnPointID } ) , responseType : Responses . UseItemCaptureResponse } ) ; } ; this . useItemRevive = function ( itemID , pokemonID ) { return self . callOrChain ( { type : RequestType . USE_ITEM_REVIVE , message : new RequestMessages . UseItemReviveMessage ( { item_id : itemID , pokemon_id : pokemonID } ) , responseType : Responses . UseItemReviveResponse } ) ; } ; this . getPlayerProfile = function ( playerName ) { return self . callOrChain ( { type : RequestType . GET_PLAYER_PROFILE , message : new RequestMessages . GetPlayerProfileMessage ( { player_name : playerName } ) , responseType : Responses . GetPlayerProfileResponse } ) ; } ; this . evolvePokemon = function ( pokemonID , evolutionRequirementItemID ) { return self . callOrChain ( { type : RequestType . EVOLVE_POKEMON , message : new RequestMessages . EvolvePokemonMessage ( { pokemon_id : pokemonID , evolution_item_requirement : evolutionRequirementItemID } ) , responseType : Responses . EvolvePokemonResponse } ) ; } ; this . getHatchedEggs = function ( ) { return self . callOrChain ( { type : RequestType . GET_HATCHED_EGGS , responseType : Responses . GetHatchedEggsResponse } ) ; } ; this . encounterTutorialComplete = function ( pokemonID ) { return self . callOrChain ( { type : RequestType . ENCOUNTER_TUTORIAL_COMPLETE , message : new RequestMessages . EncounterTutorialCompleteMessage ( { pokemon_id : pokemonID } ) , responseType : Responses . EncounterTutorialCompleteResponse } ) ; } ; this . levelUpRewards = function ( level ) { return self . callOrChain ( { type : RequestType . LEVEL_UP_REWARDS , message : new RequestMessages . LevelUpRewardsMessage ( { level : level } ) , responseType : Responses . LevelUpRewardsResponse } ) ; } ; this . checkAwardedBadges = function ( ) { return self . callOrChain ( { type : RequestType . CHECK_AWARDED_BADGES , responseType : Responses . CheckAwardedBadgesResponse } ) ; } ; this . useItemGym = function ( itemID , gymID ) { return self . callOrChain ( { type : RequestType . USE_ITEM_GYM , message : new RequestMessages . UseItemGymMessage ( { item_id : itemID , gym_id : gymID , player_latitude : self . playerLatitude , player_longitude : self . playerLongitude } ) , responseType : Responses . UseItemGymResponse } ) ; } ; this . getGymDetails = function ( gymID , gymLatitude , gymLongitude , clientVersion ) { return self . callOrChain ( { type : RequestType . GET_GYM_DETAILS , message : new RequestMessages . GetGymDetailsMessage ( { gym_id : gymID , player_latitude : self . playerLatitude , player_longitude : self . playerLongitude , gym_latitude : gymLatitude , gym_longitude : gymLongitude , client_version : clientVersion } ) , responseType : Responses . GetGymDetailsResponse } ) ; } ; this . startGymBattle = function ( gymID , attackingPokemonIDs , defendingPokemonID ) { return self . callOrChain ( { type : RequestType . START_GYM_BATTLE , message : new RequestMessages . StartGymBattleMessage ( { gym_id : gymID , attacking_pokemon_ids : attackingPokemonIDs , defending_pokemon_id : defendingPokemonID , player_latitude : self . playerLatitude , player_longitude : self . playerLongitude } ) , responseType : Responses . StartGymBattleResponse } ) ; } ; this . attackGym = function ( gymID , battleID , attackActions , lastRetrievedAction ) { return self . callOrChain ( { type : RequestType . ATTACK_GYM , message : new RequestMessages . AttackGymMessage ( { gym_id : gymID , battle_id : battleID , attack_actions : attackActions , last_retrieved_action : lastRetrievedAction , player_latitude : self . playerLatitude , player_longitude : self . playerLongitude } ) , responseType : Responses . AttackGymResponse } ) ; } ; this . recycleInventoryItem = function ( itemID , count ) { return self . callOrChain ( { type : RequestType . RECYCLE_INVENTORY_ITEM , message : new RequestMessages . RecycleInventoryItemMessage ( { item_id : itemID , count : count } ) , responseType : Responses . RecycleInventoryItemResponse } ) ; } ; this . collectDailyBonus = function ( ) { return self . callOrChain ( { type : RequestType . COLLECT_DAILY_BONUS , responseType : Responses . CollectDailyBonusResponse } ) ; } ; this . useItemXPBoost = function ( itemID ) { return self . callOrChain ( { type : RequestType . USE_ITEM_XP_BOOST , message : new RequestMessages . UseItemXpBoostMessage ( { item_id : itemID } ) , responseType : Responses . UseItemXpBoostResponse } ) ; } ; this . useItemEggIncubator = function ( itemID , pokemonID ) { return self . callOrChain ( { type : RequestType . USE_ITEM_EGG_INCUBATOR , message : new RequestMessages . UseItemEggIncubatorMessage ( { item_id : itemID , pokemon_id : pokemonID } ) , responseType : Responses . UseItemEggIncubatorResponse } ) ; } ; this . useIncense = function ( itemID ) { return self . callOrChain ( { type : RequestType . USE_INCENSE , message : new RequestMessages . UseIncenseMessage ( { incense_type : itemID } ) , responseType : Responses . UseIncenseResponse } ) ; } ; this . getIncensePokemon = function ( ) { return self . callOrChain ( { type : RequestType . GET_INCENSE_POKEMON , message : new RequestMessages . GetIncensePokemonMessage ( { player_latitude : self . playerLatitude , player_longitude : self . playerLongitude } ) , responseType : Responses . GetIncensePokmeonResponse } ) ; } ; this . incenseEncounter = function ( encounterID , encounterLocation ) { return self . callOrChain ( { type : RequestType . INCENSE_ENCOUNTER , message : new RequestMessages . IncenseEncounterMessage ( { encounter_id : encounterID , encounter_location : encounterLocation } ) , responseType : Responses . IncenseEncounterResponse } ) ; } ; this . addFortModifier = function ( modifierItemID , fortID ) { return self . callOrChain ( { type : RequestType . ADD_FORT_MODIFIER , message : new RequestMessages . AddFortModifierMessage ( { modifier_type : modifierItemID , fort_id : fortID , player_latitude : self . playerLatitude , player_longitude : self . playerLongitude } ) } ) ; } ; this . diskEncounter = function ( encounterID , fortID ) { return self . callOrChain ( { type : RequestType . DISK_ENCOUNTER , message : new RequestMessages . DiskEncounterMessage ( { encounter_id : encounterID , fort_id : fortID , player_latitude : self . playerLatitude , player_longitude : self . playerLongitude } ) , responseType : Responses . DiskEncounterResponse } ) ; } ; this . collectDailyDefenderBonus = function ( ) { return self . callOrChain ( { type : RequestType . COLLECT_DAILY_DEFENDER_BONUS , responseType : Responses . CollectDailyDefenderBonusResponse } ) ; } ; this . upgradePokemon = function ( pokemonID ) { return self . callOrChain ( { type : RequestType . UPGRADE_POKEMON , message : new RequestMessages . UpgradePokemonMessage ( { pokemon_id : pokemonID } ) , responseType : Responses . UpgradePokemonResponse } ) ; } ; this . setFavoritePokemon = function ( pokemonID , isFavorite ) { return self . callOrChain ( { type : RequestType . SET_FAVORITE_POKEMON , message : new RequestMessages . SetFavoritePokemonMessage ( { pokemon_id : pokemonID , is_favorite : isFavorite } ) , responseType : Responses . SetFavoritePokemonResponse } ) ; } ; this . nicknamePokemon = function ( pokemonID , nickname ) { return self . callOrChain ( { type : RequestType . NICKNAME_POKEMON , message : new RequestMessages . NicknamePokemonMessage ( { pokemon_id : pokemonID , nickname : nickname } ) , responseType : Responses . NicknamePokemonResponse } ) ; } ; this . equipBadge = function ( badgeType ) { return self . callOrChain ( { type : RequestType . EQUIP_BADGE , message : new RequestMessages . EquipBadgeMessage ( { badge_type : badgeType } ) , responseType : Responses . EquipBadgeResponse } ) ; } ; this . setContactSettings = function ( sendMarketingEmails , sendPushNotifications ) { return self . callOrChain ( { type : RequestType . SET_CONTACT_SETTINGS , message : new RequestMessages . SetContactSettingsMessage ( { contact_settings : { send_marketing_emails : sendMarketingEmails , send_push_notifications : sendPushNotifications } } ) , responseType : Responses . SetContactSettingsResponse } ) ; } ; this . setBuddyPokemon = function ( pokemonID ) { return self . callOrChain ( { type : RequestType . SET_BUDDY_POKEMON , message : new RequestMessages . SetBuddyPokemonMessage ( { pokemon_id : pokemonID } ) , responseType : Responses . SetBuddyPokemonResponse } ) ; } ; this . getBuddyWalked = function ( ) { return self . callOrChain ( { type : RequestType . GET_BUDDY_WALKED , responseType : Responses . GetBuddyWalkedResponse } ) ; } ; this . useItemEncounter = function ( itemID , encounterID , spawnPointGUID ) { return self . callOrChain ( { type : RequestType . USE_ITEM_ENCOUNTER , message : new RequestMessages . UseItemEncounterMessage ( { item : itemID , encounter_id : encounterID , spawn_point_guid : spawnPointGUID } ) , responseType : Responses . UseItemEncounterResponse } ) ; } ; this . getAssetDigest = function ( platform , deviceManufacturer , deviceModel , locale , appVersion ) { return self . callOrChain ( { type : RequestType . GET_ASSET_DIGEST , message : new RequestMessages . GetAssetDigestMessage ( { platform : platform , device_manufacturer : deviceManufacturer , device_model : deviceModel , locale : locale , app_version : appVersion } ) , responseType : Responses . GetAssetDigestResponse } ) ; } ; this . getDownloadURLs = function ( assetIDs ) { return self . callOrChain ( { type : RequestType . GET_DOWNLOAD_URLS , message : new RequestMessages . GetDownloadUrlsMessage ( { asset_id : assetIDs } ) , responseType : Responses . GetDownloadUrlsResponse } ) ; } ; this . claimCodename = function ( codename ) { return self . callOrChain ( { type : RequestType . CLAIM_CODENAME , message : new RequestMessages . ClaimCodenameMessage ( { codename : codename } ) , responseType : Responses . ClaimCodenameResponse } ) ; } ; this . setAvatar = function ( playerAvatar ) { return self . callOrChain ( { type : RequestType . SET_AVATAR , message : new RequestMessages . SetAvatarMessage ( { player_avatar : playerAvatar } ) , responseType : Responses . SetAvatarResponse } ) ; } ; this . setPlayerTeam = function ( teamColor ) { return self . callOrChain ( { type : RequestType . SET_PLAYER_TEAM , message : new RequestMessages . SetPlayerTeamMessage ( { team : teamColor } ) , responseType : Responses . SetPlayerTeamResponse } ) ; } ; this . markTutorialComplete = function ( tutorialsCompleted , sendMarketingEmails , sendPushNotifications ) { return self . callOrChain ( { type : RequestType . MARK_TUTORIAL_COMPLETE , message : new RequestMessages . MarkTutorialCompleteMessage ( { tutorials_completed : tutorialsCompleted , send_marketing_emails : sendMarketingEmails , send_push_notifications : sendPushNotifications } ) , responseType : Responses . MarkTutorialCompleteResponse } ) ; } ; this . checkChallenge = function ( isDebugRequest ) { return self . callOrChain ( { type : RequestType . CHECK_CHALLENGE , message : new RequestMessages . CheckChallengeMessage ( { debug_request : isDebugRequest } ) , responseType : Responses . CheckChallengeResponse } ) ; } ; this . verifyChallenge = function ( token ) { return self . callOrChain ( { type : RequestType . VERIFY_CHALLENGE , message : new RequestMessages . VerifyChallengeMessage ( { token : token } ) , responseType : Responses . VerifyChallengeResponse } ) ; } ; this . echo = function ( ) { return self . callOrChain ( { type : RequestType . ECHO , responseType : Responses . EchoResponse } ) ; } ; this . sfidaActionLog = function ( ) { return self . callOrChain ( { type : RequestType . SFIDA_ACTION_LOG , responseType : Responses . SfidaActionLogResponse } ) ; } ; this . listAvatarCustomizations = function ( avatarType , slots , filters , start , limit ) { return self . callOrChain ( { type : RequestType . LIST_AVATAR_CUSTOMIZATIONS , message : new RequestMessages . ListAvatarCustomizationsMessage ( { avatar_type : avatarType , slot : slots , filters : filters , start : start , limit : limit } ) , responseType : Responses . ListAvatarCustomizationsResponse } ) ; } ; this . setAvatarItemAsViewed = function ( avatarTemplateIDs ) { return self . callOrChain ( { type : RequestType . SET_AVATAR_ITEM_AS_VIEWED , message : new RequestMessages . SetAvatarItemAsViewedMessage ( { avatar_template_id : avatarTemplateIDs } ) , responseType : Responses . SetAvatarItemAsViewdResponse } ) ; } ; /*\n     * INTERNAL STUFF\n     */ this . request = request . defaults ( { headers : { 'User-Agent' : 'Niantic App' , 'Accept' : '*/*' , 'Content-Type' : 'application/x-www-form-urlencoded' } , encoding : null } ) ; this . options = Object . assign ( { } , defaultOptions , options || { } ) ; this . authTicket = null ; this . rpcId = 2 ; this . lastHashingKeyIndex = 0 ; this . firstGetMapObjects = true ; this . lehmer = new Lehmer ( 16807 ) ; this . ptr8 = INITIAL_PTR8 ; /**\n     * Executes a request and returns a Promise or, if we are in batch mode, adds it to the\n     * list of batched requests and returns this (for chaining).\n     * @private\n     * @param {object} requestMessage - RPC request object\n     * @return {Promise|Client}\n     */ this . callOrChain = function ( requestMessage ) { if ( self . batchRequests ) { self . batchRequests . push ( requestMessage ) ; return self ; } else { return self . callRPC ( [ requestMessage ] ) ; } } ; /**\n     * Generates next rpc request id\n     * @private\n     * @return {Long}\n     */ this . getRequestID = function ( ) { return new Long ( self . rpcId ++ , this . lehmer . nextInt ( ) ) ; } ; /**\n     * Creates an RPC envelope with the given list of requests.\n     * @private\n     * @param {Object[]} requests - Array of requests to build\n     * @return {POGOProtos.Networking.Envelopes.RequestEnvelope}\n     */ this . buildEnvelope = function ( requests ) { var envelopeData = { status_code : 2 , request_id : self . getRequestID ( ) , ms_since_last_locationfix : 100 + Math . floor ( Math . random ( ) * 900 ) } ; if ( self . playerLatitude ) envelopeData . latitude = self . playerLatitude ; if ( self . playerLongitude ) envelopeData . longitude = self . playerLongitude ; if ( self . playerLocationAccuracy ) { envelopeData . accuracy = self . playerLocationAccuracy ; } else { const values = [ 5 , 5 , 5 , 5 , 10 , 10 , 10 , 30 , 30 , 50 , 65 ] ; values . unshift ( Math . floor ( Math . random ( ) * ( 80 - 66 ) ) + 66 ) ; envelopeData . accuracy = values [ Math . floor ( values . length * Math . random ( ) ) ] ; } if ( self . authTicket ) { envelopeData . auth_ticket = self . authTicket ; } else if ( ! self . options . authType || ! self . options . authToken ) { throw Error ( 'No auth info provided' ) ; } else { let unknown2 = 0 ; if ( self . options . authType === 'ptc' ) { const values = [ 2 , 8 , 21 , 21 , 21 , 28 , 37 , 56 , 59 , 59 , 59 ] ; unknown2 = values [ Math . floor ( values . length * Math . random ( ) ) ] ; } envelopeData . auth_info = { provider : self . options . authType , token : { contents : self . options . authToken , unknown2 : unknown2 , } } ; } if ( requests ) { self . emit ( 'request' , { request_id : envelopeData . request_id . toString ( ) , requests : requests . map ( r => ( { name : Utils . getEnumKeyByValue ( RequestType , r . type ) , type : r . type , data : r . message } ) ) } ) ; envelopeData . requests = requests . map ( r => { var requestData = { request_type : r . type } ; if ( r . message ) { requestData . request_message = r . message . encode ( ) ; } return requestData ; } ) ; } self . emit ( 'raw-request' , envelopeData ) ; return new POGOProtos . Networking . Envelopes . RequestEnvelope ( envelopeData ) ; } ; /**\n     * Constructs and adds a platform request to a request envelope.\n     * @private\n     * @param {RequestEnvelope} envelope - Request envelope\n     * @param {PlatformRequestType} requestType - Type of the platform request to add\n     * @param {Object} requestMessage - Pre-built but not encoded PlatformRequest protobuf message\n     * @return {RequestEnvelope} The envelope (for convenience only)\n     */ this . addPlatformRequestToEnvelope = function ( envelope , requestType , requestMessage ) { envelope . platform_requests . push ( new POGOProtos . Networking . Envelopes . RequestEnvelope . PlatformRequest ( { type : requestType , request_message : requestMessage . encode ( ) } ) ) ; return envelope ; } ; /**\n     * Determines whether the as of yet unknown platform request type 8 should be added\n     * to the envelope based on the given type of requests.\n     * @private\n     * @param {Object[]} requests - Array of request data\n     * @return {boolean}\n     */ this . needsPtr8 = function ( requests ) { // Single GET_PLAYER request always gets PTR8 if ( requests . length === 1 && requests [ 0 ] . type === RequestType . GET_PLAYER ) { return true ; } // Any GET_MAP_OBJECTS requests get PTR8 except the first one in the session if ( requests . some ( r => r . type === RequestType . GET_MAP_OBJECTS ) ) { if ( self . firstGetMapObjects ) { self . firstGetMapObjects = false ; return false ; } return true ; } return false ; } ; /**\n     * Creates an RPC envelope with the given list of requests and adds the encrypted signature,\n     * or adds the signature to an existing envelope.\n     * @private\n     * @param {Object[]} requests - Array of requests to build\n     * @param {RequestEnvelope} [envelope] - Pre-built request envelope to sign\n     * @return {Promise} - A Promise that will be resolved with a RequestEnvelope instance\n     */ this . buildSignedEnvelope = function ( requests , envelope ) { if ( ! envelope ) { try { envelope = self . buildEnvelope ( requests ) ; } catch ( e ) { throw new retry . StopError ( e ) ; } } if ( self . needsPtr8 ( requests ) ) { self . addPlatformRequestToEnvelope ( envelope , PlatformRequestType . UNKNOWN_PTR_8 , new PlatformRequestMessages . UnknownPtr8Request ( { message : self . ptr8 , } ) ) ; } let authTicket = envelope . auth_ticket ; if ( ! authTicket ) { authTicket = envelope . auth_info ; } if ( ! authTicket ) { // Can't sign before we have received an auth ticket return Promise . resolve ( envelope ) ; } if ( self . options . useHashingServer ) { let key = self . options . hashingKey ; if ( Array . isArray ( key ) ) { key = key [ self . lastHashingKeyIndex ] ; self . lastHashingKeyIndex = ( self . lastHashingKeyIndex + 1 ) % self . options . hashingKey . length ; } self . signatureBuilder . useHashingServer ( self . options . hashingServer + self . hashingVersion , key ) ; } self . signatureBuilder . setAuthTicket ( authTicket ) ; if ( typeof self . options . signatureInfo === 'function' ) { self . signatureBuilder . setFields ( self . options . signatureInfo ( envelope ) ) ; } else if ( self . options . signatureInfo ) { self . signatureBuilder . setFields ( self . options . signatureInfo ) ; } self . signatureBuilder . setLocation ( envelope . latitude , envelope . longitude , envelope . accuracy ) ; return retry ( ( ) => self . signatureBuilder . encryptAsync ( envelope . requests ) . catch ( err => { if ( err . name === 'HashServerError' && err . message === 'Request limited' ) { throw err ; } else { throw new retry . StopError ( err ) ; } } ) , { interval : 1000 , backoff : 2 , max_tries : 10 , args : envelope . requests , } ) . then ( sigEncrypted => self . addPlatformRequestToEnvelope ( envelope , PlatformRequestType . SEND_ENCRYPTED_SIGNATURE , new PlatformRequestMessages . SendEncryptedSignatureRequest ( { encrypted_signature : sigEncrypted } ) ) ) ; } ; /**\n     * Executes an RPC call with the given list of requests, retrying if necessary.\n     * @private\n     * @param {Object[]} requests - Array of requests to send\n     * @param {RequestEnvelope} [envelope] - Pre-built request envelope to use\n     * @return {Promise} - A Promise that will be resolved with the (list of) response messages,\n     *     or true if there aren't any\n     */ this . callRPC = function ( requests , envelope ) { // If the requests include a map objects request, make sure the minimum delay // since the last call has passed if ( requests . some ( r => r . type === RequestType . GET_MAP_OBJECTS ) ) { var now = new Date ( ) . getTime ( ) , delayNeeded = self . lastMapObjectsCall + self . options . mapObjectsMinDelay - now ; if ( delayNeeded > 0 && self . options . mapObjectsThrottling ) { return Promise . delay ( delayNeeded ) . then ( ( ) => self . callRPC ( requests , envelope ) ) ; } self . lastMapObjectsCall = now ; } if ( self . options . maxTries <= 1 ) return self . tryCallRPC ( requests , envelope ) ; return retry ( ( ) => self . tryCallRPC ( requests , envelope ) , { interval : 300 , backoff : 2 , max_tries : self . options . maxTries } ) ; } ; /**\n     * Handle redirection to new API endpoint and resend last request to new endpoint.\n     * @private\n     * @param {Object[]} requests - Array of requests\n     * @param {RequestEnvelope} signedEnvelope - Request envelope\n     * @param {ResponseEnvelope} responseEnvelope - Result from API call\n     * @return {Promise}\n     */ this . redirect = function ( requests , signedEnvelope , responseEnvelope ) { return new Promise ( ( resolve , reject ) => { if ( ! responseEnvelope . api_url ) { reject ( Error ( 'Fetching RPC endpoint failed, none supplied in response' ) ) ; return ; } self . endpoint = 'https://' + responseEnvelope . api_url + '/rpc' ; self . emit ( 'endpoint-response' , { status_code : responseEnvelope . status_code , request_id : responseEnvelope . request_id . toString ( ) , api_url : responseEnvelope . api_url } ) ; signedEnvelope . platform_requests = [ ] ; resolve ( self . callRPC ( requests , signedEnvelope ) ) ; } ) ; } ; /**\n     * Executes an RPC call with the given list of requests.\n     * @private\n     * @param {Object[]} requests - Array of requests to send\n     * @param {RequestEnvelope} [envelope] - Pre-built request envelope to use\n     * @return {Promise} - A Promise that will be resolved with the (list of) response messages,\n     *     or true if there aren't any\n     */ this . tryCallRPC = function ( requests , envelope ) { return self . buildSignedEnvelope ( requests , envelope ) . then ( signedEnvelope => new Promise ( ( resolve , reject ) => { self . request ( { method : 'POST' , url : self . endpoint , proxy : self . options . proxy , body : signedEnvelope . toBuffer ( ) } , ( err , response , body ) => { if ( err ) { reject ( Error ( err ) ) ; return ; } if ( response . statusCode !== 200 ) { if ( response . statusCode >= 400 && response . statusCode < 500 ) { /* These are permanent errors so throw StopError */ reject ( new retry . StopError ( ` ${ response . statusCode } ` ) ) ; } else { /* Anything else might be recoverable so throw regular Error */ reject ( Error ( ` ${ response . statusCode } ` ) ) ; } return ; } var responseEnvelope ; try { responseEnvelope = POGOProtos . Networking . Envelopes . ResponseEnvelope . decode ( body ) ; } catch ( e ) { self . emit ( 'parse-envelope-error' , body , e ) ; if ( e . decoded ) { responseEnvelope = e . decoded ; } else { reject ( new retry . StopError ( e ) ) ; return ; } } self . emit ( 'raw-response' , responseEnvelope ) ; if ( responseEnvelope . error ) { reject ( new retry . StopError ( responseEnvelope . error ) ) ; return ; } if ( responseEnvelope . auth_ticket ) self . authTicket = responseEnvelope . auth_ticket ; if ( responseEnvelope . status_code === 53 || ( responseEnvelope . status_code === 2 && self . endpoint === INITIAL_ENDPOINT ) ) { resolve ( self . redirect ( requests , signedEnvelope , responseEnvelope ) ) ; return ; } responseEnvelope . platform_returns . forEach ( platformReturn => { if ( platformReturn . type === PlatformRequestType . UNKNOWN_PTR_8 ) { const ptr8 = PlatformResponses . UnknownPtr8Response . decode ( platformReturn . response ) ; if ( ptr8 ) self . ptr8 = ptr8 . message ; } } ) ; /* Throttling, retry same request later */ if ( responseEnvelope . status_code === 52 ) { signedEnvelope . platform_requests = [ ] ; Promise . delay ( 2000 ) . then ( ( ) => { resolve ( self . callRPC ( requests , signedEnvelope ) ) ; } ) ; return ; } /* These codes indicate invalid input, no use in retrying so throw StopError */ if ( responseEnvelope . status_code === 3 || responseEnvelope . status_code === 51 || responseEnvelope . status_code >= 100 ) { reject ( new retry . StopError ( ` ${ responseEnvelope . status_code } ` ) ) ; } /* These can be temporary so throw regular Error */ if ( responseEnvelope . status_code !== 2 && responseEnvelope . status_code !== 1 ) { reject ( Error ( ` ${ responseEnvelope . status_code } ` ) ) ; return ; } var responses = [ ] ; if ( requests ) { if ( requests . length !== responseEnvelope . returns . length ) { reject ( Error ( 'Request count does not match response count' ) ) ; return ; } for ( var i = 0 ; i < responseEnvelope . returns . length ; i ++ ) { if ( ! requests [ i ] . responseType ) continue ; var responseMessage ; try { responseMessage = requests [ i ] . responseType . decode ( responseEnvelope . returns [ i ] ) ; } catch ( e ) { self . emit ( 'parse-response-error' , responseEnvelope . returns [ i ] . toBuffer ( ) , e ) ; reject ( new retry . StopError ( e ) ) ; return ; } if ( self . options . includeRequestTypeInResponse ) { // eslint-disable-next-line no-underscore-dangle responseMessage . _requestType = requests [ i ] . type ; } responses . push ( responseMessage ) ; } } self . emit ( 'response' , { status_code : responseEnvelope . status_code , request_id : responseEnvelope . request_id . toString ( ) , responses : responses . map ( ( r , h ) => ( { name : Utils . getEnumKeyByValue ( RequestType , requests [ h ] . type ) , type : requests [ h ] . type , data : r } ) ) } ) ; if ( self . options . automaticLongConversion ) { responses = Utils . convertLongs ( responses ) ; } if ( ! responses . length ) resolve ( true ) ; else if ( responses . length === 1 ) resolve ( responses [ 0 ] ) ; else resolve ( responses ) ; } ) ; } ) ) ; } ; /**\n     * Processes the data received from the downloadSettings API call during init().\n     * @private\n     * @param {Object} settingsResponse - Response from API call\n     * @return {Object} response - Unomdified response (to send back to Promise)\n     */ this . processSettingsResponse = function ( settingsResponse ) { // Extract the minimum delay of getMapObjects() if ( settingsResponse && ! settingsResponse . error && settingsResponse . settings && settingsResponse . settings . map_settings && settingsResponse . settings . map_settings . get_map_objects_min_refresh_seconds ) { self . setOption ( 'mapObjectsMinDelay' , settingsResponse . settings . map_settings . get_map_objects_min_refresh_seconds * 1000 ) ; } return settingsResponse ; } ; /**\n     * Makes an initial call to the hashing server to verify API version.\n     * @private\n     * @return {Promise}\n     */ this . initializeHashingServer = function ( ) { if ( ! self . options . hashingServer ) throw new Error ( 'Hashing server enabled without host' ) ; if ( ! self . options . hashingKey ) throw new Error ( 'Hashing server enabled without key' ) ; if ( self . options . hashingServer . slice ( - 1 ) !== '/' ) { self . setOption ( 'hashingServer' , self . options . hashingServer + '/' ) ; } return Signature . versions . getHashingEndpoint ( self . options . hashingServer , self . options . version ) . then ( version => { self . hashingVersion = version ; } ) ; } ; /*\n     * DEPRECATED METHODS\n     */ /**\n     * Sets the authType and authToken options.\n     * @deprecated Use options object or setOption() instead\n     * @param {string} authType\n     * @param {string} authToken\n     */ this . setAuthInfo = function ( authType , authToken ) { self . setOption ( 'authType' , authType ) ; self . setOption ( 'authToken' , authToken ) ; } ; /**\n     * Sets the includeRequestTypeInResponse option.\n     * @deprecated Use options object or setOption() instead\n     * @param {bool} includeRequestTypeInResponse\n     */ this . setIncludeRequestTypeInResponse = function ( includeRequestTypeInResponse ) { self . setOption ( 'includeRequestTypeInResponse' , includeRequestTypeInResponse ) ; } ; /**\n     * Sets the maxTries option.\n     * @deprecated Use options object or setOption() instead\n     * @param {integer} maxTries\n     */ this . setMaxTries = function ( maxTries ) { self . setOption ( 'maxTries' , maxTries ) ; } ; /**\n     * Sets the proxy option.\n     * @deprecated Use options object or setOption() instead\n     * @param {string} proxy\n     */ this . setProxy = function ( proxy ) { self . setOption ( 'proxy' , proxy ) ; } ; /**\n     * Sets the mapObjectsThrottling option.\n     * @deprecated Use options object or setOption() instead\n     * @param {boolean} enable\n     */ this . setMapObjectsThrottlingEnabled = function ( enable ) { self . setOption ( 'mapObjectsThrottling' , enable ) ; } ; /**\n     * Sets a callback to be called for any envelope or request just before it is sent to\n     * the server (mostly for debugging purposes).\n     * @deprecated Use the raw-request event instead\n     * @param {function} callback - function to call on requests\n     */ this . setRequestCallback = function ( callback ) { self . on ( 'raw-request' , callback ) ; } ; /**\n     * Sets a callback to be called for any envelope or response just after it has been\n     * received from the server (mostly for debugging purposes).\n     * @deprecated Use the raw-response event instead\n     * @param {function} callback - function to call on responses\n     */ this . setResponseCallback = function ( callback ) { self . on ( 'raw-response' , callback ) ; } ; /**\n     * Sets the automaticLongConversion option.\n     * @deprecated Use options object or setOption() instead\n     * @param {boolean} enable\n     */ this . setAutomaticLongConversionEnabled = function ( enable ) { if ( typeof enable !== 'boolean' ) return ; self . setOption ( 'automaticLongConversion' , enable ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pokémon Trainer Club login client . [CODESPLIT] function PTCLogin ( ) { if ( ! ( this instanceof PTCLogin ) ) { return new PTCLogin ( ) ; } const self = this ; self . request = request . defaults ( { headers : { 'User-Agent' : 'pokemongo/1 CFNetwork/808.2.16 Darwin/16.3.0' } , jar : request . jar ( ) } ) ; /**\n     * Performs the PTC login process and returns a Promise that will be resolved with the\n     * auth token.\n     * @param {string} username\n     * @param {string} password\n     * @return {Promise}\n     */ this . login = function ( username , password ) { return self . getSession ( ) . then ( sessionData => self . getTicket ( sessionData , username , password ) ) . then ( self . getToken ) ; } ; /**\n     * Starts a session on the PTC website and returns a Promise that will be resolved with\n     * the session parameters lt and execution.\n     * @private\n     * @return {Promise}\n     */ this . getSession = function ( ) { return new Promise ( ( resolve , reject ) => { self . request ( { method : 'GET' , url : 'https://sso.pokemon.com/sso/login' , qs : { service : 'https://sso.pokemon.com/sso/oauth2.0/callbackAuthorize' } } , ( err , response , body ) => { if ( err ) { reject ( Error ( err ) ) ; return ; } if ( response . statusCode !== 200 ) { reject ( Error ( ` ${ response . statusCode } ` ) ) ; return ; } var sessionResponse = null ; try { sessionResponse = JSON . parse ( body ) ; } catch ( e ) { reject ( Error ( 'Unexpected response received from PTC login' ) ) ; return ; } if ( ! sessionResponse || ! sessionResponse . lt && ! sessionResponse . execution ) { reject ( Error ( 'No session data received from PTC login' ) ) ; return ; } resolve ( { lt : sessionResponse . lt , execution : sessionResponse . execution } ) ; } ) ; } ) ; } ; /**\n     * Performs the actual login on the PTC website and returns a Promise that will be resolved\n     * with a login ticket.\n     * @private\n     * @param {Object} sessionData - Session parameters from the {@link #getSession} method\n     * @param {string} username\n     * @param {string} password\n     * @return {Promise}\n     */ this . getTicket = function ( sessionData , username , password ) { return new Promise ( ( resolve , reject ) => { self . request ( { method : 'POST' , url : 'https://sso.pokemon.com/sso/login' , qs : { service : 'https://sso.pokemon.com/sso/oauth2.0/callbackAuthorize' } , form : { 'lt' : sessionData . lt , 'execution' : sessionData . execution , '_eventId' : 'submit' , 'username' : username , 'password' : password } } , ( err , response ) => { if ( err ) { reject ( Error ( err ) ) ; return ; } if ( response . statusCode !== 302 || ! response . headers . location ) { reject ( Error ( 'Invalid response received from PTC login' ) ) ; return ; } var ticketURL = url . parse ( response . headers . location , true ) ; if ( ! ticketURL || ! ticketURL . query . ticket ) { reject ( Error ( 'No login ticket received from PTC login' ) ) ; return ; } resolve ( ticketURL . query . ticket ) ; } ) ; } ) ; } ; /**\n     * Takes the login ticket from the PTC website and turns it into an auth token.\n     * @private\n     * @param {string} ticket - Login ticket from the {@link #getTicket} method\n     * @return {Promise}\n     */ this . getToken = function ( ticket ) { return new Promise ( ( resolve , reject ) => { self . request ( { method : 'POST' , url : 'https://sso.pokemon.com/sso/oauth2.0/accessToken' , form : { client_id : 'mobile-app_pokemon-go' , client_secret : 'w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR' , redirect_uri : 'https://www.nianticlabs.com/pokemongo/error' , grant_type : 'refresh_token' , code : ticket } } , ( err , response , body ) => { if ( err ) { reject ( Error ( err ) ) ; return ; } if ( response . statusCode !== 200 ) { reject ( Error ( ` ${ response . statusCode } ` ) ) ; return ; } var qs = querystring . parse ( body ) ; if ( ! qs || ! qs . access_token ) { reject ( Error ( 'Invalid data received from PTC OAuth' ) ) ; return ; } resolve ( qs . access_token ) ; } ) ; } ) ; } ; /**\n     * Sets a proxy address to use for PTC logins.\n     * @param {string} proxy\n     */ this . setProxy = function ( proxy ) { self . request = self . request . defaults ( { proxy : proxy } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Google login client . [CODESPLIT] function GoogleLogin ( ) { if ( ! ( this instanceof GoogleLogin ) ) { return new GoogleLogin ( ) ; } const self = this ; /**\n     * Based of https://github.com/tejado/pgoapi/blob/master/pgoapi/auth_google.py#L33\n     */ const GOOGLE_LOGIN_ANDROID_ID = '9774d56d682e549c' ; const GOOGLE_LOGIN_SERVICE = 'audience:server:client_id:848232511240-7so421jotr2609rmqakceuu1luuq0ptb.apps.googleusercontent.com' ; const GOOGLE_LOGIN_APP = 'com.nianticlabs.pokemongo' ; const GOOGLE_LOGIN_CLIENT_SIG = '321187995bc7cdc2b5fc91b11a96e2baa8602c62' ; /**\n     * Sets a proxy address to use for logins.\n     * @param {string} proxy\n     */ this . setProxy = function ( proxy ) { google . setProxy ( proxy ) ; } ; /**\n     * Performs the Google Login using Android Device and returns a Promise that will be resolved\n     * with the auth token.\n     * @param {string} username\n     * @param {string} password\n     * @return {Promise}\n     */ this . login = function ( username , password ) { return self . getMasterToken ( username , password ) . then ( loginData => self . getToken ( username , loginData ) ) . then ( authData => authData . Auth ) ; } ; /**\n     * Performs the Google login by skipping the password step and starting with the Master Token\n     * instead. Returns a Promise that will be resolved with the auth token.\n     * @param {string} username\n     * @param {string} token\n     * @return {Promise}\n     */ this . loginWithToken = function ( username , token ) { var loginData = { androidId : GOOGLE_LOGIN_ANDROID_ID , masterToken : token } ; return self . getToken ( username , loginData ) . then ( authData => authData . Auth ) ; } ; /**\n     * Initialize Google Login\n     * @param {string} username\n     * @param {string} password\n     * @return {Promise}\n     */ this . getMasterToken = function ( username , password ) { return new Promise ( ( resolve , reject ) => { google . login ( username , password , GOOGLE_LOGIN_ANDROID_ID , ( err , data ) => { if ( err ) { if ( err . response . statusCode === 403 ) { reject ( Error ( 'Received code 403 from Google login. This could be because your account has ' + '2-Step-Verification enabled. If that is the case, you need to generate an ' + 'App Password and use that instead of your regular password: ' + 'https://security.google.com/settings/security/apppasswords' ) ) ; } else { reject ( Error ( err . response . statusCode + ': ' + err . response . statusMessage ) ) ; } return ; } resolve ( data ) ; } ) ; } ) ; } ; /**\n     * Finalizes oAuth request using master token and resolved with the auth data\n     * @private\n     * @param {string} username\n     * @param {string} loginData\n     * @return {Promise}\n     */ this . getToken = function ( username , loginData ) { return new Promise ( ( resolve , reject ) => { google . oauth ( username , loginData . masterToken , loginData . androidId , GOOGLE_LOGIN_SERVICE , GOOGLE_LOGIN_APP , GOOGLE_LOGIN_CLIENT_SIG , ( err , data ) => { if ( err ) { reject ( Error ( err . response . statusCode + ': ' + err . response . statusMessage ) ) ; return ; } resolve ( data ) ; } ) ; } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides cell IDs of nearby cells based on the given coords and radius [CODESPLIT] function ( lat , lng , radius , level ) { if ( typeof radius === 'undefined' ) radius = 3 ; if ( typeof level === 'undefined' ) level = 15 ; /* eslint-disable new-cap */ var origin = s2 . S2Cell . FromLatLng ( { lat : lat , lng : lng } , level ) ; var cells = [ ] ; cells . push ( origin . toHilbertQuadkey ( ) ) ; // middle block for ( var i = 1 ; i < radius ; i ++ ) { // cross in middle cells . push ( s2 . S2Cell . FromFaceIJ ( origin . face , [ origin . ij [ 0 ] , origin . ij [ 1 ] - i ] , origin . level ) . toHilbertQuadkey ( ) ) ; cells . push ( s2 . S2Cell . FromFaceIJ ( origin . face , [ origin . ij [ 0 ] , origin . ij [ 1 ] + i ] , origin . level ) . toHilbertQuadkey ( ) ) ; cells . push ( s2 . S2Cell . FromFaceIJ ( origin . face , [ origin . ij [ 0 ] - i , origin . ij [ 1 ] ] , origin . level ) . toHilbertQuadkey ( ) ) ; cells . push ( s2 . S2Cell . FromFaceIJ ( origin . face , [ origin . ij [ 0 ] + i , origin . ij [ 1 ] ] , origin . level ) . toHilbertQuadkey ( ) ) ; for ( var j = 1 ; j < radius ; j ++ ) { cells . push ( s2 . S2Cell . FromFaceIJ ( origin . face , [ origin . ij [ 0 ] - j , origin . ij [ 1 ] - i ] , origin . level ) . toHilbertQuadkey ( ) ) ; cells . push ( s2 . S2Cell . FromFaceIJ ( origin . face , [ origin . ij [ 0 ] + j , origin . ij [ 1 ] - i ] , origin . level ) . toHilbertQuadkey ( ) ) ; cells . push ( s2 . S2Cell . FromFaceIJ ( origin . face , [ origin . ij [ 0 ] - j , origin . ij [ 1 ] + i ] , origin . level ) . toHilbertQuadkey ( ) ) ; cells . push ( s2 . S2Cell . FromFaceIJ ( origin . face , [ origin . ij [ 0 ] + j , origin . ij [ 1 ] + i ] , origin . level ) . toHilbertQuadkey ( ) ) ; } } /* eslint-enable new-cap */ return cells . map ( s2 . toId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a getInventory () response and separates it into pokemon items candies player data eggs quests and pokedex . [CODESPLIT] function ( inventory ) { if ( ! inventory || ! inventory . success || ! inventory . inventory_delta || ! inventory . inventory_delta . inventory_items ) { return { } ; } var ret = { pokemon : [ ] , removed_pokemon : [ ] , items : [ ] , pokedex : [ ] , player : null , currency : [ ] , camera : null , inventory_upgrades : [ ] , applied_items : [ ] , egg_incubators : [ ] , candies : [ ] , quests : [ ] } ; inventory . inventory_delta . inventory_items . forEach ( item => { if ( item . inventory_item_data ) { const itemdata = item . inventory_item_data ; if ( itemdata . pokemon_data ) { ret . pokemon . push ( itemdata . pokemon_data ) ; } if ( itemdata . item ) { ret . items . push ( itemdata . item ) ; } if ( itemdata . pokedex_entry ) { ret . pokedex . push ( itemdata . pokedex_entry ) ; } if ( itemdata . player_stats ) { ret . player = itemdata . player_stats ; } if ( itemdata . player_currency ) { ret . currency . push ( itemdata . player_currency ) ; } if ( itemdata . player_camera ) { ret . camera = itemdata . player_camera ; } if ( itemdata . inventory_upgrades ) { ret . inventory_upgrades . push ( itemdata . inventory_upgrades ) ; } if ( itemdata . applied_items ) { ret . applied_items . push ( itemdata . applied_items ) ; } if ( itemdata . egg_incubators ) { const incubators = itemdata . egg_incubators . egg_incubator || [ ] ; ret . egg_incubators = ret . egg_incubators . concat ( incubators ) ; } if ( itemdata . candy ) { ret . candies . push ( itemdata . candy ) ; } if ( itemdata . quest ) { ret . quests . push ( itemdata . quest ) ; } } if ( item . deleted_item && item . deleted_item . pokemon_id ) { ret . removed_pokemon . push ( item . deleted_item . pokemon_id ) ; } } ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a downloadItemTemplates () response and separates it into the individual settings objects . [CODESPLIT] function ( templates ) { if ( ! templates || ! templates . success || ! templates . item_templates ) return { } ; var ret = { pokemon_settings : [ ] , item_settings : [ ] , move_settings : [ ] , move_sequence_settings : [ ] , type_effective_settings : [ ] , badge_settings : [ ] , camera_settings : null , player_level_settings : null , gym_level_settings : null , battle_settings : null , encounter_settings : null , iap_item_display : [ ] , iap_settings : null , pokemon_upgrade_settings : null , equipped_badge_settings : null } ; templates . item_templates . forEach ( template => { if ( template . pokemon_settings ) { ret . pokemon_settings . push ( template . pokemon_settings ) ; } if ( template . item_settings ) { ret . item_settings . push ( template . item_settings ) ; } if ( template . move_settings ) { ret . move_settings . push ( template . move_settings ) ; } if ( template . move_sequence_settings ) { ret . move_sequence_settings . push ( template . move_sequence_settings . sequence ) ; } if ( template . type_effective ) { ret . type_effective_settings . push ( template . type_effective ) ; } if ( template . badge_settings ) { ret . badge_settings . push ( template . badge_settings ) ; } if ( template . camera ) { ret . camera_settings = template . camera ; } if ( template . player_level ) { ret . player_level_settings = template . player_level ; } if ( template . gym_level ) { ret . gym_level_settings = template . gym_level ; } if ( template . battle_settings ) { ret . battle_settings = template . battle_settings ; } if ( template . encounter_settings ) { ret . encounter_settings = template . encounter_settings ; } if ( template . iap_item_display ) { ret . iap_item_display . push ( template . iap_item_display ) ; } if ( template . iap_settings ) { ret . iap_settings = template . iap_settings ; } if ( template . pokemon_upgrades ) { ret . pokemon_upgrade_settings = template . pokemon_upgrades ; } if ( template . equipped_badges ) { ret . equipped_badge_settings = template . equipped_badges ; } } ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method that finds the name of the key for a given enum value and makes it look a little nicer . [CODESPLIT] function ( enumObj , val ) { for ( var key of Object . keys ( enumObj ) ) { if ( enumObj [ key ] === val ) { return key . split ( '_' ) . map ( word => word . charAt ( 0 ) . toUpperCase ( ) + word . slice ( 1 ) . toLowerCase ( ) ) . join ( ' ' ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method to get the Individual Values from Pokémon [CODESPLIT] function ( pokemon , decimals ) { if ( typeof decimals === 'undefined' ) decimals = - 1 ; decimals = Math . min ( decimals , 20 ) ; var att = pokemon . individual_attack , def = pokemon . individual_defense , stam = pokemon . individual_stamina ; var unroundedPercentage = ( att + def + stam ) / 45 * 100 ; var percent = decimals < 0 ? unroundedPercentage : + unroundedPercentage . toFixed ( decimals ) ; return { att : att , def : def , stam : stam , percent : percent } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method to convert all Long . js objects to integers or strings [CODESPLIT] function ( object ) { if ( ! object || typeof object !== 'object' ) return object ; if ( object instanceof ByteBuffer ) return object ; if ( Long . isLong ( object ) ) { return object . lessThanOrEqual ( Number . MAX_SAFE_INTEGER ) && object . greaterThanOrEqual ( Number . MIN_SAFE_INTEGER ) ? object . toNumber ( ) : object . toString ( ) ; } for ( var i in object ) { if ( object . hasOwnProperty ( i ) ) { if ( Long . isLong ( object [ i ] ) ) { object [ i ] = object [ i ] . lessThanOrEqual ( Number . MAX_SAFE_INTEGER ) && object [ i ] . greaterThanOrEqual ( Number . MIN_SAFE_INTEGER ) ? object [ i ] . toNumber ( ) : object [ i ] . toString ( ) ; } else if ( typeof object [ i ] === 'object' ) { object [ i ] = this . convertLongs ( object [ i ] ) ; } } } return object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lehmer random module used by the app to generate request ids [CODESPLIT] function Random ( seed ) { this . multiplier = 16807 ; this . modulus = 0x7fffffff ; this . seed = seed ; this . mq = Math . floor ( this . modulus / this . multiplier ) ; this . mr = this . modulus % this . multiplier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes an ISO time and returns a string representing how long ago the date represents . [CODESPLIT] function prettyDate ( time ) { /*var date = new Date((time || \"\")*/ var diff = ( ( ( new Date ( ) ) . getTime ( ) - time ) / 1000 ) , day_diff = Math . floor ( diff / 86400 ) ; if ( isNaN ( day_diff ) || day_diff < 0 || day_diff >= 31 ) return ; return day_diff == 0 && ( diff < 60 && \"just now\" || diff < 120 && \"1 minute ago\" || diff < 3600 && Math . floor ( diff / 60 ) + \" minutes ago\" || diff < 7200 && \"1 hour ago\" || diff < 86400 && Math . floor ( diff / 3600 ) + \" hours ago\" ) || day_diff == 1 && \"Yesterday\" || day_diff < 7 && day_diff + \" days ago\" || day_diff < 31 && Math . ceil ( day_diff / 7 ) + \" weeks ago\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ALERT CLASS DEFINITION ====================== [CODESPLIT] function ( content , options ) { this . settings = $ . extend ( { } , $ . fn . alert . defaults , options ) this . $element = $ ( content ) . delegate ( this . settings . selector , 'click' , this . close ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A little logger for this library to use internally . Basically just a wrapper around console . log with support for feature - detection . [CODESPLIT] function LoggerFactory ( options ) { options = options || { prefix : true } ; // If `console.log` is not accessible, `log` is a noop. if ( typeof console !== 'object' || typeof console . log !== 'function' || typeof console . log . bind !== 'function' ) { return function noop ( ) { } ; } return function log ( ) { var args = Array . prototype . slice . call ( arguments ) ; // All logs are disabled when `io.sails.environment = 'production'`. if ( io . sails . environment === 'production' ) return ; // Add prefix to log messages (unless disabled) var PREFIX = '' ; if ( options . prefix ) { args . unshift ( PREFIX ) ; } // Call wrapped logger console . log . bind ( console ) . apply ( this , args ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "What is the requestQueue ? [CODESPLIT] function runRequestQueue ( socket ) { var queue = socket . requestQueue ; if ( ! queue ) return ; for ( var i in queue ) { // Double-check that `queue[i]` will not // inadvertently discover extra properties attached to the Object // and/or Array prototype by other libraries/frameworks/tools. // (e.g. Ember does this. See https://github.com/balderdashy/sails.io.js/pull/5) var isSafeToDereference = ( { } ) . hasOwnProperty . call ( queue , i ) ; if ( isSafeToDereference ) { // Get the arguments that were originally made to the \"request\" method var requestArgs = queue [ i ] ; // Call the request method again in the context of the socket, with the original args socket . request . apply ( socket , requestArgs ) ; } } // Now empty the queue to remove it as a source of additional complexity. socket . requestQueue = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a JSONP request . [CODESPLIT] function jsonp ( opts , cb ) { opts = opts || { } ; if ( typeof window === 'undefined' ) { // FUTURE: refactor node usage to live in here return cb ( ) ; } var scriptEl = document . createElement ( 'script' ) ; window . _sailsIoJSConnect = function ( response ) { // In rare circumstances our script may have been vaporised. // Remove it, but only if it still exists // https://github.com/balderdashy/sails.io.js/issues/92 if ( scriptEl && scriptEl . parentNode ) { scriptEl . parentNode . removeChild ( scriptEl ) ; } cb ( response ) ; } ; scriptEl . src = opts . url ; document . getElementsByTagName ( 'head' ) [ 0 ] . appendChild ( scriptEl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "██╗███████╗ ██████╗ ███╗ ██╗ ██╗ ██╗███████╗██████╗ ███████╗ ██████╗ ██████╗██╗ ██╗███████╗████████╗ ██║██╔════╝██╔═══██╗████╗ ██║ ██║ ██║██╔════╝██╔══██╗██╔════╝██╔═══██╗██╔════╝██║ ██╔╝██╔════╝╚══██╔══╝ ██║███████╗██║ ██║██╔██╗ ██║█████╗██║ █╗ ██║█████╗ ██████╔╝███████╗██║ ██║██║ █████╔╝ █████╗ ██║ ██ ██║╚════██║██║ ██║██║╚██╗██║╚════╝██║███╗██║██╔══╝ ██╔══██╗╚════██║██║ ██║██║ ██╔═██╗ ██╔══╝ ██║ ╚█████╔╝███████║╚██████╔╝██║ ╚████║ ╚███╔███╔╝███████╗██████╔╝███████║╚██████╔╝╚██████╗██║ ██╗███████╗ ██║ ╚════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚══╝╚══╝ ╚══════╝╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═╝ ██████╗ ███████╗███████╗██████╗ ██████╗ ███╗ ██╗███████╗███████╗ ██╗ ██╗██╗ ██╗██████╗ ██╗ ██╔══██╗██╔════╝██╔════╝██╔══██╗██╔═══██╗████╗ ██║██╔════╝██╔════╝ ██╔╝ ██║██║ ██║██╔══██╗╚██╗ ██████╔╝█████╗ ███████╗██████╔╝██║ ██║██╔██╗ ██║███████╗█████╗ ██║ ██║██║ █╗ ██║██████╔╝ ██║ ██╔══██╗██╔══╝ ╚════██║██╔═══╝ ██║ ██║██║╚██╗██║╚════██║██╔══╝ ██║ ██ ██║██║███╗██║██╔══██╗ ██║ ██║ ██║███████╗███████║██║ ╚██████╔╝██║ ╚████║███████║███████╗ ╚██╗╚█████╔╝╚███╔███╔╝██║ ██║██╔╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝╚══════╝ ╚═╝ ╚════╝ ╚══╝╚══╝ ╚═╝ ╚═╝╚═╝ The JWR ( JSON WebSocket Response ) received from a Sails server . [CODESPLIT] function JWR ( responseCtx ) { this . body = responseCtx . body ; this . headers = responseCtx . headers || { } ; this . statusCode = ( typeof responseCtx . statusCode === 'undefined' ) ? 200 : responseCtx . statusCode ; // FUTURE: Replace this typeof short-circuit with an assertion (statusCode should always be set) if ( this . statusCode < 200 || this . statusCode >= 400 ) { // Determine the appropriate error message. var msg ; if ( this . statusCode === 0 ) { msg = 'The socket request failed.' ; } else { msg = 'Server responded with a ' + this . statusCode + ' status code' ; msg += ':\\n```\\n' + JSON . stringify ( this . body , null , 2 ) + '\\n```' ; // (^^Note that we should always be able to rely on socket.io to give us // non-circular data here, so we don't have to worry about wrapping the // above in a try...catch) } // Now build and attach Error instance. this . error = new Error ( msg ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "███████╗███╗ ███╗██╗████████╗███████╗██████╗ ██████╗ ███╗ ███╗ ██╗██╗ ██╔════╝████╗ ████║██║╚══██╔══╝██╔════╝██╔══██╗██╔═══██╗████╗ ████║██╔╝╚██╗ █████╗ ██╔████╔██║██║ ██║ █████╗ ██████╔╝██║ ██║██╔████╔██║██║ ██║ ██╔══╝ ██║╚██╔╝██║██║ ██║ ██╔══╝ ██╔══██╗██║ ██║██║╚██╔╝██║██║ ██║ ███████╗███████╗██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║╚██████╔╝██║ ╚═╝ ██║╚██╗██╔╝ ╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ [CODESPLIT] function _emitFrom ( socket , requestCtx ) { if ( ! socket . _raw ) { throw new Error ( 'Failed to emit from socket- raw SIO socket is missing.' ) ; } // Since callback is embedded in requestCtx, // retrieve it and delete the key before continuing. var cb = requestCtx . cb ; delete requestCtx . cb ; // Name of the appropriate socket.io listener on the server // ( === the request method or \"verb\", e.g. 'get', 'post', 'put', etc. ) var sailsEndpoint = requestCtx . method ; socket . _raw . emit ( sailsEndpoint , requestCtx , function serverResponded ( responseCtx ) { // Send back (emulatedHTTPBody, jsonWebSocketResponse) if ( cb ) { cb ( responseCtx . body , new JWR ( responseCtx ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "███████╗ █████╗ ██╗██╗ ███████╗███████╗ ██████╗ ██████╗██╗ ██╗███████╗████████╗ ██╔════╝██╔══██╗██║██║ ██╔════╝██╔════╝██╔═══██╗██╔════╝██║ ██╔╝██╔════╝╚══██╔══╝ ███████╗███████║██║██║ ███████╗███████╗██║ ██║██║ █████╔╝ █████╗ ██║ ╚════██║██╔══██║██║██║ ╚════██║╚════██║██║ ██║██║ ██╔═██╗ ██╔══╝ ██║ ███████║██║ ██║██║███████╗███████║███████║╚██████╔╝╚██████╗██║ ██╗███████╗ ██║ ╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═╝ SailsSocket [CODESPLIT] function SailsSocket ( opts ) { var self = this ; opts = opts || { } ; // Initialize private properties self . _isConnecting = false ; self . _mightBeAboutToAutoConnect = false ; // Set up connection options so that they can only be changed when socket is disconnected. var _opts = { } ; SOCKET_OPTIONS . forEach ( function ( option ) { // Okay to change global headers while socket is connected if ( option == 'headers' ) { return ; } Object . defineProperty ( self , option , { get : function ( ) { if ( option == 'url' ) { return _opts [ option ] || ( self . _raw && self . _raw . io && self . _raw . io . uri ) ; } return _opts [ option ] ; } , set : function ( value ) { // Don't allow value to be changed while socket is connected if ( self . isConnected ( ) && io . sails . strict !== false && value != _opts [ option ] ) { throw new Error ( 'Cannot change value of `' + option + '` while socket is connected.' ) ; } // If socket is attempting to reconnect, stop it. if ( self . _raw && self . _raw . io && self . _raw . io . reconnecting && ! self . _raw . io . skipReconnect ) { self . _raw . io . skipReconnect = true ; consolog ( 'Stopping reconnect; use .reconnect() to connect socket after changing options.' ) ; } _opts [ option ] = value ; } } ) ; } ) ; // Absorb opts into SailsSocket instance // See http://sailsjs.com/documentation/reference/web-sockets/socket-client/sails-socket/properties // for description of options SOCKET_OPTIONS . forEach ( function ( option ) { self [ option ] = opts [ option ] ; } ) ; // Set up \"eventQueue\" to hold event handlers which have not been set on the actual raw socket yet. self . eventQueue = { } ; // Listen for special `parseError` event sent from sockets hook on the backend // if an error occurs but a valid callback was not received from the client // (i.e. so the server had no other way to send back the error information) self . on ( 'sails:parseError' , function ( err ) { consolog ( 'Sails encountered an error parsing a socket message sent from this client, and did not have access to a callback function to respond with.' ) ; consolog ( 'Error details:' , err ) ; } ) ; // FUTURE: // Listen for a special private message on any connected that allows the server // to set the environment (giving us 100% certainty that we guessed right) // However, note that the `console.log`s called before and after connection // are still forced to rely on our existing heuristics (to disable, tack #production // onto the URL used to fetch this file.) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "~∞%° [CODESPLIT] function _afterReplacingAllCollections ( err ) { if ( err ) { return done ( err ) ; } //  ╔═╗╔═╗╔╦╗╔═╗╦═╗  ┬ ┬┌─┐┌┬┐┌─┐┌┬┐┌─┐  ┌─┐┌─┐┬  ┬  ┌┐ ┌─┐┌─┐┬┌─ //  ╠═╣╠╣  ║ ║╣ ╠╦╝  │ │├─┘ ││├─┤ │ ├┤   │  ├─┤│  │  ├┴┐├─┤│  ├┴┐ //  ╩ ╩╚   ╩ ╚═╝╩╚═  └─┘┴  ─┴┘┴ ┴ ┴ └─┘  └─┘┴ ┴┴─┘┴─┘└─┘┴ ┴└─┘┴ ┴ // Run \"after\" lifecycle callback AGAIN and AGAIN- once for each record. // ============================================================ // FUTURE: look into this // (we probably shouldn't call this again and again-- // plus what if `fetch` is not in use and you want to use an LC? // Then again- the right answer isn't immediately clear.  And it // probably not worth breaking compatibility until we have a much // better solution) // ============================================================ async . each ( transformedRecords , function _eachRecord ( record , next ) { // If the `skipAllLifecycleCallbacks` meta flag was set, don't run any of // the methods. if ( _ . has ( query . meta , 'skipAllLifecycleCallbacks' ) && query . meta . skipAllLifecycleCallbacks ) { return next ( ) ; } // Skip \"after\" lifecycle callback, if not defined. if ( ! _ . has ( WLModel . _callbacks , 'afterUpdate' ) ) { return next ( ) ; } // Otherwise run it. WLModel . _callbacks . afterUpdate ( record , function _afterMaybeRunningAfterUpdateForThisRecord ( err ) { if ( err ) { return next ( err ) ; } return next ( ) ; } ) ; } , // ~∞%° function _afterIteratingOverRecords ( err ) { if ( err ) { return done ( err ) ; } return done ( undefined , transformedRecords ) ; } ) ; //</ async.each() -- ran \"after\" lifecycle callback on each record > }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "constructor [CODESPLIT] function _constructor ( host , port , schema , adapter , user , password , database , identity ) { if ( _self . cleanArguments ( arguments ) . length == 1 && typeof arguments [ 0 ] === 'object' ) { _self . host = arguments [ 0 ] . host ; _self . port = arguments [ 0 ] . port ; _self . schema = arguments [ 0 ] . schema ; _self . adapter = arguments [ 0 ] . adapter ; _self . user = arguments [ 0 ] . user ; _self . password = arguments [ 0 ] . password ; _self . database = arguments [ 0 ] . database ; _self . identity = arguments [ 0 ] . identity ; _self . validate ( ) ; } else { _self . host = host ; _self . port = port ; _self . schema = schema ; _self . adapter = adapter ; _self . user = user ; _self . password = password ; _self . database = database ; if ( identity ) _self . identity = identity ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "~∞%° [CODESPLIT] function _beginBatchMaybe ( next ) { // 0   => 15 // 15  => 15 // 30  => 15 // 45  => 5 // 50 var numRecordsLeftUntilAbsLimit = query . criteria . limit - ( i * BATCH_SIZE ) ; var limitForThisBatch = Math . min ( numRecordsLeftUntilAbsLimit , BATCH_SIZE ) ; var skipForThisBatch = query . criteria . skip + ( i * BATCH_SIZE ) ; //                     |_initial offset    +  |_relative offset from end of previous batch // If we've exceeded the absolute limit, then we go ahead and stop. if ( limitForThisBatch <= 0 ) { reachedLastBatch = true ; return next ( ) ; } //-• // Build the criteria + deferred object to do a `.find()` for this batch. var criteriaForThisBatch = { skip : skipForThisBatch , limit : limitForThisBatch , sort : query . criteria . sort , select : query . criteria . select , omit : query . criteria . omit , where : query . criteria . where } ; // console.log('---iterating---'); // console.log('i:',i); // console.log('   BATCH_SIZE:',BATCH_SIZE); // console.log('   query.criteria.limit:',query.criteria.limit); // console.log('   query.criteria.skip:',query.criteria.skip); // console.log('   query.criteria.sort:',query.criteria.sort); // console.log('   query.criteria.where:',query.criteria.where); // console.log('   query.criteria.select:',query.criteria.select); // console.log('   query.criteria.omit:',query.criteria.omit); // console.log('   --'); // console.log('   criteriaForThisBatch.limit:',criteriaForThisBatch.limit); // console.log('   criteriaForThisBatch.skip:',criteriaForThisBatch.skip); // console.log('   criteriaForThisBatch.sort:',criteriaForThisBatch.sort); // console.log('   criteriaForThisBatch.where:',criteriaForThisBatch.where); // console.log('   criteriaForThisBatch.select:',criteriaForThisBatch.select); // console.log('   criteriaForThisBatch.omit:',criteriaForThisBatch.omit); // console.log('---•••••••••---'); var deferredForThisBatch = WLModel . find ( criteriaForThisBatch ) ; _ . each ( query . populates , function ( assocCriteria , assocName ) { deferredForThisBatch = deferredForThisBatch . populate ( assocName , assocCriteria ) ; } ) ; // Pass through `meta` so we're sure to use the same db connection // and settings (i.e. esp. relevant if we happen to be inside a transaction) deferredForThisBatch . meta ( query . meta ) ; deferredForThisBatch . exec ( function ( err , batchOfRecords ) { if ( err ) { return next ( err ) ; } // If there were no records returned, then we have already reached the last batch of results. // (i.e. it was the previous batch-- since this batch was empty) // In this case, we'll set the `reachedLastBatch` flag and trigger our callback, // allowing `async.whilst()` to call _its_ callback, which will pass control back // to userland. if ( batchOfRecords . length === 0 ) { reachedLastBatch = true ; return next ( ) ; } // --• // But otherwise, we need to go ahead and call the appropriate // iteratee for this batch.  If it's eachBatchFn, we'll call it // once.  If it's eachRecordFn, we'll call it once per record. ( function _makeCallOrCallsToAppropriateIteratee ( proceed ) { // If an `eachBatchFn` iteratee was provided, we'll call it. // > At this point we already know it's a function, because // > we validated usage at the very beginning. if ( query . eachBatchFn ) { // Note that, if you try to call next() more than once in the iteratee, Waterline // logs a warning explaining what's up, ignoring all subsequent calls to next() // that occur after the first. var didIterateeAlreadyHalt ; try { var promiseMaybe = query . eachBatchFn ( batchOfRecords , function ( err ) { if ( err ) { return proceed ( err ) ; } if ( didIterateeAlreadyHalt ) { console . warn ( 'Warning: The per-batch iteratee provided to `.stream()` triggered its callback \\n' + 'again-- after already triggering it once!  Please carefully check your iteratee\\'s \\n' + 'code to figure out why this is happening.  (Ignoring this subsequent invocation...)' ) ; return ; } //-• didIterateeAlreadyHalt = true ; return proceed ( ) ; } ) ; //_∏_  </ invoked per-batch iteratee > // Take care of unhandled promise rejections from `await`. if ( query . eachBatchFn . constructor . name === 'AsyncFunction' ) { promiseMaybe . catch ( function ( e ) { proceed ( e ) ; } ) ; //_∏_ } } catch ( e ) { return proceed ( e ) ; } //>-• return ; } //_∏_. // Otherwise `eachRecordFn` iteratee must have been provided. // We'll call it once per record in this batch. // > We validated usage at the very beginning, so we know that // > one or the other iteratee must have been provided as a // > valid function if we made it here. async . eachSeries ( batchOfRecords , function _eachRecordInBatch ( record , next ) { // Note that, if you try to call next() more than once in the iteratee, Waterline // logs a warning explaining what's up, ignoring all subsequent calls to next() // that occur after the first. var didIterateeAlreadyHalt ; try { var promiseMaybe = query . eachRecordFn ( record , function ( err ) { if ( err ) { return next ( err ) ; } if ( didIterateeAlreadyHalt ) { console . warn ( 'Warning: The per-record iteratee provided to `.stream()` triggered its callback\\n' + 'again-- after already triggering it once!  Please carefully check your iteratee\\'s\\n' + 'code to figure out why this is happening.  (Ignoring this subsequent invocation...)' ) ; return ; } //-• didIterateeAlreadyHalt = true ; return next ( ) ; } ) ; //_∏_  </ invoked per-record iteratee > // Take care of unhandled promise rejections from `await`. if ( query . eachRecordFn . constructor . name === 'AsyncFunction' ) { promiseMaybe . catch ( function ( e ) { next ( e ) ; } ) ; //_∏_ } } catch ( e ) { return next ( e ) ; } } , // ~∞%° function _afterIteratingOverRecordsInBatch ( err ) { if ( err ) { return proceed ( err ) ; } return proceed ( ) ; } ) ; //</async.eachSeries()> } ) ( function _afterCallingIteratee ( err ) { if ( err ) { return next ( err ) ; } // Increment the batch counter. i ++ ; // On to the next batch! return next ( ) ; } ) ; //</self-calling function :: process this batch by making either one call or multiple calls to the appropriate iteratee> } ) ; //</deferredForThisBatch.exec()> }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates parameter value [CODESPLIT] function validateParameterValue ( parameter , type , format , value ) { if ( type === 'integer' ) { const parsedValue = Number . parseInt ( value ) if ( _ . isNaN ( parsedValue ) ) { throw new Error ( ` ${ parameter } ${ value } ` ) } return parsedValue } else if ( type === 'number' ) { const parsedValue = Number . parseFloat ( value ) if ( _ . isNaN ( parsedValue ) ) { throw new Error ( ` ${ parameter } ${ value } ` ) } return Number . isInteger ( parsedValue ) ? Number . parseInt ( value ) : parsedValue } else if ( type === 'string' && format ) { if ( format === 'date-time' && ! moment ( value , moment . ISO_8601 ) . isValid ( ) ) { throw new Error ( ` ${ parameter } ${ value } ` ) } else if ( format === 'date' && ! moment ( value , 'YYYY-MM-DD' ) . isValid ( ) ) { throw new Error ( ` ${ parameter } ${ value } ` ) } return value } return value }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts parameter declaration to yargs [CODESPLIT] function parameterDeclarationToYargs ( yargs , parameter , declaration ) { const optionName = _ . kebabCase ( parameter ) let option = { } if ( declaration . description ) { option . describe = declaration . description } if ( declaration . type ) { if ( declaration . type === 'integer' ) { option . type = 'number' } else { option . type = declaration . type } } if ( declaration . enum ) { option . choices = declaration . enum } if ( declaration . default ) { option . default = declaration . default } if ( declaration . required ) { option . demandOption = declaration . required } if ( declaration . conflicts ) { option . conflicts = declaration . conflicts } yargs . option ( optionName , option ) yargs . coerce ( optionName , ( value ) => { if ( declaration . type === 'array' ) { return _ . map ( value , ( value ) => { return validateParameterValue ( ` ${ optionName } ` , declaration . item , declaration . format , value ) } ) } return validateParameterValue ( optionName , declaration . type , declaration . format , value ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts configuration declaration to yargs options [CODESPLIT] function configDeclarationToYargs ( yargs , configDeclaration ) { _ . forOwn ( configDeclaration , ( parameter , parameterName ) => { parameterDeclarationToYargs ( yargs , parameterName , parameter ) } ) return yargs }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ----- Modal functions ----- [CODESPLIT] function createModal ( id , title , body , footer ) { var $modalHeaderButton = $ ( '<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">&times;</button>' ) ; var $modalHeaderTitle = $ ( '<h4 class=\"modal-title\" id=\"' + id + '_modal_title\">' + title + '</h4>' ) ; var $modalHeader = $ ( '<div class=\"modal-header\"></div>' ) ; $modalHeader . append ( $modalHeaderButton ) ; $modalHeader . append ( $modalHeaderTitle ) ; var $modalBody = $ ( '<div class=\"modal-body\" id=\"' + id + '_modal_body\">' + body + '</div>' ) ; var $modalFooter = $ ( '<div class=\"modal-footer\" id=\"' + id + '_modal_footer\"></div>' ) ; if ( typeof ( footer ) !== 'undefined' ) { var $modalFooterAddOn = $ ( '<div>' + footer + '</div>' ) ; $modalFooter . append ( $modalFooterAddOn ) ; } var $modalContent = $ ( '<div class=\"modal-content\"></div>' ) ; $modalContent . append ( $modalHeader ) ; $modalContent . append ( $modalBody ) ; $modalContent . append ( $modalFooter ) ; var $modalDialog = $ ( '<div class=\"modal-dialog\"></div>' ) ; $modalDialog . append ( $modalContent ) ; var $modalFade = $ ( '<div class=\"modal fade\" id=\"' + id + '_modal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"' + id + '_modal_title\" aria-hidden=\"true\"></div>' ) ; $modalFade . append ( $modalDialog ) ; $modalFade . data ( 'dateId' , id ) ; $modalFade . attr ( \"dateId\" , id ) ; return $modalFade ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ----- Event functions ----- [CODESPLIT] function checkEvents ( $calendarElement , year , month ) { var jsonData = $calendarElement . data ( 'jsonData' ) ; var ajaxSettings = $calendarElement . data ( 'ajaxSettings' ) ; $calendarElement . data ( 'events' , false ) ; if ( false !== jsonData ) { return jsonEvents ( $calendarElement ) ; } else if ( false !== ajaxSettings ) { return ajaxEvents ( $calendarElement , year , month ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ----- Helper functions ----- [CODESPLIT] function isToday ( year , month , day ) { var todayObj = new Date ( ) ; var dateObj = new Date ( year , month , day ) ; return ( dateObj . toDateString ( ) == todayObj . toDateString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////// ///// HTTPS TRAFFIC REDIRECT //////// ///////////////////////////////////////// Redirect all HTTP traffic to HTTPS [CODESPLIT] function ensureSecure ( req , res , next ) { if ( req . headers [ \"x-forwarded-proto\" ] === \"https\" ) { // OK, continue return next ( ) ; } ; res . redirect ( 'https://' + req . hostname + req . url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////// // SIGN UP EMAIL SEND //// /////////////////////////////////// [CODESPLIT] function signupEmail ( user ) { var port = process . env . MAIL_PORT var useremail = process . env . MAIL_USERNAME var passwords = process . env . MAIL_PASSWORD var host = process . env . MAIL_HOST var temp = { } 'use strict' ; var nodemailer = require ( 'nodemailer' ) ; // create reusable transporter object using the default SMTP transport var transporter = nodemailer . createTransport ( { host : host , tls : { rejectUnauthorized : false } , secure : false , // secure:true for port 465, secure:false for port 587 auth : { user : useremail , pass : passwords , } } ) ; var mailOptions = { from : user . username + ' ' + '<' + user . email + '>' , // sender address to : process . env . MAIL_USERNAME , // list of receivers subject : '✔ A user has edited their information '+  s tename + ' ',  /  Subject line html : '<h2>The following user has been edited.</h2><p>Code :</p> <pre>' + user + '</pre>' , } // send mail with defined transport object transporter . sendMail ( mailOptions , ( error , info ) => { if ( error ) { return console . log ( error ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binary search implementation ( recursive ) [CODESPLIT] function binarySearch ( arr , searchValue ) { function find ( arr , searchValue , left , right ) { if ( right < left ) return - 1 ; /*\n    int mid = mid = (left + right) / 2;\n    There is a bug in the above line;\n    Joshua Bloch suggests the following replacement:\n    */ var mid = Math . floor ( ( left + right ) >>> 1 ) ; if ( searchValue > arr [ mid ] ) return find ( arr , searchValue , mid + 1 , right ) ; if ( searchValue < arr [ mid ] ) return find ( arr , searchValue , left , mid - 1 ) ; return mid ; } ; return find ( arr , searchValue , 0 , arr . length - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Character iterated character class . Recognizers for specific mbcs encodings make their characters available by providing a nextChar () function that fills in an instance of iteratedChar with the next char from the input . The returned characters are not converted to Unicode but remain as the raw bytes ( concatenated into an int ) from the codepage data . For Asian charsets use the raw input rather than the input that has been stripped of markup . Detection only considers multi - byte chars effectively stripping markup anyway and double byte chars do occur in markup too . [CODESPLIT] function IteratedChar ( ) { this . charValue = 0 ; // 1-4 bytes from the raw input data this . index = 0 ; this . nextIndex = 0 ; this . error = false ; this . done = false ; this . reset = function ( ) { this . charValue = 0 ; this . index = - 1 ; this . nextIndex = 0 ; this . error = false ; this . done = false ; } ; this . nextByte = function ( det ) { if ( this . nextIndex >= det . fRawLength ) { this . done = true ; return - 1 ; } var byteValue = det . fRawInput [ this . nextIndex ++ ] & 0x00ff ; return byteValue ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This class recognizes single - byte encodings . Because the encoding scheme is so simple language statistics are used to do the matching . [CODESPLIT] function NGramParser ( theNgramList , theByteMap ) { var N_GRAM_MASK = 0xFFFFFF ; this . byteIndex = 0 ; this . ngram = 0 ; this . ngramList = theNgramList ; this . byteMap = theByteMap ; this . ngramCount = 0 ; this . hitCount = 0 ; this . spaceChar ; /*\n   * Binary search for value in table, which must have exactly 64 entries.\n   */ this . search = function ( table , value ) { var index = 0 ; if ( table [ index + 32 ] <= value ) index += 32 ; if ( table [ index + 16 ] <= value ) index += 16 ; if ( table [ index + 8 ] <= value ) index += 8 ; if ( table [ index + 4 ] <= value ) index += 4 ; if ( table [ index + 2 ] <= value ) index += 2 ; if ( table [ index + 1 ] <= value ) index += 1 ; if ( table [ index ] > value ) index -= 1 ; if ( index < 0 || table [ index ] != value ) return - 1 ; return index ; } ; this . lookup = function ( thisNgram ) { this . ngramCount += 1 ; if ( this . search ( this . ngramList , thisNgram ) >= 0 ) { this . hitCount += 1 ; } } ; this . addByte = function ( b ) { this . ngram = ( ( this . ngram << 8 ) + ( b & 0xFF ) ) & N_GRAM_MASK ; this . lookup ( this . ngram ) ; } this . nextByte = function ( det ) { if ( this . byteIndex >= det . fInputLen ) return - 1 ; return det . fInputBytes [ this . byteIndex ++ ] & 0xFF ; } this . parse = function ( det , spaceCh ) { var b , ignoreSpace = false ; this . spaceChar = spaceCh ; while ( ( b = this . nextByte ( det ) ) >= 0 ) { var mb = this . byteMap [ b ] ; // TODO: 0x20 might not be a space in all character sets... if ( mb != 0 ) { if ( ! ( mb == this . spaceChar && ignoreSpace ) ) { this . addByte ( mb ) ; } ignoreSpace = ( mb == this . spaceChar ) ; } } // TODO: Is this OK? The buffer could have ended in the middle of a word... this . addByte ( this . spaceChar ) ; var rawPercent = this . hitCount / this . ngramCount ; // TODO - This is a bit of a hack to take care of a case // were we were getting a confidence of 135... if ( rawPercent > 0.33 ) return 98 ; return Math . floor ( rawPercent * 300.0 ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "iconic wrapper [CODESPLIT] function Iconic ( ) { // default path var assetPath = 'assets/img/iconic/' ; /**\n     * Sets the path used to locate the iconic SVG files\n     * @param {string} path - the base path used to locate the iconic SVG files\n     */ this . setAssetPath = function ( path ) { assetPath = angular . isString ( path ) ? path : assetPath ; } ; /**\n     * Service implementation\n     * @returns {{}}\n     */ this . $get = function ( ) { var iconicObject = new IconicJS ( ) ; var service = { getAccess : getAccess , getAssetPath : getAssetPath } ; return service ; /**\n       *\n       * @returns {Window.IconicJS}\n       */ function getAccess ( ) { return iconicObject ; } /**\n       *\n       * @returns {string}\n       */ function getAssetPath ( ) { return assetPath ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "special thanks to Chris Ferdinandi for this solution . http : // gomakethings . com / climbing - up - and - down - the - dom - tree - with - vanilla - javascript / [CODESPLIT] function getParentsUntil ( elem , parent ) { for ( ; elem && elem !== document . body ; elem = elem . parentNode ) { if ( elem . hasAttribute ( parent ) ) { if ( elem . classList . contains ( 'is-active' ) ) { return elem ; } break ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects a scenario object and templates from element [CODESPLIT] function collectScenariosFromElement ( parentElement ) { var scenarios = [ ] ; var templates = [ ] ; var elements = parentElement . children ( ) ; var i = 0 ; angular . forEach ( elements , function ( el ) { var elem = angular . element ( el ) ; //if no source or no html, capture element itself if ( ! elem . attr ( 'src' ) || ! elem . attr ( 'src' ) . match ( / .html$ / ) ) { templates [ i ] = elem ; scenarios [ i ] = { media : elem . attr ( 'media' ) , templ : i } ; } else { scenarios [ i ] = { media : elem . attr ( 'media' ) , src : elem . attr ( 'src' ) } ; } i ++ ; } ) ; return { scenarios : scenarios , templates : templates } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "accordion item [CODESPLIT] function zfAccordionItem ( ) { var directive = { restrict : 'EA' , templateUrl : 'components/accordion/accordion-item.html' , transclude : true , scope : { title : '@' } , require : '^zfAccordion' , replace : true , controller : function ( ) { } , link : link } ; return directive ; function link ( scope , element , attrs , controller , transclude ) { scope . active = false ; controller . addSection ( scope ) ; scope . activate = function ( ) { controller . select ( scope ) ; } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extended : Invoke a callback with each filesystem event that occurs beneath a specified path . watchPath handles the efficient re - use of operating system resources across living watchers . Watching the same path more than once or the child of a watched path will re - use the existing native watcher . * rootPath { String } specifies the absolute path to the root of the filesystem content to watch . * options Control the watcher s behavior . * eventCallback { Function } or other callable to be called each time a batch of filesystem events is observed . * events { Array } of objects that describe the events that have occurred . * action { String } describing the filesystem action that occurred . One of created modified deleted or renamed . * kind { String } distinguishing the type of filesystem entry that was acted upon when available . One of file directory or unknown . * path { String } containing the absolute path to the filesystem entry that was acted upon . * oldPath For rename events { String } containing the filesystem entry s former absolute path . Returns a { Promise } that will resolve to a { PathWatcher } once it has started . Note that every { PathWatcher } is a { Disposable } so they can be managed by a { CompositeDisposable } if desired . js const { watchPath } = require ( [CODESPLIT] function watchPath ( rootPath , options , eventCallback ) { const watcher = PathWatcherManager . instance ( ) . createWatcher ( rootPath , options , eventCallback ) return watcher . getStartPromise ( ) . then ( ( ) => watcher ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private : re - join the segments split from an absolute path to form another absolute path . [CODESPLIT] function absolute ( ... parts ) { let candidate = parts . length !== 1 ? path . join ( ... parts ) : parts [ 0 ] if ( process . platform === 'win32' && / ^[A-Z]:$ / . test ( candidate ) ) candidate += '\\\\' return path . isAbsolute ( candidate ) ? candidate : path . join ( path . sep , candidate ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A facade to Server#handle [CODESPLIT] function middleware ( opts ) { const srv = new Server ( opts ) ; servers . push ( srv ) ; return function tinylr ( req , res , next ) { srv . handler ( req , res , next ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changed helper helps with notifying the server of a file change [CODESPLIT] function changed ( done ) { const files = [ ] . slice . call ( arguments ) ; if ( typeof files [ files . length - 1 ] === 'function' ) done = files . pop ( ) ; done = typeof done === 'function' ? done : ( ) => { } ; debug ( 'Notifying %d servers - Files: ' , servers . length , files ) ; servers . forEach ( srv => { const params = { params : { files : files } } ; srv && srv . changed ( params ) ; } ) ; done ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Usabilla SDK Functions [CODESPLIT] function initialize ( appId ) { if ( Platform . OS == 'android' ) { usabillaEventEmitter . addListener ( 'UBFormNotFoundFragmentActivity' , ( ) => console . log ( \"The Activity does not extend FragmentActivity and cannot call getSupportFragmentManager()\" ) ) } UsabillaBridge . initialize ( appId ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new detatched DOM node to render child components within . [CODESPLIT] function ( children , element ) { this . portalNode = document . createElement ( 'div' ) ; ( element || document . body ) . appendChild ( this . portalNode ) ; ReactDOM . render ( children , this . portalNode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unmounts the components rendered in the portal and removes the associated DOM node . [CODESPLIT] function ( ) { /* eslint-disable no-alert */ var close = typeof this . portalConfirmOnCloseMessage === 'string' ? confirm ( this . portalConfirmOnCloseMessage ) : true ; /* eslint-enable no-alert */ if ( this . portalNode && this . portalNode . parentNode && close ) { ReactDOM . unmountComponentAtNode ( this . portalNode ) ; this . portalNode . parentNode . removeChild ( this . portalNode ) ; this . portalNode = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A Table requires a definition to operate upon . The table definition requires a url for requesting data and an array of cols ( column definitions ) . An object in the cols array requires a headerLabel dataProperty and a percentage width . The Table may also receive a sortColIndex which adds required fields to the cols objects of sortDirection ( ascending / descending ) and dataType ( string number percent time or status ) . The table definition may also include a pagination object with two required properties ( cursor - the starting index and size - number of lines per page ) . [CODESPLIT] function ( id , definition , dataFormatter ) { this . id = id ; this . url = definition . url ; this . cols = definition . cols ; this . sortColIndex = definition . sortColIndex ; this . pagination = definition . pagination ; this . cursor = definition . cursor ; this . rowClick = definition . rowClick ; this . advancedFilters = definition . advancedFilters ; this . data = null ; this . filteredData = null ; this . displayedData = null ; this . dataCount = null ; this . dataFormatter = dataFormatter ; this . selectedItems = { } ; this . selectDataProperty = _ . result ( _ . find ( this . cols , { 'dataType' : 'select' } ) , 'dataProperty' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggered when data is received correctly from the server . [CODESPLIT] function ( data ) { this . data = _ . values ( _ . cloneDeep ( data ) ) ; // Run data through definition formatter if it exists. if ( this . dataFormatter ) { this . data = this . dataFormatter ( data ) ; } this . dataCount = this . data . length ; var formatPercent = ( col , item ) => { // Set any null or undefined percent values to 0. if ( item [ col . dataProperty ] === null || typeof item [ col . dataProperty ] === 'undefined' ) { item [ col . dataProperty ] = 0 ; } // Provide formatted value in different field. item [ ` ${ col . dataProperty } ` ] = item [ col . dataProperty ] + '%' ; } ; var formatTimeStatus = ( col , item ) => { if ( col . dataType === 'status' && item [ col . dataProperty ] ) { item . online = moment ( item [ col . dataProperty ] ) . valueOf ( ) > moment ( Date . now ( ) ) . subtract ( col . onlineLimit , 'minutes' ) . valueOf ( ) ; } item [ col . dataProperty ] = item [ col . dataProperty ] || null ; // Provide formatted value in different field. item [ ` ${ col . dataProperty } ` ] = item [ col . dataProperty ] ? ( typeof col . timeFormat === 'function' ? col . timeFormat ( item [ col . dataProperty ] ) : moment ( item [ col . dataProperty ] ) . format ( col . timeFormat ) ) : '--' ; } ; var formatDuration = ( col , item ) => { // Set any null or undefined duration values to 0. if ( item [ col . dataProperty ] === null || typeof item [ col . dataProperty ] === 'undefined' ) { item [ col . dataProperty ] = 0 ; } // Format the duration, e.g. '2d 0h 5m', '40m'. var formattedDuration = ( value , limit ) => { var times = [ // Use `asDays` instead of `days` since we are not looking at longer segments of time (i.e. years and months). { time : 'days' , formatter : 'asDays' , suffix : 'd' } , { time : 'hours' , formatter : 'hours' , suffix : 'h' } , { time : 'minutes' , formatter : 'minutes' , suffix : 'm' } , { time : 'seconds' , formatter : 'seconds' , suffix : 's' } , { time : 'milliseconds' , formatter : 'milliseconds' , suffix : 'ms' } ] , indexOfTime = _ . findIndex ( times , { time : limit } ) ; if ( indexOfTime !== - 1 ) { times = times . slice ( 0 , indexOfTime + 1 ) ; } return _ . reduce ( times , ( formattedValue , currentTime ) => { var currentTimeValue = Math . floor ( value [ currentTime . formatter ] ( ) ) ; // Do not return a zero value for the current time if it would be the first value in the result. if ( currentTimeValue === 0 && formattedValue . length === 0 ) { return '' ; } return ` ${ formattedValue } ${ currentTimeValue } ${ currentTime . suffix } ` ; } , '' ) . trim ( ) ; } ; // Provide formatted value in different field. item [ ` ${ col . dataProperty } ` ] = formattedDuration ( moment . duration ( item [ col . dataProperty ] ) , col . durationFormat || 'minutes' ) ; } ; // Run data through built in data formatters. _ . forEach ( this . cols , function ( col ) { // store the original passed in sort direction col . defaultSortDirection = col . sortDirection ; // Default to 15 minutes if the onlineLimit for the col was not set or was set incorrectly. if ( col . dataType === 'status' && ( typeof col . onlineLimit !== 'number' || col . onlineLimit < 1 ) ) { col . onlineLimit = 15 ; } _ . forEach ( this . data , function ( item ) { if ( col . dataType === 'percent' ) { formatPercent ( col , item ) ; } else if ( col . dataType === 'time' || col . dataType === 'status' ) { formatTimeStatus ( col , item ) ; } else if ( col . dataType === 'duration' ) { formatDuration ( col , item ) ; } } ) ; } , this ) ; this . selectedItems = { } ; //Reset the filter value on data change to clear any filtered state. Anytime new data comes in we want to clear all quick filters //that might applied and show the full result set. this . filterValue = '' ; if ( typeof this . sortColIndex === 'number' ) { this . sortData ( this . sortColIndex , this . cols [ this . sortColIndex ] . sortDirection ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the data for the table ( also triggers pagination ) . [CODESPLIT] function ( ) { this . dataCount = this . data . length ; this . filteredData = this . filterData ( this . data ) ; this . displayedData = this . pagination ? this . sliceData ( this . filteredData ) : this . filteredData ; return this . displayedData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers quick filtering and advanced filtering of the data if either of those properties have been set . [CODESPLIT] function ( data ) { if ( this . filterValue ) { data = this . quickFilterData ( data , this . filterValue ) ; } if ( this . advancedFilters ) { data = this . advancedFilterData ( data , this . advancedFilters ) ; } this . dataCount = data . length ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters out table data that does not match the filter value for table cols that have quickFilter set to true . Also checks to see if there is a specified column to apply the filter to - denoted by filterValue being separated by : . [CODESPLIT] function ( data , filterValue ) { var filterCol ; filterValue = filterValue . toString ( ) . toLowerCase ( ) . split ( ':' ) ; if ( filterValue . length > 1 ) { filterCol = filterValue [ 0 ] ; filterValue = filterValue [ 1 ] ; } else { filterValue = filterValue [ 0 ] ; } var filterProperties = [ ] ; //Collect all of the data properties we're going to check for filtering _ . each ( this . cols , function ( col ) { var headerLabel = col . headerLabel ? col . headerLabel . toLowerCase ( ) : '' ; if ( col . quickFilter && ( ! filterCol || headerLabel === filterCol ) ) { filterProperties . push ( col . dataProperty ) ; } } ) ; if ( filterProperties . length ) { //Iterate over the data set and remove items that don't match the filter return _ . filter ( data , function ( item ) { //Use some so that we return as soon as we find a column that matches the value return _ . some ( filterProperties , function ( propName ) { if ( ! item [ propName ] ) { return false ; } if ( filterCol ) { return item [ propName ] . toString ( ) . toLowerCase ( ) === filterValue ; } return item [ propName ] . toString ( ) . toLowerCase ( ) . indexOf ( filterValue ) > - 1 ; } ) ; } ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters out table data where any property value equals a matching property value on an advanced filter unless the advanced filter has been checked . [CODESPLIT] function ( data , filters ) { return _ . filter ( _ . map ( data , function ( item ) { var shown = true ; _ . each ( filters , function ( filter ) { if ( item [ filter . dataProperty ] === filter . filterValue ) { if ( filter . checked ) { item = _ . cloneDeep ( item ) ; //Clone this item since we're going to modify it if ( ! item . shownByAdvancedFilters ) { item . shownByAdvancedFilters = [ ] ; } item . shownByAdvancedFilters . push ( filter . dataProperty ) ; shown = true ; } else if ( ! item . shownByAdvancedFilters ) { shown = false ; } } } ) ; if ( shown ) { return item ; } } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts the array of data for the Table based on the sort column index and the direction . [CODESPLIT] function ( colIndex , direction ) { this . sortColIndex = colIndex ; this . cols [ colIndex ] . sortDirection = direction ; var defaultDirection = this . cols [ colIndex ] . defaultSortDirection ; var dataType = this . cols [ this . sortColIndex ] . dataType ; var key = this . cols [ this . sortColIndex ] . dataProperty ; if ( this . pagination ) { this . resetPagination ( ) ; } /* eslint-disable complexity */ this . data . sort ( function ( a , b ) { var first = a [ key ] ; var second = b [ key ] ; // undefined/null values are sorted to the end of the table when the sort direction is equal to the default // sort direction, and to the top of the table when the sort direction is opposite of default if ( first === null || first === undefined ) { if ( second === null || second === undefined ) { return 0 ; } return defaultDirection === direction ? 1 : - 1 ; } if ( second === null || second === undefined ) { return defaultDirection === direction ? - 1 : 1 ; } if ( dataType === 'string' ) { first = first . toLowerCase ( ) ; second = second . toLowerCase ( ) ; } if ( first > second ) { return direction === 'ascending' ? 1 : - 1 ; } if ( first < second ) { return direction === 'ascending' ? - 1 : 1 ; } // a must be equal to b return 0 ; } ) ; /* eslint-enable complexity */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bulk add or remove keys to / from the Table s selected items . [CODESPLIT] function ( deselect ) { _ . forEach ( this . filteredData , function ( data ) { if ( deselect ) { delete this . selectedItems [ data [ this . selectDataProperty ] ] ; } else { this . selectedItems [ data [ this . selectDataProperty ] ] = data ; } } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add or remove a key to / from the Table s selected items . [CODESPLIT] function ( rowIndex ) { var key = this . displayedData [ rowIndex ] [ this . selectDataProperty ] ; if ( this . selectedItems [ key ] ) { delete this . selectedItems [ key ] ; } else { this . selectedItems [ key ] = this . displayedData [ rowIndex ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of Table . [CODESPLIT] function ( id , definition , dataFormatter ) { this . collection [ id ] = new Table ( id , definition , dataFormatter ) ; return this . collection [ id ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles all events sent from the dispatcher . Filters out to only those sent via the Table [CODESPLIT] function ( payload ) { var action = payload . action ; if ( ! this . shouldHandleAction ( action . component ) ) { return ; } switch ( action . actionType ) { case ActionTypes . REQUEST_DATA : this . handleRequestDataAction ( action ) ; break ; case ActionTypes . TABLE_SORT : this . collection [ action . id ] . sortData ( action . data . colIndex , action . data . direction ) ; this . emitChange ( action . id ) ; break ; case ActionTypes . FILTER : this . collection [ action . id ] . setFilterValue ( action . data . value ) ; this . emitChange ( action . id ) ; break ; case ActionTypes . ADVANCED_FILTER : this . collection [ action . id ] . setAdvancedFilters ( action . data . advancedFilters ) ; this . emitChange ( action . id ) ; break ; case ActionTypes . PAGINATE : this . collection [ action . id ] . paginate ( action . data . direction ) ; this . emitChange ( action . id ) ; break ; case ActionTypes . TOGGLE_BULK_SELECT : this . collection [ action . id ] . updateBulkSelection ( action . data . deselect ) ; this . emitChange ( action . id ) ; break ; case ActionTypes . TOGGLE_ROW_SELECT : this . collection [ action . id ] . updateRowSelection ( action . data . rowIndex ) ; this . emitChange ( action . id ) ; break ; case ActionTypes . DESTROY_INSTANCE : this . destroyInstance ( action . id ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests data for a component when the filter property changes . When comparing filters we do a direct comparison in addition to a JSON stringify comparison . This fixes issues where the filters object is a new literal object every time but isn t actually changing . Using a JSON stringify has the downside of causing requestData to be called if the objects are in a different order but that is pretty unlikely to happen . The setTimeout insures that the currently dispatched action has completed the dispatching process before the request data action is kicked off . [CODESPLIT] function ( nextProps ) { if ( this . props . filters !== nextProps . filters && JSON . stringify ( this . props . filters ) !== JSON . stringify ( nextProps . filters ) ) { setTimeout ( function ( ) { this . requestData ( ) ; } . bind ( this ) , 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to add and remove the listeners required when requesting data from the server . [CODESPLIT] function ( store ) { return { /**\n             * Adds the listeners required when requesting data from the server.\n             */ componentDidMount : function ( ) { store . on ( 'change:' + this . props . componentId , this . onDataReceived ) ; store . on ( 'fail:' + this . props . componentId , this . onError ) ; } , /**\n             * Removes the listeners required when requesting data from the server.\n             */ componentWillUnmount : function ( ) { store . removeListener ( 'change:' + this . props . componentId , this . onDataReceived ) ; store . removeListener ( 'fail:' + this . props . componentId , this . onError ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the listeners required when requesting data from the server . [CODESPLIT] function ( ) { store . on ( 'change:' + this . props . componentId , this . onDataReceived ) ; store . on ( 'fail:' + this . props . componentId , this . onError ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the listeners required when requesting data from the server . [CODESPLIT] function ( ) { store . removeListener ( 'change:' + this . props . componentId , this . onDataReceived ) ; store . removeListener ( 'fail:' + this . props . componentId , this . onError ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Action for populating table data . Used both for initial and subsequent loads . [CODESPLIT] function ( id , definition , dataFormatter , filters ) { AppDispatcher . dispatchAction ( { actionType : this . actionTypes . REQUEST_DATA , component : 'Table' , id : id , data : { definition : definition , dataFormatter : dataFormatter , filters : filters } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters out table data that does not match the filter value for table cols that have quickFilter set to true . [CODESPLIT] function ( id , value ) { AppDispatcher . dispatchAction ( { actionType : this . actionTypes . FILTER , component : 'Table' , id : id , data : { value : value } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters out table data where any property value equals a matching property value on an advanced filter unless the advanced filter has been checked . [CODESPLIT] function ( id , advancedFilters ) { AppDispatcher . dispatchAction ( { actionType : this . actionTypes . ADVANCED_FILTER , component : 'Table' , id : id , data : { advancedFilters : advancedFilters } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves the cursor forwards or backwards through paginated data . [CODESPLIT] function ( id , direction ) { AppDispatcher . dispatchAction ( { actionType : this . actionTypes . PAGINATE , component : 'Table' , id : id , data : { direction : direction } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts the array of data for the Table based on the sort column index and the direction . [CODESPLIT] function ( id , colIndex , direction ) { AppDispatcher . dispatchAction ( { actionType : this . actionTypes . TABLE_SORT , component : 'Table' , id : id , data : { colIndex : colIndex , direction : direction } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bulk toggle selection for table rows . [CODESPLIT] function ( id , deselect ) { AppDispatcher . dispatchAction ( { actionType : this . actionTypes . TOGGLE_BULK_SELECT , component : 'Table' , id : id , data : { deselect : deselect } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects or deselects a table row . [CODESPLIT] function ( id , rowIndex ) { AppDispatcher . dispatchAction ( { actionType : this . actionTypes . TOGGLE_ROW_SELECT , component : 'Table' , id : id , data : { rowIndex : rowIndex } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the value default translate filter behavior else if it is an attribute we need to get its value first [CODESPLIT] function extractValue ( attr , node ) { if ( attr === 'translate' ) { return node . html ( ) || getAttr ( attr ) || '' ; } return getAttr ( attr ) || node . html ( ) || '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the log array [CODESPLIT] function cleanerEval$624 ( str$629 , oldConsole$630 ) { var logArr$631 = [ ] ; var console$632 = { log : function ( msg$633 ) { logArr$631 . push ( msg$633 ) ; oldConsole$630 . log ( msg$633 ) ; } } ; eval ( str$629 ) ; return logArr$631 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the map function on the passed object with a specified callback . This uses Ember . ArrayPolyfill s - map method when necessary . [CODESPLIT] function ( obj , callback , thisArg ) { return obj . map ? obj . map . call ( obj , callback , thisArg ) : map . call ( obj , callback , thisArg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the filter function on the passed object with a specified callback . This uses Ember . ArrayPolyfill s - filter method when necessary . [CODESPLIT] function ( obj , callback , thisArg ) { return obj . filter ? obj . filter . call ( obj , callback , thisArg ) : filter . call ( obj , callback , thisArg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of indexes of the first occurrences of the passed elements on the passed object . [CODESPLIT] function ( obj , elements ) { return elements === undefined ? [ ] : utils . map ( elements , function ( item ) { return utils . indexOf ( obj , item ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an object to an array . If the array already includes the object this method has no effect . [CODESPLIT] function ( array , item ) { var index = utils . indexOf ( array , item ) ; if ( index === - 1 ) { array . push ( item ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces objects in an array with the passed objects . [CODESPLIT] function ( array , idx , amt , objects ) { if ( array . replace ) { return array . replace ( idx , amt , objects ) ; } else { return utils . _replace ( array , idx , amt , objects ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the intersection of two arrays . This method returns a new array filled with the records that the two passed arrays share with each other . If there is no intersection an empty array will be returned . [CODESPLIT] function ( array1 , array2 ) { var intersection = [ ] ; utils . forEach ( array1 , function ( element ) { if ( utils . indexOf ( array2 , element ) >= 0 ) { intersection . push ( element ) ; } } ) ; return intersection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an event listener [CODESPLIT] function removeListener ( obj , eventName , target , method ) { Ember . assert ( \"You must pass at least an object and event name to Ember.removeListener\" , ! ! obj && ! ! eventName ) ; if ( ! method && 'function' === typeof target ) { method = target ; target = null ; } function _removeListener ( target , method ) { var actions = actionsFor ( obj , eventName ) , actionIndex = indexOf ( actions , target , method ) ; // action doesn't exist, give up silently if ( actionIndex === - 1 ) { return ; } actions . splice ( actionIndex , 3 ) ; if ( 'function' === typeof obj . didRemoveListener ) { obj . didRemoveListener ( eventName , target , method ) ; } } if ( method ) { _removeListener ( target , method ) ; } else { var meta = obj [ META_KEY ] , actions = meta && meta . listeners && meta . listeners [ eventName ] ; if ( ! actions ) { return ; } for ( var i = actions . length - 3 ; i >= 0 ; i -= 3 ) { _removeListener ( actions [ i ] , actions [ i + 1 ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Suspend listener during callback . [CODESPLIT] function suspendListener ( obj , eventName , target , method , callback ) { if ( ! method && 'function' === typeof target ) { method = target ; target = null ; } var actions = actionsFor ( obj , eventName ) , actionIndex = indexOf ( actions , target , method ) ; if ( actionIndex !== - 1 ) { actions [ actionIndex + 2 ] |= SUSPENDED ; // mark the action as suspended } function tryable ( ) { return callback . call ( target ) ; } function finalizer ( ) { if ( actionIndex !== - 1 ) { actions [ actionIndex + 2 ] &= ~ SUSPENDED ; } } return Ember . tryFinally ( tryable , finalizer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called whenever a property has just changed to update dependent keys [CODESPLIT] function dependentKeysDidChange ( obj , depKey , meta ) { if ( obj . isDestroying ) { return ; } var seen = DID_SEEN , top = ! seen ; if ( top ) { seen = DID_SEEN = { } ; } iterDeps ( propertyDidChange , obj , depKey , seen , meta ) ; if ( top ) { DID_SEEN = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of a property on an object respecting computed properties and notifying observers and other listeners of the change . If the property is not defined but the object implements the setUnknownProperty method then that will be invoked as well . [CODESPLIT] function set ( obj , keyName , value , tolerant ) { if ( typeof obj === 'string' ) { Ember . assert ( \"Path '\" + obj + \"' must be global if no obj is given.\" , IS_GLOBAL . test ( obj ) ) ; value = keyName ; keyName = obj ; obj = null ; } Ember . assert ( \"Cannot call set with \" + keyName + \" key.\" , ! ! keyName ) ; if ( ! obj || keyName . indexOf ( '.' ) !== - 1 ) { return setPath ( obj , keyName , value , tolerant ) ; } Ember . assert ( \"You need to provide an object and key to `set`.\" , ! ! obj && keyName !== undefined ) ; Ember . assert ( 'calling set on destroyed object' , ! obj . isDestroyed ) ; var meta = obj [ META_KEY ] , desc = meta && meta . descs [ keyName ] , isUnknown , currentValue ; if ( desc ) { desc . set ( obj , keyName , value ) ; } else { isUnknown = 'object' === typeof obj && ! ( keyName in obj ) ; // setUnknownProperty is called if `obj` is an object, // the property does not already exist, and the // `setUnknownProperty` method exists on the object if ( isUnknown && 'function' === typeof obj . setUnknownProperty ) { obj . setUnknownProperty ( keyName , value ) ; } else if ( meta && meta . watching [ keyName ] > 0 ) { if ( MANDATORY_SETTER ) { currentValue = meta . values [ keyName ] ; } else { currentValue = obj [ keyName ] ; } // only trigger a change if the value has changed if ( value !== currentValue ) { Ember . propertyWillChange ( obj , keyName ) ; if ( MANDATORY_SETTER ) { if ( ( currentValue === undefined && ! ( keyName in obj ) ) || ! obj . propertyIsEnumerable ( keyName ) ) { Ember . defineProperty ( obj , keyName , null , value ) ; // setup mandatory setter } else { meta . values [ keyName ] = value ; } } else { obj [ keyName ] = value ; } Ember . propertyDidChange ( obj , keyName ) ; } } else { obj [ keyName ] = value ; } } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a value to the map . If a value for the given key has already been provided the new value will replace the old value . [CODESPLIT] function ( key , value ) { var keys = this . keys , values = this . values , guid = guidFor ( key ) ; keys . add ( key ) ; values [ guid ] = value ; set ( this , 'length' , keys . list . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a value from the map for an associated key . [CODESPLIT] function ( key ) { // don't use ES6 \"delete\" because it will be annoying // to use in browsers that are not ES6 friendly; var keys = this . keys , values = this . values , guid = guidFor ( key ) ; if ( values . hasOwnProperty ( guid ) ) { keys . remove ( key ) ; delete values [ guid ] ; set ( this , 'length' , keys . list . length ) ; return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate over all the keys and values . Calls the function once for each key passing in the key and value in that order . [CODESPLIT] function ( callback , self ) { var keys = this . keys , values = this . values ; keys . forEach ( function ( key ) { var guid = guidFor ( key ) ; callback . call ( self , key , values [ guid ] ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": ".......................................................... COMPUTED PROPERTY A computed property transforms an objects function into a property . [CODESPLIT] function ComputedProperty ( func , opts ) { this . func = func ; if ( Ember . FEATURES . isEnabled ( 'composable-computed-properties' ) ) { setDependentKeys ( this , opts && opts . dependentKeys ) ; } else { this . _dependentKeys = opts && opts . dependentKeys ; } this . _cacheable = ( opts && opts . cacheable !== undefined ) ? opts . cacheable : true ; this . _readOnly = opts && ( opts . readOnly !== undefined || ! ! opts . readOnly ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : remove me only being used for Ember . run . sync [CODESPLIT] function ( ) { var queue = this . _queue , options = this . options , before = options && options . before , after = options && options . after , target , method , args , stack , i , l = queue . length ; if ( l && before ) { before ( ) ; } for ( i = 0 ; i < l ; i += 4 ) { target = queue [ i ] ; method = queue [ i + 1 ] ; args = queue [ i + 2 ] ; stack = queue [ i + 3 ] ; // Debugging assistance // TODO: error handling if ( args && args . length > 0 ) { method . apply ( target , args ) ; } else { method . call ( target ) ; } } if ( l && after ) { after ( ) ; } // check if new items have been added if ( queue . length > l ) { this . _queue = queue . slice ( l ) ; this . flush ( ) ; } else { this . _queue . length = 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": ".......................................................... BINDING [CODESPLIT] function ( toPath , fromPath ) { this . _direction = 'fwd' ; this . _from = fromPath ; this . _to = toPath ; this . _directionMap = Ember . Map . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": ".......................................................... CONNECT AND SYNC Attempts to connect this binding instance so that it can receive and relay changes . This method will raise an exception if you have not set the from / to properties yet . [CODESPLIT] function ( obj ) { Ember . assert ( 'Must pass a valid object to Ember.Binding.connect()' , ! ! obj ) ; var fromPath = this . _from , toPath = this . _to ; Ember . trySet ( obj , toPath , getWithGlobals ( obj , fromPath ) ) ; // add an observer on the object to be notified when the binding should be updated Ember . addObserver ( obj , fromPath , this , this . fromDidChange ) ; // if the binding is a two-way binding, also set up an observer on the target if ( ! this . _oneWay ) { Ember . addObserver ( obj , toPath , this , this . toDidChange ) ; } this . _readyToSync = true ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disconnects the binding instance . Changes will no longer be relayed . You will not usually need to call this method . [CODESPLIT] function ( obj ) { Ember . assert ( 'Must pass a valid object to Ember.Binding.disconnect()' , ! ! obj ) ; var twoWay = ! this . _oneWay ; // remove an observer on the object so we're no longer notified of // changes that should update bindings. Ember . removeObserver ( obj , this . _from , this , this . fromDidChange ) ; // if the binding is two-way, remove the observer from the target as well if ( twoWay ) { Ember . removeObserver ( obj , this . _to , this , this . toDidChange ) ; } this . _readyToSync = false ; // disable scheduled syncs... return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Binding instance and makes it apply in a single direction . A one - way binding will relay changes on the from side object ( supplied as the from argument ) the to side but not the other way around . This means that if you change the to side directly the from side may have a different value . [CODESPLIT] function ( from , flag ) { var C = this , binding = new C ( null , from ) ; return binding . oneWay ( flag ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "RSVP . filter is similar to JavaScript s native filter method except that it waits for all promises to become fulfilled before running the filterFn on each item in given to promises . RSVP . filter returns a promise that will become fulfilled with the result of running filterFn on the values the promises become fulfilled with . [CODESPLIT] function filter ( promises , filterFn , label ) { return all ( promises , label ) . then ( function ( values ) { if ( ! isArray ( promises ) ) { throw new TypeError ( 'You must pass an array to filter.' ) ; } if ( ! isFunction ( filterFn ) ) { throw new TypeError ( \"You must pass a function to filter's second argument.\" ) ; } return map ( promises , filterFn , label ) . then ( function ( filterResults ) { var i , valuesLen = values . length , filtered = [ ] ; for ( i = 0 ; i < valuesLen ; i ++ ) { if ( filterResults [ i ] ) filtered . push ( values [ i ] ) ; } return filtered ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A lightweight container that helps to assemble and decouple components . Public api for the container is still in flux . The public api specified on the application namespace should be considered the stable api . [CODESPLIT] function Container ( parent ) { this . parent = parent ; this . children = [ ] ; this . resolver = parent && parent . resolver || function ( ) { } ; this . registry = new InheritingDict ( parent && parent . registry ) ; this . cache = new InheritingDict ( parent && parent . cache ) ; this . factoryCache = new InheritingDict ( parent && parent . factoryCache ) ; this . resolveCache = new InheritingDict ( parent && parent . resolveCache ) ; this . typeInjections = new InheritingDict ( parent && parent . typeInjections ) ; this . injections = { } ; this . factoryTypeInjections = new InheritingDict ( parent && parent . factoryTypeInjections ) ; this . factoryInjections = { } ; this . _options = new InheritingDict ( parent && parent . _options ) ; this . _typeOptions = new InheritingDict ( parent && parent . _typeOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a factory for later injection . [CODESPLIT] function ( fullName , factory , options ) { validateFullName ( fullName ) ; if ( factory === undefined ) { throw new TypeError ( 'Attempting to register an unknown factory: `' + fullName + '`' ) ; } var normalizedName = this . normalize ( fullName ) ; if ( this . cache . has ( normalizedName ) ) { throw new Error ( 'Cannot re-register: `' + fullName + '`, as it has already been looked up.' ) ; } this . registry . set ( normalizedName , factory ) ; this . _options . set ( normalizedName , options || { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unregister a fullName [CODESPLIT] function ( fullName ) { validateFullName ( fullName ) ; var normalizedName = this . normalize ( fullName ) ; this . registry . remove ( normalizedName ) ; this . cache . remove ( normalizedName ) ; this . factoryCache . remove ( normalizedName ) ; this . resolveCache . remove ( normalizedName ) ; this . _options . remove ( normalizedName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a fullName return the corresponding factory . [CODESPLIT] function ( fullName ) { validateFullName ( fullName ) ; var normalizedName = this . normalize ( fullName ) ; var cached = this . resolveCache . get ( normalizedName ) ; if ( cached ) { return cached ; } var resolved = this . resolver ( normalizedName ) || this . registry . get ( normalizedName ) ; this . resolveCache . set ( normalizedName , resolved ) ; return resolved ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used only via injection . [CODESPLIT] function ( type , property , fullName ) { validateFullName ( fullName ) ; if ( this . parent ) { illegalChildOperation ( 'typeInjection' ) ; } addTypeInjection ( this . typeInjections , type , property , fullName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines injection rules . [CODESPLIT] function ( fullName , property , injectionName ) { if ( this . parent ) { illegalChildOperation ( 'injection' ) ; } validateFullName ( injectionName ) ; var normalizedInjectionName = this . normalize ( injectionName ) ; if ( fullName . indexOf ( ':' ) === - 1 ) { return this . typeInjection ( fullName , property , normalizedInjectionName ) ; } validateFullName ( fullName ) ; var normalizedName = this . normalize ( fullName ) ; addInjection ( this . injections , normalizedName , property , normalizedInjectionName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used only via factoryInjection . [CODESPLIT] function ( type , property , fullName ) { if ( this . parent ) { illegalChildOperation ( 'factoryTypeInjection' ) ; } addTypeInjection ( this . factoryTypeInjections , type , property , this . normalize ( fullName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the value given a key if the value is present at the current level use it otherwise walk up the parent hierarchy and try again . If no matching key is found return undefined . [CODESPLIT] function ( key ) { var dict = this . dict ; if ( dict . hasOwnProperty ( key ) ) { return dict [ key ] ; } if ( this . parent ) { return this . parent . get ( key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for the existence of given a key if the key is present at the current level return true otherwise walk up the parent hierarchy and try again . If no matching key is found return false . [CODESPLIT] function ( key ) { var dict = this . dict ; if ( dict . hasOwnProperty ( key ) ) { return true ; } if ( this . parent ) { return this . parent . has ( key ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate and invoke a callback for each local key - value pair . [CODESPLIT] function ( callback , binding ) { var dict = this . dict ; for ( var prop in dict ) { if ( dict . hasOwnProperty ( prop ) ) { callback . call ( binding , prop , dict [ prop ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply formatting options to the string . This will look for occurrences of %@ in your string and substitute them with the arguments you pass into this method . If you want to control the specific order of replacement you can add a number after the key as well to indicate which argument you want to insert . [CODESPLIT] function ( str , formats ) { // first, replace any ORDERED replacements. var idx = 0 ; // the current index for non-numerical replacements return str . replace ( / %@([0-9]+)? / g , function ( s , argIndex ) { argIndex = ( argIndex ) ? parseInt ( argIndex , 10 ) - 1 : idx ++ ; s = formats [ argIndex ] ; return ( s === null ) ? '(null)' : ( s === undefined ) ? '' : Ember . inspect ( s ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats the passed string but first looks up the string in the localized strings hash . This is a convenient way to localize text . See Ember . String . fmt () for more information on formatting . [CODESPLIT] function ( str , formats ) { str = Ember . STRINGS [ str ] || str ; return Ember . String . fmt ( str , formats ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces underscores spaces or camelCase with dashes . [CODESPLIT] function ( str ) { var cache = STRING_DASHERIZE_CACHE , hit = cache . hasOwnProperty ( str ) , ret ; if ( hit ) { return cache [ str ] ; } else { ret = Ember . String . decamelize ( str ) . replace ( STRING_DASHERIZE_REGEXP , '-' ) ; cache [ str ] = ret ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the value of a property to the current value plus some amount . [CODESPLIT] function ( keyName , increment ) { if ( Ember . isNone ( increment ) ) { increment = 1 ; } Ember . assert ( \"Must pass a numeric value to incrementProperty\" , ( ! isNaN ( parseFloat ( increment ) ) && isFinite ( increment ) ) ) ; set ( this , keyName , ( get ( this , keyName ) || 0 ) + increment ) ; return get ( this , keyName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the value of a property to the current value minus some amount . [CODESPLIT] function ( keyName , decrement ) { if ( Ember . isNone ( decrement ) ) { decrement = 1 ; } Ember . assert ( \"Must pass a numeric value to decrementProperty\" , ( ! isNaN ( parseFloat ( decrement ) ) && isFinite ( decrement ) ) ) ; set ( this , keyName , ( get ( this , keyName ) || 0 ) - decrement ) ; return get ( this , keyName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new subclass . [CODESPLIT] function ( ) { var Class = makeCtor ( ) , proto ; Class . ClassMixin = Mixin . create ( this . ClassMixin ) ; Class . PrototypeMixin = Mixin . create ( this . PrototypeMixin ) ; Class . ClassMixin . ownerConstructor = Class ; Class . PrototypeMixin . ownerConstructor = Class ; reopen . apply ( Class . PrototypeMixin , arguments ) ; Class . superclass = this ; Class . __super__ = this . prototype ; proto = Class . prototype = o_create ( this . prototype ) ; proto . constructor = Class ; generateGuid ( proto ) ; meta ( proto ) . proto = proto ; // this will disable observers on prototype Class . ClassMixin . apply ( Class ) ; return Class ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In some cases you may want to annotate computed properties with additional metadata about how they function or what values they operate on . For example computed property functions may close over variables that are then no longer available for introspection . [CODESPLIT] function ( key ) { var meta = this . proto ( ) [ META_KEY ] , desc = meta && meta . descs [ key ] ; Ember . assert ( \"metaForProperty() could not find a computed property with key '\" + key + \"'.\" , ! ! desc && desc instanceof Ember . ComputedProperty ) ; return desc . _meta || { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate over each computed property for the class passing its name and any associated metadata ( see metaForProperty ) to the callback . [CODESPLIT] function ( callback , binding ) { var proto = this . proto ( ) , descs = meta ( proto ) . descs , empty = { } , property ; for ( var name in descs ) { property = descs [ name ] ; if ( property instanceof Ember . ComputedProperty ) { callback . call ( binding || this , name , property . _meta || empty ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array with the items that do not have truthy values for key . You can pass an optional second argument with the target value . Otherwise this will match any property that evaluates to false . [CODESPLIT] function ( key , value ) { var exactValue = function ( item ) { return get ( item , key ) === value ; } , hasValue = function ( item ) { return ! ! get ( item , key ) ; } , use = ( arguments . length === 2 ? exactValue : hasValue ) ; return this . reject ( use ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new enumerable that excludes the passed value . The default implementation returns an array regardless of the receiver type unless the receiver does not contain the value . [CODESPLIT] function ( value ) { if ( ! this . contains ( value ) ) return this ; // nothing to do var ret = Ember . A ( ) ; this . forEach ( function ( k ) { if ( k !== value ) ret [ ret . length ] = k ; } ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new enumerable that contains only unique values . The default implementation returns an array regardless of the receiver type . [CODESPLIT] function ( ) { var ret = Ember . A ( ) ; this . forEach ( function ( k ) { if ( a_indexOf ( ret , k ) < 0 ) ret . push ( k ) ; } ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": ".......................................................... ARRAY OBSERVERS Adds an array observer to the receiving array . The array observer object normally must implement two methods : [CODESPLIT] function ( target , opts ) { var willChange = ( opts && opts . willChange ) || 'arrayWillChange' , didChange = ( opts && opts . didChange ) || 'arrayDidChange' ; var hasObservers = get ( this , 'hasArrayObservers' ) ; if ( ! hasObservers ) Ember . propertyWillChange ( this , 'hasArrayObservers' ) ; Ember . addListener ( this , '@array:before' , target , willChange ) ; Ember . addListener ( this , '@array:change' , target , didChange ) ; if ( ! hasObservers ) Ember . propertyDidChange ( this , 'hasArrayObservers' ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If you are implementing an object that supports Ember . Array call this method just before the array content changes to notify any observers and invalidate any related properties . Pass the starting index of the change as well as a delta of the amounts to change . [CODESPLIT] function ( startIdx , removeAmt , addAmt ) { // if no args are passed assume everything changes if ( startIdx === undefined ) { startIdx = 0 ; removeAmt = addAmt = - 1 ; } else { if ( removeAmt === undefined ) removeAmt = - 1 ; if ( addAmt === undefined ) addAmt = - 1 ; } // Make sure the @each proxy is set up if anyone is observing @each if ( Ember . isWatching ( this , '@each' ) ) { get ( this , '@each' ) ; } Ember . sendEvent ( this , '@array:before' , [ this , startIdx , removeAmt , addAmt ] ) ; var removing , lim ; if ( startIdx >= 0 && removeAmt >= 0 && get ( this , 'hasEnumerableObservers' ) ) { removing = [ ] ; lim = startIdx + removeAmt ; for ( var idx = startIdx ; idx < lim ; idx ++ ) removing . push ( this . objectAt ( idx ) ) ; } else { removing = removeAmt ; } this . enumerableContentWillChange ( removing , addAmt ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If you are implementing an object that supports Ember . Array call this method just after the array content changes to notify any observers and invalidate any related properties . Pass the starting index of the change as well as a delta of the amounts to change . [CODESPLIT] function ( startIdx , removeAmt , addAmt ) { // if no args are passed assume everything changes if ( startIdx === undefined ) { startIdx = 0 ; removeAmt = addAmt = - 1 ; } else { if ( removeAmt === undefined ) removeAmt = - 1 ; if ( addAmt === undefined ) addAmt = - 1 ; } var adding , lim ; if ( startIdx >= 0 && addAmt >= 0 && get ( this , 'hasEnumerableObservers' ) ) { adding = [ ] ; lim = startIdx + addAmt ; for ( var idx = startIdx ; idx < lim ; idx ++ ) adding . push ( this . objectAt ( idx ) ) ; } else { adding = addAmt ; } this . enumerableContentDidChange ( removeAmt , adding ) ; Ember . sendEvent ( this , '@array:change' , [ this , startIdx , removeAmt , addAmt ] ) ; var length = get ( this , 'length' ) , cachedFirst = cacheFor ( this , 'firstObject' ) , cachedLast = cacheFor ( this , 'lastObject' ) ; if ( this . objectAt ( 0 ) !== cachedFirst ) { Ember . propertyWillChange ( this , 'firstObject' ) ; Ember . propertyDidChange ( this , 'firstObject' ) ; } if ( this . objectAt ( length - 1 ) !== cachedLast ) { Ember . propertyWillChange ( this , 'lastObject' ) ; Ember . propertyDidChange ( this , 'lastObject' ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A computed property whose dependent keys are arrays and which is updated with one at a time semantics . [CODESPLIT] function ReduceComputedProperty ( options ) { var cp = this ; this . options = options ; this . _dependentKeys = null ; // A map of dependentKey -> [itemProperty, ...] that tracks what properties of // items in the array we must track to update this property. this . _itemPropertyKeys = { } ; this . _previousItemPropertyKeys = { } ; this . readOnly ( ) ; this . cacheable ( ) ; this . recomputeOnce = function ( propertyName ) { // What we really want to do is coalesce by <cp, propertyName>. // We need a form of `scheduleOnce` that accepts an arbitrary token to // coalesce by, in addition to the target and method. Ember . run . once ( this , recompute , propertyName ) ; } ; var recompute = function ( propertyName ) { var dependentKeys = cp . _dependentKeys , meta = cp . _instanceMeta ( this , propertyName ) , callbacks = cp . _callbacks ( ) ; reset . call ( this , cp , propertyName ) ; meta . dependentArraysObserver . suspendArrayObservers ( function ( ) { forEach ( cp . _dependentKeys , function ( dependentKey ) { Ember . assert ( \"dependent array \" + dependentKey + \" must be an `Ember.Array`.  \" + \"If you are not extending arrays, you will need to wrap native arrays with `Ember.A`\" , ! ( Ember . isArray ( get ( this , dependentKey ) ) && ! Ember . Array . detect ( get ( this , dependentKey ) ) ) ) ; if ( ! partiallyRecomputeFor ( this , dependentKey ) ) { return ; } var dependentArray = get ( this , dependentKey ) , previousDependentArray = meta . dependentArrays [ dependentKey ] ; if ( dependentArray === previousDependentArray ) { // The array may be the same, but our item property keys may have // changed, so we set them up again.  We can't easily tell if they've // changed: the array may be the same object, but with different // contents. if ( cp . _previousItemPropertyKeys [ dependentKey ] ) { delete cp . _previousItemPropertyKeys [ dependentKey ] ; meta . dependentArraysObserver . setupPropertyObservers ( dependentKey , cp . _itemPropertyKeys [ dependentKey ] ) ; } } else { meta . dependentArrays [ dependentKey ] = dependentArray ; if ( previousDependentArray ) { meta . dependentArraysObserver . teardownObservers ( previousDependentArray , dependentKey ) ; } if ( dependentArray ) { meta . dependentArraysObserver . setupObservers ( dependentArray , dependentKey ) ; } } } , this ) ; } , this ) ; forEach ( cp . _dependentKeys , function ( dependentKey ) { if ( ! partiallyRecomputeFor ( this , dependentKey ) ) { return ; } var dependentArray = get ( this , dependentKey ) ; if ( dependentArray ) { addItems . call ( this , dependentArray , callbacks , cp , propertyName , meta ) ; } } , this ) ; } ; this . func = function ( propertyName ) { Ember . assert ( \"Computed reduce values require at least one dependent key\" , cp . _dependentKeys ) ; recompute . call ( this , propertyName ) ; return cp . _instanceMeta ( this , propertyName ) . getValue ( ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds each object in the passed enumerable to the receiver . [CODESPLIT] function ( objects ) { Ember . beginPropertyChanges ( this ) ; forEach ( objects , function ( obj ) { this . addObject ( obj ) ; } , this ) ; Ember . endPropertyChanges ( this ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes each object in the passed enumerable from the receiver . [CODESPLIT] function ( objects ) { Ember . beginPropertyChanges ( this ) ; forEach ( objects , function ( obj ) { this . removeObject ( obj ) ; } , this ) ; Ember . endPropertyChanges ( this ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This will use the primitive replace () method to insert an object at the specified index . [CODESPLIT] function ( idx , object ) { if ( idx > get ( this , 'length' ) ) throw new Ember . Error ( OUT_OF_RANGE_EXCEPTION ) ; this . replace ( idx , 0 , [ object ] ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pop object from array or nil if none are left . Works just like pop () but it is KVO - compliant . [CODESPLIT] function ( ) { var len = get ( this , 'length' ) ; if ( len === 0 ) return null ; var ret = this . objectAt ( len - 1 ) ; this . removeAt ( len - 1 , 1 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": ".......................................................... IMPLEMENT Ember . MutableEnumerable [CODESPLIT] function ( obj ) { var loc = get ( this , 'length' ) || 0 ; while ( -- loc >= 0 ) { var curObject = this . objectAt ( loc ) ; if ( curObject === obj ) this . removeAt ( loc ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send an action with an actionContext to a target . The action actionContext and target will be retrieved from properties of the object . For example : [CODESPLIT] function ( opts ) { opts = opts || { } ; var action = opts . action || get ( this , 'action' ) , target = opts . target || get ( this , 'targetObject' ) , actionContext = opts . actionContext ; function args ( options , actionName ) { var ret = [ ] ; if ( actionName ) { ret . push ( actionName ) ; } return ret . concat ( options ) ; } if ( typeof actionContext === 'undefined' ) { actionContext = get ( this , 'actionContextObject' ) || this ; } if ( target && action ) { var ret ; if ( target . send ) { ret = target . send . apply ( target , args ( actionContext , action ) ) ; } else { Ember . assert ( \"The action '\" + action + \"' did not exist on \" + target , typeof target [ action ] === 'function' ) ; ret = target [ action ] . apply ( target , args ( actionContext ) ) ; } if ( ret !== false ) ret = true ; return ret ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers a named event for the object . Any additional arguments will be passed as parameters to the functions that are subscribed to the event . [CODESPLIT] function ( name ) { var args = [ ] , i , l ; for ( i = 1 , l = arguments . length ; i < l ; i ++ ) { args . push ( arguments [ i ] ) ; } Ember . sendEvent ( this , name , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add handlers to be called when the Deferred object is resolved or rejected . [CODESPLIT] function ( resolve , reject , label ) { var deferred , promise , entity ; entity = this ; deferred = get ( this , '_deferred' ) ; promise = deferred . promise ; function fulfillmentHandler ( fulfillment ) { if ( fulfillment === promise ) { return resolve ( entity ) ; } else { return resolve ( fulfillment ) ; } } return promise . then ( resolve && fulfillmentHandler , reject , label ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve a Deferred object and call any doneCallbacks with the given args . [CODESPLIT] function ( value ) { var deferred , promise ; deferred = get ( this , '_deferred' ) ; promise = deferred . promise ; if ( value === this ) { deferred . resolve ( promise ) ; } else { deferred . resolve ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The collection of functions keyed by name available on this ActionHandler as action targets . [CODESPLIT] function ( props ) { var hashName ; if ( ! props . _actions ) { Ember . assert ( \"'actions' should not be a function\" , typeof ( props . actions ) !== 'function' ) ; if ( typeOf ( props . actions ) === 'object' ) { hashName = 'actions' ; } else if ( typeOf ( props . events ) === 'object' ) { Ember . deprecate ( 'Action handlers contained in an `events` object are deprecated in favor of putting them in an `actions` object' , false ) ; hashName = 'events' ; } if ( hashName ) { props . _actions = Ember . merge ( props . _actions || { } , props [ hashName ] ) ; } delete props [ hashName ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers a named action on the ActionHandler . Any parameters supplied after the actionName string will be passed as arguments to the action target function . [CODESPLIT] function ( actionName ) { var args = [ ] . slice . call ( arguments , 1 ) , target ; if ( this . _actions && this . _actions [ actionName ] ) { if ( this . _actions [ actionName ] . apply ( this , args ) === true ) { // handler returned true, so this action will bubble } else { return ; } } else if ( ! Ember . FEATURES . isEnabled ( 'ember-routing-drop-deprecated-action-style' ) && this . deprecatedSend && this . deprecatedSendHandles && this . deprecatedSendHandles ( actionName ) ) { Ember . warn ( \"The current default is deprecated but will prefer to handle actions directly on the controller instead of a similarly named action in the actions hash. To turn off this deprecated feature set: Ember.FEATURES['ember-routing-drop-deprecated-action-style'] = true\" ) ; if ( this . deprecatedSend . apply ( this , [ ] . slice . call ( arguments ) ) === true ) { // handler return true, so this action will bubble } else { return ; } } if ( target = get ( this , 'target' ) ) { Ember . assert ( \"The `target` for \" + this + \" (\" + target + \") does not have a `send` method\" , typeof target . send === 'function' ) ; target . send . apply ( target , arguments ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Track that newItems were added to the tracked array at index . [CODESPLIT] function ( index , newItems ) { var count = get ( newItems , 'length' ) ; if ( count < 1 ) { return ; } var match = this . _findArrayOperation ( index ) , arrayOperation = match . operation , arrayOperationIndex = match . index , arrayOperationRangeStart = match . rangeStart , composeIndex , splitIndex , splitItems , splitArrayOperation , newArrayOperation ; newArrayOperation = new ArrayOperation ( INSERT , count , newItems ) ; if ( arrayOperation ) { if ( ! match . split ) { // insert left of arrayOperation this . _operations . splice ( arrayOperationIndex , 0 , newArrayOperation ) ; composeIndex = arrayOperationIndex ; } else { this . _split ( arrayOperationIndex , index - arrayOperationRangeStart , newArrayOperation ) ; composeIndex = arrayOperationIndex + 1 ; } } else { // insert at end this . _operations . push ( newArrayOperation ) ; composeIndex = arrayOperationIndex ; } this . _composeInsert ( composeIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Track that count items were removed at index . [CODESPLIT] function ( index , count ) { if ( count < 1 ) { return ; } var match = this . _findArrayOperation ( index ) , arrayOperation = match . operation , arrayOperationIndex = match . index , arrayOperationRangeStart = match . rangeStart , newArrayOperation , composeIndex ; newArrayOperation = new ArrayOperation ( DELETE , count ) ; if ( ! match . split ) { // insert left of arrayOperation this . _operations . splice ( arrayOperationIndex , 0 , newArrayOperation ) ; composeIndex = arrayOperationIndex ; } else { this . _split ( arrayOperationIndex , index - arrayOperationRangeStart , newArrayOperation ) ; composeIndex = arrayOperationIndex + 1 ; } return this . _composeDelete ( composeIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply all operations reducing them to retain : n for n the number of items in the array . [CODESPLIT] function ( callback ) { var items = [ ] , offset = 0 ; forEach ( this . _operations , function ( arrayOperation ) { callback ( arrayOperation . items , offset , arrayOperation . type ) ; if ( arrayOperation . type !== DELETE ) { offset += arrayOperation . count ; items = items . concat ( arrayOperation . items ) ; } } ) ; this . _operations = [ new ArrayOperation ( RETAIN , items . length , items ) ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "see SubArray for a better implementation . [CODESPLIT] function ( index ) { var newArrayOperation = this . _operations [ index ] , leftArrayOperation = this . _operations [ index - 1 ] , // may be undefined rightArrayOperation = this . _operations [ index + 1 ] , // may be undefined leftOp = leftArrayOperation && leftArrayOperation . type , rightOp = rightArrayOperation && rightArrayOperation . type ; if ( leftOp === INSERT ) { // merge left leftArrayOperation . count += newArrayOperation . count ; leftArrayOperation . items = leftArrayOperation . items . concat ( newArrayOperation . items ) ; if ( rightOp === INSERT ) { // also merge right (we have split an insert with an insert) leftArrayOperation . count += rightArrayOperation . count ; leftArrayOperation . items = leftArrayOperation . items . concat ( rightArrayOperation . items ) ; this . _operations . splice ( index , 2 ) ; } else { // only merge left this . _operations . splice ( index , 1 ) ; } } else if ( rightOp === INSERT ) { // merge right newArrayOperation . count += rightArrayOperation . count ; newArrayOperation . items = newArrayOperation . items . concat ( rightArrayOperation . items ) ; this . _operations . splice ( index + 1 , 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal data structure to represent an array operation . [CODESPLIT] function ArrayOperation ( operation , count , items ) { this . type = operation ; // RETAIN | INSERT | DELETE this . count = count ; this . items = items ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal data structure used to include information when looking up operations by item index . [CODESPLIT] function ArrayOperationMatch ( operation , index , split , rangeStart ) { this . operation = operation ; this . index = index ; this . split = split ; this . rangeStart = rangeStart ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Track that an item was added to the tracked array . [CODESPLIT] function ( index , match ) { var returnValue = - 1 , itemType = match ? RETAIN : FILTER , self = this ; this . _findOperation ( index , function ( operation , operationIndex , rangeStart , rangeEnd , seenInSubArray ) { var newOperation , splitOperation ; if ( itemType === operation . type ) { ++ operation . count ; } else if ( index === rangeStart ) { // insert to the left of `operation` self . _operations . splice ( operationIndex , 0 , new Operation ( itemType , 1 ) ) ; } else { newOperation = new Operation ( itemType , 1 ) ; splitOperation = new Operation ( operation . type , rangeEnd - index + 1 ) ; operation . count = index - rangeStart ; self . _operations . splice ( operationIndex + 1 , 0 , newOperation , splitOperation ) ; } if ( match ) { if ( operation . type === RETAIN ) { returnValue = seenInSubArray + ( index - rangeStart ) ; } else { returnValue = seenInSubArray ; } } self . _composeAt ( operationIndex ) ; } , function ( seenInSubArray ) { self . _operations . push ( new Operation ( itemType , 1 ) ) ; if ( match ) { returnValue = seenInSubArray ; } self . _composeAt ( self . _operations . length - 1 ) ; } ) ; return returnValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Track that an item was removed from the tracked array . [CODESPLIT] function ( index ) { var returnValue = - 1 , self = this ; this . _findOperation ( index , function ( operation , operationIndex , rangeStart , rangeEnd , seenInSubArray ) { if ( operation . type === RETAIN ) { returnValue = seenInSubArray + ( index - rangeStart ) ; } if ( operation . count > 1 ) { -- operation . count ; } else { self . _operations . splice ( operationIndex , 1 ) ; self . _composeAt ( operationIndex ) ; } } , function ( ) { throw new Ember . Error ( \"Can't remove an item that has never been added.\" ) ; } ) ; return returnValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "You can directly access mapped properties by simply requesting them . The unknownProperty handler will generate an EachArray of each item . [CODESPLIT] function ( keyName , value ) { var ret ; ret = new EachArray ( this . _content , keyName , this ) ; Ember . defineProperty ( this , keyName , null , ret ) ; this . beginObservingContentKey ( keyName ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "primitive for array support . [CODESPLIT] function ( idx , amt , objects ) { if ( this . isFrozen ) throw Ember . FROZEN_ERROR ; // if we replaced exactly the same number of items, then pass only the // replaced range. Otherwise, pass the full remaining array length // since everything has shifted var len = objects ? get ( objects , 'length' ) : 0 ; this . arrayContentWillChange ( idx , amt , len ) ; if ( len === 0 ) { this . splice ( idx , amt ) ; } else { replace ( this , idx , amt , objects ) ; } this . arrayContentDidChange ( idx , amt , len ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears the set . This is useful if you want to reuse an existing set without having to recreate it . [CODESPLIT] function ( ) { if ( this . isFrozen ) { throw new Ember . Error ( Ember . FROZEN_ERROR ) ; } var len = get ( this , 'length' ) ; if ( len === 0 ) { return this ; } var guid ; this . enumerableContentWillChange ( len , 0 ) ; Ember . propertyWillChange ( this , 'firstObject' ) ; Ember . propertyWillChange ( this , 'lastObject' ) ; for ( var i = 0 ; i < len ; i ++ ) { guid = guidFor ( this [ i ] ) ; delete this [ guid ] ; delete this [ i ] ; } set ( this , 'length' , 0 ) ; Ember . propertyDidChange ( this , 'firstObject' ) ; Ember . propertyDidChange ( this , 'lastObject' ) ; this . enumerableContentDidChange ( len , 0 ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the last element from the set and returns it or null if it s empty . [CODESPLIT] function ( ) { if ( get ( this , 'isFrozen' ) ) throw new Ember . Error ( Ember . FROZEN_ERROR ) ; var obj = this . length > 0 ? this [ this . length - 1 ] : null ; this . remove ( obj ) ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use this to find children by ID instead of using jQuery [CODESPLIT] function ( element , id ) { if ( element . getAttribute ( 'id' ) === id ) { return element ; } var len = element . childNodes . length , idx , node , found ; for ( idx = 0 ; idx < len ; idx ++ ) { node = element . childNodes [ idx ] ; found = node . nodeType === 1 && findChildById ( node , id ) ; if ( found ) { return found ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a class to the buffer which will be rendered to the class attribute . [CODESPLIT] function ( className ) { // lazily create elementClasses this . elementClasses = ( this . elementClasses || new ClassSet ( ) ) ; this . elementClasses . add ( className ) ; this . classes = this . elementClasses . list ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "duck type attribute functionality like jQuery so a render buffer can be used like a jQuery object in attribute binding scenarios . Adds an attribute which will be rendered to the element . [CODESPLIT] function ( name , value ) { var attributes = this . elementAttributes = ( this . elementAttributes || { } ) ; if ( arguments . length === 1 ) { return attributes [ name ] ; } else { attributes [ name ] = value ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a property which will be rendered to the element . [CODESPLIT] function ( name , value ) { var properties = this . elementProperties = ( this . elementProperties || { } ) ; if ( arguments . length === 1 ) { return properties [ name ] ; } else { properties [ name ] = value ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the HTML content for this buffer . [CODESPLIT] function ( ) { if ( this . _hasElement && this . _element ) { // Firefox versions < 11 do not have support for element.outerHTML. var thisElement = this . element ( ) , outerHTML = thisElement . outerHTML ; if ( typeof outerHTML === 'undefined' ) { return Ember . $ ( '<div/>' ) . append ( thisElement ) . html ( ) ; } return outerHTML ; } else { return this . innerString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up event listeners for standard browser events . [CODESPLIT] function ( addedEvents , rootElement ) { var event , events = get ( this , 'events' ) ; Ember . $ . extend ( events , addedEvents || { } ) ; if ( ! Ember . isNone ( rootElement ) ) { set ( this , 'rootElement' , rootElement ) ; } rootElement = Ember . $ ( get ( this , 'rootElement' ) ) ; Ember . assert ( fmt ( 'You cannot use the same root element (%@) multiple times in an Ember.Application' , [ rootElement . selector || rootElement [ 0 ] . tagName ] ) , ! rootElement . is ( '.ember-application' ) ) ; Ember . assert ( 'You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application' , ! rootElement . closest ( '.ember-application' ) . length ) ; Ember . assert ( 'You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application' , ! rootElement . find ( '.ember-application' ) . length ) ; rootElement . addClass ( 'ember-application' ) ; Ember . assert ( 'Unable to add \"ember-application\" class to rootElement. Make sure you set rootElement to the body or an element in the body.' , rootElement . is ( '.ember-application' ) ) ; for ( event in events ) { if ( events . hasOwnProperty ( event ) ) { this . setupHandler ( rootElement , event , events [ event ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers an event listener on the document . If the given event is triggered the provided event handler will be triggered on the target view . [CODESPLIT] function ( rootElement , event , eventName ) { var self = this ; rootElement . on ( event + '.ember' , '.ember-view' , function ( evt , triggeringManager ) { var view = Ember . View . views [ this . id ] , result = true , manager = null ; manager = self . _findNearestEventManager ( view , eventName ) ; if ( manager && manager !== triggeringManager ) { result = self . _dispatchEvent ( manager , evt , eventName , view ) ; } else if ( view ) { result = self . _bubbleEvent ( view , evt , eventName ) ; } else { evt . stopPropagation ( ) ; } return result ; } ) ; rootElement . on ( event + '.ember' , '[data-ember-action]' , function ( evt ) { var actionId = Ember . $ ( evt . currentTarget ) . attr ( 'data-ember-action' ) , action = Ember . Handlebars . ActionHelper . registeredActions [ actionId ] ; // We have to check for action here since in some cases, jQuery will trigger // an event on `removeChild` (i.e. focusout) after we've already torn down the // action handlers for the view. if ( action && action . eventName === eventName ) { return action . handler ( evt ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked by the view system when this view needs to produce an HTML representation . This method will create a new render buffer if needed then apply any default attributes such as class names and visibility . Finally the render () method is invoked which is responsible for doing the bulk of the rendering . [CODESPLIT] function ( parentBuffer , bufferOperation ) { var name = 'render.' + this . instrumentName , details = { } ; this . instrumentDetails ( details ) ; return Ember . instrument ( name , details , function instrumentRenderToBuffer ( ) { return this . _renderToBuffer ( parentBuffer , bufferOperation ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override the default event firing from Ember . Evented to also call methods with the given name . [CODESPLIT] function ( name ) { this . _super . apply ( this , arguments ) ; var method = this [ name ] ; if ( method ) { var args = [ ] , i , l ; for ( i = 1 , l = arguments . length ; i < l ; i ++ ) { args . push ( arguments [ i ] ) ; } return method . apply ( this , args ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the nearest ancestor that is an instance of the provided class . [CODESPLIT] function ( klass ) { Ember . deprecate ( \"nearestInstanceOf is deprecated and will be removed from future releases. Use nearestOfType.\" ) ; var view = get ( this , 'parentView' ) ; while ( view ) { if ( view instanceof klass ) { return view ; } view = get ( view , 'parentView' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the nearest ancestor that has a given property . [CODESPLIT] function ( property ) { var view = get ( this , 'parentView' ) ; while ( view ) { if ( property in view ) { return view ; } view = get ( view , 'parentView' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the nearest ancestor whose parent is an instance of klass . [CODESPLIT] function ( klass ) { var view = get ( this , 'parentView' ) ; while ( view ) { if ( get ( view , 'parentView' ) instanceof klass ) { return view ; } view = get ( view , 'parentView' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called on your view when it should push strings of HTML into a Ember . RenderBuffer . Most users will want to override the template or templateName properties instead of this method . [CODESPLIT] function ( buffer ) { // If this view has a layout, it is the responsibility of the // the layout to render the view's template. Otherwise, render the template // directly. var template = get ( this , 'layout' ) || get ( this , 'template' ) ; if ( template ) { var context = get ( this , 'context' ) ; var keywords = this . cloneKeywords ( ) ; var output ; var data = { view : this , buffer : buffer , isRenderData : true , keywords : keywords , insideGroup : get ( this , 'templateData.insideGroup' ) } ; // Invoke the template with the provided template context, which // is the view's controller by default. A hash of data is also passed that provides // the template with access to the view and render buffer. Ember . assert ( 'template must be a function. Did you mean to call Ember.Handlebars.compile(\"...\") or specify templateName instead?' , typeof template === 'function' ) ; // The template should write directly to the render buffer instead // of returning a string. output = template ( context , { data : data } ) ; // If the template returned a string instead of writing to the buffer, // push the string onto the buffer. if ( output !== undefined ) { buffer . push ( output ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set up an observer on the context . If the property changes toggle the class name . [CODESPLIT] function ( ) { // Get the current value of the property newClass = this . _classStringForProperty ( binding ) ; elem = this . $ ( ) ; // If we had previously added a class to the element, remove it. if ( oldClass ) { elem . removeClass ( oldClass ) ; // Also remove from classNames so that if the view gets rerendered, // the class doesn't get added back to the DOM. classNames . removeObject ( oldClass ) ; } // If necessary, add a new class. Make sure we keep track of it so // it can be removed in the future. if ( newClass ) { elem . addClass ( newClass ) ; oldClass = newClass ; } else { oldClass = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates through the view s attribute bindings sets up observers for each then applies the current value of the attributes to the passed render buffer . [CODESPLIT] function ( buffer , attributeBindings ) { var attributeValue , unspecifiedAttributeBindings = this . _unspecifiedAttributeBindings = this . _unspecifiedAttributeBindings || { } ; a_forEach ( attributeBindings , function ( binding ) { var split = binding . split ( ':' ) , property = split [ 0 ] , attributeName = split [ 1 ] || property ; if ( property in this ) { this . _setupAttributeBindingObservation ( property , attributeName ) ; // Determine the current value and add it to the render buffer // if necessary. attributeValue = get ( this , property ) ; Ember . View . applyAttributeBindings ( buffer , attributeName , attributeValue ) ; } else { unspecifiedAttributeBindings [ property ] = attributeName ; } } , this ) ; // Lazily setup setUnknownProperty after attributeBindings are initially applied this . setUnknownProperty = this . _setUnknownProperty ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets defined after initialization by _applyAttributeBindings [CODESPLIT] function ( key , value ) { var attributeName = this . _unspecifiedAttributeBindings && this . _unspecifiedAttributeBindings [ key ] ; if ( attributeName ) { this . _setupAttributeBindingObservation ( key , attributeName ) ; } defineProperty ( this , key ) ; return set ( this , key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run this callback on the current view ( unless includeSelf is false ) and recursively on child views . [CODESPLIT] function ( fn , includeSelf ) { var childViews = ( includeSelf === false ) ? this . _childViews : [ this ] ; var currentViews , view , currentChildViews ; while ( childViews . length ) { currentViews = childViews . slice ( ) ; childViews = [ ] ; for ( var i = 0 , l = currentViews . length ; i < l ; i ++ ) { view = currentViews [ i ] ; currentChildViews = view . _childViews ? view . _childViews . slice ( 0 ) : null ; fn ( view ) ; if ( currentChildViews ) { childViews . push . apply ( childViews , currentChildViews ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "....................................................... CORE DISPLAY METHODS Setup a view but do not finish waking it up . [CODESPLIT] function ( ) { this . elementId = this . elementId || guidFor ( this ) ; this . _super ( ) ; // setup child views. be sure to clone the child views array first this . _childViews = this . _childViews . slice ( ) ; Ember . assert ( \"Only arrays are allowed for 'classNameBindings'\" , Ember . typeOf ( this . classNameBindings ) === 'array' ) ; this . classNameBindings = Ember . A ( this . classNameBindings . slice ( ) ) ; Ember . assert ( \"Only arrays are allowed for 'classNames'\" , Ember . typeOf ( this . classNames ) === 'array' ) ; this . classNames = Ember . A ( this . classNames . slice ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "You must call destroy on a view to destroy the view ( and all of its child views ) . This will remove the view from any parent node then make sure that the DOM element managed by the view can be released by the memory manager . [CODESPLIT] function ( ) { var childViews = this . _childViews , // get parentView before calling super because it'll be destroyed nonVirtualParentView = get ( this , 'parentView' ) , viewName = this . viewName , childLen , i ; if ( ! this . _super ( ) ) { return ; } childLen = childViews . length ; for ( i = childLen - 1 ; i >= 0 ; i -- ) { childViews [ i ] . removedFromDOM = true ; } // remove from non-virtual parent view if viewName was specified if ( viewName && nonVirtualParentView ) { nonVirtualParentView . set ( viewName , null ) ; } childLen = childViews . length ; for ( i = childLen - 1 ; i >= 0 ; i -- ) { childViews [ i ] . destroy ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates a view to be added to the childViews array during view initialization . You generally will not call this method directly unless you are overriding createChildViews () . Note that this method will automatically configure the correct settings on the new view instance to act as a child of the parent . [CODESPLIT] function ( view , attrs ) { if ( ! view ) { throw new TypeError ( \"createChildViews first argument must exist\" ) ; } if ( view . isView && view . _parentView === this && view . container === this . container ) { return view ; } attrs = attrs || { } ; attrs . _parentView = this ; if ( Ember . CoreView . detect ( view ) ) { attrs . templateData = attrs . templateData || get ( this , 'templateData' ) ; attrs . container = this . container ; view = view . create ( attrs ) ; // don't set the property on a virtual view, as they are invisible to // consumers of the view API if ( view . viewName ) { set ( get ( this , 'concreteView' ) , view . viewName , view ) ; } } else if ( 'string' === typeof view ) { var fullName = 'view:' + view ; var View = this . container . lookupFactory ( fullName ) ; Ember . assert ( \"Could not find view: '\" + fullName + \"'\" , ! ! View ) ; attrs . templateData = get ( this , 'templateData' ) ; view = View . create ( attrs ) ; } else { Ember . assert ( 'You must pass instance or subclass of View' , view . isView ) ; attrs . container = this . container ; if ( ! get ( view , 'templateData' ) ) { attrs . templateData = get ( this , 'templateData' ) ; } Ember . setProperties ( view , attrs ) ; } return view ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a path and return an object which holds the parsed properties . [CODESPLIT] function ( path ) { var split = path . split ( ':' ) , propertyPath = split [ 0 ] , classNames = \"\" , className , falsyClassName ; // check if the property is defined as prop:class or prop:trueClass:falseClass if ( split . length > 1 ) { className = split [ 1 ] ; if ( split . length === 3 ) { falsyClassName = split [ 2 ] ; } classNames = ':' + className ; if ( falsyClassName ) { classNames += \":\" + falsyClassName ; } } return { path : propertyPath , classNames : classNames , className : ( className === '' ) ? undefined : className , falsyClassName : falsyClassName } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a view leaves the preRender state once its element has been created ( createElement ) . [CODESPLIT] function ( view , fn ) { view . createElement ( ) ; var viewCollection = view . viewHierarchyCollection ( ) ; viewCollection . trigger ( 'willInsertElement' ) ; fn . call ( view ) ; // We transition to `inDOM` if the element exists in the DOM var element = view . get ( 'element' ) ; if ( document . body . contains ( element ) ) { viewCollection . transitionTo ( 'inDOM' , false ) ; viewCollection . trigger ( 'didInsertElement' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "when a view is rendered in a buffer appending a child view will render that view and append the resulting buffer into its buffer . [CODESPLIT] function ( view , childView , options ) { var buffer = view . buffer , _childViews = view . _childViews ; childView = view . createChildView ( childView , options ) ; if ( ! _childViews . length ) { _childViews = view . _childViews = _childViews . slice ( ) ; } _childViews . push ( childView ) ; childView . renderToBuffer ( buffer ) ; view . propertyDidChange ( 'childViews' ) ; return childView ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "when a view is rendered in a buffer destroying the element will simply destroy the buffer and put the state back into the preRender state . [CODESPLIT] function ( view ) { view . clearBuffer ( ) ; var viewCollection = view . _notifyWillDestroyElement ( ) ; viewCollection . transitionTo ( 'preRender' , false ) ; return view ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "once the view has been inserted into the DOM rerendering is deferred to allow bindings to synchronize . [CODESPLIT] function ( view ) { view . triggerRecursively ( 'willClearRender' ) ; view . clearRenderedChildren ( ) ; view . domManager . replace ( view ) ; return view ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "once the view is already in the DOM destroying it removes it from the DOM nukes its element and puts it back into the preRender state if inDOM . [CODESPLIT] function ( view ) { view . _notifyWillDestroyElement ( ) ; view . domManager . remove ( view ) ; set ( view , 'element' , null ) ; if ( view . _scheduledInsert ) { Ember . run . cancel ( view . _scheduledInsert ) ; view . _scheduledInsert = null ; } return view ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle events from Ember . EventDispatcher [CODESPLIT] function ( view , eventName , evt ) { if ( view . has ( eventName ) ) { // Handler should be able to re-dispatch events, so we don't // preventDefault or stopPropagation. return view . trigger ( eventName , evt ) ; } else { return true ; // continue event propagation } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When a child view is removed destroy its element so that it is removed from the DOM . [CODESPLIT] function ( views , start , removed ) { this . propertyWillChange ( 'childViews' ) ; if ( removed > 0 ) { var changedViews = views . slice ( start , start + removed ) ; // transition to preRender before clearing parentView this . currentState . childViewsWillChange ( this , views , start , removed ) ; this . initializeViews ( changedViews , null , null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When a child view is added make sure the DOM gets updated appropriately . [CODESPLIT] function ( views , start , removed , added ) { if ( added > 0 ) { var changedViews = views . slice ( start , start + added ) ; this . initializeViews ( changedViews , this , get ( this , 'templateData' ) ) ; this . currentState . childViewsDidChange ( this , views , start , added ) ; } this . propertyDidChange ( 'childViews' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when a mutation to the underlying content array will occur . [CODESPLIT] function ( content , start , removedCount ) { // If the contents were empty before and this template collection has an // empty view remove it now. var emptyView = get ( this , 'emptyView' ) ; if ( emptyView && emptyView instanceof Ember . View ) { emptyView . removeFromParent ( ) ; } // Loop through child views that correspond with the removed items. // Note that we loop from the end of the array to the beginning because // we are mutating it as we go. var childViews = this . _childViews , childView , idx , len ; len = this . _childViews . length ; var removingAll = removedCount === len ; if ( removingAll ) { this . currentState . empty ( this ) ; this . invokeRecursively ( function ( view ) { view . removedFromDOM = true ; } , false ) ; } for ( idx = start + removedCount - 1 ; idx >= start ; idx -- ) { childView = childViews [ idx ] ; childView . destroy ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when a mutation to the underlying content array occurs . [CODESPLIT] function ( content , start , removed , added ) { var addedViews = [ ] , view , item , idx , len , itemViewClass , emptyView ; len = content ? get ( content , 'length' ) : 0 ; if ( len ) { itemViewClass = get ( this , 'itemViewClass' ) ; if ( 'string' === typeof itemViewClass ) { itemViewClass = get ( itemViewClass ) || itemViewClass ; } Ember . assert ( fmt ( \"itemViewClass must be a subclass of Ember.View, not %@\" , [ itemViewClass ] ) , 'string' === typeof itemViewClass || Ember . View . detect ( itemViewClass ) ) ; for ( idx = start ; idx < start + added ; idx ++ ) { item = content . objectAt ( idx ) ; view = this . createChildView ( itemViewClass , { content : item , contentIndex : idx } ) ; addedViews . push ( view ) ; } } else { emptyView = get ( this , 'emptyView' ) ; if ( ! emptyView ) { return ; } if ( 'string' === typeof emptyView ) { emptyView = get ( emptyView ) || emptyView ; } emptyView = this . createChildView ( emptyView ) ; addedViews . push ( emptyView ) ; set ( this , 'emptyView' , emptyView ) ; if ( Ember . CoreView . detect ( emptyView ) ) { this . _createdEmptyView = emptyView ; } } this . replace ( start , 0 , addedViews ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private [CODESPLIT] function ( props ) { // must call _super here to ensure that the ActionHandler // mixin is setup properly (moves actions -> _actions) // // Calling super is only OK here since we KNOW that // there is another Mixin loaded first. this . _super . apply ( this , arguments ) ; var deprecatedProperty , replacementProperty , layoutSpecified = ( props . layoutName || props . layout || get ( this , 'layoutName' ) ) ; if ( props . templateName && ! layoutSpecified ) { deprecatedProperty = 'templateName' ; replacementProperty = 'layoutName' ; props . layoutName = props . templateName ; delete props [ 'templateName' ] ; } if ( props . template && ! layoutSpecified ) { deprecatedProperty = 'template' ; replacementProperty = 'layout' ; props . layout = props . template ; delete props [ 'template' ] ; } if ( deprecatedProperty ) { Ember . deprecate ( 'Do not specify ' + deprecatedProperty + ' on a Component, use ' + replacementProperty + ' instead.' , false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers a named action on the controller context where the component is used if this controller has registered for notifications of the action . [CODESPLIT] function ( action ) { var actionName , contexts = a_slice . call ( arguments , 1 ) ; // Send the default action if ( action === undefined ) { actionName = get ( this , 'action' ) ; Ember . assert ( \"The default action was triggered on the component \" + this . toString ( ) + \", but the action name (\" + actionName + \") was not a string.\" , isNone ( actionName ) || typeof actionName === 'string' ) ; } else { actionName = get ( this , action ) ; Ember . assert ( \"The \" + action + \" action was triggered on the component \" + this . toString ( ) + \", but the action name (\" + actionName + \") was not a string.\" , isNone ( actionName ) || typeof actionName === 'string' ) ; } // If no action name for that action could be found, just abort. if ( actionName === undefined ) { return ; } this . triggerAction ( { action : actionName , actionContext : contexts } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor that supports either Metamorph ( foo ) or new Metamorph ( foo ) ; Takes a string of HTML as the argument . [CODESPLIT] function ( html ) { var self ; if ( this instanceof Metamorph ) { self = this ; } else { self = new K ( ) ; } self . innerHTML = html ; var myGuid = 'metamorph-' + ( guid ++ ) ; self . start = myGuid + '-start' ; self . end = myGuid + '-end' ; return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Given a parent node and some HTML generate a set of nodes . Return the first node which will allow us to traverse the rest using nextSibling . [CODESPLIT] function ( parentNode , html ) { var arr = wrapMap [ parentNode . tagName . toLowerCase ( ) ] || wrapMap . _default ; var depth = arr [ 0 ] , start = arr [ 1 ] , end = arr [ 2 ] ; if ( needsShy ) { html = '&shy;' + html ; } var element = document . createElement ( 'div' ) ; setInnerHTML ( element , start + html + end ) ; for ( var i = 0 ; i <= depth ; i ++ ) { element = element . firstChild ; } // Look for &shy; to remove it. if ( needsShy ) { var shyElement = element ; // Sometimes we get nameless elements with the shy inside while ( shyElement . nodeType === 1 && ! shyElement . nodeName ) { shyElement = shyElement . firstChild ; } // At this point it's the actual unicode character. if ( shyElement . nodeType === 3 && shyElement . nodeValue . charAt ( 0 ) === \"\\u00AD\" ) { shyElement . nodeValue = shyElement . nodeValue . slice ( 1 ) ; } } return element ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * When automatically adding a tbody Internet Explorer inserts the tbody immediately before the first <tr > . Other browsers create it before the first node no matter what . [CODESPLIT] function ( start , end ) { if ( start . parentNode !== end . parentNode ) { end . parentNode . insertBefore ( start , end . parentNode . firstChild ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders the unbound form of an otherwise bound helper function . [CODESPLIT] function evaluateUnboundHelper ( context , fn , normalizedProperties , options ) { var args = [ ] , hash = options . hash , boundOptions = hash . boundOptions , types = slice . call ( options . types , 1 ) , loc , len , property , propertyType , boundOption ; for ( boundOption in boundOptions ) { if ( ! boundOptions . hasOwnProperty ( boundOption ) ) { continue ; } hash [ boundOption ] = Ember . Handlebars . get ( context , boundOptions [ boundOption ] , options ) ; } for ( loc = 0 , len = normalizedProperties . length ; loc < len ; ++ loc ) { property = normalizedProperties [ loc ] ; propertyType = types [ loc ] ; if ( propertyType === \"ID\" ) { args . push ( Ember . Handlebars . get ( property . root , property . path , options ) ) ; } else { args . push ( property . path ) ; } } args . push ( options ) ; return fn . apply ( context , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is messed up . [CODESPLIT] function ( view ) { var morph = view . morph ; view . transitionTo ( 'preRender' ) ; Ember . run . schedule ( 'render' , this , function renderMetamorphView ( ) { if ( view . isDestroying ) { return ; } view . clearRenderedChildren ( ) ; var buffer = view . renderToBuffer ( ) ; view . invokeRecursively ( function ( view ) { view . propertyWillChange ( 'element' ) ; } ) ; view . triggerRecursively ( 'willInsertElement' ) ; morph . replaceWith ( buffer . string ( ) ) ; view . transitionTo ( 'inDOM' ) ; view . invokeRecursively ( function ( view ) { view . propertyDidChange ( 'element' ) ; } ) ; view . triggerRecursively ( 'didInsertElement' ) ; notifyMutationListeners ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds a property into the DOM . This will create a hook in DOM that the KVO system will look for and update if the property changes . [CODESPLIT] function bind ( property , options , preserveContext , shouldDisplay , valueNormalizer , childProperties ) { var data = options . data , fn = options . fn , inverse = options . inverse , view = data . view , currentContext = this , normalized , observer , i ; normalized = normalizePath ( currentContext , property , data ) ; // Set up observers for observable objects if ( 'object' === typeof this ) { if ( data . insideGroup ) { observer = function ( ) { Ember . run . once ( view , 'rerender' ) ; } ; var template , context , result = handlebarsGet ( currentContext , property , options ) ; result = valueNormalizer ? valueNormalizer ( result ) : result ; context = preserveContext ? currentContext : result ; if ( shouldDisplay ( result ) ) { template = fn ; } else if ( inverse ) { template = inverse ; } template ( context , { data : options . data } ) ; } else { // Create the view that will wrap the output of this template/property // and add it to the nearest view's childViews array. // See the documentation of Ember._HandlebarsBoundView for more. var bindView = view . createChildView ( Ember . _HandlebarsBoundView , { preserveContext : preserveContext , shouldDisplayFunc : shouldDisplay , valueNormalizerFunc : valueNormalizer , displayTemplate : fn , inverseTemplate : inverse , path : property , pathRoot : currentContext , previousContext : currentContext , isEscaped : ! options . hash . unescaped , templateData : options . data } ) ; if ( options . hash . controller ) { bindView . set ( '_contextController' , this . container . lookupFactory ( 'controller:' + options . hash . controller ) . create ( { container : currentContext . container , parentController : currentContext , target : currentContext } ) ) ; } view . appendChild ( bindView ) ; observer = function ( ) { Ember . run . scheduleOnce ( 'render' , bindView , 'rerenderIfNeeded' ) ; } ; } // Observes the given property on the context and // tells the Ember._HandlebarsBoundView to re-render. If property // is an empty string, we are printing the current context // object ({{this}}) so updating it is not our responsibility. if ( normalized . path !== '' ) { view . registerObserver ( normalized . root , normalized . path , observer ) ; if ( childProperties ) { for ( i = 0 ; i < childProperties . length ; i ++ ) { view . registerObserver ( normalized . root , normalized . path + '.' + childProperties [ i ] , observer ) ; } } } } else { // The object is not observable, so just render it out and // be done with it. data . buffer . push ( handlebarsGetEscaped ( currentContext , property , options ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform bindings from the current context to a context that can be evaluated within the view . Returns null if the path shouldn t be changed . TODO : consider the addition of a prefix that would allow this method to return path . [CODESPLIT] function ( path , data ) { var normalized = Ember . Handlebars . normalizePath ( null , path , data ) ; if ( normalized . isKeyword ) { return 'templateData.keywords.' + path ; } else if ( Ember . isGlobalPath ( path ) ) { return null ; } else if ( path === 'this' || path === '' ) { return '_parentView.context' ; } else { return '_parentView.context.' + path ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defeatureify doesn t seem to like nested functions that need to be removed [CODESPLIT] function _addMetamorphCheck ( ) { Ember . Handlebars . EachView . reopen ( { _checkMetamorph : Ember . on ( 'didInsertElement' , function ( ) { Ember . assert ( \"The metamorph tags, \" + this . morph . start + \" and \" + this . morph . end + \", have different parents.\\nThe browser has fixed your template to output valid HTML (for example, check that you have properly closed all tags and have used a TBODY tag when creating a table with '{{#each}}')\" , document . getElementById ( this . morph . start ) . parentNode === document . getElementById ( this . morph . end ) . parentNode ) ; } ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NOTE : this doesn t really belong here but here it shall remain until our ES6 transpiler can handle cyclical deps . [CODESPLIT] function ( intent , isIntermediate ) { var wasTransitioning = ! ! this . activeTransition ; var oldState = wasTransitioning ? this . activeTransition . state : this . state ; var newTransition ; var router = this ; try { var newState = intent . applyToState ( oldState , this . recognizer , this . getHandler , isIntermediate ) ; if ( handlerInfosEqual ( newState . handlerInfos , oldState . handlerInfos ) ) { // This is a no-op transition. See if query params changed. var queryParamChangelist = getChangelist ( oldState . queryParams , newState . queryParams ) ; if ( queryParamChangelist ) { // This is a little hacky but we need some way of storing // changed query params given that no activeTransition // is guaranteed to have occurred. this . _changedQueryParams = queryParamChangelist . changed ; trigger ( this , newState . handlerInfos , true , [ 'queryParamsDidChange' , queryParamChangelist . changed , queryParamChangelist . all , queryParamChangelist . removed ] ) ; this . _changedQueryParams = null ; if ( ! wasTransitioning && this . activeTransition ) { // One of the handlers in queryParamsDidChange // caused a transition. Just return that transition. return this . activeTransition ; } else { // Running queryParamsDidChange didn't change anything. // Just update query params and be on our way. oldState . queryParams = finalizeQueryParamChange ( this , newState . handlerInfos , newState . queryParams ) ; // We have to return a noop transition that will // perform a URL update at the end. This gives // the user the ability to set the url update // method (default is replaceState). newTransition = new Transition ( this ) ; newTransition . urlMethod = 'replace' ; newTransition . promise = newTransition . promise . then ( function ( result ) { updateURL ( newTransition , oldState , true ) ; if ( router . didTransition ) { router . didTransition ( router . currentHandlerInfos ) ; } return result ; } , null , promiseLabel ( \"Transition complete\" ) ) ; return newTransition ; } } // No-op. No need to create a new transition. return new Transition ( this ) ; } if ( isIntermediate ) { setupContexts ( this , newState ) ; return ; } // Create a new transition to the destination route. newTransition = new Transition ( this , intent , newState ) ; // Abort and usurp any previously active transition. if ( this . activeTransition ) { this . activeTransition . abort ( ) ; } this . activeTransition = newTransition ; // Transition promises by default resolve with resolved state. // For our purposes, swap out the promise to resolve // after the transition has been finalized. newTransition . promise = newTransition . promise . then ( function ( result ) { return router . async ( function ( ) { return finalizeTransition ( newTransition , result . state ) ; } , \"Finalize transition\" ) ; } , null , promiseLabel ( \"Settle transition promise when transition is finalized\" ) ) ; if ( ! wasTransitioning ) { trigger ( this , this . state . handlerInfos , true , [ 'willTransition' , newTransition ] ) ; } return newTransition ; } catch ( e ) { return new Transition ( this , intent , null , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears the current and target route handlers and triggers exit on each of them starting at the leaf and traversing up through its ancestors . [CODESPLIT] function ( ) { if ( this . state ) { forEach ( this . state . handlerInfos , function ( handlerInfo ) { var handler = handlerInfo . handler ; if ( handler . exit ) { handler . exit ( ) ; } } ) ; } this . state = new TransitionState ( ) ; this . currentHandlerInfos = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "var handler = handlerInfo . handler ; The entry point for handling a change to the URL ( usually via the back and forward button ) . [CODESPLIT] function ( url ) { // Perform a URL-based transition, but don't change // the URL afterward, since it already happened. var args = slice . call ( arguments ) ; if ( url . charAt ( 0 ) !== '/' ) { args [ 0 ] = '/' + url ; } return doTransition ( this , args ) . method ( 'replaceQuery' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private [CODESPLIT] function setupContexts ( router , newState , transition ) { var partition = partitionHandlers ( router . state , newState ) ; forEach ( partition . exited , function ( handlerInfo ) { var handler = handlerInfo . handler ; delete handler . context ; if ( handler . exit ) { handler . exit ( ) ; } } ) ; var oldState = router . oldState = router . state ; router . state = newState ; var currentHandlerInfos = router . currentHandlerInfos = partition . unchanged . slice ( ) ; try { forEach ( partition . updatedContext , function ( handlerInfo ) { return handlerEnteredOrUpdated ( currentHandlerInfos , handlerInfo , false , transition ) ; } ) ; forEach ( partition . entered , function ( handlerInfo ) { return handlerEnteredOrUpdated ( currentHandlerInfos , handlerInfo , true , transition ) ; } ) ; } catch ( e ) { router . state = oldState ; router . currentHandlerInfos = oldState . handlerInfos ; throw e ; } router . state . queryParams = finalizeQueryParamChange ( router , currentHandlerInfos , newState . queryParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private [CODESPLIT] function handlerEnteredOrUpdated ( currentHandlerInfos , handlerInfo , enter , transition ) { var handler = handlerInfo . handler , context = handlerInfo . context ; if ( enter && handler . enter ) { handler . enter ( transition ) ; } if ( transition && transition . isAborted ) { throw new TransitionAborted ( ) ; } handler . context = context ; if ( handler . contextDidChange ) { handler . contextDidChange ( ) ; } if ( handler . setup ) { handler . setup ( context , transition ) ; } if ( transition && transition . isAborted ) { throw new TransitionAborted ( ) ; } currentHandlerInfos . push ( handlerInfo ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private [CODESPLIT] function doTransition ( router , args , isIntermediate ) { // Normalize blank transitions to root URL transitions. var name = args [ 0 ] || '/' ; var lastArg = args [ args . length - 1 ] ; var queryParams = { } ; if ( lastArg && lastArg . hasOwnProperty ( 'queryParams' ) ) { queryParams = pop . call ( args ) . queryParams ; } var intent ; if ( args . length === 0 ) { log ( router , \"Updating query params\" ) ; // A query param update is really just a transition // into the route you're already on. var handlerInfos = router . state . handlerInfos ; intent = new NamedTransitionIntent ( { name : handlerInfos [ handlerInfos . length - 1 ] . name , contexts : [ ] , queryParams : queryParams } ) ; } else if ( name . charAt ( 0 ) === '/' ) { log ( router , \"Attempting URL transition to \" + name ) ; intent = new URLTransitionIntent ( { url : name } ) ; } else { log ( router , \"Attempting transition to \" + name ) ; intent = new NamedTransitionIntent ( { name : args [ 0 ] , contexts : slice . call ( args , 1 ) , queryParams : queryParams } ) ; } return router . transitionByIntent ( intent , isIntermediate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@public [CODESPLIT] function ( ) { if ( this . isAborted ) { return this ; } log ( this . router , this . sequence , this . targetName + \": transition was aborted\" ) ; this . isAborted = true ; this . isActive = false ; this . router . activeTransition = null ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@public [CODESPLIT] function ( ) { var router = this . router ; return this . promise [ 'catch' ] ( function ( reason ) { if ( router . activeTransition ) { return router . activeTransition . followRedirects ( ) ; } return reject ( reason ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private [CODESPLIT] function extractQueryParams ( array ) { var len = ( array && array . length ) , head , queryParams ; if ( len && len > 0 && array [ len - 1 ] && array [ len - 1 ] . hasOwnProperty ( 'queryParams' ) ) { queryParams = array [ len - 1 ] . queryParams ; head = slice . call ( array , 0 , len - 1 ) ; return [ head , queryParams ] ; } else { return [ array , null ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private [CODESPLIT] function serialize ( handler , model , names ) { var object = { } ; if ( isParam ( model ) ) { object [ names [ 0 ] ] = model ; return object ; } // Use custom serialize if it exists. if ( handler . serialize ) { return handler . serialize ( model , names ) ; } if ( names . length !== 1 ) { return ; } var name = names [ 0 ] ; if ( / _id$ / . test ( name ) ) { object [ name ] = model . id ; } else { object [ name ] = model ; } return object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the current router instance and sets up the change handling event listeners used by the instances location implementation . [CODESPLIT] function ( ) { this . router = this . router || this . constructor . map ( Ember . K ) ; var router = this . router , location = get ( this , 'location' ) , container = this . container , self = this , initialURL = get ( this , 'initialURL' ) ; // Allow the Location class to cancel the router setup while it refreshes // the page if ( get ( location , 'cancelRouterSetup' ) ) { return ; } this . _setupRouter ( router , location ) ; container . register ( 'view:default' , DefaultView ) ; container . register ( 'view:toplevel' , Ember . View . extend ( ) ) ; location . onUpdateURL ( function ( url ) { self . handleURL ( url ) ; } ) ; if ( typeof initialURL === \"undefined\" ) { initialURL = location . getURL ( ) ; } this . handleURL ( initialURL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private [CODESPLIT] function ( results , queryParams , callback ) { for ( var name in queryParams ) { var parts = name . split ( ':' ) ; var controller = controllerOrProtoFor ( parts [ 0 ] , this . container ) ; Ember . assert ( fmt ( \"Could not lookup controller '%@' while setting up query params\" , [ controller ] ) , controller ) ; // Now assign the final URL-serialized key-value pair, // e.g. \"foo[propName]\": \"value\" results [ queryParams [ name ] ] = get ( controller , parts [ 1 ] ) ; if ( callback ) { // Give callback a chance to override. callback ( name , queryParams [ name ] , name ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This hook is the entry point for router . js [CODESPLIT] function ( context , transition ) { var controllerName = this . controllerName || this . routeName , controller = this . controllerFor ( controllerName , true ) ; if ( ! controller ) { controller = this . generateController ( controllerName , context ) ; } // Assign the route's controller so that it can more easily be // referenced in action handlers this . controller = controller ; if ( this . setupControllers ) { Ember . deprecate ( \"Ember.Route.setupControllers is deprecated. Please use Ember.Route.setupController(controller, model) instead.\" ) ; this . setupControllers ( controller , context ) ; } else { this . setupController ( controller , context ) ; } if ( this . renderTemplates ) { Ember . deprecate ( \"Ember.Route.renderTemplates is deprecated. Please use Ember.Route.renderTemplate(controller, model) instead.\" ) ; this . renderTemplates ( context ) ; } else { this . renderTemplate ( controller , context ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A hook you can implement to convert the URL into the model for this route . [CODESPLIT] function ( params , transition ) { var match , name , sawParams , value ; for ( var prop in params ) { if ( prop === 'queryParams' ) { continue ; } if ( match = prop . match ( / ^(.*)_id$ / ) ) { name = match [ 1 ] ; value = params [ prop ] ; } sawParams = true ; } if ( ! name && sawParams ) { return Ember . copy ( params ) ; } else if ( ! name ) { if ( transition . resolveIndex !== transition . state . handlerInfos . length - 1 ) { return ; } var parentModel = transition . state . handlerInfos [ transition . resolveIndex - 1 ] . context ; return parentModel ; } return this . findModel ( name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A hook you can implement to convert the route s model into parameters for the URL . [CODESPLIT] function ( model , params ) { if ( params . length < 1 ) { return ; } if ( ! model ) { return ; } var name = params [ 0 ] , object = { } ; if ( / _id$ / . test ( name ) && params . length === 1 ) { object [ name ] = get ( model , \"id\" ) ; } else { object = getProperties ( model , params ) ; } return object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the controller for a particular route or name . [CODESPLIT] function ( name , _skipAssert ) { var container = this . container , route = container . lookup ( 'route:' + name ) , controller ; if ( route && route . controllerName ) { name = route . controllerName ; } controller = container . lookup ( 'controller:' + name ) ; // NOTE: We're specifically checking that skipAssert is true, because according //   to the old API the second parameter was model. We do not want people who //   passed a model to skip the assertion. Ember . assert ( \"The controller named '\" + name + \"' could not be found. Make sure \" + \"that this route exists and has already been entered at least \" + \"once. If you are accessing a controller not associated with a \" + \"route, make sure the controller class is explicitly defined.\" , controller || _skipAssert === true ) ; return controller ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disconnects a view that has been rendered into an outlet . [CODESPLIT] function ( options ) { if ( ! options || typeof options === \"string\" ) { var outletName = options ; options = { } ; options . outlet = outletName ; } options . parentView = options . parentView ? options . parentView . replace ( / \\/ / g , '.' ) : parentTemplate ( this ) ; options . outlet = options . outlet || 'main' ; var parentView = this . router . _lookupActiveView ( options . parentView ) ; if ( parentView ) { parentView . disconnectOutlet ( options . outlet ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private [CODESPLIT] function ( ) { // Tear down the top level view if ( this . teardownTopLevelView ) { this . teardownTopLevelView ( ) ; } // Tear down any outlets rendered with 'into' var teardownOutletViews = this . teardownOutletViews || [ ] ; a_forEach ( teardownOutletViews , function ( teardownOutletView ) { teardownOutletView ( ) ; } ) ; delete this . teardownTopLevelView ; delete this . teardownOutletViews ; delete this . lastRenderedTemplate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is called to setup observers that will trigger a rerender . [CODESPLIT] function ( ) { var helperParameters = this . parameters , linkTextPath = helperParameters . options . linkTextPath , paths = getResolvedPaths ( helperParameters ) , length = paths . length , path , i , normalizedPath ; if ( linkTextPath ) { normalizedPath = Ember . Handlebars . normalizePath ( helperParameters . context , linkTextPath , helperParameters . options . data ) ; this . registerObserver ( normalizedPath . root , normalizedPath . path , this , this . rerender ) ; } for ( i = 0 ; i < length ; i ++ ) { path = paths [ i ] ; if ( null === path ) { // A literal value was provided, not a path, so nothing to observe. continue ; } normalizedPath = Ember . Handlebars . normalizePath ( helperParameters . context , path , helperParameters . options . data ) ; this . registerObserver ( normalizedPath . root , normalizedPath . path , this , this . _paramsChanged ) ; } var queryParamsObject = this . queryParamsObject ; if ( queryParamsObject ) { var values = queryParamsObject . values ; // Install observers for all of the hash options // provided in the (query-params) subexpression. for ( var k in values ) { if ( ! values . hasOwnProperty ( k ) ) { continue ; } if ( queryParamsObject . types [ k ] === 'ID' ) { normalizedPath = Ember . Handlebars . normalizePath ( helperParameters . context , values [ k ] , helperParameters . options . data ) ; this . registerObserver ( normalizedPath . root , normalizedPath . path , this , this . _paramsChanged ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler that invokes the link activating the associated route . [CODESPLIT] function ( event ) { if ( ! isSimpleClick ( event ) ) { return true ; } if ( this . preventDefault !== false ) { event . preventDefault ( ) ; } if ( this . bubbles === false ) { event . stopPropagation ( ) ; } if ( get ( this , '_isDisabled' ) ) { return false ; } if ( get ( this , 'loading' ) ) { Ember . Logger . warn ( \"This link-to is in an inactive loading state because at least one of its parameters presently has a null/undefined value, or the provided route name is invalid.\" ) ; return false ; } var router = get ( this , 'router' ) , routeArgs = get ( this , 'routeArgs' ) ; var transition ; if ( get ( this , 'replace' ) ) { transition = router . replaceWith . apply ( router , routeArgs ) ; } else { transition = router . transitionTo . apply ( router , routeArgs ) ; } // Schedule eager URL update, but after we've given the transition // a chance to synchronously redirect. // We need to always generate the URL instead of using the href because // the href will include any rootURL set, but the router expects a URL // without it! Note that we don't use the first level router because it // calls location.formatURL(), which also would add the rootURL! var url = router . router . generate . apply ( router . router , get ( this , 'routeArgs' ) ) ; Ember . run . scheduleOnce ( 'routerTransitions' , this , this . _eagerUpdateUrl , transition , url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transition the application into another route . The route may be either a single route or route path : [CODESPLIT] function ( ) { // target may be either another controller or a router var target = get ( this , 'target' ) , method = target . transitionToRoute || target . transitionTo ; return method . apply ( target , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transition into another route while replacing the current URL if possible . This will replace the current history entry instead of adding a new one . Beside that it is identical to transitionToRoute in all other respects . [CODESPLIT] function ( ) { // target may be either another controller or a router var target = get ( this , 'target' ) , method = target . replaceRoute || target . replaceWith ; return method . apply ( target , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the view has already been created by checking if the view has the same constructor template and context as the view in the _outlets object . [CODESPLIT] function ( outletName , view ) { var existingView = get ( this , '_outlets.' + outletName ) ; return existingView && existingView . constructor === view . constructor && existingView . get ( 'template' ) === view . get ( 'template' ) && existingView . get ( 'context' ) === view . get ( 'context' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets an outlet that is pending disconnection and then nullifys the object on the _outlet object . [CODESPLIT] function ( ) { if ( this . isDestroyed ) return ; // _outlets will be gone anyway var outlets = get ( this , '_outlets' ) ; var pendingDisconnections = this . _pendingDisconnections ; this . _pendingDisconnections = null ; for ( var outletName in pendingDisconnections ) { set ( outlets , outletName , null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the current location . hash by parsing location . href since browsers inconsistently URL - decode location . hash . [CODESPLIT] function ( ) { // AutoLocation has it at _location, HashLocation at .location. // Being nice and not changing  var href = ( this . _location || this . location ) . href , hashIndex = href . indexOf ( '#' ) ; if ( hashIndex === - 1 ) { return '' ; } else { return href . substr ( hashIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the current state . [CODESPLIT] function ( path ) { var state = { path : path } ; get ( this , 'history' ) . replaceState ( state , null , path ) ; // store state if browser doesn't support `history.state` if ( ! supportsHistoryState ) { this . _historyState = state ; } // used for webkit workaround this . _previousURL = this . getURL ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a callback to be invoked whenever the browser history changes including using forward and back buttons . [CODESPLIT] function ( callback ) { var guid = Ember . guidFor ( this ) , self = this ; Ember . $ ( window ) . on ( 'popstate.ember-location-' + guid , function ( e ) { // Ignore initial page load popstate event in Chrome if ( ! popstateFired ) { popstateFired = true ; if ( self . getURL ( ) === self . _previousURL ) { return ; } } callback ( self . getURL ( ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private [CODESPLIT] function ( ) { // Boosted from Modernizr: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js // The stock browser on Android 2.2 & 2.3 returns positive on history support // Unfortunately support is really buggy and there is no clean way to detect // these bugs, so we fall back to a user agent sniff :( var userAgent = this . _window . navigator . userAgent ; // We only want Android 2, stock browser, and not Chrome which identifies // itself as 'Mobile Safari' as well if ( userAgent . indexOf ( 'Android 2' ) !== - 1 && userAgent . indexOf ( 'Mobile Safari' ) !== - 1 && userAgent . indexOf ( 'Chrome' ) === - 1 ) { return false ; } return ! ! ( this . _history && 'pushState' in this . _history ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private [CODESPLIT] function ( ) { var window = this . _window , documentMode = window . document . documentMode ; return ( 'onhashchange' in window && ( documentMode === undefined || documentMode > 7 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects the best location option based off browser support and returns an instance of that Location class . [CODESPLIT] function ( options ) { if ( options && options . rootURL ) { Ember . assert ( 'rootURL must end with a trailing forward slash e.g. \"/app/\"' , options . rootURL . charAt ( options . rootURL . length - 1 ) === '/' ) ; this . rootURL = options . rootURL ; } var historyPath , hashPath , cancelRouterSetup = false , implementationClass = this . _NoneLocation , currentPath = this . _getFullPath ( ) ; if ( this . _getSupportsHistory ( ) ) { historyPath = this . _getHistoryPath ( ) ; // Since we support history paths, let's be sure we're using them else // switch the location over to it. if ( currentPath === historyPath ) { implementationClass = this . _HistoryLocation ; } else { cancelRouterSetup = true ; this . _replacePath ( historyPath ) ; } } else if ( this . _getSupportsHashChange ( ) ) { hashPath = this . _getHashPath ( ) ; // Be sure we're using a hashed path, otherwise let's switch over it to so // we start off clean and consistent. We'll count an index path with no // hash as \"good enough\" as well. if ( currentPath === hashPath || ( currentPath === '/' && hashPath === '/#/' ) ) { implementationClass = this . _HashLocation ; } else { // Our URL isn't in the expected hash-supported format, so we want to // cancel the router setup and replace the URL to start off clean cancelRouterSetup = true ; this . _replacePath ( hashPath ) ; } } var implementation = implementationClass . create . apply ( implementationClass , arguments ) ; if ( cancelRouterSetup ) { set ( implementation , 'cancelRouterSetup' , true ) ; } return implementation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called via the container s resolver method . It parses the provided fullName and then looks up and returns the appropriate template or class . [CODESPLIT] function ( fullName ) { var parsedName = this . parseName ( fullName ) , resolveMethodName = parsedName . resolveMethodName ; if ( ! ( parsedName . name && parsedName . type ) ) { throw new TypeError ( \"Invalid fullName: `\" + fullName + \"`, must be of the form `type:name` \" ) ; } if ( this [ resolveMethodName ] ) { var resolved = this [ resolveMethodName ] ( parsedName ) ; if ( resolved ) { return resolved ; } } return this . resolveOther ( parsedName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the string name of the form type : name to a Javascript object with the parsed aspects of the name broken out . [CODESPLIT] function ( fullName ) { var nameParts = fullName . split ( \":\" ) , type = nameParts [ 0 ] , fullNameWithoutType = nameParts [ 1 ] , name = fullNameWithoutType , namespace = get ( this , 'namespace' ) , root = namespace ; if ( type !== 'template' && name . indexOf ( '/' ) !== - 1 ) { var parts = name . split ( '/' ) ; name = parts [ parts . length - 1 ] ; var namespaceName = capitalize ( parts . slice ( 0 , - 1 ) . join ( '.' ) ) ; root = Ember . Namespace . byName ( namespaceName ) ; Ember . assert ( 'You are looking for a ' + name + ' ' + type + ' in the ' + namespaceName + ' namespace, but the namespace could not be found' , root ) ; } return { fullName : fullName , type : type , fullNameWithoutType : fullNameWithoutType , name : name , root : root , resolveMethodName : \"resolve\" + classify ( type ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look up the template in Ember . TEMPLATES [CODESPLIT] function ( parsedName ) { var templateName = parsedName . fullNameWithoutType . replace ( / \\. / g , '/' ) ; if ( Ember . TEMPLATES [ templateName ] ) { return Ember . TEMPLATES [ templateName ] ; } templateName = decamelize ( templateName ) ; if ( Ember . TEMPLATES [ templateName ] ) { return Ember . TEMPLATES [ templateName ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the application has not opted out of routing and has not explicitly defined a router supply a default router for the application author to configure . [CODESPLIT] function ( ) { if ( this . Router === false ) { return ; } var container = this . __container__ ; if ( this . Router ) { container . unregister ( 'router:main' ) ; container . register ( 'router:main' , this . Router ) ; } return container . lookupFactory ( 'router:main' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Automatically initialize the application once the DOM has become ready . [CODESPLIT] function ( ) { var self = this ; if ( ! this . $ || this . $ . isReady ) { Ember . run . schedule ( 'actions' , self , '_initialize' ) ; } else { this . $ ( ) . ready ( function runInitialize ( ) { Ember . run ( self , '_initialize' ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call advanceReadiness after any asynchronous setup logic has completed . Each call to deferReadiness must be matched by a call to advanceReadiness or the application will never become ready and routing will not begin . [CODESPLIT] function ( ) { Ember . assert ( \"You must call advanceReadiness on an instance of Ember.Application\" , this instanceof Ember . Application ) ; this . _readinessDeferrals -- ; if ( this . _readinessDeferrals === 0 ) { Ember . run . once ( this , this . didBecomeReady ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset the application . This is typically used only in tests . It cleans up the application in the following order : [CODESPLIT] function ( ) { this . _readinessDeferrals = 1 ; function handleReset ( ) { var router = this . __container__ . lookup ( 'router:main' ) ; router . reset ( ) ; Ember . run ( this . __container__ , 'destroy' ) ; this . buildContainer ( ) ; Ember . run . schedule ( 'actions' , this , function ( ) { this . _initialize ( ) ; } ) ; } Ember . run . join ( this , handleReset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup up the event dispatcher to receive events on the application s rootElement with any registered customEvents . [CODESPLIT] function ( ) { var customEvents = get ( this , 'customEvents' ) , rootElement = get ( this , 'rootElement' ) , dispatcher = this . __container__ . lookup ( 'event_dispatcher:main' ) ; set ( this , 'eventDispatcher' , dispatcher ) ; dispatcher . setup ( customEvents , rootElement ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This creates a container with the default Ember naming conventions . [CODESPLIT] function ( namespace ) { var container = new Ember . Container ( ) ; Ember . Container . defaultContainer = new DeprecatedContainer ( container ) ; container . set = Ember . set ; container . resolver = resolverFor ( namespace ) ; container . normalize = container . resolver . normalize ; container . describe = container . resolver . describe ; container . makeToString = container . resolver . makeToString ; container . optionsForType ( 'component' , { singleton : false } ) ; container . optionsForType ( 'view' , { singleton : false } ) ; container . optionsForType ( 'template' , { instantiate : false } ) ; container . optionsForType ( 'helper' , { instantiate : false } ) ; container . register ( 'application:main' , namespace , { instantiate : false } ) ; container . register ( 'controller:basic' , Ember . Controller , { instantiate : false } ) ; container . register ( 'controller:object' , Ember . ObjectController , { instantiate : false } ) ; container . register ( 'controller:array' , Ember . ArrayController , { instantiate : false } ) ; container . register ( 'route:basic' , Ember . Route , { instantiate : false } ) ; container . register ( 'event_dispatcher:main' , Ember . EventDispatcher ) ; container . register ( 'router:main' , Ember . Router ) ; container . injection ( 'router:main' , 'namespace' , 'application:main' ) ; container . register ( 'location:auto' , Ember . AutoLocation ) ; container . register ( 'location:hash' , Ember . HashLocation ) ; container . register ( 'location:history' , Ember . HistoryLocation ) ; container . register ( 'location:none' , Ember . NoneLocation ) ; container . injection ( 'controller' , 'target' , 'router:main' ) ; container . injection ( 'controller' , 'namespace' , 'application:main' ) ; container . injection ( 'route' , 'router' , 'router:main' ) ; container . injection ( 'location' , 'rootURL' , '-location-setting:root-url' ) ; // DEBUGGING container . register ( 'resolver-for-debugging:main' , container . resolver . __resolver__ , { instantiate : false } ) ; container . injection ( 'container-debug-adapter:main' , 'resolver' , 'resolver-for-debugging:main' ) ; container . injection ( 'data-adapter:main' , 'containerDebugAdapter' , 'container-debug-adapter:main' ) ; // Custom resolver authors may want to register their own ContainerDebugAdapter with this key container . register ( 'container-debug-adapter:main' , Ember . ContainerDebugAdapter ) ; return container ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch the records of a given type and observe them for changes . [CODESPLIT] function ( type , recordsAdded , recordsUpdated , recordsRemoved ) { var self = this , releaseMethods = Ember . A ( ) , records = this . getRecords ( type ) , release ; var recordUpdated = function ( updatedRecord ) { recordsUpdated ( [ updatedRecord ] ) ; } ; var recordsToSend = records . map ( function ( record ) { releaseMethods . push ( self . observeRecord ( record , recordUpdated ) ) ; return self . wrapRecord ( record ) ; } ) ; var contentDidChange = function ( array , idx , removedCount , addedCount ) { for ( var i = idx ; i < idx + addedCount ; i ++ ) { var record = array . objectAt ( i ) ; var wrapped = self . wrapRecord ( record ) ; releaseMethods . push ( self . observeRecord ( record , recordUpdated ) ) ; recordsAdded ( [ wrapped ] ) ; } if ( removedCount ) { recordsRemoved ( idx , removedCount ) ; } } ; var observer = { didChange : contentDidChange , willChange : Ember . K } ; records . addArrayObserver ( self , observer ) ; release = function ( ) { releaseMethods . forEach ( function ( fn ) { fn ( ) ; } ) ; records . removeArrayObserver ( self , observer ) ; self . releaseMethods . removeObject ( release ) ; } ; recordsAdded ( recordsToSend ) ; this . releaseMethods . pushObject ( release ) ; return release ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds observers to a model type class . [CODESPLIT] function ( type , typesUpdated ) { var self = this , records = this . getRecords ( type ) ; var onChange = function ( ) { typesUpdated ( [ self . wrapModelType ( type ) ] ) ; } ; var observer = { didChange : function ( ) { Ember . run . scheduleOnce ( 'actions' , this , onChange ) ; } , willChange : Ember . K } ; records . addArrayObserver ( this , observer ) ; var release = function ( ) { records . removeArrayObserver ( self , observer ) ; } ; return release ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loops over all namespaces and all objects attached to them [CODESPLIT] function ( ) { var namespaces = Ember . A ( Ember . Namespace . NAMESPACES ) , types = Ember . A ( ) ; namespaces . forEach ( function ( namespace ) { for ( var key in namespace ) { if ( ! namespace . hasOwnProperty ( key ) ) { continue ; } var name = Ember . String . dasherize ( key ) ; if ( ! ( namespace instanceof Ember . Application ) && namespace . toString ( ) ) { name = namespace + '/' + name ; } types . push ( name ) ; } } ) ; return types ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This allows ember - testing to play nicely with other asynchronous events such as an application that is waiting for a CSS3 transition or an IndexDB transaction . [CODESPLIT] function ( context , callback ) { if ( arguments . length === 1 ) { callback = context ; context = null ; } if ( ! this . waiters ) { this . waiters = Ember . A ( ) ; } this . waiters . push ( [ context , callback ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unregisterWaiter is used to unregister a callback that was registered with registerWaiter . [CODESPLIT] function ( context , callback ) { var pair ; if ( ! this . waiters ) { return ; } if ( arguments . length === 1 ) { callback = context ; context = null ; } pair = [ context , callback ] ; this . waiters = Ember . A ( this . waiters . filter ( function ( elt ) { return Ember . compare ( elt , pair ) !== 0 ; } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This injects the test helpers into the helperContainer object . If an object is provided it will be used as the helperContainer . If helperContainer is not set it will default to window . If a function of the same name has already been defined it will be cached ( so that it can be reset if the helper is removed with unregisterHelper or removeTestHelpers ) . [CODESPLIT] function ( helperContainer ) { if ( helperContainer ) { this . helperContainer = helperContainer ; } this . testHelpers = { } ; for ( var name in helpers ) { this . originalMethods [ name ] = this . helperContainer [ name ] ; this . testHelpers [ name ] = this . helperContainer [ name ] = helper ( this , name ) ; protoWrap ( Ember . Test . Promise . prototype , name , helper ( this , name ) , helpers [ name ] . meta . wait ) ; } for ( var i = 0 , l = injectHelpersCallbacks . length ; i < l ; i ++ ) { injectHelpersCallbacks [ i ] ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This removes all helpers that have been registered and resets and functions that were overridden by the helpers . [CODESPLIT] function ( ) { for ( var name in helpers ) { this . helperContainer [ name ] = this . originalMethods [ name ] ; delete this . testHelpers [ name ] ; delete this . originalMethods [ name ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is no longer needed But still here for backwards compatibility of helper chaining [CODESPLIT] function protoWrap ( proto , name , callback , isAsync ) { proto [ name ] = function ( ) { var args = arguments ; if ( isAsync ) { return callback . apply ( this , args ) ; } else { return this . then ( function ( ) { return callback . apply ( this , args ) ; } ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the log array [CODESPLIT] function cleanerEval ( str , oldConsole ) { var logArr = [ ] ; var console = { log : function ( msg ) { logArr . push ( msg ) ; oldConsole . log ( msg ) ; } } ; eval ( str ) ; return logArr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adapted from ES5 section 8 . 10 . 5 [CODESPLIT] function toPropertyDescriptor ( obj ) { if ( Object ( obj ) !== obj ) { throw new TypeError ( \"property descriptor should be an Object, given: \" + obj ) ; } var desc = { } ; if ( 'enumerable' in obj ) { desc . enumerable = ! ! obj . enumerable ; } if ( 'configurable' in obj ) { desc . configurable = ! ! obj . configurable ; } if ( 'value' in obj ) { desc . value = obj . value ; } if ( 'writable' in obj ) { desc . writable = ! ! obj . writable ; } if ( 'get' in obj ) { var getter = obj . get ; if ( getter !== undefined && typeof getter !== \"function\" ) { throw new TypeError ( \"property descriptor 'get' attribute must be \" + \"callable or undefined, given: \" + getter ) ; } desc . get = getter ; } if ( 'set' in obj ) { var setter = obj . set ; if ( setter !== undefined && typeof setter !== \"function\" ) { throw new TypeError ( \"property descriptor 'set' attribute must be \" + \"callable or undefined, given: \" + setter ) ; } desc . set = setter ; } if ( 'get' in desc || 'set' in desc ) { if ( 'value' in desc || 'writable' in desc ) { throw new TypeError ( \"property descriptor cannot be both a data and an \" + \"accessor descriptor: \" + obj ) ; } } return desc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a fresh property descriptor that is guaranteed to be complete ( i . e . contain all the standard attributes ) . Additionally any non - standard enumerable properties of attributes are copied over to the fresh descriptor . [CODESPLIT] function normalizeAndCompletePropertyDescriptor ( attributes ) { if ( attributes === undefined ) { return undefined ; } var desc = toCompletePropertyDescriptor ( attributes ) ; // Note: no need to call FromPropertyDescriptor(desc), as we represent // \"internal\" property descriptors as proper Objects from the start for ( var name in attributes ) { if ( ! isStandardAttribute ( name ) ) { Object . defineProperty ( desc , name , { value : attributes [ name ] , writable : true , enumerable : true , configurable : true } ) ; } } return desc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a fresh property descriptor whose standard attributes are guaranteed to be data properties of the right type . Additionally any non - standard enumerable properties of attributes are copied over to the fresh descriptor . [CODESPLIT] function normalizePropertyDescriptor ( attributes ) { var desc = toPropertyDescriptor ( attributes ) ; // Note: no need to call FromGenericPropertyDescriptor(desc), as we represent // \"internal\" property descriptors as proper Objects from the start for ( var name in attributes ) { if ( ! isStandardAttribute ( name ) ) { Object . defineProperty ( desc , name , { value : attributes [ name ] , writable : true , enumerable : true , configurable : true } ) ; } } return desc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs all validation that Object . defineProperty performs without actually defining the property . Returns a boolean indicating whether validation succeeded . [CODESPLIT] function isCompatibleDescriptor ( extensible , current , desc ) { if ( current === undefined && extensible === false ) { return false ; } if ( current === undefined && extensible === true ) { return true ; } if ( isEmptyDescriptor ( desc ) ) { return true ; } if ( isEquivalentDescriptor ( current , desc ) ) { return true ; } if ( current . configurable === false ) { if ( desc . configurable === true ) { return false ; } if ( 'enumerable' in desc && desc . enumerable !== current . enumerable ) { return false ; } } if ( isGenericDescriptor ( desc ) ) { return true ; } if ( isDataDescriptor ( current ) !== isDataDescriptor ( desc ) ) { if ( current . configurable === false ) { return false ; } return true ; } if ( isDataDescriptor ( current ) && isDataDescriptor ( desc ) ) { if ( current . configurable === false ) { if ( current . writable === false && desc . writable === true ) { return false ; } if ( current . writable === false ) { if ( 'value' in desc && ! sameValue ( desc . value , current . value ) ) { return false ; } } } return true ; } if ( isAccessorDescriptor ( current ) && isAccessorDescriptor ( desc ) ) { if ( current . configurable === false ) { if ( 'set' in desc && ! sameValue ( desc . set , current . set ) ) { return false ; } if ( 'get' in desc && ! sameValue ( desc . get , current . get ) ) { return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If getTrap returns undefined the caller should perform the default forwarding behavior . If getTrap returns normally otherwise the return value will be a callable trap function . When calling the trap function the caller is responsible for binding its |this| to |this . handler| . [CODESPLIT] function ( trapName ) { var trap = this . handler [ trapName ] ; if ( trap === undefined ) { // the trap was not defined, // perform the default forwarding behavior return undefined ; } if ( typeof trap !== \"function\" ) { throw new TypeError ( trapName + \" trap is not callable: \" + trap ) ; } return trap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "=== fundamental traps === If name denotes a fixed property check : - whether targetHandler reports it as existent - whether the returned descriptor is compatible with the fixed property If the proxy is non - extensible check : - whether name is not a new property Additionally the returned descriptor is normalized and completed . [CODESPLIT] function ( name ) { \"use strict\" ; var trap = this . getTrap ( \"getOwnPropertyDescriptor\" ) ; if ( trap === undefined ) { return Reflect . getOwnPropertyDescriptor ( this . target , name ) ; } name = String ( name ) ; var desc = trap . call ( this . handler , this . target , name ) ; desc = normalizeAndCompletePropertyDescriptor ( desc ) ; var targetDesc = Object . getOwnPropertyDescriptor ( this . target , name ) ; var extensible = Object . isExtensible ( this . target ) ; if ( desc === undefined ) { if ( isSealedDesc ( targetDesc ) ) { throw new TypeError ( \"cannot report non-configurable property '\" + name + \"' as non-existent\" ) ; } if ( ! extensible && targetDesc !== undefined ) { // if handler is allowed to return undefined, we cannot guarantee // that it will not return a descriptor for this property later. // Once a property has been reported as non-existent on a non-extensible // object, it should forever be reported as non-existent throw new TypeError ( \"cannot report existing own property '\" + name + \"' as non-existent on a non-extensible object\" ) ; } return undefined ; } // at this point, we know (desc !== undefined), i.e. // targetHandler reports 'name' as an existing property // Note: we could collapse the following two if-tests into a single // test. Separating out the cases to improve error reporting. if ( ! extensible ) { if ( targetDesc === undefined ) { throw new TypeError ( \"cannot report a new own property '\" + name + \"' on a non-extensible object\" ) ; } } if ( name !== undefined ) { if ( ! isCompatibleDescriptor ( extensible , targetDesc , desc ) ) { throw new TypeError ( \"cannot report incompatible property descriptor \" + \"for property '\" + name + \"'\" ) ; } } if ( desc . configurable === false && ! isSealedDesc ( targetDesc ) ) { // if the property is configurable or non-existent on the target, // but is reported as a non-configurable property, it may later be // reported as configurable or non-existent, which violates the // invariant that if the property might change or disappear, the // configurable attribute must be true. throw new TypeError ( \"cannot report a non-configurable descriptor \" + \"for configurable or non-existent property '\" + name + \"'\" ) ; } return desc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In the direct proxies design with refactored prototype climbing this trap is deprecated . For proxies - as - prototypes instead of calling this trap the get set has or enumerate traps are called instead . [CODESPLIT] function ( name ) { var handler = this ; if ( ! handler . has ( name ) ) return undefined ; return { get : function ( ) { return handler . get ( this , name ) ; } , set : function ( val ) { if ( handler . set ( this , name , val ) ) { return val ; } else { throw new TypeError ( \"failed assignment to \" + name ) ; } } , enumerable : true , configurable : true } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "On success check whether the target object is indeed frozen . [CODESPLIT] function ( ) { var trap = this . getTrap ( \"freeze\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . freeze ( this . target ) ; } var success = trap . call ( this . handler , this . target ) ; success = ! ! success ; // coerce to Boolean if ( success ) { if ( ! Object_isFrozen ( this . target ) ) { throw new TypeError ( \"can't report non-frozen object as frozen: \" + this . target ) ; } } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "On success check whether the target object is indeed sealed . [CODESPLIT] function ( ) { var trap = this . getTrap ( \"seal\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . seal ( this . target ) ; } var success = trap . call ( this . handler , this . target ) ; success = ! ! success ; // coerce to Boolean if ( success ) { if ( ! Object_isSealed ( this . target ) ) { throw new TypeError ( \"can't report non-sealed object as sealed: \" + this . target ) ; } } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "On success check whether the target object is indeed non - extensible . [CODESPLIT] function ( ) { var trap = this . getTrap ( \"preventExtensions\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . preventExtensions ( this . target ) ; } var success = trap . call ( this . handler , this . target ) ; success = ! ! success ; // coerce to Boolean if ( success ) { if ( Object_isExtensible ( this . target ) ) { throw new TypeError ( \"can't report extensible object as non-extensible: \" + this . target ) ; } } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If name denotes a sealed property check whether handler rejects . [CODESPLIT] function ( name ) { \"use strict\" ; var trap = this . getTrap ( \"deleteProperty\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . deleteProperty ( this . target , name ) ; } name = String ( name ) ; var res = trap . call ( this . handler , this . target , name ) ; res = ! ! res ; // coerce to Boolean if ( res === true ) { if ( isSealed ( name , this . target ) ) { throw new TypeError ( \"property '\" + name + \"' is non-configurable \" + \"and can't be deleted\" ) ; } } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the trap result is consistent with the state of the wrapped target . [CODESPLIT] function ( ) { var trap = this . getTrap ( \"isExtensible\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . isExtensible ( this . target ) ; } var result = trap . call ( this . handler , this . target ) ; result = ! ! result ; // coerce to Boolean var state = Object_isExtensible ( this . target ) ; if ( result !== state ) { if ( result ) { throw new TypeError ( \"cannot report non-extensible object as extensible: \" + this . target ) ; } else { throw new TypeError ( \"cannot report extensible object as non-extensible: \" + this . target ) ; } } return state ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether the trap result corresponds to the target s [[ Prototype ]] [CODESPLIT] function ( ) { var trap = this . getTrap ( \"getPrototypeOf\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . getPrototypeOf ( this . target ) ; } var allegedProto = trap . call ( this . handler , this . target ) ; if ( ! Object_isExtensible ( this . target ) ) { var actualProto = Object_getPrototypeOf ( this . target ) ; if ( ! sameValue ( allegedProto , actualProto ) ) { throw new TypeError ( \"prototype value does not match: \" + this . target ) ; } } return allegedProto ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If target is non - extensible and setPrototypeOf trap returns true check whether the trap result corresponds to the target s [[ Prototype ]] [CODESPLIT] function ( newProto ) { var trap = this . getTrap ( \"setPrototypeOf\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . setPrototypeOf ( this . target , newProto ) ; } var success = trap . call ( this . handler , this . target , newProto ) ; success = ! ! success ; if ( success && ! Object_isExtensible ( this . target ) ) { var actualProto = Object_getPrototypeOf ( this . target ) ; if ( ! sameValue ( newProto , actualProto ) ) { throw new TypeError ( \"prototype value does not match: \" + this . target ) ; } } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "=== derived traps === If name denotes a fixed property check whether the trap returns true . If name denotes a new property on a non - extensible proxy check whether the trap returns false . [CODESPLIT] function ( name ) { \"use strict\" ; var trap = this . getTrap ( \"hasOwn\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . hasOwn ( this . target , name ) ; } name = String ( name ) ; var res = trap . call ( this . handler , this . target , name ) ; res = ! ! res ; // coerce to Boolean if ( res === false ) { if ( isSealed ( name , this . target ) ) { throw new TypeError ( \"cannot report existing non-configurable own \" + \"property '\" + name + \"' as a non-existent own \" + \"property\" ) ; } if ( ! Object . isExtensible ( this . target ) && isFixed ( name , this . target ) ) { // if handler is allowed to return false, we cannot guarantee // that it will return true for this property later. // Once a property has been reported as non-existent on a non-extensible // object, it should forever be reported as non-existent throw new TypeError ( \"cannot report existing own property '\" + name + \"' as non-existent on a non-extensible object\" ) ; } } else { // res === true, if the proxy is non-extensible, // check that name is no new property if ( ! Object . isExtensible ( this . target ) ) { if ( ! isFixed ( name , this . target ) ) { throw new TypeError ( \"cannot report a new own property '\" + name + \"' on a non-extensible object\" ) ; } } } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Experimental implementation of the invoke () trap on platforms that support __noSuchMethod__ ( e . g . Spidermonkey / FF ) . / * invoke : function ( receiver name args ) { var trap = this . getTrap ( invoke ) ; if ( trap === undefined ) { default forwarding behavior return Reflect . invoke ( this . target name args receiver ) ; } [CODESPLIT] function ( receiver , name ) { // experimental support for invoke() trap on platforms that // support __noSuchMethod__ /*\n    if (name === '__noSuchMethod__') {\n      var handler = this;\n      return function(name, args) {\n        return handler.invoke(receiver, name, args);\n      }\n    }\n    */ var trap = this . getTrap ( \"get\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . get ( this . target , name , receiver ) ; } name = String ( name ) ; var res = trap . call ( this . handler , this . target , name , receiver ) ; var fixedDesc = Object . getOwnPropertyDescriptor ( this . target , name ) ; // check consistency of the returned value if ( fixedDesc !== undefined ) { // getting an existing property if ( isDataDescriptor ( fixedDesc ) && fixedDesc . configurable === false && fixedDesc . writable === false ) { // own frozen data property if ( ! sameValue ( res , fixedDesc . value ) ) { throw new TypeError ( \"cannot report inconsistent value for \" + \"non-writable, non-configurable property '\" + name + \"'\" ) ; } } else { // it's an accessor property if ( isAccessorDescriptor ( fixedDesc ) && fixedDesc . configurable === false && fixedDesc . get === undefined ) { if ( res !== undefined ) { throw new TypeError ( \"must report undefined for non-configurable \" + \"accessor property '\" + name + \"' without getter\" ) ; } } } } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The iterate trap should return an iterator object . [CODESPLIT] function ( ) { var trap = this . getTrap ( \"iterate\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . iterate ( this . target ) ; } var trapResult = trap . call ( this . handler , this . target ) ; if ( Object ( trapResult ) !== trapResult ) { throw new TypeError ( \"iterate trap should return an iterator object, \" + \"got: \" + trapResult ) ; } return trapResult ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Any own non - configurable properties of the target that are not included in the trap result give rise to a TypeError . As such we check whether the returned result contains at least all sealed properties of the target object . [CODESPLIT] function ( ) { var trap = this . getTrap ( \"keys\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . keys ( this . target ) ; } var trapResult = trap . call ( this . handler , this . target ) ; // propNames is used as a set of strings var propNames = Object . create ( null ) ; var numProps = + trapResult . length ; var result = new Array ( numProps ) ; for ( var i = 0 ; i < numProps ; i ++ ) { var s = String ( trapResult [ i ] ) ; if ( propNames [ s ] ) { throw new TypeError ( \"keys trap cannot list a \" + \"duplicate property '\" + s + \"'\" ) ; } if ( ! Object . isExtensible ( this . target ) && ! isFixed ( s , this . target ) ) { // non-extensible proxies don't tolerate new own property names throw new TypeError ( \"keys trap cannot list a new \" + \"property '\" + s + \"' on a non-extensible object\" ) ; } propNames [ s ] = true ; result [ i ] = s ; } var ownEnumerableProps = Object . keys ( this . target ) ; var target = this . target ; ownEnumerableProps . forEach ( function ( ownEnumerableProp ) { if ( ! propNames [ ownEnumerableProp ] ) { if ( isSealed ( ownEnumerableProp , target ) ) { throw new TypeError ( \"keys trap failed to include \" + \"non-configurable enumerable property '\" + ownEnumerableProp + \"'\" ) ; } if ( ! Object . isExtensible ( target ) && isFixed ( ownEnumerableProp , target ) ) { // if handler is allowed not to report ownEnumerableProp as an own // property, we cannot guarantee that it will never report it as // an own property later. Once a property has been reported as // non-existent on a non-extensible object, it should forever be // reported as non-existent throw new TypeError ( \"cannot report existing own property '\" + ownEnumerableProp + \"' as non-existent on a \" + \"non-extensible object\" ) ; } } } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In ES6 this trap is called for all operations that require a list of an object s properties including Object . getOwnPropertyNames and Object . keys . [CODESPLIT] function ( ) { var trap = this . getTrap ( \"ownKeys\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . ownKeys ( this . target ) ; } var trapResult = trap . call ( this . handler , this . target ) ; if ( trapResult === null || typeof trapResult !== \"object\" ) { throw new TypeError ( \"ownKeys should return an iterator object, got \" + trapResult ) ; } return trapResult ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "New trap that reifies [[ Call ]] . If the target is a function then a call to proxy ( ... args ) Triggers this trap [CODESPLIT] function ( target , thisBinding , args ) { var trap = this . getTrap ( \"apply\" ) ; if ( trap === undefined ) { return Reflect . apply ( target , thisBinding , args ) ; } if ( typeof this . target === \"function\" ) { return trap . call ( this . handler , target , thisBinding , args ) ; } else { throw new TypeError ( \"apply: \" + target + \" is not a function\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "New trap that reifies [[ Construct ]] . If the target is a function then a call to new proxy ( ... args ) Triggers this trap [CODESPLIT] function ( target , args ) { var trap = this . getTrap ( \"construct\" ) ; if ( trap === undefined ) { return Reflect . construct ( target , args ) ; } if ( typeof this . target === \"function\" ) { return trap . call ( this . handler , target , args ) ; } else { throw new TypeError ( \"new: \" + target + \" is not a function\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the trap result is consistent with the state of the wrapped target . [CODESPLIT] function ( ) { var trap = this . getTrap ( \"isSealed\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . isSealed ( this . target ) ; } var result = trap . call ( this . handler , this . target ) ; result = ! ! result ; // coerce to Boolean var state = Object_isSealed ( this . target ) ; if ( result !== state ) { if ( result ) { throw new TypeError ( \"cannot report unsealed object as sealed: \" + this . target ) ; } else { throw new TypeError ( \"cannot report sealed object as unsealed: \" + this . target ) ; } } return state ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the trap result is consistent with the state of the wrapped target . [CODESPLIT] function ( ) { var trap = this . getTrap ( \"isFrozen\" ) ; if ( trap === undefined ) { // default forwarding behavior return Reflect . isFrozen ( this . target ) ; } var result = trap . call ( this . handler , this . target ) ; result = ! ! result ; // coerce to Boolean var state = Object_isFrozen ( this . target ) ; if ( result !== state ) { if ( result ) { throw new TypeError ( \"cannot report unfrozen object as frozen: \" + this . target ) ; } else { throw new TypeError ( \"cannot report frozen object as unfrozen: \" + this . target ) ; } } return state ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns a new function of zero arguments that recursively unwraps any proxies specified as the |this| - value . The primitive is assumed to be a zero - argument method that uses its |this| - binding . [CODESPLIT] function makeUnwrapping0ArgMethod ( primitive ) { return function builtin ( ) { var vHandler = safeWeakMapGet ( directProxies , this ) ; if ( vHandler !== undefined ) { return builtin . call ( vHandler . target ) ; } else { return primitive . call ( this ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "imperfect ownKeys implemenation : in ES6 should also include symbol - keyed properties . [CODESPLIT] function ( target ) { var handler = directProxies . get ( target ) ; if ( handler !== undefined ) { return handler . ownKeys ( handler . target ) ; } var result = Reflect . getOwnPropertyNames ( target ) ; var l = + result . length ; var idx = 0 ; return { next : function ( ) { if ( idx === l ) throw StopIteration ; return result [ idx ++ ] ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "derived traps [CODESPLIT] function ( target ) { var success = this . preventExtensions ( target ) ; success = ! ! success ; // coerce to Boolean if ( success ) { var props = this . getOwnPropertyNames ( target ) ; var l = + props . length ; for ( var i = 0 ; i < l ; i ++ ) { var name = props [ i ] ; success = success && this . defineProperty ( target , name , { configurable : false } ) ; } } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "call trap [CODESPLIT] function ( ) { var args = Array . prototype . slice . call ( arguments ) ; return vHandler . apply ( target , this , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "load all the contract identifiers into the global scope [CODESPLIT] function load ( obj ) { var name , root ; root = typeof global !== \"undefined\" && global !== null ? global : this ; for ( name in obj ) { if ( obj . hasOwnProperty ( name ) ) { root [ name ] = obj [ name ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a subclass of DS . Model and a JSON object this method will iterate through each attribute of the DS . Model and invoke the DS . Transform#deserialize method on the matching property of the JSON object . This method is typically called after the serializer s normalize method . [CODESPLIT] function ( type , data ) { type . eachTransformedAttribute ( function ( key , type ) { var transform = this . transformFor ( type ) ; data [ key ] = transform . deserialize ( data [ key ] ) ; } , this ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SERIALIZE Called when a record is saved in order to convert the record into JSON . [CODESPLIT] function ( record , options ) { var json = { } ; if ( options && options . includeId ) { var id = get ( record , 'id' ) ; if ( id ) { json [ get ( this , 'primaryKey' ) ] = id ; } } record . eachAttribute ( function ( key , attribute ) { this . serializeAttribute ( record , json , key , attribute ) ; } , this ) ; record . eachRelationship ( function ( key , relationship ) { if ( relationship . kind === 'belongsTo' ) { this . serializeBelongsTo ( record , json , relationship ) ; } else if ( relationship . kind === 'hasMany' ) { this . serializeHasMany ( record , json , relationship ) ; } } , this ) ; return json ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "serializeAttribute can be used to customize how DS . attr properties are serialized [CODESPLIT] function ( record , json , key , attribute ) { var attrs = get ( this , 'attrs' ) ; var value = get ( record , key ) , type = attribute . type ; if ( type ) { var transform = this . transformFor ( type ) ; value = transform . serialize ( value ) ; } // if provided, use the mapping provided by `attrs` in // the serializer key = attrs && attrs [ key ] || ( this . keyForAttribute ? this . keyForAttribute ( key ) : key ) ; json [ key ] = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "serializeBelongsTo can be used to customize how DS . belongsTo properties are serialized . [CODESPLIT] function ( record , json , relationship ) { var key = relationship . key ; var belongsTo = get ( record , key ) ; key = this . keyForRelationship ? this . keyForRelationship ( key , \"belongsTo\" ) : key ; if ( isNone ( belongsTo ) ) { json [ key ] = belongsTo ; } else { json [ key ] = get ( belongsTo , 'id' ) ; } if ( relationship . options . polymorphic ) { this . serializePolymorphicType ( record , json , relationship ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "serializeHasMany can be used to customize how DS . hasMany properties are serialized . [CODESPLIT] function ( record , json , relationship ) { var key = relationship . key ; var relationshipType = DS . RelationshipChange . determineRelationshipType ( record . constructor , relationship ) ; if ( relationshipType === 'manyToNone' || relationshipType === 'manyToMany' ) { json [ key ] = get ( record , key ) . mapBy ( 'id' ) ; // TODO support for polymorphic manyToNone and manyToMany relationships } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "EXTRACT The extract method is used to deserialize payload data from the server . By default the JSONSerializer does not push the records into the store . However records that subclass JSONSerializer such as the RESTSerializer may push records into the store as part of the extract call . [CODESPLIT] function ( store , type , payload , id , requestType ) { this . extractMeta ( store , type , payload ) ; var specificExtract = \"extract\" + requestType . charAt ( 0 ) . toUpperCase ( ) + requestType . substr ( 1 ) ; return this [ specificExtract ] ( store , type , payload , id , requestType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "extractMeta is used to deserialize any meta information in the adapter payload . By default Ember Data expects meta information to be located on the meta property of the payload object . [CODESPLIT] function ( store , type , payload ) { if ( payload && payload . meta ) { store . metaForType ( type , payload . meta ) ; delete payload . meta ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "HELPERS [CODESPLIT] function ( attributeType , skipAssertion ) { var transform = this . container . lookup ( 'transform:' + attributeType ) ; Ember . assert ( \"Unable to find transform for '\" + attributeType + \"'\" , skipAssertion || ! ! transform ) ; return transform ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves all of the records in the RecordArray . [CODESPLIT] function ( ) { var promiseLabel = \"DS: RecordArray#save \" + get ( this , 'type' ) ; var promise = Ember . RSVP . all ( this . invoke ( \"save\" ) , promiseLabel ) . then ( function ( array ) { return Ember . A ( array ) ; } , null , \"DS: RecordArray#save apply Ember.NativeArray\" ) ; return DS . PromiseArray . create ( { promise : promise } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overrides Ember . Array s replace method to implement [CODESPLIT] function ( index , removed , added ) { // Map the array of record objects into an array of  client ids. added = map ( added , function ( record ) { Ember . assert ( \"You cannot add '\" + record . constructor . typeKey + \"' records to this relationship (only '\" + this . type . typeKey + \"' allowed)\" , ! this . type || record instanceof this . type ) ; return record ; } , this ) ; this . _super ( index , removed , added ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a child record within the owner [CODESPLIT] function ( hash ) { var owner = get ( this , 'owner' ) , store = get ( owner , 'store' ) , type = get ( this , 'type' ) , record ; Ember . assert ( \"You cannot add '\" + type . typeKey + \"' records to this polymorphic relationship.\" , ! get ( this , 'isPolymorphic' ) ) ; record = store . createRecord . call ( store , type , hash ) ; this . pushObject ( record ) ; return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "..................... . CREATE NEW RECORD . ..................... Create a new record in the current store . The properties passed to this method are set on the newly created record . [CODESPLIT] function ( type , properties ) { type = this . modelFor ( type ) ; properties = copy ( properties ) || { } ; // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if ( isNone ( properties . id ) ) { properties . id = this . _generateId ( type ) ; } // Coerce ID to a string properties . id = coerceId ( properties . id ) ; var record = this . buildRecord ( type , properties . id ) ; // Move the record out of its initial `empty` state into // the `loaded` state. record . loadedData ( ) ; // Set the properties specified on the record. record . setProperties ( properties ) ; return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If possible this method asks the adapter to generate an ID for a newly created record . [CODESPLIT] function ( type ) { var adapter = this . adapterFor ( type ) ; if ( adapter && adapter . generateIdForRecord ) { return adapter . generateIdForRecord ( this ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "................ . FIND RECORDS . ................ This is the main entry point into finding records . The first parameter to this method is the model s name as a string . [CODESPLIT] function ( type , id ) { if ( id === undefined ) { return this . findAll ( type ) ; } // We are passed a query instead of an id. if ( Ember . typeOf ( id ) === 'object' ) { return this . findQuery ( type , id ) ; } return this . findById ( type , coerceId ( id ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns a record for a given type and id combination . [CODESPLIT] function ( type , id ) { type = this . modelFor ( type ) ; var record = this . recordForId ( type , id ) ; var promise = this . fetchRecord ( record ) || resolve ( record , \"DS: Store#findById \" + type + \" with id: \" + id ) ; return promiseObject ( promise ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method makes a series of requests to the adapter s find method and returns a promise that resolves once they are all loaded . [CODESPLIT] function ( type , ids ) { var store = this ; var promiseLabel = \"DS: Store#findByIds \" + type ; return promiseArray ( Ember . RSVP . all ( map ( ids , function ( id ) { return store . findById ( type , id ) ; } ) ) . then ( Ember . A , null , \"DS: Store#findByIds of \" + type + \" complete\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called by findById if it discovers that a particular type / id pair hasn t been loaded yet to kick off a request to the adapter . [CODESPLIT] function ( record ) { if ( isNone ( record ) ) { return null ; } if ( record . _loadingPromise ) { return record . _loadingPromise ; } if ( ! get ( record , 'isEmpty' ) ) { return null ; } var type = record . constructor , id = get ( record , 'id' ) ; var adapter = this . adapterFor ( type ) ; Ember . assert ( \"You tried to find a record but you have no adapter (for \" + type + \")\" , adapter ) ; Ember . assert ( \"You tried to find a record but your adapter (for \" + type + \") does not implement 'find'\" , adapter . find ) ; var promise = _find ( adapter , this , type , id ) ; record . loadingData ( promise ) ; return promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called by the record s reload method . [CODESPLIT] function ( record ) { var type = record . constructor , adapter = this . adapterFor ( type ) , id = get ( record , 'id' ) ; Ember . assert ( \"You cannot reload a record without an ID\" , id ) ; Ember . assert ( \"You tried to reload a record but you have no adapter (for \" + type + \")\" , adapter ) ; Ember . assert ( \"You tried to reload a record but your adapter does not implement `find`\" , adapter . find ) ; return _find ( adapter , this , type , id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method takes a list of records groups the records by type converts the records into IDs and then invokes the adapter s findMany method . [CODESPLIT] function ( records , owner , resolver ) { if ( ! records . length ) { return ; } // Group By Type var recordsByTypeMap = Ember . MapWithDefault . create ( { defaultValue : function ( ) { return Ember . A ( ) ; } } ) ; forEach ( records , function ( record ) { recordsByTypeMap . get ( record . constructor ) . push ( record ) ; } ) ; forEach ( recordsByTypeMap , function ( type , records ) { var ids = records . mapProperty ( 'id' ) , adapter = this . adapterFor ( type ) ; Ember . assert ( \"You tried to load many records but you have no adapter (for \" + type + \")\" , adapter ) ; Ember . assert ( \"You tried to load many records but your adapter does not implement `findMany`\" , adapter . findMany ) ; resolver . resolve ( _findMany ( adapter , this , type , ids , owner ) ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if a record for a given type and ID is already loaded . [CODESPLIT] function ( type , id ) { id = coerceId ( id ) ; type = this . modelFor ( type ) ; return ! ! this . typeMapFor ( type ) . idToRecord [ id ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns id record for a given type and ID . If one isn t already loaded it builds a new record and leaves it in the empty state . [CODESPLIT] function ( type , id ) { type = this . modelFor ( type ) ; id = coerceId ( id ) ; var record = this . typeMapFor ( type ) . idToRecord [ id ] ; if ( ! record ) { record = this . buildRecord ( type , id ) ; } return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a relationship was originally populated by the adapter as a link ( as opposed to a list of IDs ) this method is called when the relationship is fetched . [CODESPLIT] function ( owner , link , relationship , resolver ) { var adapter = this . adapterFor ( owner . constructor ) ; Ember . assert ( \"You tried to load a hasMany relationship but you have no adapter (for \" + owner . constructor + \")\" , adapter ) ; Ember . assert ( \"You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`\" , adapter . findHasMany ) ; var records = this . recordArrayManager . createManyArray ( relationship . type , Ember . A ( [ ] ) ) ; resolver . resolve ( _findHasMany ( adapter , this , owner , link , relationship ) ) ; return records ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method delegates a query to the adapter . This is the one place where adapter - level semantics are exposed to the application . [CODESPLIT] function ( type , query ) { type = this . modelFor ( type ) ; var array = this . recordArrayManager . createAdapterPopulatedRecordArray ( type , query ) ; var adapter = this . adapterFor ( type ) , promiseLabel = \"DS: Store#findQuery \" + type , resolver = Ember . RSVP . defer ( promiseLabel ) ; Ember . assert ( \"You tried to load a query but you have no adapter (for \" + type + \")\" , adapter ) ; Ember . assert ( \"You tried to load a query but your adapter does not implement `findQuery`\" , adapter . findQuery ) ; resolver . resolve ( _findQuery ( adapter , this , type , query , array ) ) ; return promiseArray ( resolver . promise ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns a filtered array that contains all of the known records for a given type . [CODESPLIT] function ( type ) { type = this . modelFor ( type ) ; var typeMap = this . typeMapFor ( type ) , findAllCache = typeMap . findAllCache ; if ( findAllCache ) { return findAllCache ; } var array = this . recordArrayManager . createRecordArray ( type ) ; typeMap . findAllCache = array ; return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method unloads all of the known records for a given type . [CODESPLIT] function ( type ) { type = this . modelFor ( type ) ; var typeMap = this . typeMapFor ( type ) , records = typeMap . records , record ; while ( record = records . pop ( ) ) { record . unloadRecord ( ) ; } typeMap . findAllCache = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a type and filter function and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally . [CODESPLIT] function ( type , query , filter ) { var promise ; // allow an optional server query if ( arguments . length === 3 ) { promise = this . findQuery ( type , query ) ; } else if ( arguments . length === 2 ) { filter = query ; } type = this . modelFor ( type ) ; var array = this . recordArrayManager . createFilteredRecordArray ( type , filter ) ; promise = promise || resolve ( array ) ; return promiseArray ( promise . then ( function ( ) { return array ; } , null , \"DS: Store#filter of \" + type ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns if a certain record is already loaded in the store . Use this function to know beforehand if a find () will result in a request or that it will be a cache hit . [CODESPLIT] function ( type , id ) { if ( ! this . hasRecordForId ( type , id ) ) { return false ; } return ! get ( this . recordForId ( type , id ) , 'isEmpty' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called at the end of the run loop and flushes any records passed into scheduleSave [CODESPLIT] function ( ) { var pending = this . _pendingSave . slice ( ) ; this . _pendingSave = [ ] ; forEach ( pending , function ( tuple ) { var record = tuple [ 0 ] , resolver = tuple [ 1 ] , adapter = this . adapterFor ( record . constructor ) , operation ; if ( get ( record , 'isNew' ) ) { operation = 'createRecord' ; } else if ( get ( record , 'isDeleted' ) ) { operation = 'deleteRecord' ; } else { operation = 'updateRecord' ; } resolver . resolve ( _commit ( adapter , this , operation , record ) ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called once the promise returned by an adapter s createRecord updateRecord or deleteRecord is resolved . [CODESPLIT] function ( record , data ) { if ( data ) { // normalize relationship IDs into records data = normalizeRelationships ( this , record . constructor , data , record ) ; this . updateId ( record , data ) ; } record . adapterDidCommit ( data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When an adapter s createRecord updateRecord or deleteRecord resolves with data this method extracts the ID from the supplied data . [CODESPLIT] function ( record , data ) { var oldId = get ( record , 'id' ) , id = coerceId ( data . id ) ; Ember . assert ( \"An adapter cannot assign a new id to a record that already has an id. \" + record + \" had id: \" + oldId + \" and you tried to update it with \" + id + \". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.\" , oldId === null || id === oldId ) ; this . typeMapFor ( record . constructor ) . idToRecord [ id ] = record ; set ( record , 'id' , id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a map of IDs to client IDs for a given type . [CODESPLIT] function ( type ) { var typeMaps = get ( this , 'typeMaps' ) , guid = Ember . guidFor ( type ) , typeMap ; typeMap = typeMaps [ guid ] ; if ( typeMap ) { return typeMap ; } typeMap = { idToRecord : { } , records : [ ] , metadata : { } } ; typeMaps [ guid ] = typeMap ; return typeMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "................ . LOADING DATA . ................ This internal method is used by push . [CODESPLIT] function ( type , data , partial ) { var id = coerceId ( data . id ) , record = this . recordForId ( type , id ) ; record . setupData ( data , partial ) ; this . recordArrayManager . recordDidChange ( record ) ; return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a model class for a particular key . Used by methods that take a type key ( like find createRecord etc . ) [CODESPLIT] function ( key ) { var factory ; if ( typeof key === 'string' ) { var normalizedKey = this . container . normalize ( 'model:' + key ) ; factory = this . container . lookupFactory ( normalizedKey ) ; if ( ! factory ) { throw new Ember . Error ( \"No model was found for '\" + key + \"'\" ) ; } factory . typeKey = normalizedKey . split ( ':' , 2 ) [ 1 ] ; } else { // A factory already supplied. factory = key ; } factory . store = this ; return factory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push some data for a given type into the store . [CODESPLIT] function ( type , data , _partial ) { // _partial is an internal param used by `update`. // If passed, it means that the data should be // merged into the existing data, not replace it. Ember . assert ( \"You must include an `id` in a hash passed to `push`\" , data . id != null ) ; type = this . modelFor ( type ) ; // normalize relationship IDs into records data = normalizeRelationships ( this , type , data ) ; this . _load ( type , data , _partial ) ; return this . recordForId ( type , data . id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push some raw data into the store . [CODESPLIT] function ( type , payload ) { var serializer ; if ( ! payload ) { payload = type ; serializer = defaultSerializer ( this . container ) ; Ember . assert ( \"You cannot use `store#pushPayload` without a type unless your default serializer defines `pushPayload`\" , serializer . pushPayload ) ; } else { serializer = this . serializerFor ( type ) ; } serializer . pushPayload ( this , payload ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If you have some metadata to set for a type you can call metaForType . [CODESPLIT] function ( type , metadata ) { type = this . modelFor ( type ) ; Ember . merge ( this . typeMapFor ( type ) . metadata , metadata ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a brand new record for a given type ID and initial data . [CODESPLIT] function ( type , id , data ) { var typeMap = this . typeMapFor ( type ) , idToRecord = typeMap . idToRecord ; Ember . assert ( 'The id ' + id + ' has already been used with another record of type ' + type . toString ( ) + '.' , ! id || ! idToRecord [ id ] ) ; // lookupFactory should really return an object that creates // instances with the injections applied var record = type . _create ( { id : id , store : this , container : this . container } ) ; if ( data ) { record . setupData ( data ) ; } // if we're creating an item, this process will be done // later, once the object has been persisted. if ( id ) { idToRecord [ id ] = record ; } typeMap . records . push ( record ) ; return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "............... . DESTRUCTION . ............... When a record is destroyed this un - indexes it and removes it from any record arrays so it can be GCed . [CODESPLIT] function ( record ) { var type = record . constructor , typeMap = this . typeMapFor ( type ) , id = get ( record , 'id' ) ; record . updateRecordArrays ( ) ; if ( id ) { delete typeMap . idToRecord [ id ] ; } var loc = indexOf ( typeMap . records , record ) ; typeMap . records . splice ( loc , 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "........................ . RELATIONSHIP CHANGES . ........................ [CODESPLIT] function ( childRecord , childKey , parentRecord , parentKey , change ) { var clientId = childRecord . clientId , parentClientId = parentRecord ? parentRecord : parentRecord ; var key = childKey + parentKey ; var changes = this . _relationshipChanges ; if ( ! ( clientId in changes ) ) { changes [ clientId ] = { } ; } if ( ! ( parentClientId in changes [ clientId ] ) ) { changes [ clientId ] [ parentClientId ] = { } ; } if ( ! ( key in changes [ clientId ] [ parentClientId ] ) ) { changes [ clientId ] [ parentClientId ] [ key ] = { } ; } changes [ clientId ] [ parentClientId ] [ key ] [ change . changeType ] = change ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "...................... . PER - TYPE ADAPTERS ...................... Returns the adapter for a given type . [CODESPLIT] function ( type ) { var container = this . container , adapter ; if ( container ) { adapter = container . lookup ( 'adapter:' + type . typeKey ) || container . lookup ( 'adapter:application' ) ; } return adapter || get ( this , 'defaultAdapter' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": ".............................. . RECORD CHANGE NOTIFICATION . .............................. Returns an instance of the serializer for a given type . For example serializerFor ( person ) will return an instance of App . PersonSerializer . [CODESPLIT] function ( type ) { type = this . modelFor ( type ) ; var adapter = this . adapterFor ( type ) ; return serializerFor ( this . container , type . typeKey , adapter && adapter . defaultSerializer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If there are any unsaved records that are in a hasMany they won t be in the payload so add them back in manually . [CODESPLIT] function addUnsavedRecords ( record , key , data ) { if ( record ) { data . pushObjects ( record . get ( key ) . filterBy ( 'isNew' ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This file encapsulates the various states that a record can transition through during its lifecycle . ### State [CODESPLIT] function ( object ) { // Ignore internal property defined by simulated `Ember.create`. var names = Ember . keys ( object ) ; var i , l , name ; for ( i = 0 , l = names . length ; i < l ; i ++ ) { name = names [ i ] ; if ( object . hasOwnProperty ( name ) && object [ name ] ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The created and updated states are created outside the state chart so we can reopen their substates and add mixins as necessary . [CODESPLIT] function deepClone ( object ) { var clone = { } , value ; for ( var prop in object ) { value = object [ prop ] ; if ( value && typeof value === 'object' ) { clone [ prop ] = deepClone ( value ) ; } else { clone [ prop ] = value ; } } return clone ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds error messages to a given attribute and sends becameInvalid event to the record . [CODESPLIT] function ( attribute , messages ) { var wasEmpty = get ( this , 'isEmpty' ) ; messages = this . _findOrCreateMessages ( attribute , messages ) ; get ( this , 'content' ) . addObjects ( messages ) ; this . notifyPropertyChange ( attribute ) ; this . enumerableContentDidChange ( ) ; if ( wasEmpty && ! get ( this , 'isEmpty' ) ) { this . trigger ( 'becameInvalid' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all error messages from the given attribute and sends becameValid event to the record if there no more errors left . [CODESPLIT] function ( attribute ) { if ( get ( this , 'isEmpty' ) ) { return ; } var content = get ( this , 'content' ) . rejectBy ( 'attribute' , attribute ) ; get ( this , 'content' ) . setObjects ( content ) ; this . notifyPropertyChange ( attribute ) ; this . enumerableContentDidChange ( ) ; if ( get ( this , 'isEmpty' ) ) { this . trigger ( 'becameValid' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use [ DS . JSONSerializer ] ( DS . JSONSerializer . html ) to get the JSON representation of a record . [CODESPLIT] function ( options ) { // container is for lazy transform lookups var serializer = DS . JSONSerializer . create ( { container : this . container } ) ; return serializer . serialize ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an object whose keys are changed properties and value is an [ oldProp newProp ] array . [CODESPLIT] function ( ) { var oldData = get ( this , '_data' ) , newData = get ( this , '_attributes' ) , diffData = { } , prop ; for ( prop in newData ) { diffData [ prop ] = [ oldData [ prop ] , newData [ prop ] ] ; } return diffData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the adapter did not return a hash in response to a commit merge the changed attributes and relationships into the existing saved data . [CODESPLIT] function ( data ) { set ( this , 'isError' , false ) ; if ( data ) { this . _data = data ; } else { Ember . mixin ( this . _data , this . _inFlightAttributes ) ; } this . _inFlightAttributes = { } ; this . send ( 'didCommit' ) ; this . updateRecordArraysLater ( ) ; if ( ! data ) { return ; } this . suspendRelationshipObservers ( function ( ) { this . notifyPropertyChange ( 'data' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the model isDirty this function will which discard any unsaved changes [CODESPLIT] function ( ) { this . _attributes = { } ; if ( get ( this , 'isError' ) ) { this . _inFlightAttributes = { } ; set ( this , 'isError' , false ) ; } if ( ! get ( this , 'isValid' ) ) { this . _inFlightAttributes = { } ; } this . send ( 'rolledBack' ) ; this . suspendRelationshipObservers ( function ( ) { this . notifyPropertyChange ( 'data' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The goal of this method is to temporarily disable specific observers that take action in response to application changes . [CODESPLIT] function ( callback , binding ) { var observers = get ( this . constructor , 'relationshipNames' ) . belongsTo ; var self = this ; try { this . _suspendedRelationships = true ; Ember . _suspendObservers ( self , observers , null , 'belongsToDidChange' , function ( ) { Ember . _suspendBeforeObservers ( self , observers , null , 'belongsToWillChange' , function ( ) { callback . call ( binding || self ) ; } ) ; } ) ; } finally { this . _suspendedRelationships = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the record and persist any changes to the record to an extenal source via the adapter . [CODESPLIT] function ( ) { var promiseLabel = \"DS: Model#save \" + this ; var resolver = Ember . RSVP . defer ( promiseLabel ) ; this . get ( 'store' ) . scheduleSave ( this , resolver ) ; this . _inFlightAttributes = this . _attributes ; this . _attributes = { } ; return DS . PromiseObject . create ( { promise : resolver . promise } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reload the record from the adapter . [CODESPLIT] function ( ) { set ( this , 'isReloading' , true ) ; var record = this ; var promiseLabel = \"DS: Model#reload of \" + this ; var promise = new Ember . RSVP . Promise ( function ( resolve ) { record . send ( 'reloadRecord' , resolve ) ; } , promiseLabel ) . then ( function ( ) { record . set ( 'isReloading' , false ) ; record . set ( 'isError' , false ) ; return record ; } , function ( reason ) { record . set ( 'isError' , true ) ; throw reason ; } , \"DS: Model#reload complete, update flags\" ) ; return DS . PromiseObject . create ( { promise : promise } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FOR USE DURING COMMIT PROCESS [CODESPLIT] function ( attributeName , value ) { // If a value is passed in, update the internal attributes and clear // the attribute cache so it picks up the new value. Otherwise, // collapse the current value into the internal attributes because // the adapter has acknowledged it. if ( value !== undefined ) { this . _data [ attributeName ] = value ; this . notifyPropertyChange ( attributeName ) ; } else { this . _data [ attributeName ] = this . _inFlightAttributes [ attributeName ] ; } this . updateRecordArraysLater ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override the default event firing from Ember . Evented to also call methods with the given name . [CODESPLIT] function ( name ) { Ember . tryInvoke ( this , name , [ ] . slice . call ( arguments , 1 ) ) ; this . _super . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates through the attributes of the model calling the passed function on each attribute . [CODESPLIT] function ( callback , binding ) { get ( this , 'attributes' ) . forEach ( function ( name , meta ) { callback . call ( binding , name , meta ) ; } , binding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates through the transformedAttributes of the model calling the passed function on each attribute . Note the callback will not be called for any attributes that do not have an transformation type . [CODESPLIT] function ( callback , binding ) { get ( this , 'transformedAttributes' ) . forEach ( function ( name , type ) { callback . call ( binding , name , type ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This Ember . js hook allows an object to be notified when a property is defined . [CODESPLIT] function ( proto , key , value ) { // Check if the value being set is a computed property. if ( value instanceof Ember . Descriptor ) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value . meta ( ) ; if ( meta . isRelationship && meta . kind === 'belongsTo' ) { Ember . addObserver ( proto , key , null , 'belongsToDidChange' ) ; Ember . addBeforeObserver ( proto , key , null , 'belongsToWillChange' ) ; } meta . parentType = proto . constructor ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a callback iterates over each of the relationships in the model invoking the callback with the name of each relationship and its relationship descriptor . [CODESPLIT] function ( callback , binding ) { get ( this , 'relationshipsByName' ) . forEach ( function ( name , relationship ) { callback . call ( binding , name , relationship ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter or when a record has changed . [CODESPLIT] function ( ) { forEach ( this . changedRecords , function ( record ) { if ( get ( record , 'isDeleted' ) ) { this . _recordWasDeleted ( record ) ; } else { this . _recordWasChanged ( record ) ; } } , this ) ; this . changedRecords = [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an individual filter . [CODESPLIT] function ( array , filter , type , record ) { var shouldBeInArray ; if ( ! filter ) { shouldBeInArray = true ; } else { shouldBeInArray = filter ( record ) ; } var recordArrays = this . recordArraysForRecord ( record ) ; if ( shouldBeInArray ) { recordArrays . add ( array ) ; array . addRecord ( record ) ; } else if ( ! shouldBeInArray ) { recordArrays . remove ( array ) ; array . removeRecord ( record ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is invoked if the filterFunction property is changed on a DS . FilteredRecordArray . [CODESPLIT] function ( array , type , filter ) { var typeMap = this . store . typeMapFor ( type ) , records = typeMap . records , record ; for ( var i = 0 , l = records . length ; i < l ; i ++ ) { record = records [ i ] ; if ( ! get ( record , 'isDeleted' ) && ! get ( record , 'isEmpty' ) ) { this . updateRecordArray ( array , filter , type , record ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a DS . ManyArray for a type and list of record references and index the ManyArray under each reference . This allows us to efficiently remove records from ManyArray s when they are deleted . [CODESPLIT] function ( type , records ) { var manyArray = DS . ManyArray . create ( { type : type , content : records , store : this . store } ) ; forEach ( records , function ( record ) { var arrays = this . recordArraysForRecord ( record ) ; arrays . add ( manyArray ) ; } , this ) ; return manyArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a DS . RecordArray for a type and register it for updates . [CODESPLIT] function ( type ) { var array = DS . RecordArray . create ( { type : type , content : Ember . A ( ) , store : this . store , isLoaded : true } ) ; this . registerFilteredRecordArray ( array , type ) ; return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a DS . FilteredRecordArray for a type and register it for updates . [CODESPLIT] function ( type , filter ) { var array = DS . FilteredRecordArray . create ( { type : type , content : Ember . A ( ) , store : this . store , manager : this , filterFunction : filter } ) ; this . registerFilteredRecordArray ( array , type , filter ) ; return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a DS . AdapterPopulatedRecordArray for a type with given query . [CODESPLIT] function ( type , query ) { return DS . AdapterPopulatedRecordArray . create ( { type : type , query : query , content : Ember . A ( ) , store : this . store } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a RecordArray for a given type to be backed by a filter function . This will cause the array to update automatically when records of that type change attribute values or states . [CODESPLIT] function ( array , type , filter ) { var recordArrays = this . filteredRecordArrays . get ( type ) ; recordArrays . push ( array ) ; this . updateFilter ( array , type , filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internally we maintain a map of all unloaded IDs requested by a ManyArray . As the adapter loads data into the store the store notifies any interested ManyArrays . When the ManyArray s total number of loading records drops to zero it becomes isLoaded and fires a didLoad event . [CODESPLIT] function ( record , array ) { var loadingRecordArrays = record . _loadingRecordArrays || [ ] ; loadingRecordArrays . push ( array ) ; record . _loadingRecordArrays = loadingRecordArrays ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Proxies to the serializer s serialize method . [CODESPLIT] function ( record , options ) { return get ( record , 'store' ) . serializerFor ( record . constructor . typeKey ) . serialize ( record , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find multiple records at once . [CODESPLIT] function ( store , type , ids ) { var promises = map . call ( ids , function ( id ) { return this . find ( store , type , id ) ; } , this ) ; return Ember . RSVP . all ( promises ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implement this method in order to provide data associated with a type [CODESPLIT] function ( type ) { if ( type . FIXTURES ) { var fixtures = Ember . A ( type . FIXTURES ) ; return fixtures . map ( function ( fixture ) { var fixtureIdType = typeof fixture . id ; if ( fixtureIdType !== \"number\" && fixtureIdType !== \"string\" ) { throw new Error ( fmt ( 'the id property must be defined as a number or string for fixture %@' , [ fixture ] ) ) ; } fixture . id = fixture . id + '' ; return fixture ; } ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implement this method in order to provide json for CRUD methods [CODESPLIT] function ( store , type , record ) { return store . serializerFor ( type ) . serialize ( record , { includeId : true } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function ( type , record ) { var existingFixture = this . findExistingFixture ( type , record ) ; if ( existingFixture ) { var index = indexOf ( type . FIXTURES , existingFixture ) ; type . FIXTURES . splice ( index , 1 ) ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function ( type , record ) { var fixtures = this . fixturesForType ( type ) ; var id = get ( record , 'id' ) ; return this . findFixtureById ( fixtures , id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function ( fixtures , id ) { return Ember . A ( fixtures ) . find ( function ( r ) { if ( '' + get ( r , 'id' ) === '' + id ) { return true ; } else { return false ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If you want to do normalizations specific to some part of the payload you can specify those under normalizeHash . [CODESPLIT] function ( type , hash , prop ) { this . normalizeId ( hash ) ; this . normalizeAttributes ( type , hash ) ; this . normalizeRelationships ( type , hash ) ; this . normalizeUsingDeclaredMapping ( type , hash ) ; if ( this . normalizeHash && this . normalizeHash [ prop ] ) { this . normalizeHash [ prop ] ( hash ) ; } return this . _super ( type , hash , prop ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the server has returned a payload representing a single record such as in response to a find or save . [CODESPLIT] function ( store , primaryType , payload , recordId , requestType ) { payload = this . normalizePayload ( primaryType , payload ) ; var primaryTypeName = primaryType . typeKey , primaryRecord ; for ( var prop in payload ) { var typeName = this . typeForRoot ( prop ) , isPrimary = typeName === primaryTypeName ; // legacy support for singular resources if ( isPrimary && Ember . typeOf ( payload [ prop ] ) !== \"array\" ) { primaryRecord = this . normalize ( primaryType , payload [ prop ] , prop ) ; continue ; } var type = store . modelFor ( typeName ) ; /*jshint loopfunc:true*/ forEach . call ( payload [ prop ] , function ( hash ) { var typeName = this . typeForRoot ( prop ) , type = store . modelFor ( typeName ) , typeSerializer = store . serializerFor ( type ) ; hash = typeSerializer . normalize ( type , hash , prop ) ; var isFirstCreatedRecord = isPrimary && ! recordId && ! primaryRecord , isUpdatedRecord = isPrimary && coerceId ( hash . id ) === recordId ; // find the primary record. // // It's either: // * the record with the same ID as the original request // * in the case of a newly created record that didn't have an ID, the first //   record in the Array if ( isFirstCreatedRecord || isUpdatedRecord ) { primaryRecord = hash ; } else { store . push ( typeName , hash ) ; } } , this ) ; } return primaryRecord ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the server has returned a payload representing multiple records such as in response to a findAll or findQuery . [CODESPLIT] function ( store , primaryType , payload ) { payload = this . normalizePayload ( primaryType , payload ) ; var primaryTypeName = primaryType . typeKey , primaryArray ; for ( var prop in payload ) { var typeKey = prop , forcedSecondary = false ; if ( prop . charAt ( 0 ) === '_' ) { forcedSecondary = true ; typeKey = prop . substr ( 1 ) ; } var typeName = this . typeForRoot ( typeKey ) , type = store . modelFor ( typeName ) , typeSerializer = store . serializerFor ( type ) , isPrimary = ( ! forcedSecondary && ( typeName === primaryTypeName ) ) ; /*jshint loopfunc:true*/ var normalizedArray = map . call ( payload [ prop ] , function ( hash ) { return typeSerializer . normalize ( type , hash , prop ) ; } , this ) ; if ( isPrimary ) { primaryArray = normalizedArray ; } else { store . pushMany ( typeName , normalizedArray ) ; } } return primaryArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method allows you to push a payload containing top - level collections of records organized per type . [CODESPLIT] function ( store , payload ) { payload = this . normalizePayload ( null , payload ) ; for ( var prop in payload ) { var typeName = this . typeForRoot ( prop ) , type = store . modelFor ( typeName ) ; /*jshint loopfunc:true*/ var normalizedArray = map . call ( Ember . makeArray ( payload [ prop ] ) , function ( hash ) { return this . normalize ( type , hash , prop ) ; } , this ) ; store . pushMany ( typeName , normalizedArray ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "You can use this method to customize the root keys serialized into the JSON . By default the REST Serializer sends camelized root keys . For example your server may expect underscored root objects . [CODESPLIT] function ( hash , type , record , options ) { hash [ type . typeKey ] = this . serialize ( record , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "You can use this method to customize how polymorphic objects are serialized . By default the JSON Serializer creates the key by appending Type to the attribute and value from the model s camelcased model name . [CODESPLIT] function ( record , json , relationship ) { var key = relationship . key , belongsTo = get ( record , key ) ; key = this . keyForAttribute ? this . keyForAttribute ( key ) : key ; json [ key + \"Type\" ] = belongsTo . constructor . typeKey ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by the store in order to fetch a JSON array for all of the records for a given type . [CODESPLIT] function ( store , type , sinceToken ) { var query ; if ( sinceToken ) { query = { since : sinceToken } ; } return this . ajax ( this . buildURL ( type . typeKey ) , 'GET' , { data : query } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by the store in order to fetch a JSON array for the unloaded records in a has - many relationship that were originally specified as IDs . [CODESPLIT] function ( store , type , ids ) { return this . ajax ( this . buildURL ( type . typeKey ) , 'GET' , { data : { ids : ids } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by the store in order to fetch a JSON array for the unloaded records in a has - many relationship that were originally specified as a URL ( inside of links ) . [CODESPLIT] function ( store , record , url ) { var host = get ( this , 'host' ) , id = get ( record , 'id' ) , type = record . constructor . typeKey ; if ( host && url . charAt ( 0 ) === '/' && url . charAt ( 1 ) !== '/' ) { url = host + url ; } return this . ajax ( this . urlPrefix ( url , this . buildURL ( type , id ) ) , 'GET' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by the store in order to fetch a JSON array for the unloaded records in a belongs - to relationship that were originally specified as a URL ( inside of links ) . [CODESPLIT] function ( store , record , url ) { var id = get ( record , 'id' ) , type = record . constructor . typeKey ; return this . ajax ( this . urlPrefix ( url , this . buildURL ( type , id ) ) , 'GET' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by the store when a newly created record is saved via the save method on a model record instance . [CODESPLIT] function ( store , type , record ) { var data = { } ; var serializer = store . serializerFor ( type . typeKey ) ; serializer . serializeIntoHash ( data , type , record , { includeId : true } ) ; return this . ajax ( this . buildURL ( type . typeKey ) , \"POST\" , { data : data } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by the store when an existing record is saved via the save method on a model record instance . [CODESPLIT] function ( store , type , record ) { var data = { } ; var serializer = store . serializerFor ( type . typeKey ) ; serializer . serializeIntoHash ( data , type , record ) ; var id = get ( record , 'id' ) ; return this . ajax ( this . buildURL ( type . typeKey , id ) , \"PUT\" , { data : data } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by the store when a record is deleted . [CODESPLIT] function ( store , type , record ) { var id = get ( record , 'id' ) ; return this . ajax ( this . buildURL ( type . typeKey , id ) , \"DELETE\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a URL for a given type and optional ID . [CODESPLIT] function ( type , id ) { var url = [ ] , host = get ( this , 'host' ) , prefix = this . urlPrefix ( ) ; if ( type ) { url . push ( this . pathForType ( type ) ) ; } if ( id ) { url . push ( id ) ; } if ( prefix ) { url . unshift ( prefix ) ; } url = url . join ( '/' ) ; if ( ! host && url ) { url = '/' + url ; } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a URL an HTTP method and a hash of data and makes an HTTP request . [CODESPLIT] function ( url , type , hash ) { var adapter = this ; return new Ember . RSVP . Promise ( function ( resolve , reject ) { hash = adapter . ajaxOptions ( url , type , hash ) ; hash . success = function ( json ) { Ember . run ( null , resolve , json ) ; } ; hash . error = function ( jqXHR , textStatus , errorThrown ) { Ember . run ( null , reject , adapter . ajaxError ( jqXHR ) ) ; } ; Ember . $ . ajax ( hash ) ; } , \"DS: RestAdapter#ajax \" + type + \" to \" + url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inflector . Ember provides a mechanism for supplying inflection rules for your application . Ember includes a default set of inflection rules and provides an API for providing additional rules . [CODESPLIT] function Inflector ( ruleSet ) { ruleSet = ruleSet || { } ; ruleSet . uncountable = ruleSet . uncountable || { } ; ruleSet . irregularPairs = ruleSet . irregularPairs || { } ; var rules = this . rules = { plurals : ruleSet . plurals || [ ] , singular : ruleSet . singular || [ ] , irregular : { } , irregularInverse : { } , uncountable : { } } ; loadUncountable ( rules , ruleSet . uncountable ) ; loadIrregular ( rules , ruleSet . irregularPairs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@protected [CODESPLIT] function ( word , typeRules , irregular ) { var inflection , substitution , result , lowercase , isBlank , isUncountable , isIrregular , isIrregularInverse , rule ; isBlank = BLANK_REGEX . test ( word ) ; if ( isBlank ) { return word ; } lowercase = word . toLowerCase ( ) ; isUncountable = this . rules . uncountable [ lowercase ] ; if ( isUncountable ) { return word ; } isIrregular = irregular && irregular [ lowercase ] ; if ( isIrregular ) { return isIrregular ; } for ( var i = typeRules . length , min = 0 ; i > min ; i -- ) { inflection = typeRules [ i - 1 ] ; rule = inflection [ 0 ] ; if ( rule . test ( word ) ) { break ; } } inflection = inflection || [ ] ; rule = inflection [ 0 ] ; substitution = inflection [ 1 ] ; result = word . replace ( rule , substitution ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Underscores relationship names and appends _id or _ids when serializing relationship keys . [CODESPLIT] function ( key , kind ) { key = Ember . String . decamelize ( key ) ; if ( kind === \"belongsTo\" ) { return key + \"_id\" ; } else if ( kind === \"hasMany\" ) { return Ember . String . singularize ( key ) + \"_ids\" ; } else { return key ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Underscores the JSON root keys when serializing . [CODESPLIT] function ( data , type , record , options ) { var root = Ember . String . decamelize ( type . typeKey ) ; data [ root ] = this . serialize ( record , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a polymorphic type as a fully capitalized model name . [CODESPLIT] function ( record , json , relationship ) { var key = relationship . key , belongsTo = get ( record , key ) ; key = this . keyForAttribute ( key ) ; json [ key + \"_type\" ] = Ember . String . capitalize ( belongsTo . constructor . typeKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "EXTRACT Extracts the model typeKey from underscored root objects . [CODESPLIT] function ( root ) { var camelized = Ember . String . camelize ( root ) ; return Ember . String . singularize ( camelized ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert snake_cased links to camelCase [CODESPLIT] function ( data ) { if ( data . links ) { var links = data . links ; for ( var link in links ) { var camelizedLink = Ember . String . camelize ( link ) ; if ( camelizedLink !== link ) { links [ camelizedLink ] = links [ link ] ; delete links [ link ] ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize the polymorphic type from the JSON . [CODESPLIT] function ( type , hash ) { var payloadKey , payload ; if ( this . keyForRelationship ) { type . eachRelationship ( function ( key , relationship ) { if ( relationship . options . polymorphic ) { payloadKey = this . keyForAttribute ( key ) ; payload = hash [ payloadKey ] ; if ( payload && payload . type ) { payload . type = this . typeForRoot ( payload . type ) ; } else if ( payload && relationship . kind === \"hasMany\" ) { var self = this ; forEach ( payload , function ( single ) { single . type = self . typeForRoot ( single . type ) ; } ) ; } } else { payloadKey = this . keyForRelationship ( key , relationship . kind ) ; payload = hash [ payloadKey ] ; } hash [ key ] = payload ; if ( key !== payloadKey ) { delete hash [ payloadKey ] ; } } , this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize has - may relationship when it is configured as embedded objects . [CODESPLIT] function ( record , json , relationship ) { var key = relationship . key , attrs = get ( this , 'attrs' ) , embed = attrs && attrs [ key ] && attrs [ key ] . embedded === 'always' ; if ( embed ) { json [ this . keyForAttribute ( key ) ] = get ( record , key ) . map ( function ( relation ) { var data = relation . serialize ( ) , primaryKey = get ( this , 'primaryKey' ) ; data [ primaryKey ] = get ( relation , primaryKey ) ; return data ; } , this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract embedded objects out of the payload for a single object and add them as sideloaded objects instead . [CODESPLIT] function ( store , primaryType , payload , recordId , requestType ) { var root = this . keyForAttribute ( primaryType . typeKey ) , partial = payload [ root ] ; updatePayloadWithEmbedded ( store , this , primaryType , partial , payload ) ; return this . _super ( store , primaryType , payload , recordId , requestType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract embedded objects out of a standard payload and add them as sideloaded objects instead . [CODESPLIT] function ( store , type , payload ) { var root = this . keyForAttribute ( type . typeKey ) , partials = payload [ Ember . String . pluralize ( root ) ] ; forEach ( partials , function ( partial ) { updatePayloadWithEmbedded ( store , this , type , partial , payload ) ; } , this ) ; return this . _super ( store , type , payload ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The ActiveModelAdapter overrides the pathForType method to build underscored URLs by decamelizing and pluralizing the object type name . [CODESPLIT] function ( type ) { var decamelized = Ember . String . decamelize ( type ) ; return Ember . String . pluralize ( decamelized ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The ActiveModelAdapter overrides the ajaxError method to return a DS . InvalidError for all 422 Unprocessable Entity responses . [CODESPLIT] function ( jqXHR ) { var error = this . _super ( jqXHR ) ; if ( jqXHR && jqXHR . status === 422 ) { var jsonErrors = Ember . $ . parseJSON ( jqXHR . responseText ) [ \"errors\" ] , errors = { } ; forEach ( Ember . keys ( jsonErrors ) , function ( key ) { errors [ Ember . String . camelize ( key ) ] = jsonErrors [ key ] ; } ) ; return new DS . InvalidError ( errors ) ; } else { return error ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc function @name angular . extend @function [CODESPLIT] function extend ( dst ) { var h = dst . $$hashKey ; forEach ( arguments , function ( obj ) { if ( obj !== dst ) { forEach ( obj , function ( value , key ) { dst [ key ] = value ; } ) ; } } ) ; setHashKey ( dst , h ) ; return dst ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc function @name angular . copy @function [CODESPLIT] function copy ( source , destination ) { if ( isWindow ( source ) || isScope ( source ) ) { throw ngMinErr ( 'cpws' , \"Can't copy! Making copies of Window or Scope instances is not supported.\" ) ; } if ( ! destination ) { destination = source ; if ( source ) { if ( isArray ( source ) ) { destination = copy ( source , [ ] ) ; } else if ( isDate ( source ) ) { destination = new Date ( source . getTime ( ) ) ; } else if ( isRegExp ( source ) ) { destination = new RegExp ( source . source ) ; } else if ( isObject ( source ) ) { destination = copy ( source , { } ) ; } } } else { if ( source === destination ) throw ngMinErr ( 'cpi' , \"Can't copy! Source and destination are identical.\" ) ; if ( isArray ( source ) ) { destination . length = 0 ; for ( var i = 0 ; i < source . length ; i ++ ) { destination . push ( copy ( source [ i ] ) ) ; } } else { var h = destination . $$hashKey ; forEach ( destination , function ( value , key ) { delete destination [ key ] ; } ) ; for ( var key in source ) { destination [ key ] = copy ( source [ key ] ) ; } setHashKey ( destination , h ) ; } } return destination ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses an escaped url query string into key - value pairs . [CODESPLIT] function parseKeyValue ( /**string*/ keyValue ) { var obj = { } , key_value , key ; forEach ( ( keyValue || \"\" ) . split ( '&' ) , function ( keyValue ) { if ( keyValue ) { key_value = keyValue . split ( '=' ) ; key = tryDecodeURIComponent ( key_value [ 0 ] ) ; if ( isDefined ( key ) ) { var val = isDefined ( key_value [ 1 ] ) ? tryDecodeURIComponent ( key_value [ 1 ] ) : true ; if ( ! obj [ key ] ) { obj [ key ] = val ; } else if ( isArray ( obj [ key ] ) ) { obj [ key ] . push ( val ) ; } else { obj [ key ] = [ obj [ key ] , val ] ; } } } } ) ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////// Module Loading ////////////////////////////////// [CODESPLIT] function loadModules ( modulesToLoad ) { var runBlocks = [ ] ; forEach ( modulesToLoad , function ( module ) { if ( loadedModules . get ( module ) ) return ; loadedModules . put ( module , true ) ; try { if ( isString ( module ) ) { var moduleFn = angularModule ( module ) ; runBlocks = runBlocks . concat ( loadModules ( moduleFn . requires ) ) . concat ( moduleFn . _runBlocks ) ; for ( var invokeQueue = moduleFn . _invokeQueue , i = 0 , ii = invokeQueue . length ; i < ii ; i ++ ) { var invokeArgs = invokeQueue [ i ] , provider = providerInjector . get ( invokeArgs [ 0 ] ) ; provider [ invokeArgs [ 1 ] ] . apply ( provider , invokeArgs [ 2 ] ) ; } } else if ( isFunction ( module ) ) { runBlocks . push ( providerInjector . invoke ( module ) ) ; } else if ( isArray ( module ) ) { runBlocks . push ( providerInjector . invoke ( module ) ) ; } else { assertArgFn ( module , 'module' ) ; } } catch ( e ) { if ( isArray ( module ) ) { module = module [ module . length - 1 ] ; } if ( e . message && e . stack && e . stack . indexOf ( e . message ) == - 1 ) { // Safari & FF's stack traces don't contain error.message content unlike those of Chrome and IE // So if stack doesn't contain message, we create a new string that contains both. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. e = e . message + '\\n' + e . stack ; } throw $injectorMinErr ( 'modulerr' , \"Failed to instantiate module {0} due to:\\n{1}\" , module , e . stack || e . message || e ) ; } } ) ; return runBlocks ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc function @name ng . $anchorScroll @requires $window @requires $location @requires $rootScope [CODESPLIT] function $AnchorScrollProvider ( ) { var autoScrollingEnabled = true ; this . disableAutoScrolling = function ( ) { autoScrollingEnabled = false ; } ; this . $get = [ '$window' , '$location' , '$rootScope' , function ( $window , $location , $rootScope ) { var document = $window . document ; // helper function to get first anchor from a NodeList // can't use filter.filter, as it accepts only instances of Array // and IE can't convert NodeList to an array using [].slice // TODO(vojta): use filter if we change it to accept lists as well function getFirstAnchor ( list ) { var result = null ; forEach ( list , function ( element ) { if ( ! result && lowercase ( element . nodeName ) === 'a' ) result = element ; } ) ; return result ; } function scroll ( ) { var hash = $location . hash ( ) , elm ; // empty hash, scroll to the top of the page if ( ! hash ) $window . scrollTo ( 0 , 0 ) ; // element with given id else if ( ( elm = document . getElementById ( hash ) ) ) elm . scrollIntoView ( ) ; // first anchor with given name :-D else if ( ( elm = getFirstAnchor ( document . getElementsByName ( hash ) ) ) ) elm . scrollIntoView ( ) ; // no element and hash == 'top', scroll to the top of the page else if ( hash === 'top' ) $window . scrollTo ( 0 , 0 ) ; } // does not scroll when user clicks on anchor link that is currently on // (no url change, no $location.hash() change), browser native does scroll if ( autoScrollingEnabled ) { $rootScope . $watch ( function autoScrollWatch ( ) { return $location . hash ( ) ; } , function autoScrollWatchAction ( ) { $rootScope . $evalAsync ( scroll ) ; } ) ; } return scroll ; } ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc function @name ng . $animate#enter @methodOf ng . $animate @function [CODESPLIT] function ( element , parent , after , done ) { var afterNode = after && after [ after . length - 1 ] ; var parentNode = parent && parent [ 0 ] || afterNode && afterNode . parentNode ; // IE does not like undefined so we have to pass null. var afterNextSibling = ( afterNode && afterNode . nextSibling ) || null ; forEach ( element , function ( node ) { parentNode . insertBefore ( node , afterNextSibling ) ; } ) ; done && $timeout ( done , 0 , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc function @name ng . $animate#addClass @methodOf ng . $animate @function [CODESPLIT] function ( element , className , done ) { className = isString ( className ) ? className : isArray ( className ) ? className . join ( ' ' ) : '' ; forEach ( element , function ( element ) { JQLiteAddClass ( element , className ) ; } ) ; done && $timeout ( done , 0 , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "! This is a private undocumented service ! [CODESPLIT] function Browser ( window , document , $log , $sniffer ) { var self = this , rawDocument = document [ 0 ] , location = window . location , history = window . history , setTimeout = window . setTimeout , clearTimeout = window . clearTimeout , pendingDeferIds = { } ; self . isMock = false ; var outstandingRequestCount = 0 ; var outstandingRequestCallbacks = [ ] ; // TODO(vojta): remove this temporary api self . $$completeOutstandingRequest = completeOutstandingRequest ; self . $$incOutstandingRequestCount = function ( ) { outstandingRequestCount ++ ; } ; /**\n   * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`\n   * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.\n   */ function completeOutstandingRequest ( fn ) { try { fn . apply ( null , sliceArgs ( arguments , 1 ) ) ; } finally { outstandingRequestCount -- ; if ( outstandingRequestCount === 0 ) { while ( outstandingRequestCallbacks . length ) { try { outstandingRequestCallbacks . pop ( ) ( ) ; } catch ( e ) { $log . error ( e ) ; } } } } } /**\n   * @private\n   * Note: this method is used only by scenario runner\n   * TODO(vojta): prefix this method with $$ ?\n   * @param {function()} callback Function that will be called when no outstanding request\n   */ self . notifyWhenNoOutstandingRequests = function ( callback ) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach ( pollFns , function ( pollFn ) { pollFn ( ) ; } ) ; if ( outstandingRequestCount === 0 ) { callback ( ) ; } else { outstandingRequestCallbacks . push ( callback ) ; } } ; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [ ] , pollTimeout ; /**\n   * @name ng.$browser#addPollFn\n   * @methodOf ng.$browser\n   *\n   * @param {function()} fn Poll function to add\n   *\n   * @description\n   * Adds a function to the list of functions that poller periodically executes,\n   * and starts polling if not started yet.\n   *\n   * @returns {function()} the added function\n   */ self . addPollFn = function ( fn ) { if ( isUndefined ( pollTimeout ) ) startPoller ( 100 , setTimeout ) ; pollFns . push ( fn ) ; return fn ; } ; /**\n   * @param {number} interval How often should browser call poll functions (ms)\n   * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.\n   *\n   * @description\n   * Configures the poller to run in the specified intervals, using the specified\n   * setTimeout fn and kicks it off.\n   */ function startPoller ( interval , setTimeout ) { ( function check ( ) { forEach ( pollFns , function ( pollFn ) { pollFn ( ) ; } ) ; pollTimeout = setTimeout ( check , interval ) ; } ) ( ) ; } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var lastBrowserUrl = location . href , baseElement = document . find ( 'base' ) , replacedUrl = null ; /**\n   * @name ng.$browser#url\n   * @methodOf ng.$browser\n   *\n   * @description\n   * GETTER:\n   * Without any argument, this method just returns current value of location.href.\n   *\n   * SETTER:\n   * With at least one argument, this method sets url to new value.\n   * If html5 history api supported, pushState/replaceState is used, otherwise\n   * location.href/location.replace is used.\n   * Returns its own instance to allow chaining\n   *\n   * NOTE: this api is intended for use only by the $location service. Please use the\n   * {@link ng.$location $location service} to change url.\n   *\n   * @param {string} url New url (when used as setter)\n   * @param {boolean=} replace Should new url replace current history record ?\n   */ self . url = function ( url , replace ) { // setter if ( url ) { if ( lastBrowserUrl == url ) return ; lastBrowserUrl = url ; if ( $sniffer . history ) { if ( replace ) history . replaceState ( null , '' , url ) ; else { history . pushState ( null , '' , url ) ; // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 baseElement . attr ( 'href' , baseElement . attr ( 'href' ) ) ; } } else { if ( replace ) { location . replace ( url ) ; replacedUrl = url ; } else { location . href = url ; replacedUrl = null ; } } return self ; // getter } else { // - the replacedUrl is a workaround for an IE8-9 issue with location.replace method that doesn't update //   location.href synchronously // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 return replacedUrl || location . href . replace ( / %27 / g , \"'\" ) ; } } ; var urlChangeListeners = [ ] , urlChangeInit = false ; function fireUrlChange ( ) { if ( lastBrowserUrl == self . url ( ) ) return ; lastBrowserUrl = self . url ( ) ; forEach ( urlChangeListeners , function ( listener ) { listener ( self . url ( ) ) ; } ) ; } /**\n   * @name ng.$browser#onUrlChange\n   * @methodOf ng.$browser\n   * @TODO(vojta): refactor to use node's syntax for events\n   *\n   * @description\n   * Register callback function that will be called, when url changes.\n   *\n   * It's only called when the url is changed by outside of angular:\n   * - user types different url into address bar\n   * - user clicks on history (forward/back) button\n   * - user clicks on a link\n   *\n   * It's not called when url is changed by $browser.url() method\n   *\n   * The listener gets called with new url as parameter.\n   *\n   * NOTE: this api is intended for use only by the $location service. Please use the\n   * {@link ng.$location $location service} to monitor url changes in angular apps.\n   *\n   * @param {function(string)} listener Listener function to be called when url changes.\n   * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.\n   */ self . onUrlChange = function ( callback ) { if ( ! urlChangeInit ) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ( $sniffer . history ) jqLite ( window ) . on ( 'popstate' , fireUrlChange ) ; // hashchange event if ( $sniffer . hashchange ) jqLite ( window ) . on ( 'hashchange' , fireUrlChange ) ; // polling else self . addPollFn ( fireUrlChange ) ; urlChangeInit = true ; } urlChangeListeners . push ( callback ) ; return callback ; } ; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /**\n   * @name ng.$browser#baseHref\n   * @methodOf ng.$browser\n   * \n   * @description\n   * Returns current <base href>\n   * (always relative - without domain)\n   *\n   * @returns {string=} current <base href>\n   */ self . baseHref = function ( ) { var href = baseElement . attr ( 'href' ) ; return href ? href . replace ( / ^https?\\:\\/\\/[^\\/]* / , '' ) : '' ; } ; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = { } ; var lastCookieString = '' ; var cookiePath = self . baseHref ( ) ; /**\n   * @name ng.$browser#cookies\n   * @methodOf ng.$browser\n   *\n   * @param {string=} name Cookie name\n   * @param {string=} value Cookie value\n   *\n   * @description\n   * The cookies method provides a 'private' low level access to browser cookies.\n   * It is not meant to be used directly, use the $cookie service instead.\n   *\n   * The return values vary depending on the arguments that the method was called with as follows:\n   * <ul>\n   *   <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li>\n   *   <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li>\n   *   <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li>\n   * </ul>\n   *\n   * @returns {Object} Hash of all cookies (if called without any parameter)\n   */ self . cookies = function ( name , value ) { var cookieLength , cookieArray , cookie , i , index ; if ( name ) { if ( value === undefined ) { rawDocument . cookie = escape ( name ) + \"=;path=\" + cookiePath + \";expires=Thu, 01 Jan 1970 00:00:00 GMT\" ; } else { if ( isString ( value ) ) { cookieLength = ( rawDocument . cookie = escape ( name ) + '=' + escape ( value ) + ';path=' + cookiePath ) . length + 1 ; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie if ( cookieLength > 4096 ) { $log . warn ( \"Cookie '\" + name + \"' possibly not set or overflowed because it was too large (\" + cookieLength + \" > 4096 bytes)!\" ) ; } } } } else { if ( rawDocument . cookie !== lastCookieString ) { lastCookieString = rawDocument . cookie ; cookieArray = lastCookieString . split ( \"; \" ) ; lastCookies = { } ; for ( i = 0 ; i < cookieArray . length ; i ++ ) { cookie = cookieArray [ i ] ; index = cookie . indexOf ( '=' ) ; if ( index > 0 ) { //ignore nameless cookies var name = unescape ( cookie . substring ( 0 , index ) ) ; // the first value that is seen for a cookie is the most // specific one.  values for the same cookie name that // follow are for less specific paths. if ( lastCookies [ name ] === undefined ) { lastCookies [ name ] = unescape ( cookie . substring ( index + 1 ) ) ; } } } } return lastCookies ; } } ; /**\n   * @name ng.$browser#defer\n   * @methodOf ng.$browser\n   * @param {function()} fn A function, who's execution should be deferred.\n   * @param {number=} [delay=0] of milliseconds to defer the function execution.\n   * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.\n   *\n   * @description\n   * Executes a fn asynchronously via `setTimeout(fn, delay)`.\n   *\n   * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using\n   * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed\n   * via `$browser.defer.flush()`.\n   *\n   */ self . defer = function ( fn , delay ) { var timeoutId ; outstandingRequestCount ++ ; timeoutId = setTimeout ( function ( ) { delete pendingDeferIds [ timeoutId ] ; completeOutstandingRequest ( fn ) ; } , delay || 0 ) ; pendingDeferIds [ timeoutId ] = true ; return timeoutId ; } ; /**\n   * @name ng.$browser#defer.cancel\n   * @methodOf ng.$browser.defer\n   *\n   * @description\n   * Cancels a deferred task identified with `deferId`.\n   *\n   * @param {*} deferId Token returned by the `$browser.defer` function.\n   * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully canceled.\n   */ self . defer . cancel = function ( deferId ) { if ( pendingDeferIds [ deferId ] ) { delete pendingDeferIds [ deferId ] ; clearTimeout ( deferId ) ; completeOutstandingRequest ( noop ) ; return true ; } return false ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a normalized attribute on the element in a way such that all directives can share the attribute . This function properly handles boolean attributes . [CODESPLIT] function ( key , value , writeAttr , attrName ) { //special case for class attribute addition + removal //so that class changes can tap into the animation //hooks provided by the $animate service if ( key == 'class' ) { value = value || '' ; var current = this . $$element . attr ( 'class' ) || '' ; this . $removeClass ( tokenDifference ( current , value ) . join ( ' ' ) ) ; this . $addClass ( tokenDifference ( value , current ) . join ( ' ' ) ) ; } else { var booleanKey = getBooleanAttrName ( this . $$element [ 0 ] , key ) , normalizedVal , nodeName ; if ( booleanKey ) { this . $$element . prop ( key , value ) ; attrName = booleanKey ; } this [ key ] = value ; // translate normalized key to actual key if ( attrName ) { this . $attr [ key ] = attrName ; } else { attrName = this . $attr [ key ] ; if ( ! attrName ) { this . $attr [ key ] = attrName = snake_case ( key , '-' ) ; } } nodeName = nodeName_ ( this . $$element ) ; // sanitize a[href] and img[src] values if ( ( nodeName === 'A' && key === 'href' ) || ( nodeName === 'IMG' && key === 'src' ) ) { // NOTE: $$urlUtils.resolve() doesn't support IE < 8 so we don't sanitize for that case. if ( ! msie || msie >= 8 ) { normalizedVal = $$urlUtils . resolve ( value ) ; if ( normalizedVal !== '' ) { if ( ( key === 'href' && ! normalizedVal . match ( aHrefSanitizationWhitelist ) ) || ( key === 'src' && ! normalizedVal . match ( imgSrcSanitizationWhitelist ) ) ) { this [ key ] = value = 'unsafe:' + normalizedVal ; } } } } if ( writeAttr !== false ) { if ( value === null || value === undefined ) { this . $$element . removeAttr ( attrName ) ; } else { this . $$element . attr ( attrName , value ) ; } } } // fire observers var $$observers = this . $$observers ; $$observers && forEach ( $$observers [ key ] , function ( fn ) { try { fn ( value ) ; } catch ( e ) { $exceptionHandler ( e ) ; } } ) ; function tokenDifference ( str1 , str2 ) { var values = [ ] , tokens1 = str1 . split ( / \\s+ / ) , tokens2 = str2 . split ( / \\s+ / ) ; outer : for ( var i = 0 ; i < tokens1 . length ; i ++ ) { var token = tokens1 [ i ] ; for ( var j = 0 ; j < tokens2 . length ; j ++ ) { if ( token == tokens2 [ j ] ) continue outer ; } values . push ( token ) ; } return values ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile function matches each node in nodeList against the directives . Once all directives for a particular node are collected their compile functions are executed . The compile functions return values - the linking functions - are combined into a composite linking function which is the a linking function for the node . [CODESPLIT] function compileNodes ( nodeList , transcludeFn , $rootElement , maxPriority , ignoreDirective ) { var linkFns = [ ] , nodeLinkFn , childLinkFn , directives , attrs , linkFnFound ; for ( var i = 0 ; i < nodeList . length ; i ++ ) { attrs = new Attributes ( ) ; // we must always refer to nodeList[i] since the nodes can be replaced underneath us. directives = collectDirectives ( nodeList [ i ] , [ ] , attrs , i == 0 ? maxPriority : undefined , ignoreDirective ) ; nodeLinkFn = ( directives . length ) ? applyDirectivesToNode ( directives , nodeList [ i ] , attrs , transcludeFn , $rootElement ) : null ; childLinkFn = ( nodeLinkFn && nodeLinkFn . terminal || ! nodeList [ i ] . childNodes || ! nodeList [ i ] . childNodes . length ) ? null : compileNodes ( nodeList [ i ] . childNodes , nodeLinkFn ? nodeLinkFn . transclude : transcludeFn ) ; linkFns . push ( nodeLinkFn ) ; linkFns . push ( childLinkFn ) ; linkFnFound = ( linkFnFound || nodeLinkFn || childLinkFn ) ; } // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null ; function compositeLinkFn ( scope , nodeList , $rootElement , boundTranscludeFn ) { var nodeLinkFn , childLinkFn , node , childScope , childTranscludeFn , i , ii , n ; // copy nodeList so that linking doesn't break due to live list updates. var stableNodeList = [ ] ; for ( i = 0 , ii = nodeList . length ; i < ii ; i ++ ) { stableNodeList . push ( nodeList [ i ] ) ; } for ( i = 0 , n = 0 , ii = linkFns . length ; i < ii ; n ++ ) { node = stableNodeList [ n ] ; nodeLinkFn = linkFns [ i ++ ] ; childLinkFn = linkFns [ i ++ ] ; if ( nodeLinkFn ) { if ( nodeLinkFn . scope ) { childScope = scope . $new ( isObject ( nodeLinkFn . scope ) ) ; jqLite ( node ) . data ( '$scope' , childScope ) ; } else { childScope = scope ; } childTranscludeFn = nodeLinkFn . transclude ; if ( childTranscludeFn || ( ! boundTranscludeFn && transcludeFn ) ) { nodeLinkFn ( childLinkFn , childScope , node , $rootElement , ( function ( transcludeFn ) { return function ( cloneFn ) { var transcludeScope = scope . $new ( ) ; transcludeScope . $$transcluded = true ; return transcludeFn ( transcludeScope , cloneFn ) . on ( '$destroy' , bind ( transcludeScope , transcludeScope . $destroy ) ) ; } ; } ) ( childTranscludeFn || transcludeFn ) ) ; } else { nodeLinkFn ( childLinkFn , childScope , node , undefined , boundTranscludeFn ) ; } } else if ( childLinkFn ) { childLinkFn ( scope , node . childNodes , undefined , boundTranscludeFn ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for linking function which converts normal linking function into a grouped linking function . [CODESPLIT] function groupElementsLinkFnWrapper ( linkFn , attrStart , attrEnd ) { return function ( scope , element , attrs , controllers ) { element = groupScan ( element [ 0 ] , attrStart , attrEnd ) ; return linkFn ( scope , element , attrs , controllers ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////// [CODESPLIT] function addLinkFns ( pre , post , attrStart , attrEnd ) { if ( pre ) { if ( attrStart ) pre = groupElementsLinkFnWrapper ( pre , attrStart , attrEnd ) ; pre . require = directive . require ; preLinkFns . push ( pre ) ; } if ( post ) { if ( attrStart ) post = groupElementsLinkFnWrapper ( post , attrStart , attrEnd ) ; post . require = directive . require ; postLinkFns . push ( post ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a special jqLite . replaceWith which can replace items which have no parents provided that the containing jqLite collection is provided . [CODESPLIT] function replaceWith ( $rootElement , elementsToRemove , newNode ) { var firstElementToRemove = elementsToRemove [ 0 ] , removeCount = elementsToRemove . length , parent = firstElementToRemove . parentNode , i , ii ; if ( $rootElement ) { for ( i = 0 , ii = $rootElement . length ; i < ii ; i ++ ) { if ( $rootElement [ i ] == firstElementToRemove ) { $rootElement [ i ++ ] = newNode ; for ( var j = i , j2 = j + removeCount - 1 , jj = $rootElement . length ; j < jj ; j ++ , j2 ++ ) { if ( j2 < jj ) { $rootElement [ j ] = $rootElement [ j2 ] ; } else { delete $rootElement [ j ] ; } } $rootElement . length -= removeCount - 1 ; break ; } } } if ( parent ) { parent . replaceChild ( newNode , firstElementToRemove ) ; } var fragment = document . createDocumentFragment ( ) ; fragment . appendChild ( firstElementToRemove ) ; newNode [ jqLite . expando ] = firstElementToRemove [ jqLite . expando ] ; for ( var k = 1 , kk = elementsToRemove . length ; k < kk ; k ++ ) { var element = elementsToRemove [ k ] ; jqLite ( element ) . remove ( ) ; // must do this way to clean up expando fragment . appendChild ( element ) ; delete elementsToRemove [ k ] ; } elementsToRemove [ 0 ] = newNode ; elementsToRemove . length = 1 }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc object @name ng . $controllerProvider @description The { @link ng . $controller $controller service } is used by Angular to create new controllers . [CODESPLIT] function $ControllerProvider ( ) { var controllers = { } , CNTRL_REG = / ^(\\S+)(\\s+as\\s+(\\w+))?$ / ; /**\n   * @ngdoc function\n   * @name ng.$controllerProvider#register\n   * @methodOf ng.$controllerProvider\n   * @param {string|Object} name Controller name, or an object map of controllers where the keys are\n   *    the names and the values are the constructors.\n   * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI\n   *    annotations in the array notation).\n   */ this . register = function ( name , constructor ) { if ( isObject ( name ) ) { extend ( controllers , name ) } else { controllers [ name ] = constructor ; } } ; this . $get = [ '$injector' , '$window' , function ( $injector , $window ) { /**\n     * @ngdoc function\n     * @name ng.$controller\n     * @requires $injector\n     *\n     * @param {Function|string} constructor If called with a function then it's considered to be the\n     *    controller constructor function. Otherwise it's considered to be a string which is used\n     *    to retrieve the controller constructor using the following steps:\n     *\n     *    * check if a controller with given name is registered via `$controllerProvider`\n     *    * check if evaluating the string on the current scope returns a constructor\n     *    * check `window[constructor]` on the global `window` object\n     *\n     * @param {Object} locals Injection locals for Controller.\n     * @return {Object} Instance of given controller.\n     *\n     * @description\n     * `$controller` service is responsible for instantiating controllers.\n     *\n     * It's just a simple call to {@link AUTO.$injector $injector}, but extracted into\n     * a service, so that one can override this service with {@link https://gist.github.com/1649788\n     * BC version}.\n     */ return function ( expression , locals ) { var instance , match , constructor , identifier ; if ( isString ( expression ) ) { match = expression . match ( CNTRL_REG ) , constructor = match [ 1 ] , identifier = match [ 3 ] ; expression = controllers . hasOwnProperty ( constructor ) ? controllers [ constructor ] : getter ( locals . $scope , constructor , true ) || getter ( $window , constructor , true ) ; assertArgFn ( expression , constructor , true ) ; } instance = $injector . instantiate ( expression , locals ) ; if ( identifier ) { if ( ! ( locals && typeof locals . $scope == 'object' ) ) { throw minErr ( '$controller' ) ( 'noscp' , \"Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.\" , constructor || expression . name , identifier ) ; } locals . $scope [ identifier ] = instance ; } return instance ; } ; } ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LocationHtml5Url represents an url This object is exposed as $location service when HTML5 mode is enabled and supported [CODESPLIT] function LocationHtml5Url ( appBase , basePrefix ) { this . $$html5 = true ; basePrefix = basePrefix || '' ; var appBaseNoFile = stripFile ( appBase ) ; /**\n   * Parse given html5 (regular) url string into properties\n   * @param {string} newAbsoluteUrl HTML5 url\n   * @private\n   */ this . $$parse = function ( url ) { var parsed = { } matchUrl ( url , parsed ) ; var pathUrl = beginsWith ( appBaseNoFile , url ) ; if ( ! isString ( pathUrl ) ) { throw $locationMinErr ( 'ipthprfx' , 'Invalid url \"{0}\", missing path prefix \"{1}\".' , url , appBaseNoFile ) ; } matchAppUrl ( pathUrl , parsed ) ; extend ( this , parsed ) ; if ( ! this . $$path ) { this . $$path = '/' ; } this . $$compose ( ) ; } ; /**\n   * Compose url and update `absUrl` property\n   * @private\n   */ this . $$compose = function ( ) { var search = toKeyValue ( this . $$search ) , hash = this . $$hash ? '#' + encodeUriSegment ( this . $$hash ) : '' ; this . $$url = encodePath ( this . $$path ) + ( search ? '?' + search : '' ) + hash ; this . $$absUrl = appBaseNoFile + this . $$url . substr ( 1 ) ; // first char is always '/' } ; this . $$rewrite = function ( url ) { var appUrl , prevAppUrl ; if ( ( appUrl = beginsWith ( appBase , url ) ) !== undefined ) { prevAppUrl = appUrl ; if ( ( appUrl = beginsWith ( basePrefix , appUrl ) ) !== undefined ) { return appBaseNoFile + ( beginsWith ( '/' , appUrl ) || appUrl ) ; } else { return appBase + prevAppUrl ; } } else if ( ( appUrl = beginsWith ( appBaseNoFile , url ) ) !== undefined ) { return appBaseNoFile + appUrl ; } else if ( appBaseNoFile == url + '/' ) { return appBaseNoFile ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LocationHashbangUrl represents url This object is exposed as $location service when developer doesn t opt into html5 mode . It also serves as the base class for html5 mode fallback on legacy browsers . [CODESPLIT] function LocationHashbangUrl ( appBase , hashPrefix ) { var appBaseNoFile = stripFile ( appBase ) ; matchUrl ( appBase , this ) ; /**\n   * Parse given hashbang url into properties\n   * @param {string} url Hashbang url\n   * @private\n   */ this . $$parse = function ( url ) { var withoutBaseUrl = beginsWith ( appBase , url ) || beginsWith ( appBaseNoFile , url ) ; var withoutHashUrl = withoutBaseUrl . charAt ( 0 ) == '#' ? beginsWith ( hashPrefix , withoutBaseUrl ) : ( this . $$html5 ) ? withoutBaseUrl : '' ; if ( ! isString ( withoutHashUrl ) ) { throw $locationMinErr ( 'ihshprfx' , 'Invalid url \"{0}\", missing hash prefix \"{1}\".' , url , hashPrefix ) ; } matchAppUrl ( withoutHashUrl , this ) ; this . $$compose ( ) ; } ; /**\n   * Compose hashbang url and update `absUrl` property\n   * @private\n   */ this . $$compose = function ( ) { var search = toKeyValue ( this . $$search ) , hash = this . $$hash ? '#' + encodeUriSegment ( this . $$hash ) : '' ; this . $$url = encodePath ( this . $$path ) + ( search ? '?' + search : '' ) + hash ; this . $$absUrl = appBase + ( this . $$url ? hashPrefix + this . $$url : '' ) ; } ; this . $$rewrite = function ( url ) { if ( stripHash ( appBase ) == stripHash ( url ) ) { return url ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LocationHashbangUrl represents url This object is exposed as $location service when html5 history api is enabled but the browser does not support it . [CODESPLIT] function LocationHashbangInHtml5Url ( appBase , hashPrefix ) { this . $$html5 = true ; LocationHashbangUrl . apply ( this , arguments ) ; var appBaseNoFile = stripFile ( appBase ) ; this . $$rewrite = function ( url ) { var appUrl ; if ( appBase == stripHash ( url ) ) { return url ; } else if ( ( appUrl = beginsWith ( appBaseNoFile , url ) ) ) { return appBase + hashPrefix + appUrl ; } else if ( appBaseNoFile === url + '/' ) { return appBaseNoFile ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc method @name ng . $location#search @methodOf ng . $location [CODESPLIT] function ( search , paramValue ) { switch ( arguments . length ) { case 0 : return this . $$search ; case 1 : if ( isString ( search ) ) { this . $$search = parseKeyValue ( search ) ; } else if ( isObject ( search ) ) { this . $$search = search ; } else { throw $locationMinErr ( 'isrcharg' , 'The first argument of the `$location#search()` call must be a string or an object.' ) ; } break ; default : if ( paramValue == undefined || paramValue == null ) { delete this . $$search [ search ] ; } else { this . $$search [ search ] = paramValue ; } } this . $$compose ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is used with json array declaration [CODESPLIT] function arrayDeclaration ( ) { var elementFns = [ ] ; var allConstant = true ; if ( peekToken ( ) . text != ']' ) { do { var elementFn = expression ( ) ; elementFns . push ( elementFn ) ; if ( ! elementFn . constant ) { allConstant = false ; } } while ( expect ( ',' ) ) ; } consume ( ']' ) ; return extend ( function ( self , locals ) { var array = [ ] ; for ( var i = 0 ; i < elementFns . length ; i ++ ) { array . push ( elementFns [ i ] ( self , locals ) ) ; } return array ; } , { literal : true , constant : allConstant } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////// Parser helper functions //////////////////////////////////////////////// [CODESPLIT] function setter ( obj , path , setValue , fullExp ) { var element = path . split ( '.' ) , key ; for ( var i = 0 ; element . length > 1 ; i ++ ) { key = ensureSafeMemberName ( element . shift ( ) , fullExp ) ; var propertyObj = obj [ key ] ; if ( ! propertyObj ) { propertyObj = { } ; obj [ key ] = propertyObj ; } obj = propertyObj ; if ( obj . then ) { if ( ! ( \"$$v\" in obj ) ) { ( function ( promise ) { promise . then ( function ( val ) { promise . $$v = val ; } ) ; } ) ( obj ) ; } if ( obj . $$v === undefined ) { obj . $$v = { } ; } obj = obj . $$v ; } } key = ensureSafeMemberName ( element . shift ( ) , fullExp ) ; obj [ key ] = setValue ; return setValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc @name ng . $q#reject @methodOf ng . $q @description Creates a promise that is resolved as rejected with the specified reason . This api should be used to forward rejection in a chain of promises . If you are dealing with the last promise in a promise chain you don t need to worry about it . [CODESPLIT] function ( reason ) { return { then : function ( callback , errback ) { var result = defer ( ) ; nextTick ( function ( ) { try { result . resolve ( ( isFunction ( errback ) ? errback : defaultErrback ) ( reason ) ) ; } catch ( e ) { result . reject ( e ) ; exceptionHandler ( e ) ; } } ) ; return result . promise ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc @name ng . $q#when @methodOf ng . $q @description Wraps an object that might be a value or a ( 3rd party ) then - able promise into a $q promise . This is useful when you are dealing with an object that might or might not be a promise or if the promise comes from a source that can t be trusted . [CODESPLIT] function ( value , callback , errback , progressback ) { var result = defer ( ) , done ; var wrappedCallback = function ( value ) { try { return ( isFunction ( callback ) ? callback : defaultCallback ) ( value ) ; } catch ( e ) { exceptionHandler ( e ) ; return reject ( e ) ; } } ; var wrappedErrback = function ( reason ) { try { return ( isFunction ( errback ) ? errback : defaultErrback ) ( reason ) ; } catch ( e ) { exceptionHandler ( e ) ; return reject ( e ) ; } } ; var wrappedProgressback = function ( progress ) { try { return ( isFunction ( progressback ) ? progressback : defaultCallback ) ( progress ) ; } catch ( e ) { exceptionHandler ( e ) ; } } ; nextTick ( function ( ) { ref ( value ) . then ( function ( value ) { if ( done ) return ; done = true ; result . resolve ( ref ( value ) . then ( wrappedCallback , wrappedErrback , wrappedProgressback ) ) ; } , function ( reason ) { if ( done ) return ; done = true ; result . resolve ( wrappedErrback ( reason ) ) ; } , function ( progress ) { if ( done ) return ; result . notify ( wrappedProgressback ( progress ) ) ; } ) ; } ) ; return result . promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc function @name ng . $rootScope . Scope#$new @methodOf ng . $rootScope . Scope @function [CODESPLIT] function ( isolate ) { var Child , child ; if ( isolate ) { child = new Scope ( ) ; child . $root = this . $root ; // ensure that there is just one async queue per $rootScope and its children child . $$asyncQueue = this . $$asyncQueue ; child . $$postDigestQueue = this . $$postDigestQueue ; } else { Child = function ( ) { } ; // should be anonymous; This is so that when the minifier munges // the name it does not become random set of chars. This will then show up as class // name in the debugger. Child . prototype = this ; child = new Child ( ) ; child . $id = nextUid ( ) ; } child [ 'this' ] = child ; child . $$listeners = { } ; child . $parent = this ; child . $$watchers = child . $$nextSibling = child . $$childHead = child . $$childTail = null ; child . $$prevSibling = this . $$childTail ; if ( this . $$childHead ) { this . $$childTail . $$nextSibling = child ; this . $$childTail = child ; } else { this . $$childHead = this . $$childTail = child ; } return child ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc function @name ng . $rootScope . Scope#$watch @methodOf ng . $rootScope . Scope @function [CODESPLIT] function ( watchExp , listener , objectEquality ) { var scope = this , get = compileToFn ( watchExp , 'watch' ) , array = scope . $$watchers , watcher = { fn : listener , last : initWatchVal , get : get , exp : watchExp , eq : ! ! objectEquality } ; // in the case user pass string, we need to compile it, do we really need this ? if ( ! isFunction ( listener ) ) { var listenFn = compileToFn ( listener || noop , 'listener' ) ; watcher . fn = function ( newVal , oldVal , scope ) { listenFn ( scope ) ; } ; } if ( typeof watchExp == 'string' && get . constant ) { var originalFn = watcher . fn ; watcher . fn = function ( newVal , oldVal , scope ) { originalFn . call ( this , newVal , oldVal , scope ) ; arrayRemove ( array , watcher ) ; } ; } if ( ! array ) { array = scope . $$watchers = [ ] ; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array . unshift ( watcher ) ; return function ( ) { arrayRemove ( array , watcher ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc function @name ng . $rootScope . Scope#$watchCollection @methodOf ng . $rootScope . Scope @function [CODESPLIT] function ( obj , listener ) { var self = this ; var oldValue ; var newValue ; var changeDetected = 0 ; var objGetter = $parse ( obj ) ; var internalArray = [ ] ; var internalObject = { } ; var oldLength = 0 ; function $watchCollectionWatch ( ) { newValue = objGetter ( self ) ; var newLength , key ; if ( ! isObject ( newValue ) ) { if ( oldValue !== newValue ) { oldValue = newValue ; changeDetected ++ ; } } else if ( isArrayLike ( newValue ) ) { if ( oldValue !== internalArray ) { // we are transitioning from something which was not an array into array. oldValue = internalArray ; oldLength = oldValue . length = 0 ; changeDetected ++ ; } newLength = newValue . length ; if ( oldLength !== newLength ) { // if lengths do not match we need to trigger change notification changeDetected ++ ; oldValue . length = oldLength = newLength ; } // copy the items to oldValue and look for changes. for ( var i = 0 ; i < newLength ; i ++ ) { if ( oldValue [ i ] !== newValue [ i ] ) { changeDetected ++ ; oldValue [ i ] = newValue [ i ] ; } } } else { if ( oldValue !== internalObject ) { // we are transitioning from something which was not an object into object. oldValue = internalObject = { } ; oldLength = 0 ; changeDetected ++ ; } // copy the items to oldValue and look for changes. newLength = 0 ; for ( key in newValue ) { if ( newValue . hasOwnProperty ( key ) ) { newLength ++ ; if ( oldValue . hasOwnProperty ( key ) ) { if ( oldValue [ key ] !== newValue [ key ] ) { changeDetected ++ ; oldValue [ key ] = newValue [ key ] ; } } else { oldLength ++ ; oldValue [ key ] = newValue [ key ] ; changeDetected ++ ; } } } if ( oldLength > newLength ) { // we used to have more keys, need to find them and destroy them. changeDetected ++ ; for ( key in oldValue ) { if ( oldValue . hasOwnProperty ( key ) && ! newValue . hasOwnProperty ( key ) ) { oldLength -- ; delete oldValue [ key ] ; } } } } return changeDetected ; } function $watchCollectionAction ( ) { listener ( newValue , oldValue , self ) ; } return this . $watch ( $watchCollectionWatch , $watchCollectionAction ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc function @name ng . $rootScope . Scope#$on @methodOf ng . $rootScope . Scope @function [CODESPLIT] function ( name , listener ) { var namedListeners = this . $$listeners [ name ] ; if ( ! namedListeners ) { this . $$listeners [ name ] = namedListeners = [ ] ; } namedListeners . push ( listener ) ; return function ( ) { namedListeners [ indexOf ( namedListeners , listener ) ] = null ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc function @name ng . $rootScope . Scope#$emit @methodOf ng . $rootScope . Scope @function [CODESPLIT] function ( name , args ) { var empty = [ ] , namedListeners , scope = this , stopPropagation = false , event = { name : name , targetScope : scope , stopPropagation : function ( ) { stopPropagation = true ; } , preventDefault : function ( ) { event . defaultPrevented = true ; } , defaultPrevented : false } , listenerArgs = concat ( [ event ] , arguments , 1 ) , i , length ; do { namedListeners = scope . $$listeners [ name ] || empty ; event . currentScope = scope ; for ( i = 0 , length = namedListeners . length ; i < length ; i ++ ) { // if listeners were deregistered, defragment the array if ( ! namedListeners [ i ] ) { namedListeners . splice ( i , 1 ) ; i -- ; length -- ; continue ; } try { namedListeners [ i ] . apply ( null , listenerArgs ) ; if ( stopPropagation ) return event ; } catch ( e ) { $exceptionHandler ( e ) ; } } //traverse upwards scope = scope . $parent ; } while ( scope ) ; return event ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@ngdoc method @name ng . $sceDelegate#trustAs @methodOf ng . $sceDelegate [CODESPLIT] function trustAs ( type , trustedValue ) { var constructor = ( byType . hasOwnProperty ( type ) ? byType [ type ] : null ) ; if ( ! constructor ) { throw $sceMinErr ( 'icontext' , 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}' , type , trustedValue ) ; } if ( trustedValue === null || trustedValue === undefined || trustedValue === '' ) { return trustedValue ; } // All the current contexts in SCE_CONTEXTS happen to be strings.  In order to avoid trusting // mutable objects, we ensure here that the value passed in is actually a string. if ( typeof trustedValue !== 'string' ) { throw $sceMinErr ( 'itype' , 'Attempted to trust a non-string value in a content requiring a string: Context: {0}' , type ) ; } return new constructor ( trustedValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@description Normalizes and optionally parses a URL . [CODESPLIT] function resolve ( url , parse ) { var href = url ; if ( msie <= 11 ) { // Normalize before parse.  Refer Implementation Notes on why this is // done in two steps on IE. urlParsingNode . setAttribute ( \"href\" , href ) ; href = urlParsingNode . href ; } urlParsingNode . setAttribute ( 'href' , href ) ; if ( ! parse ) { return urlParsingNode . href ; } // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href : urlParsingNode . href , protocol : urlParsingNode . protocol , host : urlParsingNode . host // Currently unused and hence commented out. // hostname: urlParsingNode.hostname, // port: urlParsingNode.port, // pathname: urlParsingNode.pathname, // hash: urlParsingNode.hash, // search: urlParsingNode.search } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a request URL and determine whether this is a same - origin request as the application document . [CODESPLIT] function isSameOrigin ( requestUrl ) { var parsed = ( typeof requestUrl === 'string' ) ? resolve ( requestUrl , true ) : requestUrl ; return ( parsed . protocol === originUrl . protocol && parsed . host === originUrl . host ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Make promise agnostic [CODESPLIT] function ConsumingMatcher ( matchers ) { return _ . create ( { } , { unmatchedMatchers : _ . clone ( matchers ) , matches : function ( actual ) { let matched = false ; _ . forEach ( this . unmatchedMatchers , ( matcher , index ) => { if ( matcher . matches ( actual ) ) { matched = true ; this . unmatchedMatchers . splice ( index , 1 ) ; return false ; } } , this ) ; return matched ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Traverse the specified AST . [CODESPLIT] function traverse ( node , opt_onEnter , opt_onLeave ) { if ( opt_onEnter ) opt_onEnter ( node ) ; var childNodes = _collectChildNodes ( node ) ; childNodes . forEach ( function ( childNode ) { traverse ( childNode , opt_onEnter , opt_onLeave ) ; } ) ; if ( opt_onLeave ) opt_onLeave ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "json - rpc - ws client [CODESPLIT] function Client ( ) { logger ( 'new Client' ) ; this . type = 'client' ; this . id = uuid ( ) ; this . browser = ( WebSocket . Server === undefined ) ; Base . call ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Quarantined JSON . parse try / catch block in its own function [CODESPLIT] function jsonParse ( data ) { var payload ; try { payload = JSON . parse ( data ) ; } catch ( error ) { logger ( error ) ; payload = null ; } return payload ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "json - rpc - ws connection [CODESPLIT] function Connection ( socket , parent ) { logger ( 'new Connection to %s' , parent . type ) ; this . id = uuid ( ) ; this . socket = socket ; this . parent = parent ; this . responseHandlers = { } ; if ( this . parent . browser ) { this . socket . onmessage = this . message . bind ( this ) ; this . socket . onclose = socketClosed . bind ( this ) ; this . socket . onerror = socketError . bind ( this ) ; } else { this . socket . on ( 'message' , this . message . bind ( this ) ) ; this . socket . once ( 'close' , this . close . bind ( this ) ) ; this . socket . once ( 'error' , this . close . bind ( this ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Javascript Diff Algorithm By John Resig ( http : // ejohn . org / ) Modified by Chu Alan sprite [CODESPLIT] function escapeJSDiff ( s ) { var n = s ; n = n . replace ( / & / g , \"&amp;\" ) ; n = n . replace ( / < / g , \"&lt;\" ) ; n = n . replace ( / > / g , \"&gt;\" ) ; n = n . replace ( / \" / g , \"&quot;\" ) ; return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Dialog class represents a modal dialog . The dialog class can be invoked by providing an options object containing at lest template or templateUrl and controller : var d = new Dialog ( { templateUrl : foo . html controller : BarController } ) ; Dialogs can also be created using templateUrl and controller as distinct arguments : var d = new Dialog ( path / to / dialog . html MyDialogController ) ; [CODESPLIT] function Dialog ( opts ) { var self = this , options = this . options = angular . extend ( { } , defaults , globalOptions , opts ) ; this . _open = false ; this . backdropEl = createElement ( options . backdropClass ) ; if ( options . backdropFade ) { this . backdropEl . addClass ( options . transitionClass ) ; this . backdropEl . removeClass ( options . triggerClass ) ; } this . modalEl = createElement ( options . dialogClass ) ; if ( options . dialogFade ) { this . modalEl . addClass ( options . transitionClass ) ; this . modalEl . removeClass ( options . triggerClass ) ; } this . handledEscapeKey = function ( e ) { if ( e . which === 27 ) { self . close ( ) ; e . preventDefault ( ) ; self . $scope . $apply ( ) ; } } ; this . handleBackDropClick = function ( e ) { self . close ( ) ; e . preventDefault ( ) ; self . $scope . $apply ( ) ; } ; this . handleLocationChange = function ( ) { self . close ( ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new Dialog tied to the default message box template and controller . Arguments title and message are rendered in the modal header and body sections respectively . The buttons array holds an object with the following members for each button to include in the modal footer section : * result : the result to pass to the close method of the dialog when the button is clicked * label : the label of the button * cssClass : additional css class ( es ) to apply to the button for styling [CODESPLIT] function ( title , message , buttons ) { return new Dialog ( { templateUrl : 'plugins/ui-bootstrap/html/message.html' , controller : 'MessageBoxController' , resolve : { model : function ( ) { return { title : title , message : message , buttons : buttons } ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": ": ( string ?Object ) → ( ... content : [ union<string Node > ] ) → Node Create a builder function for nodes with content . [CODESPLIT] function block ( type , attrs ) { let result = function ( ... args ) { let myAttrs = takeAttrs ( attrs , args ) let { nodes , tag } = flatten ( type . schema , args , id ) let node = type . create ( myAttrs , nodes ) if ( tag != noTag ) node . tag = tag return node } if ( type . isLeaf ) try { result . flat = [ type . create ( attrs ) ] } catch ( _ ) { } return result }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a builder function for marks . [CODESPLIT] function mark ( type , attrs ) { return function ( ... args ) { let mark = type . create ( takeAttrs ( attrs , args ) ) let { nodes , tag } = flatten ( type . schema , args , n => mark . type . isInSet ( n . marks ) ? n : n . mark ( mark . addToSet ( n . marks ) ) ) return { flat : nodes , tag } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create store [CODESPLIT] function _createStore ( ) { //start to create store const rootEpic = combineEpics ( ... _epics ) ; const _trueReducers = combineReducers ( _reducersObj ) ; //TODO extra epic inject plugin const epicMiddleware = getEpicMiddleware ( rootEpic , _plugins ) ; _middlewares . push ( epicMiddleware ) ; return _configureStore ( _trueReducers , _middlewares ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send the request using the socket [CODESPLIT] function serverRequest ( config ) { var defer = $q . defer ( ) ; if ( provider . debug ) $log . info ( '$sails ' + config . method + ' ' + config . url , config . data || '' ) ; if ( config . timeout > 0 ) { $timeout ( timeoutRequest , config . timeout ) ; } else if ( isPromiseLike ( config . timeout ) ) { config . timeout . then ( timeoutRequest ) ; } socket [ 'legacy_' + config . method . toLowerCase ( ) ] ( config . url , config . data , serverResponse ) ; function timeoutRequest ( ) { serverResponse ( null ) ; } function serverResponse ( result , jwr ) { if ( ! jwr ) { jwr = { body : result , headers : result . headers || { } , statusCode : result . statusCode || result . status || 0 , error : ( function ( ) { if ( this . statusCode < 200 || this . statusCode >= 400 ) { return this . body || this . statusCode ; } } ) ( ) } ; } jwr . data = jwr . body ; // $http compat jwr . status = jwr . statusCode ; // $http compat jwr . socket = socket ; jwr . url = config . url ; jwr . method = config . method ; jwr . config = config . config ; if ( jwr . error ) { if ( provider . debug ) $log . warn ( '$sails response ' + jwr . statusCode + ' ' + config . url , jwr ) ; defer . reject ( jwr ) ; } else { if ( provider . debug ) $log . info ( '$sails response ' + config . url , jwr ) ; defer . resolve ( jwr ) ; } } return defer . promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches for the bootstrap file until it finds one .... [CODESPLIT] function figureOutRootComponent ( ) { var rootComponents = [ '../../../src/app/app.module.ts' , '../../../src/app.ts' , '../../../boot.ts' , '../../../src/main.ts' ] ; for ( var i = 0 ; i < rootComponents . length ; i ++ ) { if ( fs . existsSync ( rootComponents [ i ] ) ) { var result = processBootStrap ( rootComponents [ i ] ) ; if ( result ) { return result ; } } } // Return a default component, if we can't find one... return { name : 'AppComponent' , path : './client/components/app.component' } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the bootstrap to figure out the default bootstrap component [CODESPLIT] function processBootStrap ( file ) { var data = fs . readFileSync ( file ) . toString ( ) ; var idx = data . indexOf ( 'bootstrap(' ) ; if ( idx === - 1 ) { return null ; } else { idx += 10 ; } var odx1 = data . indexOf ( ',' , idx ) ; var odx2 = data . indexOf ( ')' , idx ) ; if ( odx2 < odx1 && odx2 !== - 1 || odx1 === - 1 ) { odx1 = odx2 ; } if ( odx1 === - 1 ) { return null ; } var componentRef = data . substring ( idx , odx1 ) ; var exp = \"import\\\\s+\\\\{(\" + componentRef + \")\\\\}\\\\s+from+\\\\s+[\\'|\\\"](\\\\S+)[\\'|\\\"][;?]\" ; if ( debugging ) { console . log ( \"Searching for\" , exp ) ; } var result = function ( r ) { return { name : r [ 1 ] , path : r [ r . length - 1 ] } ; } ; //noinspection JSPotentiallyInvalidConstructorUsage var r = RegExp ( exp , 'i' ) . exec ( data ) ; if ( r === null || r . length <= 1 ) { // check if using current style guide with spaces exp = \"import\\\\s+\\\\{\\\\s+(\" + componentRef + \")\\\\,\\\\s+([A-Z]{0,300})\\\\w+\\\\s+\\\\}\\\\s+from+\\\\s+[\\'|\\\"](\\\\S+)[\\'|\\\"][;?]\" ; if ( debugging ) { console . log ( \"Searching for\" , exp ) ; } r = RegExp ( exp , 'i' ) . exec ( data ) ; if ( r === null || r . length <= 1 ) { // try just spaces with no angular cli style (, environment) etc. exp = \"import\\\\s+\\\\{\\\\s+(\" + componentRef + \")\\\\s+\\\\}\\\\s+from+\\\\s+[\\'|\\\"](\\\\S+)[\\'|\\\"][;?]\" ; if ( debugging ) { console . log ( \"Searching for\" , exp ) ; } r = RegExp ( exp , 'i' ) . exec ( data ) ; if ( r !== null && r . length > 1 ) { return result ( r ) ; } } else { // angular cli return result ( r ) ; } return null ; } return result ( r ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create Symlink [CODESPLIT] function createSymLink ( ) { if ( debugging ) { console . log ( \"Attempting to Symlink\" , angularSeedPath , nativescriptClientPath ) ; } fs . symlinkSync ( resolve ( angularSeedPath ) , resolve ( nativescriptClientPath ) , 'junction' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This fixes the TS Config file in the nativescript folder [CODESPLIT] function fixTsConfig ( ) { var tsConfig = { } , tsFile = '../../tsconfig.json' ; if ( fs . existsSync ( tsFile ) ) { tsConfig = require ( tsFile ) ; } if ( ! tsConfig . compilerOptions || ! tsConfig . compilerOptions . typeRoots ) { tsConfig . compilerOptions = { target : \"es5\" , module : \"commonjs\" , declaration : false , removeComments : true , noLib : false , emitDecoratorMetadata : true , experimentalDecorators : true , lib : [ \"dom\" ] , sourceMap : true , pretty : true , allowUnreachableCode : false , allowUnusedLabels : false , noImplicitAny : false , noImplicitReturns : true , noImplicitUseStrict : false , noFallthroughCasesInSwitch : true , typeRoots : [ \"node_modules/@types\" , \"node_modules\" ] , types : [ \"jasmine\" ] } ; } // See: https://github.com/NativeScript/nativescript-angular/issues/205 // tsConfig.compilerOptions.noEmitHelpers = false; // tsConfig.compilerOptions.noEmitOnError = false; if ( ! tsConfig . exclude ) { tsConfig . exclude = [ ] ; } if ( tsConfig . exclude . indexOf ( 'node_modules' ) === - 1 ) { tsConfig . exclude . push ( 'node_modules' ) ; } if ( tsConfig . exclude . indexOf ( 'platforms' ) === - 1 ) { tsConfig . exclude . push ( 'platforms' ) ; } fs . writeFileSync ( tsFile , JSON . stringify ( tsConfig , null , 4 ) , 'utf8' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This fixes the references file to work with TS 2 . 0 in the nativescript folder [CODESPLIT] function fixRefFile ( ) { var existingRef = '' , refFile = '../../references.d.ts' ; if ( fs . existsSync ( refFile ) ) { existingRef = fs . readFileSync ( refFile ) . toString ( ) ; } if ( existingRef . indexOf ( 'typescript/lib/lib.d.ts' ) === - 1 ) { // has not been previously modified var fix = '/// <reference path=\"./node_modules/tns-core-modules/tns-core-modules.d.ts\" />\\n' + '/// <reference path=\"./node_modules/typescript/lib/lib.d.ts\" />\\n' ; fs . writeFileSync ( refFile , fix , 'utf8' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fix the NativeScript Package file [CODESPLIT] function fixNativeScriptPackage ( ) { var packageJSON = { } , packageFile = '../../package.json' ; packageJSON . name = \"NativeScriptApp\" ; packageJSON . version = \"0.0.0\" ; // var AngularJSON = {}; if ( fs . existsSync ( packageFile ) ) { packageJSON = require ( packageFile ) ; } else { console . log ( \"This should not happen, your are missing your package.json file!\" ) ; return ; } // if (fs.existsSync('../angular2/package.json')) { //     AngularJSON = require('../angular2/package.json'); // } else { //     // Copied from the Angular2.0.0-beta-16 package.json, this is a fall back //     AngularJSON.peerDependencies = { //         \"es6-shim\": \"^0.35.0\", //         \"reflect-metadata\": \"0.1.2\", //         \"rxjs\": \"5.0.0-beta.6\", //         \"zone.js\": \"^0.6.12\" //     }; // } packageJSON . nativescript [ 'tns-ios' ] = { version : \"2.3.0\" } ; packageJSON . nativescript [ 'tns-android' ] = { version : \"2.3.0\" } ; // Copy over all the Peer Dependencies // for (var key in AngularJSON.peerDependencies) { //     if (AngularJSON.peerDependencies.hasOwnProperty(key)) { //         packageJSON.dependencies[key] = AngularJSON.peerDependencies[key]; //     } // } // TODO: Can we get these from somewhere rather than hardcoding them, maybe need to pull/download the package.json from the default template? if ( ! packageJSON . devDependencies ) { packageJSON . devDependencies = { } ; } packageJSON . devDependencies [ \"@types/jasmine\" ] = \"^2.5.35\" ; packageJSON . devDependencies [ \"babel-traverse\" ] = \"6.12.0\" ; packageJSON . devDependencies [ \"babel-types\" ] = \"6.11.1\" ; packageJSON . devDependencies . babylon = \"6.8.4\" ; packageJSON . devDependencies . filewalker = \"0.1.2\" ; packageJSON . devDependencies . lazy = \"1.0.11\" ; // packageJSON.devDependencies[\"nativescript-dev-typescript\"] = \"^0.3.2\"; packageJSON . devDependencies . typescript = \"^2.0.2\" ; fs . writeFileSync ( packageFile , JSON . stringify ( packageJSON , null , 4 ) , 'utf8' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fix the Angular Package [CODESPLIT] function fixAngularPackage ( ) { var packageJSON = { } , packageFile = '../../../package.json' ; if ( fs . existsSync ( packageFile ) ) { packageJSON = require ( packageFile ) ; } else { console . log ( \"This should not happen, your are missing your main package.json file!\" ) ; return ; } if ( ! packageJSON . scripts ) { packageJSON . scripts = { } ; } packageJSON . scripts [ \"start.ios\" ] = \"cd nativescript && tns emulate ios\" ; packageJSON . scripts [ \"start.livesync.ios\" ] = \"cd nativescript && tns livesync ios --emulator --watch\" ; packageJSON . scripts [ \"start.android\" ] = \"cd nativescript && tns emulate android\" ; packageJSON . scripts [ \"start.livesync.android\" ] = \"cd nativescript && tns livesync android --emulator --watch\" ; fs . writeFileSync ( packageFile , JSON . stringify ( packageJSON , null , 4 ) , 'utf8' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fix the Main NativeScript File [CODESPLIT] function fixMainFile ( component ) { var mainTS = '' , mainFile = '../../app/main.ts' ; if ( fs . existsSync ( mainFile ) ) { mainTS = fs . readFileSync ( mainFile ) . toString ( ) ; } if ( mainTS . indexOf ( 'MagicService' ) === - 1 ) { // has not been previously modified var fix = '// this import should be first in order to load some required settings (like globals and reflect-metadata)\\n' + 'import { platformNativeScriptDynamic, NativeScriptModule } from \"nativescript-angular/platform\";\\n' + 'import { NgModule } from \"@angular/core\";\\n' + 'import { AppComponent } from \"./app/app.component\";\\n' + '\\n' + '@NgModule({\\n' + '  declarations: [AppComponent],\\n' + '  bootstrap: [AppComponent],\\n' + '   imports: [NativeScriptModule],\\n' + '})\\n' + 'class AppComponentModule {}\\n\\n' + 'platformNativeScriptDynamic().bootstrapModule(AppComponentModule);' ; fs . writeFileSync ( mainFile , fix , 'utf8' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fix . gitignore [CODESPLIT] function fixGitIgnore ( ignorePattern ) { var fileString = '' , ignoreFile = '../../../.gitignore' ; if ( fs . existsSync ( ignoreFile ) ) { fileString = fs . readFileSync ( ignoreFile ) . toString ( ) ; } if ( fileString . indexOf ( ignorePattern ) === - 1 ) { // has not been previously modified var fix = fileString + '\\n' + ignorePattern ; fs . writeFileSync ( ignoreFile , fix , 'utf8' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Display final help screen! [CODESPLIT] function displayFinalHelp ( ) { console . log ( \"-------------- Welcome to the Magical World of NativeScript -----------------------------\" ) ; console . log ( \"To finish, follow this guide https://github.com/NathanWalker/nativescript-ng2-magic#usage\" ) ; console . log ( \"After you have completed the steps in the usage guide, you can then:\" ) ; console . log ( \"\" ) ; console . log ( \"Run your app in the iOS Simulator with these options:\" ) ; console . log ( \"  npm run start.ios\" ) ; console . log ( \"  npm run start.livesync.ios\" ) ; console . log ( \"\" ) ; console . log ( \"Run your app in an Android emulator with these options:\" ) ; console . log ( \"  npm run start.android\" ) ; console . log ( \"  npm run start.livesync.android\" ) ; console . log ( \"-----------------------------------------------------------------------------------------\" ) ; console . log ( \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Please use this bind not the one from Function . prototype [CODESPLIT] function bind ( func , thisObject , var_args ) { var args = slice ( arguments , 2 ) ; /**\n     * @param {...} var_args\n     */ function bound ( var_args ) { return InjectedScriptHost . callFunction ( func , thisObject , concat ( args , slice ( arguments ) ) ) ; } bound . toString = function ( ) { return \"bound: \" + toString ( func ) ; } ; return bound ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method cannot throw . [CODESPLIT] function ( object , objectGroupName , forceValueType , generatePreview , columnNames , isTable , doNotBind , customObjectConfig ) { try { return new InjectedScript . RemoteObject ( object , objectGroupName , doNotBind , forceValueType , generatePreview , columnNames , isTable , undefined , customObjectConfig ) ; } catch ( e ) { try { var description = injectedScript . _describe ( e ) ; } catch ( ex ) { var description = \"<failed to convert exception to string>\" ; } return new InjectedScript . RemoteObject ( description ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves a value from CallArgument description . [CODESPLIT] function ( callArgumentJson ) { callArgumentJson = nullifyObjectProto ( callArgumentJson ) ; var objectId = callArgumentJson . objectId ; if ( objectId ) { var parsedArgId = this . _parseObjectId ( objectId ) ; if ( ! parsedArgId || parsedArgId [ \"injectedScriptId\" ] !== injectedScriptId ) throw \"Arguments should belong to the same JavaScript world as the target object.\" ; var resolvedArg = this . _objectForId ( parsedArgId ) ; if ( ! this . _isDefined ( resolvedArg ) ) throw \"Could not find object with given id\" ; return resolvedArg ; } else if ( \"value\" in callArgumentJson ) { var value = callArgumentJson . value ; if ( callArgumentJson . type === \"number\" && typeof value !== \"number\" ) value = Number ( value ) ; return value ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Either callFrameId or functionObjectId must be specified . [CODESPLIT] function ( topCallFrame , callFrameId , functionObjectId , scopeNumber , variableName , newValueJsonString ) { try { var newValueJson = /** @type {!RuntimeAgent.CallArgument} */ ( InjectedScriptHost . eval ( \"(\" + newValueJsonString + \")\" ) ) ; var resolvedValue = this . _resolveCallArgument ( newValueJson ) ; if ( typeof callFrameId === \"string\" ) { var callFrame = this . _callFrameForId ( topCallFrame , callFrameId ) ; if ( ! callFrame ) return \"Could not find call frame with given id\" ; callFrame . setVariableValue ( scopeNumber , variableName , resolvedValue ) } else { var parsedFunctionId = this . _parseObjectId ( /** @type {string} */ ( functionObjectId ) ) ; var func = this . _objectForId ( parsedFunctionId ) ; if ( typeof func !== \"function\" ) return \"Could not resolve function by id\" ; InjectedScriptHost . setFunctionVariableValue ( func , scopeNumber , variableName , resolvedValue ) ; } } catch ( e ) { return toString ( e ) ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates a TileJSON Object [CODESPLIT] function validate ( tj ) { if ( Object . prototype . hasOwnProperty . call ( tj , 'tilejson' ) ) { if ( tj . tilejson !== '2.2.0' ) { return false ; } } else { return false ; } if ( Object . prototype . hasOwnProperty . call ( tj , 'name' ) ) { if ( typeof tj . name !== 'string' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'description' ) ) { if ( typeof tj . description !== 'string' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'version' ) ) { if ( typeof tj . version !== 'string' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'attribution' ) ) { if ( typeof tj . attribution !== 'string' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'template' ) ) { if ( typeof tj . template !== 'string' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'legend' ) ) { if ( typeof tj . legend !== 'string' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'scheme' ) ) { if ( typeof tj . scheme !== 'string' ) { return false ; } if ( tj . scheme !== 'xyz' && tj . scheme !== 'tms' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'tiles' ) ) { if ( tj . tiles . constructor !== Array ) { return false ; } if ( tj . tiles . length < 1 ) { return false ; } for ( let i = 0 ; i < tj . tiles . length ; i += 1 ) { if ( typeof tj . tiles [ i ] !== 'string' ) { return false ; } } } else { return false ; } if ( Object . prototype . hasOwnProperty . call ( tj , 'grids' ) ) { if ( tj . grids . constructor !== Array ) { return false ; } for ( let i = 0 ; i < tj . grids . length ; i += 1 ) { if ( typeof tj . grids [ i ] !== 'string' ) { return false ; } } } if ( Object . prototype . hasOwnProperty . call ( tj , 'data' ) ) { if ( tj . data . constructor !== Array ) { return false ; } for ( let i = 0 ; i < tj . data . length ; i += 1 ) { if ( typeof tj . data [ i ] !== 'string' ) { return false ; } } } let minzoom = 0 ; if ( Object . prototype . hasOwnProperty . call ( tj , 'minzoom' ) ) { if ( typeof tj . minzoom !== 'number' ) { return false ; } if ( ! Number . isInteger ( tj . minzoom ) ) { return false ; } if ( tj . minzoom < 0 || tj . minzoom > 30 ) { return false ; } minzoom = tj . minzoom ; } let maxzoom = 30 ; if ( Object . prototype . hasOwnProperty . call ( tj , 'maxzoom' ) ) { if ( typeof tj . maxzoom !== 'number' ) { return false ; } if ( ! Number . isInteger ( tj . maxzoom ) ) { return false ; } if ( tj . maxzoom < 0 || tj . maxzoom > 30 ) { return false ; } maxzoom = tj . maxzoom ; } if ( minzoom > maxzoom ) { return false ; } if ( Object . prototype . hasOwnProperty . call ( tj , 'bounds' ) ) { if ( tj . bounds . constructor !== Array ) { return false ; } for ( let i = 0 ; i < tj . bounds . length ; i += 1 ) { if ( typeof tj . bounds [ i ] !== 'number' ) { return false ; } } } if ( Object . prototype . hasOwnProperty . call ( tj , 'center' ) ) { if ( tj . center . constructor !== Array ) { return false ; } for ( let i = 0 ; i < tj . center . length ; i += 1 ) { if ( typeof tj . center [ i ] !== 'number' ) { return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates a TileJSON [CODESPLIT] function validate ( str ) { let tj ; if ( typeof str === 'object' ) { tj = str ; } else if ( typeof str === 'string' ) { try { tj = jsonlint . parse ( str ) ; } catch ( err ) { return false ; } } else { return false ; } return tilejsonValidateObject . validate ( tj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Adds a validator to the model that checks to make sure the given attributes are valid numbers . ... names - One or more attribute names . opts - An optional object containing zero or more of the following options : nonnegative - Ensure that the number is not negative . maximum - Ensure that the number is not greater than this value . minimum - Ensure that the number is not less than this value . Returns the receiver . [CODESPLIT] function validatesNumber ( ) { var names = Array . from ( arguments ) , opts = util . type ( names [ names . length - 1 ] ) === 'object' ? names . pop ( ) : { } ; names . forEach ( function ( name ) { this . validate ( name , function ( ) { this . validateNumber ( name , opts ) ; } ) ; } , this ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Adds a validator to the model that checks to make sure the given attributes are valid dates . ... names - One or more attribute names . Returns the receiver . [CODESPLIT] function validatesDate ( ) { Array . from ( arguments ) . forEach ( function ( name ) { this . validate ( name , function ( ) { this . validateDate ( name ) ; } ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Adds a validator to the model that checks to make sure the given attributes are valid emails . ... names - One or more attribute names . Returns the receiver . [CODESPLIT] function validatesEmail ( ) { Array . from ( arguments ) . forEach ( function ( name ) { this . validate ( name , function ( ) { this . validateEmail ( name ) ; } ) ; } , this ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Adds a validator to the model that checks to make sure the given attributes are valid phone numbers . ... names - One or more attribute names . Returns the receiver . [CODESPLIT] function validatesPhone ( ) { Array . from ( arguments ) . forEach ( function ( name ) { this . validate ( name , function ( ) { this . validatePhone ( name ) ; } ) ; } , this ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Adds a validator to the model that checks to make sure the given attributes are valid durations . ... names - One or more attribute names . Returns the receiver . [CODESPLIT] function validatesDuration ( ) { Array . from ( arguments ) . forEach ( function ( name ) { this . validate ( name , function ( ) { this . validateDuration ( name ) ; } ) ; } , this ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Parses a string containing a number . s - The string to parse . Returns a number or null if parsing fails . [CODESPLIT] function parseNumber ( s ) { s = String ( s ) . replace ( / [^\\d-.] / g , '' ) . replace ( / \\.$ / , '' ) ; if ( ! s . match ( NUMBER_RE ) ) { return null ; } return parseFloat ( s , 10 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Parses a string containing a percent . s - The string to parse . Returns a number or null if parsing fails . [CODESPLIT] function parsePercent ( s ) { var n = parseNumber ( String ( s ) . replace ( '%' , '' ) ) ; return n == null ? null : n / 100 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Parses a string containing a date in the following formats : - YYYY - MM - DD ( ISO8601 ) - MM / DD - MM?DD?YY where ? is a non - digit character - MM?DD?YYYY where ? is a non - digit character - MMDDYY - MMDDYYYY s - The string to parse . Returns a Date or null if parsing fails . [CODESPLIT] function parseDate ( s ) { var m , d , y , date , parts ; s = String ( s ) . replace ( / \\s / g , '' ) ; if ( parts = s . match ( ISO8601_DATE_RE ) ) { y = parseInt ( parts [ 1 ] , 10 ) ; m = parseInt ( parts [ 2 ] , 10 ) - 1 ; d = parseInt ( parts [ 3 ] , 10 ) ; date = new Date ( y , m , d ) ; return date . getMonth ( ) === m ? date : null ; } else if ( parts = s . match ( MDY_DATE_RE ) ) { m = parseInt ( parts [ 1 ] , 10 ) - 1 ; d = parseInt ( parts [ 2 ] , 10 ) ; y = parts [ 3 ] ? parseInt ( parts [ 3 ] , 10 ) : new Date ( ) . getFullYear ( ) ; if ( 0 <= y && y <= 68 ) { y += 2000 ; } if ( 69 <= y && y <= 99 ) { y += 1900 ; } date = new Date ( y , m , d ) ; return date . getMonth ( ) === m ? date : null ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Parses a string containing an ISO8601 formatted date and time . s - The string to parse . Returns a Date or null if parsing fails . [CODESPLIT] function parseDateTime ( s ) { var n ; s = String ( s ) ; if ( s . match ( NO_TZ_RE ) ) { s += 'Z' ; } return ( n = Date . parse ( s ) ) ? new Date ( n ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Parses a string containing an email . s - The string to parse . Returns the email string . [CODESPLIT] function parseEmail ( s ) { s = String ( s ) ; return EMAIL_FORMAT . test ( s ) ? s : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Parses a string containing an phone number . s - The string to parse . Returns the phone string . [CODESPLIT] function parsePhone ( s ) { s = String ( s ) ; return PHONE_FORMAT . test ( s . replace ( PHONE_CHARS , '' ) ) ? s : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Parses a string containing a time duration . The format is : HH : MM : SS where hours and minutes are optional . s - The string to parse . Returns the number of seconds or null if parsing fails . [CODESPLIT] function parseDuration ( s ) { s = String ( s ) ; if ( ! DURATION_RE . test ( s ) ) { return null ; } var parts = s . split ( ':' ) . map ( function ( p ) { return + p ; } ) ; if ( parts . length === 3 ) { return parts [ 0 ] * 3600 + parts [ 1 ] * 60 + parts [ 2 ] ; } else if ( parts . length === 2 ) { return parts [ 0 ] * 60 + parts [ 1 ] ; } else { return parts [ 0 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Used by detectRecursion to check to see if the given pair of objects has been encountered yet on a previous recursive call . o1 - The first object to check for recursion . o2 - The paired object to check for recursion . Returns true if the pair has been seen previously and false otherwise . [CODESPLIT] function seen ( o1 , o2 ) { var i , len ; for ( i = 0 , len = seenObjects . length ; i < len ; i ++ ) { if ( seenObjects [ i ] [ 0 ] === o1 && seenObjects [ i ] [ 1 ] === o2 ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Used by detectRecursion to unmark the given pair of objects after a recursive call has completed . o1 - The first object to unmark . o2 - The paired object to unmark . Returns nothing . [CODESPLIT] function unmark ( o1 , o2 ) { var i , n ; for ( i = 0 , n = seenObjects . length ; i < n ; i ++ ) { if ( seenObjects [ i ] [ 0 ] === o1 && seenObjects [ i ] [ 1 ] === o2 ) { seenObjects . splice ( i , 1 ) ; return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Used by getPath to resolve a path into a value . o - The object to resolve the path from . pathSegments - An array of strings representing segments of the path to resolve . Returns the resolved value or undefined if some segment of the path does not exist . [CODESPLIT] function _getPath ( o , pathSegments ) { if ( o == null ) { return undefined ; } var head = pathSegments [ 0 ] , tail = pathSegments . slice ( 1 ) ; if ( Array . isArray ( o ) && ! ( head in o ) ) { o = o . reduce ( function ( acc , x ) { if ( ! x ) { return acc ; } var y = x [ head ] ; if ( Array . isArray ( y ) ) { acc . push . apply ( acc , y ) ; } else { acc . push ( y ) ; } return acc ; } , [ ] ) ; } else { o = o [ head ] ; } if ( ! tail . length ) { return o ; } else { return o ? _getPath ( o , tail ) : undefined ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Used to detect cases of recursion on the same pair of objects . Returns true if the given objects have already been seen . Otherwise the given function is called and false is returned . This function is used internally when traversing objects and arrays to avoid getting stuck in infinite loops when circular objects are encountered . It should be wrapped around all recursive function calls where a circular object may be encountered . See Transis . eq for an example . o1 - The first object to check for recursion . o2 - The paired object to check for recursion ( default : undefined ) . f - A function that make the recursive funciton call . Returns true if recursion on the given objects has been detected . If the given pair of objects has yet to be seen calls f and returns false . [CODESPLIT] function detectRecursion ( o1 , o2 , f ) { if ( arguments . length === 2 ) { f = o2 ; o2 = undefined ; } if ( seen ( o1 , o2 ) ) { return true ; } else { mark ( o1 , o2 ) ; try { f ( ) ; } finally { unmark ( o1 , o2 ) ; } return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Returns a string indicating the type of the given object . This can be considered an enhanced version of the javascript typeof operator . Examples Transis . type ( [] ) // = > array Transis . type ( {} ) // = > object Transis . type ( 9 ) // = > number Transis . type ( / fo * / ) // = > regexp Transis . type ( new Date ) // = > date o - The object to get the type of . Returns a string indicating the object s type . [CODESPLIT] function type ( o ) { if ( o === null ) { return 'null' ; } if ( o === undefined ) { return 'undefined' ; } switch ( toString . call ( o ) ) { case '[object Array]' : return 'array' ; case '[object Arguments]' : return 'arguments' ; case '[object Function]' : return 'function' ; case '[object String]' : return 'string' ; case '[object Number]' : return 'number' ; case '[object Boolean]' : return 'boolean' ; case '[object Date]' : return 'date' ; case '[object RegExp]' : return 'regexp' ; case '[object Object]' : if ( o . hasOwnProperty ( 'callee' ) ) { return 'arguments' ; } // ie fallback else { return 'object' ; } } return 'unknown' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Performs an object equality test . If the first argument is a Transis . Object then it is sent the eq method otherwise custom equality code is run based on the object type . a - Any object . b - Any object . Returns true if the objects are equal and false otherwise . [CODESPLIT] function eq ( a , b ) { var atype , btype ; // identical objects are equal if ( a === b ) { return true ; } // if the first argument is a Transis.Object, delegate to its `eq` method if ( a && a . objectId && typeof a . eq === 'function' ) { return a . eq ( b ) ; } atype = type ( a ) ; btype = type ( b ) ; // native objects that are not of the same type are not equal if ( atype !== btype ) { return false ; } switch ( atype ) { case 'boolean' : case 'string' : case 'date' : case 'number' : return a . valueOf ( ) === b . valueOf ( ) ; case 'regexp' : return a . source === b . source && a . global === b . global && a . multiline === b . multiline && a . ignoreCase === b . ignoreCase ; case 'array' : return arrayEq ( a , b ) ; case 'object' : return objectEq ( a , b ) ; default : return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Performs a a deep array equality test . a - An Array object . b - An Array object . Returns true if the objects are equal and false otherwise . [CODESPLIT] function arrayEq ( a , b ) { var r ; if ( ! Array . isArray ( a ) || ! Array . isArray ( b ) ) { return false ; } if ( a . length !== b . length ) { return false ; } r = true ; detectRecursion ( a , b , function ( ) { var i , len ; for ( i = 0 , len = a . length ; i < len ; i ++ ) { if ( ! eq ( a [ i ] , b [ i ] ) ) { r = false ; break ; } } } ) ; return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Performs a a deep object equality test . a - Any object . b - Any object . Returns true if the objects are equal and false otherwise . [CODESPLIT] function objectEq ( a , b ) { var akeys = Object . keys ( a ) , bkeys = Object . keys ( b ) , r ; if ( akeys . length !== bkeys . length ) { return false ; } r = true ; detectRecursion ( a , b , function ( ) { var i , len , key ; for ( i = 0 , len = akeys . length ; i < len ; i ++ ) { key = akeys [ i ] ; if ( ! b . hasOwnProperty ( key ) ) { r = false ; break ; } if ( ! eq ( a [ key ] , b [ key ] ) ) { r = false ; break ; } } } ) ; return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Converts the given string to CamelCase . [CODESPLIT] function camelize ( s ) { return typeof s === 'string' ? s . replace ( / (?:[-_])(\\w) / g , function ( _ , c ) { return c ? c . toUpperCase ( ) : '' ; } ) : s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Converts the given string to under_score_case . [CODESPLIT] function underscore ( s ) { return typeof s === 'string' ? s . replace ( / ([a-z\\d])([A-Z]+) / g , '$1_$2' ) . replace ( / [-\\s]+ / g , '_' ) . toLowerCase ( ) : s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Capitalizes the first letter of the given string . [CODESPLIT] function capitalize ( s ) { return typeof s === 'string' && s . length ? s [ 0 ] . toUpperCase ( ) + s . slice ( 1 ) : s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Returns the Transis . Model subclass with the given name . name - A string representing the name of a Transis . Model subclass . raise - A boolean indicating whether an exception should be raised if the name can t be resolved ( default : true ) . Returns the resolved subclass constructor function or undefined if a class with the given name is not known . Throws Error if the raise argument is true and the name cannot not be resolved . [CODESPLIT] function resolve ( name ) { var raise = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : true ; var klass = typeof name === 'function' ? name : subclasses [ name ] ; if ( ! klass && raise ) { throw new Error ( \"Transis.Model.resolve: could not resolve subclass: `\" + name + \"`\" ) ; } return klass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Checks to make sure the given object is of the type specified in the given association descriptor . Returns nothing . Throws Error if the given object isn t of the type specified in the association descriptor . [CODESPLIT] function checkAssociatedType ( desc , o ) { var klass = resolve ( desc . klass ) ; if ( o && ! ( o instanceof klass ) ) { throw new Error ( desc . debugName + \": expected an object of type `\" + desc . klass + \"` but received `\" + o + \"` instead\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Wraps the given promise so that subsequent chained promises are called after the next flush cycle has been run . [CODESPLIT] function wrapPromise ( promise ) { return promise . then ( function ( value ) { return new Promise ( function ( resolve , reject ) { _object2 . default . delay ( function ( ) { resolve ( value ) ; } ) ; _object2 . default . _queueFlush ( ) ; } ) ; } , function ( reason ) { return new Promise ( function ( resolve , reject ) { _object2 . default . delay ( function ( ) { reject ( reason ) ; } ) ; _object2 . default . _queueFlush ( ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : The overridden _splice method used on hasMany arrays . This method syncs changes to the array to the inverse side of the association and maintains a list of changes made . [CODESPLIT] function hasManySplice ( i , n , added ) { var owner = this . __owner__ , desc = this . __desc__ , inverse = desc . inverse , name = desc . name , removed , changes , i ; added . forEach ( function ( o ) { return checkAssociatedType ( desc , o ) ; } ) ; removed = _array2 . default . prototype . _splice . call ( this , i , n , added ) ; if ( inverse && ! this . __handlingInverse__ ) { removed . forEach ( function ( model ) { model . _inverseRemoved ( inverse , owner ) ; } , this ) ; added . forEach ( function ( model ) { model . _inverseAdded ( inverse , owner ) ; } , this ) ; } if ( desc . owner && ! loads . length ) { changes = owner . ownChanges [ name ] = owner . ownChanges [ name ] || { added : [ ] , removed : [ ] } ; removed . forEach ( function ( m ) { if ( ( i = changes . added . indexOf ( m ) ) !== - 1 ) { changes . added . splice ( i , 1 ) ; } else if ( changes . removed . indexOf ( m ) === - 1 ) { changes . removed . push ( m ) ; } } ) ; added . forEach ( function ( m ) { if ( ( i = changes . removed . indexOf ( m ) ) !== - 1 ) { changes . removed . splice ( i , 1 ) ; } else if ( changes . added . indexOf ( m ) === - 1 ) { changes . added . push ( m ) ; } } ) ; if ( ! changes . added . length && ! changes . removed . length ) { owner . _clearChange ( name ) ; } else { owner . _setChange ( name , changes ) ; } } return removed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Called when a model is removed from the inverse side of a hasMany association in order to sync the change to the hasMany side . [CODESPLIT] function hasManyInverseRemove ( model ) { var i = this . indexOf ( model ) ; if ( i >= 0 ) { this . __handlingInverse__ = true ; this . splice ( i , 1 ) ; this . __handlingInverse__ = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Builds an array that manages a hasMany association . A hasMany array is a Transis . Array that overrides the _splice method in order to handle syncing the inverse side of the association . [CODESPLIT] function hasManyArray ( owner , desc ) { var a = _array2 . default . of ( ) ; a . proxy ( owner , desc . name ) ; a . __owner__ = owner ; a . __desc__ = desc ; a . _splice = hasManySplice ; a . _inverseAdd = hasManyInverseAdd ; a . _inverseRemove = hasManyInverseRemove ; return a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Provides the implementation of the query array s query method . [CODESPLIT] function queryArrayQuery ( ) { var _this = this ; var queryOpts = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : { } ; var opts = Object . assign ( { } , this . baseOpts , queryOpts ) ; if ( this . isPaged ) { opts . page = opts . page || 1 ; } if ( this . isBusy ) { if ( util . eq ( opts , this . currentOpts ) ) { return this ; } if ( ! this . __queued__ ) { this . __promise__ = this . __promise__ . then ( function ( ) { _this . query ( _this . __queued__ ) ; _this . __queued__ = undefined ; return _this . __promise__ ; } ) ; } this . __queued__ = opts ; } else { this . isBusy = true ; this . currentOpts = opts ; this . __promise__ = wrapPromise ( this . __modelClass__ . _callMapper ( 'query' , [ opts ] ) . then ( function ( result ) { var results = Array . isArray ( result ) ? result : result . results ; var meta = Array . isArray ( result ) ? { } : result . meta ; _this . isBusy = false ; _this . meta = meta ; _this . error = undefined ; if ( ! results ) { throw new Error ( _this + \"#query: mapper failed to return any results\" ) ; } if ( _this . isPaged && typeof meta . totalCount !== 'number' ) { throw new Error ( _this + \"#query: mapper failed to return total count for paged query\" ) ; } try { var models = _this . __modelClass__ . loadAll ( results ) ; if ( _this . isPaged ) { _this . length = meta . totalCount ; _this . splice . apply ( _this , [ ( opts . page - 1 ) * _this . baseOpts . pageSize , models . length ] . concat ( models ) ) ; } else { _this . replace ( models ) ; } } catch ( e ) { console . error ( e ) ; throw e ; } } , function ( e ) { _this . isBusy = false ; _this . error = e ; return Promise . reject ( e ) ; } ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Provides the implementation of the query array s at method . [CODESPLIT] function queryArrayAt ( i ) { var r = _array2 . default . prototype . at . apply ( this , arguments ) ; var pageSize = this . baseOpts && this . baseOpts . pageSize ; if ( arguments . length === 1 && ! r && pageSize ) { this . query ( { page : Math . floor ( i / pageSize ) + 1 } ) ; } return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Callback for a successful model deletion . Updates the model s state removes it from the identity map and removes removes it from any associations its currently participating in . [CODESPLIT] function mapperDeleteSuccess ( ) { var _this2 = this ; _id_map2 . default . delete ( this ) ; this . isBusy = false ; this . sourceState = DELETED ; this . _clearErrors ( ) ; var _loop = function _loop ( name ) { var desc = _this2 . associations [ name ] ; if ( ! desc . inverse ) { return \"continue\" ; } if ( desc . type === 'hasOne' ) { var m = void 0 ; if ( m = _this2 [ name ] ) { m . _inverseRemoved ( desc . inverse , _this2 ) ; } } else if ( desc . type === 'hasMany' ) { _this2 [ name ] . slice ( 0 ) . forEach ( function ( m ) { m . _inverseRemoved ( desc . inverse , _this2 ) ; } ) ; } } ; for ( var name in this . associations ) { var _ret = _loop ( name ) ; if ( _ret === \"continue\" ) continue ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "load and set each association [CODESPLIT] function _loop2 ( _name ) { var klass = resolve ( associations [ _name ] . klass ) ; var data = associated [ _name ] ; // clear association if ( ! data ) { model [ _name ] = null ; return \"continue\" ; } if ( associations [ _name ] . type === 'hasOne' ) { var other = ( typeof data === \"undefined\" ? \"undefined\" : _typeof ( data ) ) === 'object' ? klass . load ( data ) : klass . local ( data ) ; model [ _name ] = other ; } else if ( associations [ _name ] . type === 'hasMany' ) { var others = [ ] ; data . forEach ( function ( o ) { others . push ( ( typeof o === \"undefined\" ? \"undefined\" : _typeof ( o ) ) === 'object' ? klass . load ( o ) : klass . local ( o ) ) ; } ) ; model [ _name ] = others ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Processes recorded property changes by traversing the property dependency graph and forwarding changes to proxy objects . [CODESPLIT] function propagateChanges ( ) { var seen = { } ; var head = void 0 ; for ( var id in changedObjects ) { var _changedObjects$id = changedObjects [ id ] , object = _changedObjects$id . object , props = _changedObjects$id . props ; for ( var k in props ) { head = { object : object , name : k , next : head } ; seen [ id + k ] = true ; } } while ( head ) { var _head = head , name = _head . name , object = _head . object , _head$object = _head . object , _objectId = _head$object . objectId , __deps__ = _head$object . __deps__ , __proxies__ = _head$object . __proxies__ ; var deps = __deps__ && __deps__ [ name ] ; head = head . next ; registerChange ( object , name ) ; if ( object . __cache__ ) { var val = object . __cache__ [ name ] ; if ( val && typeof val . unproxy === 'function' ) { val . unproxy ( object , name ) ; } delete object . __cache__ [ name ] ; } if ( deps ) { for ( var i = 0 , n = deps . length ; i < n ; i ++ ) { var seenKey = _objectId + deps [ i ] ; if ( ! seen [ seenKey ] ) { head = { object : object , name : deps [ i ] , next : head } ; seen [ seenKey ] = true ; } } } if ( __proxies__ && name . indexOf ( '.' ) === - 1 ) { for ( var _k in __proxies__ ) { var proxy = __proxies__ [ _k ] ; var proxyObject = proxy . object ; var proxyName = proxy . name + '.' + name ; var proxySeenKey = proxyObject . objectId + proxyName ; if ( ! seen [ proxySeenKey ] ) { head = { object : proxyObject , name : proxyName , next : head } ; seen [ proxySeenKey ] = true ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Flushes the current change queue . This notifies observers of the changed props as well as observers of any props that depend on the changed props . Observers are only invoked once per flush regardless of how many of their dependent props have changed . Additionaly cached values are cleared where appropriate . [CODESPLIT] function flush ( ) { var f = void 0 ; while ( f = delayPreFlushCallbacks . shift ( ) ) { f ( ) ; } propagateChanges ( ) ; var curChangedObjects = changedObjects ; changedObjects = { } ; flushTimer = null ; for ( var id in curChangedObjects ) { var _curChangedObjects$id = curChangedObjects [ id ] , object = _curChangedObjects$id . object , props = _curChangedObjects$id . props ; var star = false ; for ( var k in props ) { if ( k . indexOf ( '.' ) === - 1 ) { star = true ; } object . notify ( // strip '@' suffix if present k . length > 1 && k . endsWith ( '@' ) && ! k . endsWith ( '.@' ) ? k . slice ( 0 , k . length - 1 ) : k ) ; } if ( star ) { object . notify ( '*' ) ; } } while ( f = delayPostFlushCallbacks . shift ( ) ) { f ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Defines a property on the given object . See the docs for Transis . prop . Returns nothing . [CODESPLIT] function defineProp ( object , name , opts = { } ) { validateOptions ( opts ) ; var descriptor = Object . assign ( { name : name , get : null , set : null , default : undefined , on : [ ] , cache : false , pure : ! ! ( opts . get && opts . on && ! opts . set ) , } , opts , { readonly : opts . get && ! opts . set } ) ; if ( ! object . hasOwnProperty ( '__props__' ) ) { object . __props__ = Object . create ( object . __props__ || null ) ; } object . __props__ [ name ] = descriptor ; if ( ! object . hasOwnProperty ( '__deps__' ) ) { object . __deps__ = Object . create ( object . __deps__ || null ) ; } descriptor . on . forEach ( function ( prop ) { ( object . __deps__ [ prop ] = object . __deps__ [ prop ] || [ ] ) . push ( name ) ; if ( prop . indexOf ( '.' ) !== - 1 ) { let segments = prop . split ( '.' ) , first = segments [ 0 ] , last = segments [ 1 ] ; if ( segments . length > 2 ) { throw new Error ( ` \\` ${ prop } \\` ` ) ; } ( object . __deps__ [ first ] = object . __deps__ [ first ] || [ ] ) . push ( name ) ; ( object . __deps__ [ ` ${ first } ` ] = object . __deps__ [ ` ${ first } ` ] || [ ] ) . push ( name ) ; ( object . __deps__ [ ` ${ first } ${ last } ` ] = object . __deps__ [ ` ${ first } ${ last } ` ] || [ ] ) . push ( name ) ; } else { ( object . __deps__ [ ` ${ prop } ` ] = object . __deps__ [ ` ${ prop } ` ] || [ ] ) . push ( name ) ; } } ) ; Object . defineProperty ( object , name , { get : function ( ) { return this . _getProp ( name ) ; } , set : descriptor . readonly ? undefined : function ( value ) { this . _setProp ( name , value ) ; } , configurable : false , enumerable : true } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Returns the Transis . Model subclass with the given name . name - A string representing the name of a Transis . Model subclass . raise - A boolean indicating whether an exception should be raised if the name can t be resolved ( default : true ) . Returns the resolved subclass constructor function or undefined if a class with the given name is not known . Throws Error if the raise argument is true and the name cannot not be resolved . [CODESPLIT] function resolve ( name , raise = true ) { var klass = ( typeof name === 'function' ) ? name : subclasses [ name ] ; if ( ! klass && raise ) { throw new Error ( ` \\` ${ name } \\` ` ) ; } return klass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Sets the given object on a hasOne property . desc - An association descriptor . v - The value to set . sync - Set to true to notify the inverse side of the association so that it can update itself . Returns nothing . Throws Error if the given object isn t of the type specified in the association descriptor . [CODESPLIT] function hasOneSet ( desc , v , sync ) { var name = desc . name , k = ` ${ name } ` , prev = this [ k ] , inv = desc . inverse ; checkAssociatedType ( desc , v ) ; this [ k ] = v ; if ( sync && inv && prev ) { prev . _inverseRemoved ( inv , this ) ; } if ( sync && inv && v ) { v . _inverseAdded ( inv , this ) ; } if ( prev ) { prev . unproxy ( this , name ) ; } if ( v ) { v . proxy ( this , name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal : Callback for a successful model deletion . Updates the model s state removes it from the identity map and removes removes it from any associations its currently participating in . [CODESPLIT] function mapperDeleteSuccess ( ) { IdMap . delete ( this ) ; this . isBusy = false ; this . sourceState = DELETED ; this . _clearErrors ( ) ; for ( let name in this . associations ) { let desc = this . associations [ name ] ; if ( ! desc . inverse ) { continue ; } if ( desc . type === 'hasOne' ) { let m ; if ( m = this [ name ] ) { m . _inverseRemoved ( desc . inverse , this ) ; } } else if ( desc . type === 'hasMany' ) { this [ name ] . slice ( 0 ) . forEach ( ( m ) => { m . _inverseRemoved ( desc . inverse , this ) ; } ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a fake File from fixture path to be used by .. / __mocks__ / readFile . js [CODESPLIT] function file ( relpath ) { return { name : basename ( relpath ) , path : ` ${ relpath } ` , size : 123 , type : vcard . FILE_TYPES [ 0 ] } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the default error handler [CODESPLIT] function handleErrors ( errors , data ) { const message = errors [ 0 ] . message ; const error = new Error ( ` ${ message } ` ) ; error . rawError = errors ; error . rawData = data ; throw error ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Zips a list of files or directories [CODESPLIT] function zip ( zipFile , srcList , dstPath ) { if ( ! dstPath ) { dstPath = false ; } const output = fs . createWriteStream ( zipFile ) ; const archive = archiver ( 'zip' , { zlib : { level : 9 } // Sets the compression level. } ) ; return new Promise ( ( resolve , reject ) => { output . on ( 'close' , function ( ) { return resolve ( ) ; } ) ; archive . on ( 'warning' , function ( err ) { if ( err . code === 'ENOENT' ) { console . log ( err ) ; } else { return reject ( err ) ; } } ) ; archive . on ( 'error' , function ( err ) { return reject ( err ) ; } ) ; archive . pipe ( output ) ; srcList . forEach ( ( src ) => { const stat = fs . lstatSync ( src ) ; if ( stat . isFile ( ) ) { archive . file ( src ) ; } else if ( stat . isDirectory ( ) || stat . isSymbolicLink ( ) ) { archive . directory ( src , dstPath ) ; } else { return reject ( new Error ( 'Invalid path' ) ) ; } } ) ; archive . finalize ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes shell commands synchronously and logs the stdout to console . [CODESPLIT] function exec ( cmd , verbose ) { verbose = verbose === false ? verbose : true ; const stdout = execSync ( cmd ) ; if ( verbose ) { console . log ( stdout . toString ( ) ) ; } return stdout ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates region of an AWS configuration and point to the correct of profile on ~ / . aws / credentials file if necessary [CODESPLIT] function configureAws ( region , profile , role ) { if ( region ) { AWS . config . update ( { region } ) ; } if ( profile ) { AWS . config . credentials = new AWS . SharedIniFileCredentials ( { profile } ) ; } if ( role ) { AWS . config . credentials = new AWS . TemporaryCredentials ( { RoleArn : role } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the input is a file if it is a file it reads it and return the content otherwise just pass the input as an output [CODESPLIT] function fileToString ( file ) { try { const stat = fs . lstatSync ( file ) ; if ( stat . isFile ( ) ) { const content = fs . readFileSync ( file , 'utf8' ) ; return content . toString ( ) ; } } catch ( e ) { if ( ! e . message . includes ( 'ENOENT' ) && ! e . message . includes ( 'name too long, lstat' ) ) { throw e ; } } return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges two yaml files . The merge is done using lodash . merge and it happens recursively . Meaning that values of file2 will replace values of file 1 if they have the same key . [CODESPLIT] function mergeYamls ( file1 , file2 ) { const obj1 = yaml . safeLoad ( fileToString ( file1 ) , { schema : yamlfiles . YAML_FILES_SCHEMA } ) ; const obj2 = yaml . safeLoad ( fileToString ( file2 ) , { schema : yamlfiles . YAML_FILES_SCHEMA } ) ; return yaml . safeDump ( merge ( { } , obj1 , obj2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to load a Kes override class . [CODESPLIT] function loadKesOverride ( kesFolder , kesClass = 'kes.js' ) { let kesOverridePath = path . resolve ( kesFolder , kesClass ) ; let KesOverride ; try { KesOverride = require ( kesOverridePath ) ; } catch ( e ) { // If the Kes override file exists, then the error occured when // trying to parse the file, so re-throw and prevent Kes from // going further. const fileExists = fs . existsSync ( kesOverridePath ) ; if ( fileExists ) { throw e ; } console . log ( ` ${ kesOverridePath } ` ) ; } return KesOverride ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Based on the information passed from the CLI by the commander module this function determines whether to use the default Kes class or use the override class provided by the user [CODESPLIT] function determineKesClass ( options , Kes ) { let KesOverride ; // If there is a kes class specified, use that const kesClass = get ( options , 'kesClass' ) ; if ( kesClass ) { KesOverride = loadKesOverride ( process . cwd ( ) , kesClass ) ; } else { let kesFolder ; // Check if there is kes.js in the kes folder if ( options . kesFolder ) { kesFolder = options . kesFolder ; } else { kesFolder = path . join ( process . cwd ( ) , '.kes' ) ; } KesOverride = loadKesOverride ( kesFolder ) ; // If the first Kes override didn't load, check if there is // a kes.js in the template folder. if ( ! KesOverride ) { const template = get ( options , 'template' , '/path/to/nowhere' ) ; kesFolder = path . join ( process . cwd ( ) , template ) ; KesOverride = loadKesOverride ( kesFolder ) ; } } return KesOverride || Kes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In case of error logs the error and exit with error 1 [CODESPLIT] function failure ( e ) { if ( e . message ) { console . log ( e . message ) ; } else { console . log ( e ) ; } process . exit ( 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Discover and returns the system bucket used for deployment [CODESPLIT] function getSystemBucket ( config ) { let bucket = get ( config , 'buckets.internal' ) ; if ( bucket && typeof bucket === 'string' ) { return bucket ; } bucket = get ( config , 'system_bucket' ) ; if ( bucket && typeof bucket === 'string' ) { return bucket ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds templates nested in the main template using the specified config and cf file paths [CODESPLIT] function buildNestedCfs ( config , KesClass , options ) { const limit = pLimit ( 1 ) ; if ( config . nested_templates ) { const nested = config . nested_templates ; console . log ( 'Nested templates are found!' ) ; const ps = Object . keys ( nested ) . map ( ( name ) => limit ( ( ) => { console . log ( ` ${ name } ` ) ; const newOptions = Object . assign ( { } , options ) ; newOptions . cfFile = nested [ name ] . cfFile ; newOptions . configFile = nested [ name ] . configFile ; // no templates are used in nested stacks delete newOptions . template ; delete newOptions . deployment ; // use the parent stackname newOptions . stack = config . stack ; newOptions . parent = config ; const nestedConfig = new Config ( newOptions ) ; // get the bucket name from the parent if ( ! nestedConfig . bucket ) { nestedConfig . bucket = utils . getSystemBucket ( config ) ; } // add nested deployment name nestedConfig . nested_cf_name = name ; const kes = new KesClass ( nestedConfig ) ; return kes . uploadCF ( ) . then ( ( uri ) => { config . nested_templates [ name ] . url = uri ; } ) ; } ) ) ; return Promise . all ( ps ) . then ( ( ) => config ) . catch ( utils . failure ) ; } return Promise . resolve ( config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds uploads and deploy a Cloudformation based on options passed from the commander library [CODESPLIT] function buildCf ( options , cmd ) { const KesClass = utils . determineKesClass ( options , Kes ) ; let parentConfig ; try { parentConfig = new Config ( options ) ; } catch ( e ) { return Promise . reject ( e ) ; } return buildNestedCfs ( parentConfig , KesClass , options ) . then ( ( config ) => { const kes = new KesClass ( config ) ; switch ( cmd ) { case 'create' : deprecate ( '\"kes cf create\" command is deprecated. Use \"kes cf deploy\" instead' ) ; return kes . createStack ( ) ; case 'update' : deprecate ( '\"kes cf update\" command is deprecated. Use \"kes cf deploy\" instead' ) ; return kes . updateStack ( ) ; case 'upsert' : deprecate ( '\"kes cf upsert\" command is deprecated. Use \"kes cf deploy\" instead' ) ; return kes . upsertStack ( ) ; case 'deploy' : return kes . deployStack ( ) ; case 'validate' : return kes . validateTemplate ( ) ; case 'compile' : return kes . compileCF ( ) ; case 'delete' : return kes . deleteStack ( ) ; default : console . log ( 'Wrong choice. Accepted arguments: [create|update|upsert|deploy|validate|compile]' ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds and uploads a lambda function based on the options passed by the commander [CODESPLIT] function buildLambda ( options , cmd ) { if ( cmd ) { const KesClass = utils . determineKesClass ( options , Kes ) ; const config = new Config ( options ) ; const kes = new KesClass ( config ) ; kes . updateSingleLambda ( cmd ) . then ( r => utils . success ( r ) ) . catch ( e => utils . failure ( e ) ) ; } else { utils . failure ( new Error ( 'Lambda name is missing' ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send response to the pre - signed S3 URL [CODESPLIT] function sendResponse ( event , context , responseStatus , responseData ) { const responseBody = JSON . stringify ( { Status : responseStatus , Reason : 'See the details in CloudWatch Log Stream: ' + context . logStreamName , PhysicalResourceId : context . logStreamName , StackId : event . StackId , RequestId : event . RequestId , LogicalResourceId : event . LogicalResourceId , Data : responseData } ) ; console . log ( 'RESPONSE BODY:\\n' , responseBody ) ; const https = require ( 'https' ) ; const url = require ( 'url' ) ; const parsedUrl = url . parse ( event . ResponseURL ) ; const options = { hostname : parsedUrl . hostname , port : 443 , path : parsedUrl . path , method : 'PUT' , headers : { 'content-type' : '' , 'content-length' : responseBody . length } } ; console . log ( 'SENDING RESPONSE...\\n' ) ; const request = https . request ( options , function ( response ) { console . log ( 'STATUS: ' + response . statusCode ) ; console . log ( 'HEADERS: ' + JSON . stringify ( response . headers ) ) ; // Tell AWS Lambda that the function execution is done context . done ( ) ; } ) ; request . on ( 'error' , function ( error ) { console . log ( 'sendResponse Error:' + error ) ; // Tell AWS Lambda that the function execution is done context . done ( ) ; } ) ; // write data to request body request . write ( responseBody ) ; request . end ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return options converted to a string [CODESPLIT] function optionsToString ( options ) { return Object . keys ( options ) . map ( function processOption ( key ) { return key + \"=\" + options [ key ] ; } ) . join ( \",\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert centered : true key into concrete left and top arguments Both can be overwritten [CODESPLIT] function optionsResolveCentered ( options ) { var result = options ; var width = window . outerWidth - options . width ; var height = window . outerHeight - options . height ; if ( options . centered ) { result . left = options . left || Math . round ( window . screenX + width / 2 ) ; result . top = options . top || Math . round ( window . screenY + height / 2.5 ) ; delete result . centered ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Polyfill Object . assign [CODESPLIT] function assign ( target ) { var sources = Array . prototype . slice . call ( arguments , 1 ) ; function assignArgument ( previous , source ) { Object . keys ( source ) . forEach ( function assignItem ( key ) { previous [ key ] = source [ key ] ; // eslint-disable-line no-param-reassign } ) ; return previous ; } return sources . reduce ( assignArgument , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a form element add hidden inputs for all the post data and post it into a newly opened popup [CODESPLIT] function openPopupWithPost ( url , postData , name , options ) { var form = document . createElement ( \"form\" ) ; var win ; form . setAttribute ( \"method\" , \"post\" ) ; form . setAttribute ( \"action\" , url ) ; form . setAttribute ( \"target\" , name ) ; Object . keys ( postData ) . forEach ( function addFormItem ( key ) { var input = document . createElement ( \"input\" ) ; input . type = \"hidden\" ; input . name = key ; input . value = postData [ key ] ; form . appendChild ( input ) ; } ) ; document . body . appendChild ( form ) ; win = window . open ( \"/\" , name , options ) ; win . document . write ( \"Loading...\" ) ; form . submit ( ) ; document . body . removeChild ( form ) ; return win ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a popup using the first argument . Wait for it to close . Returns the window object [CODESPLIT] function popupExecute ( execute , url , name , options , callback ) { var popupName = name || defaultPopupName ( ) ; var popupOptions = optionsResolveCentered ( assign ( { } , defaultOptions , options ) ) ; var popupCallback = callback || function noop ( ) { } ; var optionsString = optionsToString ( popupOptions ) ; var win = execute ( url , popupName , optionsString ) ; var isMessageSent = false ; var interval ; function popupCallbackOnce ( err , data ) { if ( ! isMessageSent ) { isMessageSent = true ; popupCallback ( err , data ) ; } } function onMessage ( message ) { var data = message ? message . data : undefined ; if ( data ) { popupCallbackOnce ( undefined , data ) ; window . removeEventListener ( \"message\" , onMessage ) ; } } window . addEventListener ( \"message\" , onMessage , false ) ; if ( win ) { interval = setInterval ( function closePopupCallback ( ) { if ( win == null || win . closed ) { setTimeout ( function delayWindowClosing ( ) { clearInterval ( interval ) ; popupCallbackOnce ( new Error ( \"Popup closed\" ) ) ; } , 500 ) ; } } , 100 ) ; } else { popupCallbackOnce ( new Error ( \"Popup blocked\" ) ) ; } return win ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a popup using the first argument . Wait for it to close and call the callback . Set the options string using the options object Returns the window object [CODESPLIT] function popup ( url , name , options , callback ) { return popupExecute ( window . open , url , name , options , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a popup using the first argument . Post the data into the open popup . Wait for it to close and call the callback . Set the options string using the options object Returns the window object [CODESPLIT] function popupWithPost ( url , postData , name , options , callback ) { function openWithPostData ( popupUrl , popupName , optionsString ) { return openPopupWithPost ( popupUrl , postData , popupName , optionsString ) ; } return popupExecute ( openWithPostData , url , name , options , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selector directive [CODESPLIT] function Selector ( filter , timeout , window , http , q ) { this . restrict = 'EAC' ; this . replace = true ; this . transclude = true ; this . scope = { name : '@?' , value : '=model' , disabled : '=?disable' , disableSearch : '=?' , required : '=?require' , multiple : '=?multi' , placeholder : '@?' , valueAttr : '@' , labelAttr : '@?' , groupAttr : '@?' , options : '=?' , debounce : '=?' , create : '&?' , limit : '=?' , rtl : '=?' , api : '=?' , change : '&?' , remote : '&?' , remoteParam : '@?' , remoteValidation : '&?' , remoteValidationParam : '@?' , removeButton : '=?' , softDelete : '=?' , closeAfterSelection : '=?' , viewItemTemplate : '=?' , dropdownItemTemplate : '=?' , dropdownCreateTemplate : '=?' , dropdownGroupTemplate : '=?' } ; this . templateUrl = 'selector/selector.html' ; $filter = filter ; $timeout = timeout ; $window = window ; $http = http ; $q = q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns parser - supported syntax of given editor ( like html css etc . ) . Returns null if editor’s syntax is unsupported [CODESPLIT] function getSyntax ( editor ) { const mode = editor . getMode ( ) ; if ( mode . name === 'htmlmixed' ) { return 'html' ; } return mode . name === 'xml' ? mode . configuration : mode . name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns content range that should be wrapped [CODESPLIT] function getWrappingContentRange ( editor ) { if ( editor . somethingSelected ( ) ) { const sel = editor . listSelections ( ) . filter ( sel => sel . anchor !== sel . head ) [ 0 ] ; if ( sel ) { return comparePos ( sel . anchor , sel . head ) < 0 ? { from : sel . anchor , to : sel . head } : { from : sel . head , to : sel . anchor } ; } } // Nothing selected, find parent HTML node and return range for its content return getTagRangeForPos ( editor , editor . getCursor ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns either inner or outer tag range ( depending on pos location ) for given position [CODESPLIT] function getTagRangeForPos ( editor , pos ) { const model = editor . getEmmetDocumentModel ( ) ; const tag = model && model . nodeForPoint ( pos ) ; if ( ! tag ) { return null ; } // Depending on given position, return either outer or inner tag range if ( inRange ( tag . open , pos ) || inRange ( tag . close , pos ) ) { // Outer range return rangeFromNode ( tag ) ; } // Inner range const from = tag . open . end ; const to = tag . close ? tag . close . start : tag . open . end ; return narrowToNonSpace ( editor , from , to ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if given range is a single caret between tags [CODESPLIT] function betweenTags ( editor , range ) { if ( equalCursorPos ( range . anchor , range . head ) ) { const cursor = range . anchor ; const mode = editor . getModeAt ( cursor ) ; if ( mode . name === 'xml' ) { const left = editor . getTokenAt ( cursor ) ; const right = editor . getTokenAt ( Object . assign ( { } , cursor , { ch : cursor . ch + 1 } ) ) ; return left . type === 'tag bracket' && left . string === '>' && right . type === 'tag bracket' && right . string === '</' ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if abbreviation can be extracted from given position [CODESPLIT] function canExtract ( editor , pos , config ) { const tokenType = editor . getTokenTypeAt ( pos ) ; if ( config . type === 'stylesheet' ) { return tokenType !== 'comment' && tokenType !== 'string' ; } if ( config . syntax === 'html' ) { return tokenType === null ; } if ( config . syntax === 'slim' || config . syntax === 'pug' ) { return tokenType === null || tokenType === 'tag' || ( tokenType && / attribute / . test ( tokenType ) ) ; } if ( config . syntax === 'haml' ) { return tokenType === null || tokenType === 'attribute' ; } if ( config . syntax === 'jsx' ) { // JSX a bit tricky, delegate it to caller return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns completions for markup syntaxes ( HTML Slim Pug etc . ) [CODESPLIT] function getMarkupCompletions ( editor , pos , config ) { const line = editor . getLine ( pos . line ) . slice ( 0 , pos . ch ) ; const prefix = extractPrefix ( line , / [\\w:\\-$@] / ) ; // Make sure that current position precedes element name (e.g. not attribute, // class, id etc.) if ( prefix ) { const prefixRange = { from : { line : pos . line , ch : pos . ch - prefix . length } , to : pos } ; return getSnippetCompletions ( editor , pos , config ) . filter ( completion => completion . key !== prefix && completion . key . indexOf ( prefix ) === 0 ) . map ( completion => new EmmetCompletion ( 'snippet' , editor , prefixRange , completion . key , completion . preview , completion . snippet ) ) ; } return [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns completions for stylesheet syntaxes [CODESPLIT] function getStylesheetCompletions ( editor , pos , config ) { const line = editor . getLine ( pos . line ) . slice ( 0 , pos . ch ) ; const prefix = extractPrefix ( line , / [\\w-@$] / ) ; if ( prefix ) { // Make sure that current position precedes element name (e.g. not attribute, // class, id etc.) const prefixRange = { from : { line : pos . line , ch : pos . ch - prefix . length } , to : pos } ; if ( config . options && config . options . property ) { const lowerProp = config . options . property . toLowerCase ( ) ; // Find matching CSS property snippet for keyword completions const completion = getSnippetCompletions ( editor , pos , config ) . find ( item => item . property && item . property === lowerProp ) ; if ( completion && completion . keywords . length ) { return completion . keywords . map ( kw => { return kw . key . indexOf ( prefix ) === 0 && new EmmetCompletion ( 'value' , editor , prefixRange , kw . key , kw . preview , kw . snippet ) ; } ) . filter ( Boolean ) ; } } else { return getSnippetCompletions ( editor , pos , config ) . filter ( completion => completion . key !== prefix && completion . key . indexOf ( prefix ) === 0 ) . map ( completion => new EmmetCompletion ( 'snippet' , editor , prefixRange , completion . key , completion . preview , completion . snippet ) ) ; } } return [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all possible snippets completions for given editor context . Completions are cached in editor for for re - use [CODESPLIT] function getSnippetCompletions ( editor , pos , config ) { const { type , syntax } = config ; if ( ! editor . state . emmetCompletions ) { editor . state . emmetCompletions = { } ; } const cache = editor . state . emmetCompletions ; if ( ! ( syntax in cache ) ) { const registry = createSnippetsRegistry ( type , syntax , config . snippets ) ; cache [ syntax ] = type === 'stylesheet' ? getStylesheetSnippets ( registry , config ) : getMarkupSnippets ( registry , config ) ; } return cache [ syntax ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns stylesheet snippets list [CODESPLIT] function getStylesheetSnippets ( registry ) { return convertToCSSSnippets ( registry ) . map ( snippet => { let preview = snippet . property ; const keywords = snippet . keywords ( ) ; if ( keywords . length ) { preview += ` ${ removeFields ( keywords . join ( ' | ' ) ) } ` ; } else if ( snippet . value ) { preview += ` ${ removeFields ( snippet . value ) } ` ; } return { key : snippet . key , value : snippet . value , snippet : snippet . key , property : snippet . property , keywords : keywords . map ( kw => { const m = kw . match ( / ^[\\w-]+ / ) ; return m && { key : m [ 0 ] , preview : removeFields ( kw ) , snippet : kw } ; } ) . filter ( Boolean ) , preview } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns markup snippets list [CODESPLIT] function getMarkupSnippets ( registry , config ) { return registry . all ( { type : 'string' } ) . map ( snippet => ( { key : snippet . key , value : snippet . value , preview : removeFields ( expand ( snippet . value , config ) ) , snippet : snippet . key } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts prefix from the end of given string that matches match regexp [CODESPLIT] function extractPrefix ( str , match ) { let offset = str . length ; while ( offset > 0 ) { if ( ! match . test ( str [ offset - 1 ] ) ) { break ; } offset -- ; } return str . slice ( offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that given editor Emmet abbreviation marker contains valid Emmet abbreviation and updates abbreviation model if required [CODESPLIT] function isValidMarker ( editor , marker ) { const range = marker . find ( ) ; // No newlines inside abbreviation if ( range . from . line !== range . to . line ) { return false ; } // Make sure marker contains valid abbreviation let text = editor . getRange ( range . from , range . to ) ; if ( ! text || / ^\\s|\\s$ / g . test ( text ) ) { return false ; } if ( marker . model && marker . model . config . syntax === 'jsx' && text [ 0 ] === '<' ) { text = text . slice ( 1 ) ; } if ( ! marker . model || marker . model . abbreviation !== text ) { // marker contents was updated, re-parse abbreviation try { marker . model = new Abbreviation ( text , range , marker . model . config ) ; if ( ! marker . model . valid ( editor , true ) ) { marker . model = null ; } } catch ( err ) { console . warn ( err ) ; marker . model = null ; } } return Boolean ( marker . model && marker . model . snippet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Toggle boolean properties or properties that have a values array in its definition . [CODESPLIT] function ( property ) { var def = this . _definition [ property ] ; if ( def . type === 'boolean' ) { // if it's a bool, just flip it this [ property ] = ! this [ property ] ; } else if ( def && def . values ) { // If it's a property with an array of values // skip to the next one looping back if at end. this [ property ] = arrayNext ( def . values , this [ property ] ) ; } else { throw new TypeError ( 'Can only toggle properties that are type `boolean` or have `values` array.' ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the model has changed since the last change event . If you specify an attribute name determine if that attribute has changed . [CODESPLIT] function ( attr ) { if ( attr == null ) return ! ! Object . keys ( this . _changed ) . length ; if ( has ( this . _derived , attr ) ) { return this . _derived [ attr ] . depList . some ( function ( dep ) { return this . hasChanged ( dep ) ; } , this ) ; } return has ( this . _changed , attr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a bound handler for doing event bubbling while adding a name to the change string . [CODESPLIT] function ( propertyName ) { if ( ! this . _eventBubblingHandlerCache [ propertyName ] ) { this . _eventBubblingHandlerCache [ propertyName ] = function ( name , model , newValue ) { if ( changeRE . test ( name ) ) { this . trigger ( 'change:' + propertyName + '.' + name . split ( ':' ) [ 1 ] , model , newValue ) ; } else if ( name === 'change' ) { this . trigger ( 'change' , this ) ; } } . bind ( this ) ; } return this . _eventBubblingHandlerCache [ propertyName ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helper for creating / storing property definitions and creating appropriate getters / setters [CODESPLIT] function createPropertyDefinition ( object , name , desc , isSession ) { var def = object . _definition [ name ] = { } ; var type , descArray ; if ( isString ( desc ) ) { // grab our type if all we've got is a string type = object . _ensureValidType ( desc ) ; if ( type ) def . type = type ; } else { //Transform array of ['type', required, default] to object form if ( Array . isArray ( desc ) ) { descArray = desc ; desc = { type : descArray [ 0 ] , required : descArray [ 1 ] , 'default' : descArray [ 2 ] } ; } type = object . _ensureValidType ( desc . type ) ; if ( type ) def . type = type ; if ( desc . required ) def . required = true ; if ( desc [ 'default' ] && typeof desc [ 'default' ] === 'object' ) { throw new TypeError ( 'The default value for ' + name + ' cannot be an object/array, must be a value or a function which returns a value/object/array' ) ; } def [ 'default' ] = desc [ 'default' ] ; def . allowNull = desc . allowNull ? desc . allowNull : false ; if ( desc . setOnce ) def . setOnce = true ; if ( def . required && def [ 'default' ] === undefined && ! def . setOnce ) def [ 'default' ] = object . _getDefaultForType ( type ) ; def . test = desc . test ; def . values = desc . values ; } if ( isSession ) def . session = true ; if ( ! type ) { type = isString ( desc ) ? desc : desc . type ; // TODO: start throwing a TypeError in future major versions instead of warning console . warn ( 'Invalid data type of `' + type + '` for `' + name + '` property. Use one of the default types or define your own' ) ; } // define a getter/setter on the prototype // but they get/set on the instance Object . defineProperty ( object , name , { set : function ( val ) { this . set ( name , val ) ; } , get : function ( ) { if ( ! this . _values ) { throw Error ( 'You may be trying to `extend` a state object with \"' + name + '\" which has been defined in `props` on the object being extended' ) ; } var value = this . _values [ name ] ; var typeDef = this . _dataTypes [ def . type ] ; if ( typeof value !== 'undefined' ) { if ( typeDef && typeDef . get ) { value = typeDef . get ( value ) ; } return value ; } var defaultValue = result ( def , 'default' ) ; this . _values [ name ] = defaultValue ; // If we've set a defaultValue, fire a change handler effectively marking // its change from undefined to the default value. if ( typeof defaultValue !== 'undefined' ) { var onChange = this . _getOnChangeForType ( def . type ) ; onChange ( defaultValue , value , name ) ; } return defaultValue ; } } ) ; return def ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helper for creating derived property definitions [CODESPLIT] function createDerivedProperty ( modelProto , name , definition ) { var def = modelProto . _derived [ name ] = { fn : isFunction ( definition ) ? definition : definition . fn , cache : ( definition . cache !== false ) , depList : definition . deps || [ ] } ; // add to our shared dependency list def . depList . forEach ( function ( dep ) { modelProto . _deps [ dep ] = union ( modelProto . _deps [ dep ] || [ ] , [ name ] ) ; } ) ; // defined a top-level getter for derived names Object . defineProperty ( modelProto , name , { get : function ( ) { return this . _getDerivedProperty ( name ) ; } , set : function ( ) { throw new TypeError ( \"`\" + name + \"` is a derived property, it can't be set directly.\" ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "proceed [CODESPLIT] function queue ( ) { while ( current < config . concurLimit && files . length > 0 ) { var file = files . shift ( ) allFiles . push ( Promise . resolve ( file ) . then ( function ( file ) { return clean . processOneClean ( file ) . then ( function ( filePath ) { if ( typeof filePath === 'string' ) { filesCleaned . push ( filePath ) } proceed ( ) } ) . catch ( function ( err ) { proceed ( ) functions . logError ( err ) throw err } ) } ) ) current ++ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------- Functions ----------- [CODESPLIT] function reWriter ( goCrazy , filePath , data ) { /*\n    Keep on writing a file until chokidar notices us.\n    @param  {Boolean}  goCrazy   Start or continue to write a file every 500 ms until someone stops us!\n    @param  {String}   filePath  String file path like '/source/file.txt'. Not used if goCrazy is false.\n    @param  {String}   [data]    Optional data to write to the file. Defaults to 'changed data'.\n    */ if ( goCrazy ) { data = data || 'changed data' fs . writeFileSync ( filePath , data ) reWriteTimer = setTimeout ( function ( ) { reWriter ( goCrazy , filePath , data ) } , 500 ) } else { clearTimeout ( reWriteTimer ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Normalize source maps . [CODESPLIT] function missingSource ( ) { let preferredPath = path . basename ( config . path . source ) let source = obj . source source = source . replace ( config . path . source , preferredPath ) source = source . replace ( config . path . dest , preferredPath ) source = source . replace ( path . basename ( config . path . dest ) , preferredPath ) if ( source . toLowerCase ( ) . endsWith ( '.map' ) ) { source = functions . removeExt ( source ) } if ( shared . slash !== '/' ) { // we are on windows source = source . replace ( / \\\\ / g , '/' ) } return [ source ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "proceed [CODESPLIT] function queue ( ) { while ( current < config . concurLimit && files . length > 0 ) { var file = files . shift ( ) allFiles . push ( Promise . resolve ( file ) . then ( function ( file ) { return build . processOneBuild ( file ) . then ( function ( filePath ) { if ( typeof filePath === 'string' ) { filesBuilt . push ( filePath ) } proceed ( ) } ) . catch ( function ( err ) { proceed ( ) functions . logError ( err ) throw err } ) } ) ) current ++ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Image class . [CODESPLIT] function Image ( image , address ) { var at = this . attributes = image . attribs ; this . name = path . basename ( at . src , path . extname ( at . src ) ) ; this . saveTo = path . dirname ( require . main . filename ) + \"/\" ; this . extension = path . extname ( at . src ) ; this . address = url . resolve ( address , at . src ) ; this . fromAddress = address ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shipit task . [CODESPLIT] function shipitTask ( grunt ) { 'use strict' ; // Init shipit grunt . shipit = new Shipit ( ) ; grunt . registerTask ( 'shipit' , 'Shipit Task' , function ( env ) { var config = grunt . config . get ( 'shipit' ) ; grunt . shipit . environment = env ; // Support legacy options. if ( ! config . default && config . options ) config . default = config . options ; grunt . shipit . initConfig ( config ) . initialize ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Only support for es5 modules [CODESPLIT] function injectTemplate ( s , node , offset , id ) { const t = node . src ? readSrc ( id , node . src ) : node . content // Compile template const compiled = compiler . compile ( t ) const renderFuncs = '\\nrender: ' + toFunction ( compiled . render ) + ',' + '\\nstaticRenderFns: [' + compiled . staticRenderFns . map ( toFunction ) . join ( ',' ) + '],' s . appendLeft ( offset , renderFuncs ) return renderFuncs }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * EjsElectron . listen () -- Start intercepting requests on the file : protocol looking for . ejs files . It is not necessary to call this function up - front as ejs - electron starts listening as soon as it s loaded . Use this only to start listening again after calling EjsElectron . stopListening () . [CODESPLIT] function listen ( ) { if ( state . listening ) return EjsElectron // already listening; nothing to do here protocol . interceptBufferProtocol ( 'file' , protocolListener ) state . listening = true return EjsElectron // for chaining }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * EjsElectron . stopListening () -- Stop intercepting requests restoring the original file : protocol handler . [CODESPLIT] function stopListening ( ) { if ( ! state . listening ) return EjsElectron // we're not listening; nothing to stop here protocol . uninterceptProtocol ( 'file' ) state . listening = false return EjsElectron }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper Functions [CODESPLIT] function compileEjs ( pathname , contentBuffer ) { state . data . ejse = EjsElectron state . options . filename = pathname let contentString = contentBuffer . toString ( ) let compiledEjs = ejs . render ( contentString , state . data , state . options ) return new Buffer ( compiledEjs ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A closure factory to build the checkSize function for most of our handlers [CODESPLIT] function _defaultCheckSize ( size ) { return function ( raw ) { if ( raw . length < size ) { return false ; } this . buffer = raw . substr ( size ) ; return raw . substr ( 0 , size ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Calculate the HMAC - SHA - 512 of a key and some data ( raw strings ) [CODESPLIT] function rstr_hmac_sha512 ( key , data ) { var bkey = rstr2binb ( key ) ; if ( bkey . length > 32 ) bkey = binb_sha512 ( bkey , key . length * 8 ) ; var ipad = Array ( 32 ) , opad = Array ( 32 ) ; for ( var i = 0 ; i < 32 ; i ++ ) { ipad [ i ] = bkey [ i ] ^ 0x36363636 ; opad [ i ] = bkey [ i ] ^ 0x5C5C5C5C ; } var hash = binb_sha512 ( ipad . concat ( rstr2binb ( data ) ) , 1024 + data . length * 8 ) ; return binb2rstr ( binb_sha512 ( opad . concat ( hash ) , 1024 + 512 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same except with 5 addends [CODESPLIT] function int64add5 ( dst , a , b , c , d , e ) { var w0 = ( a . l & 0xffff ) + ( b . l & 0xffff ) + ( c . l & 0xffff ) + ( d . l & 0xffff ) + ( e . l & 0xffff ) ; var w1 = ( a . l >>> 16 ) + ( b . l >>> 16 ) + ( c . l >>> 16 ) + ( d . l >>> 16 ) + ( e . l >>> 16 ) + ( w0 >>> 16 ) ; var w2 = ( a . h & 0xffff ) + ( b . h & 0xffff ) + ( c . h & 0xffff ) + ( d . h & 0xffff ) + ( e . h & 0xffff ) + ( w1 >>> 16 ) ; var w3 = ( a . h >>> 16 ) + ( b . h >>> 16 ) + ( c . h >>> 16 ) + ( d . h >>> 16 ) + ( e . h >>> 16 ) + ( w2 >>> 16 ) ; dst . l = ( w0 & 0xffff ) | ( w1 << 16 ) ; dst . h = ( w2 & 0xffff ) | ( w3 << 16 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LmdBuilder LMD Package Builder [CODESPLIT] function ( configFile , options ) { DataStream . call ( this ) ; this . options = options || { } ; var self = this ; // apply config this . configFile = configFile ; this . init ( ) ; // Bundles streams this . bundles = { } ; // Let return instance before build this . buildConfig = this . compileConfig ( configFile , self . options ) ; this . makeEmptyStreamsUnreadable ( this . buildConfig ) ; var isFatalErrors = ! this . isAllModulesExists ( this . buildConfig ) ; if ( isFatalErrors ) { this . readable = false ; this . style . readable = false ; this . sourceMap . readable = false ; } else { this . _initBundlesStreams ( this . buildConfig . bundles ) ; } process . nextTick ( function ( ) { if ( ! isFatalErrors ) { if ( configFile ) { var buildResult = self . build ( self . buildConfig ) ; self . write ( buildResult . source ) ; self . style . write ( buildResult . style ) ; self . sourceMap . write ( buildResult . sourceMap . toString ( ) ) ; self . _streamBundles ( buildResult . bundles ) ; } else { self . log . write ( 'lmd usage:\\n\\t    ' + 'lmd' . blue + ' ' + 'config.lmd.js(on)' . green + ' [output.lmd.js]\\n' ) ; } } else { self . printFatalErrors ( self . buildConfig ) ; } self . closeStreams ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses variable sandbox for create replacement map [CODESPLIT] function getSandboxMap ( ast ) { var map = { } ; walker . with_walkers ( { // looking for first var with sandbox item; \"var\" : function ( vars ) { for ( var i = 0 , c = vars . length , varItem ; i < c ; i ++ ) { varItem = vars [ i ] ; if ( varItem [ 0 ] === 'sandbox' ) { varItem [ 1 ] [ 1 ] . forEach ( function ( objectVar ) { map [ objectVar [ 0 ] ] = objectVar [ 1 ] [ 1 ] ; } ) ; throw 0 ; } } } } , function ( ) { try { return walker . walk ( ast ) ; } catch ( e ) { } } ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "looking for first var with sandbox item ; [CODESPLIT] function ( vars ) { for ( var i = 0 , c = vars . length , varItem ; i < c ; i ++ ) { varItem = vars [ i ] ; if ( varItem [ 0 ] === 'sandbox' ) { varItem [ 1 ] [ 1 ] . forEach ( function ( objectVar ) { map [ objectVar [ 0 ] ] = objectVar [ 1 ] [ 1 ] ; } ) ; throw 0 ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Brakes sendbox in one module [CODESPLIT] function breakSandbox ( ast , replaceMap ) { var sandboxName = ast [ 2 ] [ 0 ] || 'sb' ; var newAst = walker . with_walkers ( { // lookup for dot // looking for this pattern // [\"dot\", [\"name\", \"sb\"], \"require\"] -> [\"name\", map[\"require\"]] \"dot\" : function ( ) { if ( this [ 1 ] && this [ 1 ] [ 0 ] === \"name\" && this [ 1 ] [ 1 ] === sandboxName ) { var sourceName = this [ 2 ] ; return [ \"name\" , replaceMap [ sourceName ] ] ; } } } , function ( ) { return walker . walk ( ast ) ; } ) ; // remove IEFE's `sb` or whatever argument newAst [ 1 ] [ 2 ] = [ ] ; return newAst ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Brake sandbox : Using UglifyJS AST and sandbox variable in lmd . js file replace all sb . smth with actual value of sandbox [ smth ] than delete sandbox variable from lmd . js and all modules [CODESPLIT] function brakeSandboxes ( ast ) { var map = getSandboxMap ( ast ) , isSandboxVariableWiped = false ; return walker . with_walkers ( { // lookup for modules // looking for this pattern // [ 'call', //  [ 'function', null, [ 'sb' ], [ [Object] ] ], //  [ [ 'name', 'sandbox' ] ] ] \"call\" : function ( content ) { if ( this [ 2 ] && this [ 2 ] . length > 0 && this [ 2 ] [ 0 ] [ 0 ] === \"name\" && this [ 2 ] [ 0 ] [ 1 ] === \"sandbox\" && this [ 1 ] && this [ 1 ] [ 0 ] === \"function\" ) { // 1. remove sandbox argument this [ 2 ] = [ ] ; // 2. break sandbox in each module return breakSandbox ( this , map ) ; } } , // wipe sandobx variable \"var\" : function ( ) { if ( isSandboxVariableWiped ) { return ; } for ( var i = 0 , c = this [ 1 ] . length , varItem ; i < c ; i ++ ) { varItem = this [ 1 ] [ i ] ; if ( varItem [ 0 ] === 'sandbox' ) { isSandboxVariableWiped = true ; this [ 1 ] . splice ( i , 1 ) ; return this ; } } } } , function ( ) { return walker . walk ( ast ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wipe sandobx variable [CODESPLIT] function ( ) { if ( isSandboxVariableWiped ) { return ; } for ( var i = 0 , c = this [ 1 ] . length , varItem ; i < c ; i ++ ) { varItem = this [ 1 ] [ i ] ; if ( varItem [ 0 ] === 'sandbox' ) { isSandboxVariableWiped = true ; this [ 1 ] . splice ( i , 1 ) ; return this ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects all plugins events with usage and event index [CODESPLIT] function getEvents ( ast ) { var usage = { } , eventIndex = 0 ; walker . with_walkers ( { // looking for first var with sandbox item; \"call\" : function ( ) { if ( this [ 1 ] && this [ 2 ] [ 0 ] ) { var functionName = this [ 1 ] [ 1 ] ; switch ( functionName ) { case \"lmd_on\" : case \"lmd_trigger\" : var eventName = this [ 2 ] [ 0 ] [ 1 ] ; if ( ! usage [ eventName ] ) { usage [ eventName ] = { on : 0 , trigger : 0 , eventIndex : eventIndex } ; eventIndex ++ ; } if ( functionName === \"lmd_on\" ) { usage [ eventName ] . on ++ ; } else { usage [ eventName ] . trigger ++ ; } break ; } } } } , function ( ) { return walker . walk ( ast ) ; } ) ; return usage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "looking for first var with sandbox item ; [CODESPLIT] function ( ) { if ( this [ 1 ] && this [ 2 ] [ 0 ] ) { var functionName = this [ 1 ] [ 1 ] ; switch ( functionName ) { case \"lmd_on\" : case \"lmd_trigger\" : var eventName = this [ 2 ] [ 0 ] [ 1 ] ; if ( ! usage [ eventName ] ) { usage [ eventName ] = { on : 0 , trigger : 0 , eventIndex : eventIndex } ; eventIndex ++ ; } if ( functionName === \"lmd_on\" ) { usage [ eventName ] . on ++ ; } else { usage [ eventName ] . trigger ++ ; } break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wipes lmd_on lmd_trigger lmd_events variables from source [CODESPLIT] function wipeLmdEvents ( ast ) { var itemsToWipe = [ 'lmd_on' , 'lmd_trigger' , 'lmd_events' ] ; return walker . with_walkers ( { // wipe lmdEvents variables \"var\" : function ( ) { if ( ! itemsToWipe . length ) { return ; } for ( var i = 0 , c = this [ 1 ] . length , varItem ; i < c ; i ++ ) { varItem = this [ 1 ] [ i ] ; if ( varItem ) { var itemIndex = itemsToWipe . indexOf ( varItem [ 0 ] ) ; if ( itemIndex !== - 1 ) { itemsToWipe . splice ( itemIndex , 1 ) ; this [ 1 ] . splice ( i , 1 ) ; i -- ; } } } } } , function ( ) { return walker . walk ( ast ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wipe lmdEvents variables [CODESPLIT] function ( ) { if ( ! itemsToWipe . length ) { return ; } for ( var i = 0 , c = this [ 1 ] . length , varItem ; i < c ; i ++ ) { varItem = this [ 1 ] [ i ] ; if ( varItem ) { var itemIndex = itemsToWipe . indexOf ( varItem [ 0 ] ) ; if ( itemIndex !== - 1 ) { itemsToWipe . splice ( itemIndex , 1 ) ; this [ 1 ] . splice ( i , 1 ) ; i -- ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Optimizes number of lmd_ { on|trigger } calls [CODESPLIT] function reduceAndShortenLmdEvents ( ast ) { var events = getEvents ( ast ) , isWipeLmdEvents = true ; for ( var eventName in events ) { if ( isWipeLmdEvents ) { if ( events [ eventName ] . on !== 0 && events [ eventName ] . trigger !== 0 ) { // something is calling events isWipeLmdEvents = false ; } } } // If no lmd_trigger and lmd_on calls // than delete them plus lmd_events from lmd.js code if ( isWipeLmdEvents ) { ast = wipeLmdEvents ( ast ) ; } ast = walker . with_walkers ( { // looking for first var with sandbox item; \"call\" : function ( ) { if ( this [ 1 ] && this [ 2 ] [ 0 ] ) { var functionName = this [ 1 ] [ 1 ] , eventName , eventDescriptor ; switch ( functionName ) { case \"lmd_on\" : eventName = this [ 2 ] [ 0 ] [ 1 ] ; eventDescriptor = events [ eventName ] ; // if no event triggers (no lmd_trigger(event_name,...)) // delete all lmd_on(event_name,...) statements if ( eventDescriptor . trigger === 0 ) { return [ \"stat\" ] ; // wipe statement = return empty statement - ; } // Shorten event names: Using UglifyJS AST find all event names // from lmd_trigger and lmd_on and replace them with corresponding numbers //console.log(this); this [ 2 ] [ 0 ] = [ \"num\" , eventDescriptor . eventIndex ] ; break ; case \"lmd_trigger\" : eventName = this [ 2 ] [ 0 ] [ 1 ] ; eventDescriptor = events [ eventName ] ; // if no event listeners (no lmd_on(event_name,...)) // replace all lmd_trigger(event_name, argument, argument) // expressions with array [argument, argument] if ( eventDescriptor . on === 0 ) { // if parent is statement -> return void // to prevent loony arrays eg [\"pewpew\", \"ololo\"]; if ( walker . parent ( ) [ 0 ] === \"stat\" ) { return [ \"stat\" ] ; // wipe statement = return empty statement - ; } /*\n                                [\n                                    \"call\",\n                                    [\"name\", \"lmd_trigger\"],\n                                    [\n                                        [\"string\", \"lmd-register:call-sandboxed-module\"],\n                                        [\"name\", \"moduleName\"],\n                                        [\"name\", \"require\"]\n                                    ]\n                                ]\n\n                                  --->\n\n                                [\n                                    \"array\",\n                                    [\n                                        [\"name\", \"moduleName\"],\n                                        [\"name\", \"require\"]\n                                    ]\n                                ]\n                                */ return [ \"array\" , this [ 2 ] . slice ( 1 ) ] ; } // Shorten event names: Using UglifyJS AST find all event names // from lmd_trigger and lmd_on and replace them with corresponding numbers this [ 2 ] [ 0 ] = [ \"num\" , eventDescriptor . eventIndex ] ; break ; } } } } , function ( ) { return walker . walk ( ast ) ; } ) ; // #52 optimise constant expressions like [main][0] ast = walker . with_walkers ( { \"sub\" : function ( ) { // Looking for this pattern // [ 'sub', [ 'array', [ [Object], [Object] ] ], [ 'num', 1 ] ] if ( this [ 1 ] [ 0 ] === \"array\" && this [ 2 ] [ 0 ] === \"num\" ) { var isConstantArray = this [ 1 ] [ 1 ] . every ( function ( item ) { return item [ 0 ] === \"num\" || item [ 0 ] === \"string\" || item [ 0 ] === \"name\" || item [ 0 ] === \"array\" || item [ 0 ] === \"object\" ; } ) ; if ( isConstantArray ) { var index = this [ 2 ] [ 1 ] ; /*\n                         [main][0]\n\n                          --->\n\n                         main\n                        */ return this [ 1 ] [ 1 ] [ index ] ; } } } } , function ( ) { return walker . walk ( ast ) ; } ) ; return ast ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "looking for first var with sandbox item ; [CODESPLIT] function ( ) { if ( this [ 1 ] && this [ 2 ] [ 0 ] ) { var functionName = this [ 1 ] [ 1 ] , eventName , eventDescriptor ; switch ( functionName ) { case \"lmd_on\" : eventName = this [ 2 ] [ 0 ] [ 1 ] ; eventDescriptor = events [ eventName ] ; // if no event triggers (no lmd_trigger(event_name,...)) // delete all lmd_on(event_name,...) statements if ( eventDescriptor . trigger === 0 ) { return [ \"stat\" ] ; // wipe statement = return empty statement - ; } // Shorten event names: Using UglifyJS AST find all event names // from lmd_trigger and lmd_on and replace them with corresponding numbers //console.log(this); this [ 2 ] [ 0 ] = [ \"num\" , eventDescriptor . eventIndex ] ; break ; case \"lmd_trigger\" : eventName = this [ 2 ] [ 0 ] [ 1 ] ; eventDescriptor = events [ eventName ] ; // if no event listeners (no lmd_on(event_name,...)) // replace all lmd_trigger(event_name, argument, argument) // expressions with array [argument, argument] if ( eventDescriptor . on === 0 ) { // if parent is statement -> return void // to prevent loony arrays eg [\"pewpew\", \"ololo\"]; if ( walker . parent ( ) [ 0 ] === \"stat\" ) { return [ \"stat\" ] ; // wipe statement = return empty statement - ; } /*\n                                [\n                                    \"call\",\n                                    [\"name\", \"lmd_trigger\"],\n                                    [\n                                        [\"string\", \"lmd-register:call-sandboxed-module\"],\n                                        [\"name\", \"moduleName\"],\n                                        [\"name\", \"require\"]\n                                    ]\n                                ]\n\n                                  --->\n\n                                [\n                                    \"array\",\n                                    [\n                                        [\"name\", \"moduleName\"],\n                                        [\"name\", \"require\"]\n                                    ]\n                                ]\n                                */ return [ \"array\" , this [ 2 ] . slice ( 1 ) ] ; } // Shorten event names: Using UglifyJS AST find all event names // from lmd_trigger and lmd_on and replace them with corresponding numbers this [ 2 ] [ 0 ] = [ \"num\" , eventDescriptor . eventIndex ] ; break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies or removes block from lmd_js [CODESPLIT] function ( optionName , isApply , isInline ) { // /*if ($P.CSS || $P.JS || $P.ASYNC) {*/ var inlinePreprocessorBlock = isInline ? '/*if (' + optionName + ') {*/' : 'if (' + optionName + ') {' , bracesCounter = 0 , startIndex = lmd_js . indexOf ( inlinePreprocessorBlock ) , startLength = inlinePreprocessorBlock . length , endIndex = startIndex + inlinePreprocessorBlock . length , endLength = isInline ? 5 : 1 ; if ( startIndex === - 1 ) { return false ; } // lookup for own } while ( lmd_js . length > endIndex ) { if ( lmd_js [ endIndex ] === '{' ) { bracesCounter ++ ; } if ( lmd_js [ endIndex ] === '}' ) { bracesCounter -- ; } // found! if ( bracesCounter === - 1 ) { if ( isInline ) { // step back endIndex -= 2 ; } else { // remove leading spaces from open part while ( startIndex ) { startIndex -- ; startLength ++ ; if ( lmd_js [ startIndex ] !== '\\t' && lmd_js [ startIndex ] !== ' ' ) { startIndex ++ ; startLength -- ; break ; } } // remove leading spaces from close part while ( endIndex ) { endIndex -- ; endLength ++ ; if ( lmd_js [ endIndex ] !== '\\t' && lmd_js [ endIndex ] !== ' ' ) { endIndex ++ ; endLength -- ; break ; } } // add front \\n endLength ++ ; startLength ++ ; } if ( isApply ) { // wipe preprocessor blocks only // open lmd_js = lmd_js . substr ( 0 , startIndex ) + lmd_js . substr ( startIndex + startLength ) ; // close lmd_js = lmd_js . substr ( 0 , endIndex - startLength ) + lmd_js . substr ( endIndex + endLength - startLength ) ; if ( ! isInline ) { // indent block back var blockForIndent = lmd_js . substr ( startIndex , endIndex - startLength - startIndex ) ; blockForIndent = blockForIndent . split ( '\\n' ) . map ( function ( line ) { return line . replace ( / ^\\s{4} / , '' ) ; } ) . join ( '\\n' ) ; lmd_js = lmd_js . substr ( 0 , startIndex ) + blockForIndent + lmd_js . substr ( endIndex - startLength ) ; } } else { // wipe all lmd_js = lmd_js . substr ( 0 , startIndex ) + lmd_js . substr ( endIndex + endLength ) ; } break ; } endIndex ++ ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create stylesheet link [CODESPLIT] function ( e ) { if ( isNotLoaded ) { isNotLoaded = 0 ; // register or cleanup link . removeAttribute ( 'id' ) ; if ( ! e ) { sb . trigger ( '*:request-error' , moduleName , module ) ; } callback ( e ? sb . register ( moduleName , link ) : head . removeChild ( link ) && sb . undefined ) ; // e === undefined if error } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A method assignment helper for hierarchy subclasses . [CODESPLIT] function d3_layout_hierarchyRebind ( object , hierarchy ) { object . sort = d3 . rebind ( object , hierarchy . sort ) ; object . children = d3 . rebind ( object , hierarchy . children ) ; object . links = d3_layout_hierarchyLinks ; object . value = d3 . rebind ( object , hierarchy . value ) ; // If the new API is used, enabling inlining. object . nodes = function ( d ) { d3_layout_hierarchyInline = true ; return ( object . nodes = object ) ( d ) ; } ; return object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Positions the specified row of nodes . Modifies rect . [CODESPLIT] function position ( row , u , rect , flush ) { var i = - 1 , n = row . length , x = rect . x , y = rect . y , v = u ? round ( row . area / u ) : 0 , o ; if ( u == rect . dx ) { // horizontal subdivision if ( flush || v > rect . dy ) v = v ? rect . dy : 0 ; // over+underflow while ( ++ i < n ) { o = row [ i ] ; o . x = x ; o . y = y ; o . dy = v ; x += o . dx = v ? round ( o . area / v ) : 0 ; } o . z = true ; o . dx += rect . x + rect . dx - x ; // rounding error rect . y += v ; rect . dy -= v ; } else { // vertical subdivision if ( flush || v > rect . dx ) v = v ? rect . dx : 0 ; // over+underflow while ( ++ i < n ) { o = row [ i ] ; o . x = x ; o . y = y ; o . dx = v ; y += o . dy = v ? round ( o . area / v ) : 0 ; } o . z = false ; o . dy += rect . y + rect . dy - y ; // rounding error rect . x += v ; rect . dx -= v ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lazily construct the package hierarchy from class names . [CODESPLIT] function ( classes ) { var map = { } ; function find ( name , data ) { var node = map [ name ] , i ; if ( ! node ) { node = map [ name ] = data || { name : name , children : [ ] } ; if ( name . length ) { node . parent = find ( \"\" ) ; node . parent . children . push ( node ) ; node . name = name ; node . key = escapeId ( name ) ; } } return node ; } classes . forEach ( function ( d ) { find ( d . name , d ) ; } ) ; return map [ \"\" ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simple JSON stringify [CODESPLIT] function stringify ( object ) { var properties = [ ] ; for ( var key in object ) { if ( object . hasOwnProperty ( key ) ) { properties . push ( quote ( key ) + ':' + getValue ( object [ key ] ) ) ; } } return \"{\" + properties . join ( \",\" ) + \"}\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "At initialization we bind to the relevant events on the Todos collection when items are added or changed . Kick things off by loading any preexisting todos that might be saved in * localStorage * . [CODESPLIT] function ( ) { this . input = this . $ ( '#new-todo' ) ; this . allCheckbox = this . $ ( '#toggle-all' ) [ 0 ] ; this . $footer = this . $ ( '#footer' ) ; this . $main = this . $ ( '#main' ) ; todos . on ( 'add' , this . addOne , this ) ; todos . on ( 'reset' , this . addAll , this ) ; todos . on ( 'change:completed' , this . filterOne , this ) ; todos . on ( \"filter\" , this . filterAll , this ) ; todos . on ( 'all' , this . render , this ) ; todos . fetch ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - rendering the App just means refreshing the statistics -- the rest of the app doesn t change . [CODESPLIT] function ( ) { var completed = todos . completed ( ) . length ; var remaining = todos . remaining ( ) . length ; if ( todos . length ) { this . $main . show ( ) ; this . $footer . show ( ) ; this . $footer . html ( this . template ( { completed : completed , remaining : remaining } ) ) ; this . $ ( '#filters li a' ) . removeClass ( 'selected' ) . filter ( '[href=\"#/' + ( common . TodoFilter || '' ) + '\"]' ) . addClass ( 'selected' ) ; } else { this . $main . hide ( ) ; this . $footer . hide ( ) ; } this . allCheckbox . checked = ! remaining ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If you hit return in the main input field create new ** Todo ** model persisting it to * localStorage * . [CODESPLIT] function ( e ) { if ( e . which !== common . ENTER_KEY || ! this . input . val ( ) . trim ( ) ) { return ; } todos . create ( this . newAttributes ( ) ) ; this . input . val ( '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generic function for counting a line . It generates a lineId from the line number and the block name ( in minified files there are more logical lines on the same file line ) and adds a function call before the actual line of code . [CODESPLIT] function countLine ( ) { var ret ; // skip first line if ( isFirstLine ) { isFirstLine = false ; return ret ; } if ( this [ 0 ] . start && analyzing . indexOf ( this ) < 0 ) { giveNameToAnonymousFunction . call ( this ) ; var lineId = this [ 0 ] . start . line + lineOffset + '' ; //this[0].name + ':' + this[0].start.line + \":\" + this[0].start.pos; rememberStatement ( lineId ) ; analyzing . push ( this ) ; ret = [ \"splice\" , [ [ \"stat\" , [ \"call\" , [ \"dot\" , [ \"name\" , \"require\" ] , \"coverage_line\" ] , [ [ \"string\" , moduleName ] , [ \"string\" , lineId ] ] ] ] , walker . walk ( this ) ] ] ; analyzing . pop ( this ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walker for if nodes . It overrides countLine because we want to instrument conditions . [CODESPLIT] function countIf ( ) { var self = this , ret ; if ( self [ 0 ] . start && analyzing . indexOf ( self ) < 0 ) { var decision = self [ 1 ] ; var lineId = self [ 0 ] . name + ':' + ( self [ 0 ] . start . line + lineOffset ) ; self [ 1 ] = wrapCondition ( decision , lineId ) ; // We are adding new lines, make sure code blocks are actual blocks if ( self [ 2 ] && self [ 2 ] [ 0 ] . start && self [ 2 ] [ 0 ] . start . value != \"{\" ) { self [ 2 ] = [ \"block\" , [ self [ 2 ] ] ] ; } if ( self [ 3 ] && self [ 3 ] [ 0 ] . start && self [ 3 ] [ 0 ] . start . value != \"{\" ) { self [ 3 ] = [ \"block\" , [ self [ 3 ] ] ] ; } } ret = countLine . call ( self ) ; if ( decision ) { analyzing . pop ( decision ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the key function for condition coverage as it wraps every condition in a function call . The condition id is generated fron the lineId ( [CODESPLIT] function wrapCondition ( decision , lineId , parentPos ) { if ( options . condition === false ) { // condition coverage is disabled return decision ; } if ( isSingleCondition ( decision ) ) { var pos = getPositionStart ( decision , parentPos ) ; var condId = lineId + \":\" + pos ; analyzing . push ( decision ) ; allConditions . push ( condId ) ; return [ \"call\" , [ \"dot\" , [ \"name\" , \"require\" ] , \"coverage_condition\" ] , [ [ \"string\" , moduleName ] , [ \"string\" , condId ] , decision ] ] ; } else { decision [ 2 ] = wrapCondition ( decision [ 2 ] , lineId , getPositionStart ( decision , parentPos ) ) ; decision [ 3 ] = wrapCondition ( decision [ 3 ] , lineId , getPositionEnd ( decision , parentPos ) ) ; return decision ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wheter or not the if decision has only one boolean condition [CODESPLIT] function isSingleCondition ( decision ) { if ( decision [ 0 ] . start && decision [ 0 ] . name != \"binary\" ) { return true ; } else if ( decision [ 1 ] == \"&&\" || decision [ 1 ] == \"||\" ) { return false ; } else { return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Label nodes need special treatment as well . [CODESPLIT] function countLabel ( ) { var ret ; if ( this [ 0 ] . start && analyzing . indexOf ( this ) < 0 ) { var content = this [ 2 ] ; if ( content [ 0 ] . name == \"for\" && content [ 4 ] && content [ 4 ] . name != \"block\" ) { content [ 4 ] = [ \"block\" , [ content [ 4 ] ] ] ; } analyzing . push ( content ) ; var ret = countLine . call ( this ) ; analyzing . pop ( content ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instrumenting function strictly needed for statement coverage only in case of defun ( function definition ) however the block function does not correspond to a new statement . This method allows to track every function call ( function coverage ) . [CODESPLIT] function countFunction ( ) { var ret ; if ( isFirstLine ) { isFirstLine = false ; return ret ; } if ( this [ 0 ] . start && analyzing . indexOf ( this ) < 0 ) { var defun = this [ 0 ] . name === \"defun\" ; var lineId = this [ 0 ] . start . line + lineOffset + '' ; //this[0].name + \":\" + this[0].start.line + \":\" + this[0].start.pos; var fnName = this [ 1 ] || this [ 0 ] . anonymousName || \"(?)\" ; var fnId = fnName + ':' + ( this [ 0 ] . start . line + lineOffset ) + \":\" + this [ 0 ] . start . pos ; var body = this [ 3 ] ; analyzing . push ( this ) ; // put a new function call inside the body, works also on empty functions if ( options [ \"function\" ] ) { body . splice ( 0 , 0 , [ \"stat\" , [ \"call\" , [ \"dot\" , [ \"name\" , \"require\" ] , \"coverage_function\" ] , [ [ \"string\" , moduleName ] , [ \"string\" , fnId ] ] ] ] ) ; // It would be great to instrument the 'exit' from a function // but it means tracking all return statements, maybe in the future... rememberFunction ( fnId ) ; } if ( defun ) { // 'defun' should also be remembered as statements rememberStatement ( lineId ) ; ret = [ \"splice\" , [ [ \"stat\" , [ \"call\" , [ \"dot\" , [ \"name\" , \"require\" ] , \"coverage_line\" ] , [ [ \"string\" , moduleName ] , [ \"string\" , lineId ] ] ] ] , walker . walk ( this ) ] ] ; } else { ret = walker . walk ( this ) ; } analyzing . pop ( this ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function tries to extract the name of anonymous functions depending on where they are defined . [CODESPLIT] function giveNameToAnonymousFunction ( ) { var node = this ; if ( node [ 0 ] . name == \"var\" || node [ 0 ] . name == \"object\" ) { node [ 1 ] . forEach ( function ( assignemt ) { if ( assignemt [ 1 ] ) { if ( assignemt [ 1 ] [ 0 ] . name === \"function\" ) { assignemt [ 1 ] [ 0 ] . anonymousName = assignemt [ 0 ] ; } else if ( assignemt [ 1 ] [ 0 ] . name === \"conditional\" ) { if ( assignemt [ 1 ] [ 2 ] [ 0 ] && assignemt [ 1 ] [ 2 ] [ 0 ] . name === \"function\" ) { assignemt [ 1 ] [ 2 ] [ 0 ] . anonymousName = assignemt [ 0 ] ; } if ( assignemt [ 1 ] [ 3 ] [ 0 ] && assignemt [ 1 ] [ 3 ] [ 0 ] . name === \"function\" ) { assignemt [ 1 ] [ 3 ] [ 0 ] . anonymousName = assignemt [ 0 ] ; } } } } ) ; } else if ( node [ 0 ] . name == \"assign\" && node [ 1 ] === true ) { if ( node [ 3 ] [ 0 ] . name === \"function\" ) { node [ 3 ] [ 0 ] . anonymousName = getNameFromAssign ( node ) ; } else if ( node [ 3 ] [ 0 ] === \"conditional\" ) { if ( node [ 3 ] [ 2 ] [ 0 ] && node [ 3 ] [ 2 ] [ 0 ] . name === \"function\" ) { node [ 3 ] [ 2 ] [ 0 ] . anonymousName = getNameFromAssign ( node ) ; } if ( node [ 3 ] [ 3 ] [ 0 ] && node [ 3 ] [ 3 ] [ 0 ] . name === \"function\" ) { node [ 3 ] [ 3 ] [ 0 ] . anonymousName = getNameFromAssign ( node ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function wraps ternary conditionals in order to have condition coverage [CODESPLIT] function wrapConditionals ( ) { if ( options . condition === false ) { // condition coverage is disabled return ; } var self = this , ret ; if ( self [ 0 ] . start && analyzing . indexOf ( self ) < 0 ) { analyzing . push ( self ) ; var lineId = self [ 0 ] . name + ':' + ( self [ 0 ] . start . line + lineOffset ) ; self [ 1 ] = wrapCondition ( self [ 1 ] , lineId ) ; self [ 2 ] = walker . walk ( self [ 2 ] ) ; self [ 3 ] = walker . walk ( self [ 3 ] ) ; analyzing . pop ( self ) ; return self ; } else if ( self [ 1 ] ) { self [ 1 ] = wrapCondition ( self [ 1 ] , lineId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "RequireJS & AMD - style define [CODESPLIT] function ( name , deps , module ) { switch ( arguments . length ) { case 1 : // define(function () {}) module = name ; deps = name = sb . undefined ; break ; case 2 : // define(['a', 'b'], function () {}) module = deps ; deps = name ; name = sb . undefined ; break ; case 3 : // define('name', ['a', 'b'], function () {}) } if ( typeof module !== \"function\" ) { amdModules [ currentModule ] = module ; return ; } var output = { 'exports' : { } } ; if ( ! deps ) { deps = [ \"require\" , \"exports\" , \"module\" ] ; } for ( var i = 0 , c = deps . length ; i < c ; i ++ ) { switch ( deps [ i ] ) { case \"require\" : deps [ i ] = currentRequire ; break ; case \"module\" : deps [ i ] = output ; break ; case \"exports\" : deps [ i ] = output . exports ; break ; default : deps [ i ] = currentRequire && currentRequire ( deps [ i ] ) ; } } module = module . apply ( this , deps ) || output . exports ; amdModules [ currentModule ] = module ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate coverage total [CODESPLIT] function stats_calculate_coverage ( moduleName ) { var stats = sb . trigger ( '*:stats-get' , moduleName , null ) [ 1 ] , total , covered , lineId , lineNum , parts ; var lineReport = { } ; if ( ! stats . lines ) { return ; } stats . coverage = { } ; covered = 0 ; total = stats . lines . length ; for ( lineId in stats . runLines ) { if ( stats . runLines [ lineId ] > 0 ) { covered ++ ; } else { lineNum = lineId ; if ( ! lineReport [ lineNum ] ) { lineReport [ lineNum ] = { } ; } lineReport [ lineNum ] . lines = false ; } } stats . coverage . lines = { total : total , covered : covered , percentage : 100.0 * ( total ? covered / total : 1 ) } ; covered = 0 ; total = stats . functions . length ; for ( lineId in stats . runFunctions ) { if ( stats . runFunctions [ lineId ] > 0 ) { covered ++ ; } else { parts = lineId . split ( ':' ) ; lineNum = parts [ 1 ] ; if ( ! lineReport [ lineNum ] ) { lineReport [ lineNum ] = { } ; } if ( ! lineReport [ lineNum ] . functions ) { lineReport [ lineNum ] . functions = [ ] ; } lineReport [ lineNum ] . functions . push ( parts [ 0 ] ) ; } } stats . coverage . functions = { total : total , covered : covered , percentage : 100.0 * ( total ? covered / total : 1 ) } ; covered = 0 ; total = stats . conditions . length ; for ( lineId in stats . runConditions ) { if ( stats . runConditions [ lineId ] [ 1 ] > 0 ) { covered += 1 ; } if ( stats . runConditions [ lineId ] [ 1 ] === 0 ) { parts = lineId . split ( ':' ) ; lineNum = parts [ 1 ] ; if ( ! lineReport [ lineNum ] ) { lineReport [ lineNum ] = { } ; } if ( ! lineReport [ lineNum ] . conditions ) { lineReport [ lineNum ] . conditions = [ ] ; } lineReport [ lineNum ] . conditions . push ( stats . runConditions [ lineId ] ) ; } } stats . coverage . conditions = { total : total , covered : covered , percentage : 100.0 * ( total ? covered / total : 1 ) } ; stats . coverage . report = lineReport ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "require ( undefined ) [CODESPLIT] function Roster ( element ) { element . innerHTML += this . renderWrapper ( ) ; var contactsHtml = [ ] ; for ( var i = 100 ; i -- > 0 ; ) { contactsHtml . push ( this . renderItem ( ) ) ; } $ ( '.b-roster' ) . innerHTML = contactsHtml . join ( '' ) ; $ ( '.b-roster' ) . addEventListener ( 'click' , function ( e ) { // Preload talk for dialog using parallel resource loading\r require . async ( [ 'js/lmd/modules/b-dialog.min.js' , 'js/lmd/modules/b-talk.min.js' ] , function ( Dialog ) { new Dialog ( element ) ; } ) ; } , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * wrapped by builder LMD require . js () and shortcuts example [CODESPLIT] function renderMap ( ) { var $map = $ ( '#map' ) ; // @see http://api.yandex.ru/maps/jsbox/geolocation_ip ymaps . ready ( function ( ) { // IP based geolocation var geolocation = ymaps . geolocation , coords = [ geolocation . latitude , geolocation . longitude ] , myMap = new ymaps . Map ( $map [ 0 ] , { center : coords , zoom : 10 } ) ; myMap . geoObjects . add ( new ymaps . Placemark ( coords , { // add balloon balloonContentHeader : geolocation . country , balloonContent : geolocation . city , balloonContentFooter : geolocation . region } ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It uses _ . template to interpolate config strings { output : index - <% = version % > . js version : 1 . 0 . 1 } [CODESPLIT] function interpolateConfigStrings ( config , data ) { data = data || config ; for ( var key in config ) { var value = config [ key ] ; if ( typeof value === \"object\" ) { config [ key ] = interpolateConfigStrings ( value , data ) ; } else if ( typeof value === \"string\" ) { var currentInterpolation = 0 ; while ( templateParts . test ( value ) ) { currentInterpolation ++ ; if ( currentInterpolation > maxInterpolateRecursion ) { break ; } config [ key ] = value = template ( value , data ) ; } } } return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges mixins with config [CODESPLIT] function ( config , mixins ) { if ( Array . isArray ( config . mixins ) && Array . isArray ( mixins ) ) { config . mixins . push . apply ( config . mixins , mixins ) ; return config ; } return deepDestructableMerge ( config , { mixins : mixins } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Config files deep merge [CODESPLIT] function ( left , right ) { for ( var prop in right ) { if ( right . hasOwnProperty ( prop ) ) { if ( typeof left [ prop ] === \"object\" ) { deepDestructableMerge ( left [ prop ] , right [ prop ] ) ; } else { left [ prop ] = right [ prop ] ; } } } return left ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges all config files in module s lineage [CODESPLIT] function ( config , configDir ) { config = config || { } ; if ( typeof config . extends !== \"string\" ) { return config ; } var parentConfig = tryExtend ( readConfig ( configDir , config . extends ) , configDir ) ; return deepDestructableMerge ( parentConfig , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns depends config file of this module [CODESPLIT] function ( modulePath , dependsFileMask ) { modulePath = [ ] . concat ( modulePath ) ; return modulePath . map ( function ( modulePath ) { var fileName = modulePath . replace ( / ^.*\\/|\\.[a-z0-9]+$ / g , '' ) ; return path . join ( path . dirname ( modulePath ) , dependsFileMask . replace ( '*' , fileName ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges configs flags [CODESPLIT] function ( configA , configB , flagsNames , isMasterConfig ) { // Apply Flags flagsNames . forEach ( function ( optionsName ) { // if master -> B if ( typeof configB [ optionsName ] === \"undefined\" ) { return ; } if ( isMasterConfig ) { configA [ optionsName ] = configB [ optionsName ] ; } else { // if A literal B array -> B if ( configB [ optionsName ] instanceof Array && ! ( configA [ optionsName ] instanceof Array ) ) { configA [ optionsName ] = configB [ optionsName ] ; } else if ( configB [ optionsName ] instanceof Array && configA [ optionsName ] instanceof Array ) { // if A array B array -> A concat B configA [ optionsName ] = configA [ optionsName ] . concat ( configB [ optionsName ] ) ; } else { // if A literal B literal -> union // if A array B literal -> A configA [ optionsName ] = configA [ optionsName ] || configB [ optionsName ] ; } // else {} } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges configs [CODESPLIT] function ( configA , configB , flagsNames , inheritableFields , isMasterConfig , context ) { if ( isMasterConfig ) { // Apply master fields inheritableFields . forEach ( function ( fieldName ) { if ( typeof configB [ fieldName ] !== \"undefined\" ) { configA [ fieldName ] = configB [ fieldName ] ; if ( FILED_ALIASES . hasOwnProperty ( fieldName ) ) { configA [ FILED_ALIASES [ fieldName ] ] = configB [ fieldName ] ; } } } ) ; } // Save errors configA . errors = configA . errors || [ ] ; configB . errors = configB . errors || [ ] ; configA . errors = configA . errors . concat ( configB . errors ) ; // Apply Flags mergeFlags ( configA , configB , flagsNames , isMasterConfig ) ; // Apply Modules configA . modules = configA . modules || { } ; configB . modules = configB . modules || { } ; for ( var moduleName in configB . modules ) { // Warn if module exists an its not a master config if ( ! isMasterConfig && configA . modules [ moduleName ] ) { if ( ! isModulesEqual ( configA . modules [ moduleName ] , configB . modules [ moduleName ] ) ) { configA . errors . push ( 'Name conflict! Module **\"' + moduleName + '\"** will be overwritten by ' + context ) ; } } configA . modules [ moduleName ] = configB . modules [ moduleName ] ; } // Apply styles configA . styles = configA . styles || [ ] ; configB . styles = configB . styles || [ ] ; configA . styles = configA . styles . concat ( configB . styles ) ; // Apply Bundles configA . bundles = configA . bundles || { } ; configB . bundles = configB . bundles || { } ; for ( var bundleName in configB . bundles ) { if ( configB . bundles [ bundleName ] ) { if ( ! configA . bundles [ bundleName ] ) { configA . bundles [ bundleName ] = { } ; } // Bundle is not exists if ( configB . bundles [ bundleName ] instanceof Error ) { configA . bundles [ bundleName ] = configB . bundles [ bundleName ] ; } else { mergeConfigs ( configA . bundles [ bundleName ] , configB . bundles [ bundleName ] , flagsNames , MASTER_FIELDS , true , context ) ; } } } // Apply User Plugins configA . plugins = configA . plugins || { } ; configB . plugins = configB . plugins || { } ; for ( var pluginName in configB . plugins ) { // Warn if module exists an its not a master if ( ! isMasterConfig && configA . plugins [ pluginName ] ) { configA . errors . push ( 'Name conflict! User plugin **\"' + pluginName + '\"** will be overwritten by ' + context ) ; } configA . plugins [ pluginName ] = configB . plugins [ pluginName ] ; } return configA ; // not rly need... }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates LMD config : applies depends and extends [CODESPLIT] function ( rawConfig , configFile , configDir , flagsNames , extraOptions , usedConfigs ) { flagsNames = flagsNames || Object . keys ( LMD_PLUGINS ) ; var isFirstRun = typeof usedConfigs === \"undefined\" ; usedConfigs = usedConfigs || { } ; usedConfigs [ configFile ] = true ; // mark config as used var configs = [ ] , resultConfig = { modules : { } , errors : [ ] , plugins_depends : { } } ; if ( extraOptions && extraOptions . mixins ) { rawConfig = mergeMixins ( rawConfig , extraOptions . mixins ) ; } if ( extraOptions && extraOptions . styles ) { rawConfig = deepDestructableMerge ( rawConfig , { styles : extraOptions . styles } ) ; } // collect modules and module options var modules = collectModules ( rawConfig , configDir ) ; if ( rawConfig . depends ) { var /*dependsMask = rawConfig.depends === true ? DEFAULT_DEPENDS_MASK : rawConfig.depends,*/ dependsConfigPath , dependsMask ; for ( var moduleName in modules ) { if ( ! modules [ moduleName ] . is_shortcut && ! modules [ moduleName ] . is_ignored ) { dependsMask = modules [ moduleName ] . depends ; dependsConfigPath = getDependsConfigOf ( modules [ moduleName ] . path , dependsMask ) ; dependsConfigPath . forEach ( function ( dependsConfigPath ) { if ( fileExists ( dependsConfigPath ) ) { if ( ! usedConfigs [ dependsConfigPath ] ) { configs . unshift ( { context : 'depends config **' + dependsConfigPath + '**' , config : assembleLmdConfig ( dependsConfigPath , flagsNames , null , usedConfigs ) } ) ; } } } ) ; } } } // extend parent config if ( typeof rawConfig [ 'extends' ] === \"string\" ) { var parentConfigFile = fs . realpathSync ( configDir + '/' + rawConfig [ 'extends' ] ) ; if ( ! usedConfigs [ parentConfigFile ] ) { var parentConfig = assembleLmdConfig ( parentConfigFile , flagsNames , null , usedConfigs ) ; } } var processedConfig = { modules : modules , styles : collectStyles ( rawConfig , configDir ) , bundles : collectBundles ( rawConfig , configDir ) , plugins : collectUserPlugins ( rawConfig , configDir ) } ; // keep fields MASTER_FIELDS . forEach ( function ( fieldName ) { processedConfig [ fieldName ] = rawConfig [ fieldName ] ; if ( FILED_ALIASES . hasOwnProperty ( fieldName ) ) { processedConfig [ FILED_ALIASES [ fieldName ] ] = rawConfig [ fieldName ] ; } } ) ; // keep flags flagsNames . forEach ( function ( fieldName ) { processedConfig [ fieldName ] = rawConfig [ fieldName ] ; } ) ; if ( parentConfig ) { mergeConfigs ( resultConfig , parentConfig , flagsNames , INHERITABLE_FIELDS , true , 'parent config **' + parentConfigFile + '**' ) ; } for ( var i = 0 , c = configs . length , dependsMainModuleName ; i < c ; i ++ ) { // Cleanup main module from depends dependsMainModuleName = configs [ i ] . config . main || \"main\" ; if ( configs [ i ] . config . modules ) { delete configs [ i ] . config . modules [ dependsMainModuleName ] ; } mergeConfigs ( resultConfig , configs [ i ] . config , flagsNames , [ ] , false , configs [ i ] . context ) ; } mergeConfigs ( resultConfig , processedConfig , flagsNames , MASTER_FIELDS , true , 'main config **' + configFile + '**' ) ; if ( isFirstRun ) { // Apply mixins var mixins = resultConfig . mixins ; if ( Array . isArray ( mixins ) ) { mixins . forEach ( function ( mixinName ) { var mixinConfigFile = fs . realpathSync ( configDir + '/' + mixinName ) , processedMixin = assembleLmdConfig ( mixinConfigFile , flagsNames , null , usedConfigs ) ; mergeConfigs ( resultConfig , processedMixin , flagsNames , INHERITABLE_FIELDS , true , 'mixin config **' + mixinConfigFile + '**' ) ; } ) ; } if ( extraOptions ) { extraOptions . modules = collectModules ( extraOptions , configDir ) ; extraOptions . bundles = collectBundles ( extraOptions , configDir ) ; extraOptions . styles = collectStyles ( extraOptions , configDir ) ; mergeConfigs ( resultConfig , extraOptions , flagsNames , EXTRA_OPTIONS_FIELDS , true , 'CLI options' ) ; } reapplyModuleOptions ( resultConfig ) ; addPluginsFromBundles ( resultConfig ) ; addPluginsDepends ( resultConfig ) ; flattenBundles ( resultConfig ) ; resolveStyles ( resultConfig ) ; bundlesInheritFieldsFromPackage ( resultConfig ) ; removeIgnoredModules ( resultConfig ) ; } return resultConfig ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates LMD config : applies depends and extends [CODESPLIT] function ( configFile , flagsNames , extraOptions , usedConfigs ) { var configDir = path . dirname ( configFile ) , rawConfig = readConfig ( configFile ) ; configFile = fs . realpathSync ( configFile ) ; return assembleLmdConfigAsObject ( rawConfig , configFile , configDir , flagsNames , extraOptions , usedConfigs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For now add plugins from build to bundle [CODESPLIT] function addPluginsFromBundles ( resultConfig ) { if ( resultConfig . bundles ) { var bundles = Object . keys ( resultConfig . bundles ) , lmdPlugins = Object . keys ( LMD_PLUGINS ) ; // Apply flags from bundles bundles . forEach ( function ( bundleName ) { mergeFlags ( resultConfig , resultConfig . bundles [ bundleName ] , lmdPlugins , false ) ; } ) ; // Set bundle plugin if ( bundles . length ) { resultConfig . bundle = true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@name LmdModuleStruct @class [CODESPLIT] function ( config , configDir ) { var modules = { } , globalLazy = config . lazy || false , globalDepends = ( config . depends === true ? DEFAULT_DEPENDS_MASK : config . depends ) || false , moduleLazy = false , moduleTypeHint , moduleName , modulePath , moduleRealPath , moduleExists , moduleExports , moduleRequire , moduleBind , moduleFileName , moduleFilePath , moduleDesciptor , wildcardRegex , isMultiPathModule , moduleData , isThirdPartyModule , modulesDirPath = config . root || config . path || '' ; modulesDirPath = path . resolve ( configDir , modulesDirPath ) ; // grep paths for ( moduleName in config . modules ) { moduleDesciptor = config . modules [ moduleName ] ; // case \"moduleName\": null // case \"moduleName\": \"path/to/module.js\" if ( moduleDesciptor === null || typeof moduleDesciptor === \"string\" || Array . isArray ( moduleDesciptor ) ) { moduleTypeHint = false ; moduleExports = false ; moduleRequire = false ; moduleBind = false ; modulePath = moduleDesciptor ; moduleLazy = globalLazy ; } else { // case \"moduleName\": {\"path\": \"path/to/module.js\", \"lazy\": false} moduleTypeHint = moduleDesciptor . type || false ; moduleExports = moduleDesciptor . exports || false ; moduleRequire = moduleDesciptor . require || false ; moduleBind = moduleDesciptor . bind || moduleDesciptor [ 'this' ] || false ; modulePath = moduleDesciptor . path ; moduleLazy = moduleDesciptor . lazy || false ; moduleTypeHint = moduleDesciptor . type || false ; } isMultiPathModule = false ; if ( Array . isArray ( modulePath ) ) { // Try to glob // case when ['jquery*.js'] modulePath = modulePath . reduce ( function ( paths , modulePath ) { if ( globPattern . test ( modulePath ) ) { modulePath = glob . sync ( modulePath , { cwd : modulesDirPath , nosort : true } ) || [ ] ; } return paths . concat ( modulePath ) ; } , [ ] ) ; // case when ['jquery.js'] if ( modulePath . length === 1 ) { modulePath = modulePath [ 0 ] ; } else { isMultiPathModule = true ; } } isThirdPartyModule = ! ! moduleExports || ! ! moduleRequire || ! ! moduleBind ; // Override if cache flag = true if ( config . cache ) { moduleLazy = true ; } // its a glob pattern // @see https://github.com/isaacs/node-glob if ( ! isMultiPathModule && globPattern . test ( modulePath ) ) { var globModules = glob . sync ( modulePath , { cwd : modulesDirPath , nosort : true } ) ; // * -> <%= file => for backward capability var moduleNameTemplate = template ( moduleName . replace ( '*' , '<%= file %>' ) ) ; globModules . forEach ( function ( module ) { var moduleRealPath = path . join ( modulesDirPath , module ) , basename = path . basename ( moduleRealPath ) , fileParts = basename . split ( '.' ) , ext = fileParts . pop ( ) , file = fileParts . join ( '.' ) , dir = path . dirname ( moduleRealPath ) . split ( path . sep ) . reverse ( ) , subdir = createSubdirTemplateVariable ( modulesDirPath , moduleRealPath ) ; // modify module name using template var newModuleName = moduleNameTemplate ( { basename : basename , file : file , ext : ext , dir : dir , subdir : subdir } ) ; moduleExists = true ; try { moduleRealPath = fs . realpathSync ( moduleRealPath ) ; } catch ( e ) { moduleExists = false ; } moduleData = { originalModuleDesciptor : moduleDesciptor , name : newModuleName , path : moduleRealPath , originalPath : modulePath , lines : 0 , extra_exports : moduleExports , extra_require : moduleRequire , extra_bind : moduleBind , type_hint : moduleTypeHint , is_exists : moduleExists , is_third_party : isThirdPartyModule , is_lazy : moduleLazy , is_greedy : true , is_shortcut : false , is_coverage : isCoverage ( config , newModuleName ) , is_ignored : false , is_sandbox : moduleDesciptor . sandbox || false , is_multi_path_module : isMultiPathModule , depends : typeof moduleDesciptor . depends === \"undefined\" ? globalDepends : moduleDesciptor . depends } ; // wildcard have a low priority // if module was directly named it pass if ( ! ( modules [ newModuleName ] && ! modules [ newModuleName ] . is_greedy ) ) { modules [ newModuleName ] = moduleData ; } } ) ; } else if ( ! isMultiPathModule && / ^@ / . test ( modulePath ) ) { // shortcut modules [ moduleName ] = { originalModuleDesciptor : moduleDesciptor , name : moduleName , originalPath : modulePath , lines : 0 , path : modulePath , extra_exports : moduleExports , extra_require : moduleRequire , extra_bind : moduleBind , type_hint : moduleTypeHint , is_exists : true , is_third_party : isThirdPartyModule , is_lazy : moduleLazy , is_greedy : false , is_shortcut : true , is_coverage : false , is_ignored : false , is_sandbox : moduleDesciptor . sandbox || false , is_multi_path_module : isMultiPathModule , depends : typeof moduleDesciptor . depends === \"undefined\" ? globalDepends : moduleDesciptor . depends } ; } else if ( modulePath === null ) { modules [ moduleName ] = { originalModuleDesciptor : moduleDesciptor , name : moduleName , originalPath : modulePath , lines : 0 , path : modulePath , extra_exports : moduleExports , extra_require : moduleRequire , extra_bind : moduleBind , type_hint : moduleTypeHint , is_exists : true , is_third_party : false , is_lazy : false , is_greedy : false , is_shortcut : false , is_coverage : false , is_ignored : true , is_sandbox : false , is_multi_path_module : false , depends : globalDepends } ; } else { modulePath = [ ] . concat ( modulePath ) ; moduleExists = true ; moduleRealPath = modulePath . map ( function ( modulePath ) { return path . join ( modulesDirPath , modulePath ) ; } ) . map ( function ( moduleRealPath ) { try { return fs . realpathSync ( moduleRealPath ) ; } catch ( e ) { moduleExists = false ; } return moduleRealPath ; } ) ; // normal name // \"name\": \"name.js\" modules [ moduleName ] = { originalModuleDesciptor : moduleDesciptor , name : moduleName , path : isMultiPathModule ? moduleRealPath : moduleRealPath [ 0 ] , originalPath : isMultiPathModule ? modulePath : modulePath [ 0 ] , lines : 0 , extra_exports : moduleExports , extra_require : moduleRequire , extra_bind : moduleBind , type_hint : moduleTypeHint , is_exists : moduleExists , is_third_party : isThirdPartyModule , is_lazy : moduleLazy , is_greedy : false , is_shortcut : false , // Cant use code coverage with multi path module is_coverage : ! isMultiPathModule && isCoverage ( config , moduleName ) , is_ignored : false , is_sandbox : moduleDesciptor . sandbox || false , is_multi_path_module : isMultiPathModule , depends : typeof moduleDesciptor . depends === \"undefined\" ? globalDepends : moduleDesciptor . depends } ; } } return modules ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for non - lmd modules files [CODESPLIT] function ( code , options ) { var exports = [ ] , requires = [ ] , bind = [ ] , extra_exports = options . extra_exports , extra_require = options . extra_require , extra_bind = options . extra_bind , exportCode , bindModuleName ; // add exports to the module end // extra_exports = {name: code, name: code} if ( typeof extra_exports === \"object\" ) { for ( var exportName in extra_exports ) { exportCode = extra_exports [ exportName ] ; exports . push ( '    ' + JSON . stringify ( exportName ) + ': ' + exportCode ) ; } code += '\\n\\n/* added by builder */\\nreturn {\\n' + exports . join ( ',\\n' ) + '\\n};' ; } else if ( extra_exports ) { // extra_exports = string code += '\\n\\n/* added by builder */\\nreturn ' + extra_exports + ';' ; } // change context of module (this) // and proxy return value // return function(){}.call({name: require('name')}); if ( typeof extra_bind === \"object\" ) { for ( var bindName in extra_bind ) { bindModuleName = extra_bind [ bindName ] ; bind . push ( '    ' + JSON . stringify ( bindName ) + ': require(' + JSON . stringify ( bindModuleName ) + ')' ) ; } code = '\\nreturn function(){\\n\\n' + code + '\\n}.call({\\n' + bind . join ( ',\\n' ) + '\\n});' ; } else if ( extra_bind ) { // return function(){}.call(require('name')); code = '\\nreturn function(){\\n\\n' + code + '\\n}.call(require(' + JSON . stringify ( extra_bind ) + '));' ; } // add require to the module start if ( typeof extra_require === \"object\" ) { // extra_require = [name, name, name] if ( extra_require instanceof Array ) { for ( var i = 0 , c = extra_require . length , moduleName ; i < c ; i ++ ) { moduleName = extra_require [ i ] ; requires . push ( 'require(' + JSON . stringify ( moduleName ) + ');' ) ; } code = '/* added by builder */\\n' + requires . join ( '\\n' ) + '\\n\\n' + code ; } else { // extra_require = {name: name, name: name} for ( var localName in extra_require ) { moduleName = extra_require [ localName ] ; requires . push ( localName + ' = require(' + JSON . stringify ( moduleName ) + ')' ) ; } code = '/* added by builder */\\nvar ' + requires . join ( ',\\n    ' ) + ';\\n\\n' + code ; } } else if ( extra_require ) { // extra_require = string code = '/* added by builder */\\nrequire(' + JSON . stringify ( extra_require ) + ');\\n\\n' + code ; } return '(function (require) { /* wrapped by builder */\\n' + code + '\\n})' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Aggregates all module wrappers [CODESPLIT] function ( code , moduleOptions , moduleType ) { switch ( moduleType ) { case \"3-party\" : // create lmd module from non-lmd module code = wrap3partyModule ( code , moduleOptions ) ; break ; case \"plain\" : // wrap plain module code = wrapPlainModule ( code ) ; break ; case \"amd\" : // AMD RequireJS code = wrapAmdModule ( code ) ; break ; case \"fd\" : case \"fe\" : // wipe tail ; code = removeTailSemicolons ( code ) ; } return code ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks module type [CODESPLIT] function getModuleType ( code ) { var ast ; if ( typeof code === \"object\" ) { ast = code ; } else { try { JSON . parse ( code ) ; return \"json\" ; } catch ( e ) { } try { ast = parser . parse ( code ) ; } catch ( e ) { return \"string\" ; } } // Empty module if ( ast . length === 2 && ! ast [ 1 ] . length && ast [ 0 ] === 'toplevel' ) return \"plain\" ; // [\"toplevel\",[[\"defun\",\"depA\",[\"require\"],[]]]] if ( ast && ast . length === 2 && ast [ 1 ] && ast [ 1 ] . length === 1 && ast [ 1 ] [ 0 ] [ 0 ] === \"defun\" ) { return \"fd\" ; } // [\"toplevel\",[[\"stat\",[\"function\",null,[\"require\"],[]]]]] if ( ast && ast . length === 2 && ast [ 1 ] && ast [ 1 ] . length === 1 && ast [ 1 ] [ 0 ] [ 0 ] === \"stat\" && ast [ 1 ] [ 0 ] [ 1 ] && ast [ 1 ] [ 0 ] [ 1 ] [ 0 ] === \"function\" ) { return \"fe\" ; } if ( ast ) { var isAmd = ast [ 1 ] . every ( function ( ast ) { return ast [ 0 ] === \"stat\" && ast [ 1 ] [ 0 ] === \"call\" && ast [ 1 ] [ 1 ] [ 0 ] === \"name\" && ast [ 1 ] [ 1 ] [ 1 ] === \"define\" ; } ) ; if ( isAmd ) { return \"amd\" ; } } return \"plain\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param { String } lmdDir @param { String } shortName [CODESPLIT] function getModuleFileByShortName ( lmdDir , shortName ) { var files ; try { files = fs . readdirSync ( lmdDir ) ; } catch ( e ) { return void 0 ; } for ( var i = 0 , c = files . length , fileName ; i < c ; i ++ ) { fileName = files [ i ] ; var fileExtension = ( fileName . match ( reLmdFile ) || 0 ) [ 0 ] ; if ( fileExtension && path . basename ( fileName , fileExtension ) === shortName ) { return fileName ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute x - scale and normalize the first row . Compute shear and make second row orthogonal to first . Compute y - scale and normalize the second row . Finally compute the rotation . [CODESPLIT] function d3_transform ( m ) { var r0 = [ m . a , m . b ] , r1 = [ m . c , m . d ] , kx = d3_transformNormalize ( r0 ) , kz = d3_transformDot ( r0 , r1 ) , ky = d3_transformNormalize ( d3_transformCombine ( r1 , r0 , - kz ) ) ; this . translate = [ m . e , m . f ] ; this . rotate = Math . atan2 ( m . b , m . a ) * d3_transformDegrees ; this . scale = [ kx , ky || 0 ] ; this . skew = ky ? kz / ky * d3_transformDegrees : 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the specified array of data into an array of points ( x - y tuples ) by evaluating the specified x and y functions on each data point . The this context of the evaluated functions is the specified self object ; each function is passed the current datum and index . [CODESPLIT] function d3_svg_linePoints ( self , d , x , y ) { var points = [ ] , i = - 1 , n = d . length , fx = typeof x === \"function\" , fy = typeof y === \"function\" , value ; if ( fx && fy ) { while ( ++ i < n ) points . push ( [ x . call ( self , value = d [ i ] , i ) , y . call ( self , value , i ) ] ) ; } else if ( fx ) { while ( ++ i < n ) points . push ( [ x . call ( self , d [ i ] , i ) , y ] ) ; } else if ( fy ) { while ( ++ i < n ) points . push ( [ x , y . call ( self , d [ i ] , i ) ] ) ; } else { while ( ++ i < n ) points . push ( [ x , y ] ) ; } return points ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO Allow control point to be customized . [CODESPLIT] function chord ( d , i ) { var s = subgroup ( this , source , d , i ) , t = subgroup ( this , target , d , i ) ; return \"M\" + s . p0 + arc ( s . r , s . p1 ) + ( equals ( s , t ) ? curve ( s . r , s . p1 , s . r , s . p0 ) : curve ( s . r , s . p1 , t . r , t . p0 ) + arc ( t . r , t . p1 ) + curve ( t . r , t . p1 , s . r , s . p0 ) ) + \"Z\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ x0 y0 ] [ x1 y1 ] [CODESPLIT] function brush ( g ) { var resizes = x && y ? [ \"n\" , \"e\" , \"s\" , \"w\" , \"nw\" , \"ne\" , \"se\" , \"sw\" ] : x ? [ \"e\" , \"w\" ] : y ? [ \"n\" , \"s\" ] : [ ] ; g . each ( function ( ) { var g = d3 . select ( this ) . on ( \"mousedown.brush\" , down ) , bg = g . selectAll ( \".background\" ) . data ( [ , ] ) , fg = g . selectAll ( \".extent\" ) . data ( [ , ] ) , tz = g . selectAll ( \".resize\" ) . data ( resizes , String ) , e ; // An invisible, mouseable area for starting a new brush. bg . enter ( ) . append ( \"svg:rect\" ) . attr ( \"class\" , \"background\" ) . style ( \"visibility\" , \"hidden\" ) . style ( \"pointer-events\" , \"all\" ) . style ( \"cursor\" , \"crosshair\" ) ; // The visible brush extent; style this as you like! fg . enter ( ) . append ( \"svg:rect\" ) . attr ( \"class\" , \"extent\" ) . style ( \"cursor\" , \"move\" ) ; // More invisible rects for resizing the extent. tz . enter ( ) . append ( \"svg:rect\" ) . attr ( \"class\" , function ( d ) { return \"resize \" + d ; } ) . attr ( \"width\" , 6 ) . attr ( \"height\" , 6 ) . style ( \"visibility\" , \"hidden\" ) . style ( \"pointer-events\" , brush . empty ( ) ? \"none\" : \"all\" ) . style ( \"cursor\" , function ( d ) { return d3_svg_brushCursor [ d ] ; } ) ; // Remove any superfluous resizers. tz . exit ( ) . remove ( ) ; // Initialize the background to fill the defined range. // If the range isn't defined, you can post-process. if ( x ) { e = d3_scaleExtent ( x . range ( ) ) ; bg . attr ( \"x\" , e [ 0 ] ) . attr ( \"width\" , e [ 1 ] - e [ 0 ] ) ; d3_svg_brushRedrawX ( g , extent ) ; } if ( y ) { e = d3_scaleExtent ( y . range ( ) ) ; bg . attr ( \"y\" , e [ 0 ] ) . attr ( \"height\" , e [ 1 ] - e [ 0 ] ) ; d3_svg_brushRedrawY ( g , extent ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "snapshot the local context for subsequent dispatch [CODESPLIT] function start ( ) { d3_behavior_dragEvent = event ; d3_behavior_dragEventTarget = d3 . event . target ; d3_behavior_dragTarget = this ; d3_behavior_dragArguments = arguments ; d3_behavior_dragOrigin = d3_behavior_dragPoint ( ) ; if ( origin ) { d3_behavior_dragOffset = origin . apply ( d3_behavior_dragTarget , d3_behavior_dragArguments ) ; d3_behavior_dragOffset = [ d3_behavior_dragOffset . x - d3_behavior_dragOrigin [ 0 ] , d3_behavior_dragOffset . y - d3_behavior_dragOrigin [ 1 ] ] ; } else { d3_behavior_dragOffset = [ 0 , 0 ] ; } d3_behavior_dragMoved = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "snapshot the local context for subsequent dispatch [CODESPLIT] function start ( ) { d3_behavior_zoomXyz = xyz ; d3_behavior_zoomExtent = extent ; d3_behavior_zoomDispatch = event . zoom ; d3_behavior_zoomEventTarget = d3 . event . target ; d3_behavior_zoomTarget = this ; d3_behavior_zoomArguments = arguments ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "store starting mouse location [CODESPLIT] function mousewheel ( ) { start . apply ( this , arguments ) ; if ( ! d3_behavior_zoomZooming ) d3_behavior_zoomZooming = d3_behavior_zoomLocation ( d3 . svg . mouse ( d3_behavior_zoomTarget ) ) ; d3_behavior_zoomTo ( d3_behavior_zoomDelta ( ) + xyz [ 2 ] , d3 . svg . mouse ( d3_behavior_zoomTarget ) , d3_behavior_zoomZooming ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "doubletap detection [CODESPLIT] function touchstart ( ) { start . apply ( this , arguments ) ; var touches = d3_behavior_zoomTouchup ( ) , touch , now = Date . now ( ) ; if ( ( touches . length === 1 ) && ( now - d3_behavior_zoomLast < 300 ) ) { d3_behavior_zoomTo ( 1 + Math . floor ( xyz [ 2 ] ) , touch = touches [ 0 ] , d3_behavior_zoomLocations [ touch . identifier ] ) ; } d3_behavior_zoomLast = now ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "detect the pixels that would be scrolled by this wheel event [CODESPLIT] function d3_behavior_zoomDelta ( ) { // mousewheel events are totally broken! // https://bugs.webkit.org/show_bug.cgi?id=40441 // not only that, but Chrome and Safari differ in re. to acceleration! if ( ! d3_behavior_zoomDiv ) { d3_behavior_zoomDiv = d3 . select ( \"body\" ) . append ( \"div\" ) . style ( \"visibility\" , \"hidden\" ) . style ( \"top\" , 0 ) . style ( \"height\" , 0 ) . style ( \"width\" , 0 ) . style ( \"overflow-y\" , \"scroll\" ) . append ( \"div\" ) . style ( \"height\" , \"2000px\" ) . node ( ) . parentNode ; } var e = d3 . event , delta ; try { d3_behavior_zoomDiv . scrollTop = 1000 ; d3_behavior_zoomDiv . dispatchEvent ( e ) ; delta = 1000 - d3_behavior_zoomDiv . scrollTop ; } catch ( error ) { delta = e . wheelDelta || ( - e . detail * 5 ) ; } return delta * .005 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Note : Since we don t rotate it s possible for the touches to become slightly detached from their original positions . Thus we recompute the touch points on touchend as well as touchstart! [CODESPLIT] function d3_behavior_zoomTouchup ( ) { var touches = d3 . svg . touches ( d3_behavior_zoomTarget ) , i = - 1 , n = touches . length , touch ; while ( ++ i < n ) d3_behavior_zoomLocations [ ( touch = touches [ i ] ) . identifier ] = d3_behavior_zoomLocation ( touch ) ; return touches ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cases : ( { main } { modules } { options } ) ( { modules } { options } ) ( { modules } ) [CODESPLIT] function ( _main , _modules , _modules_options ) { if ( typeof _main === \"object\" ) { _modules_options = _modules ; _modules = _main ; } for ( var moduleName in _modules ) { // if already initialized - skip if ( moduleName in sb . modules ) { continue ; } // declare new modules sb . modules [ moduleName ] = _modules [ moduleName ] ; sb . initialized [ moduleName ] = 0 ; // declare module options if ( _modules_options && moduleName in _modules_options ) { sb . modules_options [ moduleName ] = _modules_options [ moduleName ] ; } } if ( typeof _main === \"function\" ) { var output = { 'exports' : { } } ; _main ( sb . trigger ( 'lmd-register:decorate-require' , \"<bundle:main>\" , sb . require ) [ 1 ] , output . exports , output ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LMD require . js () and shortcuts example [CODESPLIT] function drawImageOnCanvas ( img ) { var ctx = $ ( 'canvas' ) [ 0 ] . getContext ( '2d' ) ; ctx . drawImage ( img , 0 , 0 ) ; ctx . rotate ( - Math . PI / 12 ) ; ctx . translate ( 0 , 150 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats lmd config [CODESPLIT] function ( data ) { var config ; // case data is argv string if ( typeof data === \"string\" ) { // try to parse new version config = parseArgv ( data ) ; // its new config argv string if ( Object . keys ( config ) . length ) { // translate short params to long one config . mode = config . mode || config . m ; config . output = config . output || config . o ; config . log = config . log || config . l ; config . config = config . config || config . c ; config [ 'no-warn' ] = config [ 'no-warn' ] || config [ 'no-w' ] ; config [ 'source-map' ] = config [ 'source-map' ] || config [ 'sm' ] ; config [ 'source-map-root' ] = config [ 'source-map-root' ] || config [ 'sm-root' ] ; config [ 'source-map-www' ] = config [ 'source-map-www' ] || config [ 'sm-www' ] ; config [ 'source-map-inline' ] = config [ 'source-map-inline' ] || config [ 'sm-inline' ] ; } else { // an old argv format, split argv and parse manually data = data . split ( ' ' ) ; // without mode if ( availableModes . indexOf ( data [ 2 ] ) === - 1 ) { config = { mode : 'main' , config : data [ 2 ] , output : data [ 3 ] } ; } else { // with mode config = { mode : data [ 2 ] , config : data [ 3 ] , output : data [ 4 ] } ; } } // case data is config object } else if ( typeof config === \"object\" ) { // use as is config = data ; // case else } else { // wut? throw new Error ( 'Bad config data' ) ; } config . mode = config . mode || 'main' ; config . warn = ! config [ 'no-warn' ] ; config . sourcemap = config [ 'source-map' ] || false ; config . www_root = config [ 'source-map-root' ] || \"\" ; config . sourcemap_www = config [ 'source-map-www' ] || \"\" ; config . sourcemap_inline = config [ 'source-map-inline' ] || false ; config . log = config . log || false ; return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the urlNode is still current ( not stale ) by sitemap policy . If both lastmod and changefreq tags are supplied both are used . If only one of lastmod or changefreq are supplied then they are compared against previous output if it exists . If a test fails for any reason it is characterized as stale ( returns false ) . [CODESPLIT] function stillCurrent ( urlNode , options ) { var lesser , greater , oPath ; var now = Date . now ( ) ; var lMod = _ . first ( urlNode . lastmod ) ; var cFreq = _ . first ( urlNode . changefreq ) ? _ . first ( urlNode . changefreq ) . toLowerCase ( ) : null ; // only lastmod specified if ( lMod && ! cFreq ) { // if sitemap is malformed, just blow up oPath = base . outputFile ( options , urlNode . loc [ 0 ] ) ; lesser = now - ( ( fs . existsSync ( oPath ) && fs . statSync ( oPath ) . mtime . getTime ( ) ) || unixStart ) ; greater = now - Date . parse ( lMod ) ; } // only changefreq specified else if ( ! lMod && cFreq ) { // if sitemap is malformed, just blow up oPath = base . outputFile ( options , urlNode . loc [ 0 ] ) ; lesser = now - ( ( fs . existsSync ( oPath ) && fs . statSync ( oPath ) . mtime . getTime ( ) ) || unixStart ) ; greater = changeFreq [ cFreq ] || changeFreq . always ; } // both or neither were specified else { lesser = now - Date . parse ( lMod || unixStart ) ; greater = changeFreq [ cFreq ] || changeFreq . always ; } return lesser <= greater ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a sitemap document For each qualifying url element in urlset call base . input Stops processing if an error occurs . [CODESPLIT] function parse ( options , document , callback ) { xml2js . parseString ( document , { trim : true , normalizeTags : true , normalize : true } , function ( err , result ) { var source = options . source ; if ( ! err ) { // Process the url input, but break if base.input returns false. //   In other words, _.find is looking for a non-falsy err. // For now, this can only happen if no outputDir is defined, //   which is a fatal bad option problem and will happen immediately. _ . find ( // if the sitemap is malformed, just blow up result . urlset . url , function ( urlNode ) { // optionally ignore current urls by sitemap policy var url , process = ! options . sitemapPolicy || ! stillCurrent ( urlNode , options ) ; if ( process ) { // if sitemap is malformed, just blow up url = urlm . parse ( urlNode . loc [ 0 ] ) ; if ( ! base . input ( _ . extend ( { } , options , { protocol : url . protocol , auth : url . auth , hostname : url . hostname , port : url . port } ) , urlNode . loc [ 0 ] ) ) { source = urlNode . loc [ 0 ] ; err = base . generatorError ( ) ; } } return err ; } ) ; } callback ( common . prependMsgToErr ( err , source , true ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert Buffer input call next or callback with error [CODESPLIT] function convert ( options , buffer , next , callback ) { var gunzip = path . extname ( options . source ) === \".gz\" ; if ( gunzip ) { zlib . gunzip ( buffer , function ( err , result ) { if ( err ) { callback ( common . prependMsgToErr ( err , options . source , true ) ) ; } else { next ( options , result && result . toString ( ) , callback ) ; } } ) ; } else { next ( options , buffer . toString ( ) , callback ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the sitemap from a url and call to parse it . [CODESPLIT] function getUrl ( options , parseFn , callback ) { request ( { url : options . source , encoding : null , timeout : options . timeout ( ) // get the default timeout } , function ( err , res , body ) { var error = err || common . checkResponse ( res , [ \"text/xml\" , \"application/xml\" ] ) ; if ( error ) { callback ( common . prependMsgToErr ( error , options . source , true ) ) ; } else { convert ( options , body , parseFn , callback ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the sitemap from a file and call to parse it . [CODESPLIT] function getFile ( options , parseFn , callback ) { fs . readFile ( options . source , function ( err , data ) { if ( err ) { callback ( common . prependMsgToErr ( err , options . source , true ) ) ; } else { convert ( options , data , parseFn , callback ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "command line argument handling for selector based snapshot scripts args : PHANTOM_SCRIPT OUTPUTFILE URL SELECTOR [ TIMEOUT INTERVAL USEJQUERY FILTER ] [CODESPLIT] function ( ) { var options = { } ; var defaults = { // outputFile (required) // The file to write the snapshot to // encoding is the same as served from url outputFile : \"snapshot.html\" , // url (required) // The url to produce the snapshot from url : \"http://localhost/\" , // selector (required) // The selector to wait for before taking the snapshot // When the selector is visible, this defines document readiness selector : \"body\" , // timeout (optional) // The maximum amount of time (ms) to wait before giving up on the snapshot timeout : 10000 , // checkInterval (optional) // The frequency (ms) to check for document readiness checkInterval : 250 , // useJQuery (optional) // flag to indicate use jQuery selector or not. jQuery must already exist in page. useJQuery : false , // verbose (optional) // flag to indicate verbose output is desired. verbose : false // module (optional) // An external module to load // (default undefined) } ; if ( system . args . length < 4 ) { globals . exit ( 3 , \"phantomjs script '\" + system . args [ 0 ] + \"' expected these arguments: OUTPUTFILE URL SELECTOR [TIMEOUT INTERVAL JQUERY MODULE]\" ) ; } else { options . outputFile = system . args [ 1 ] ; options . url = system . args [ 2 ] ; options . selector = system . args [ 3 ] ; if ( system . args [ 4 ] ) { options . timeout = parseInt ( system . args [ 4 ] , 10 ) ; } if ( system . args [ 5 ] ) { options . checkInterval = parseInt ( system . args [ 5 ] , 10 ) ; } if ( system . args [ 6 ] ) { var useJQuery = system . args [ 6 ] . toLowerCase ( ) ; options . useJQuery = ( useJQuery === \"true\" || useJQuery === \"yes\" || useJQuery === \"1\" ) ; } if ( system . args [ 7 ] ) { var verbose = system . args [ 7 ] . toLowerCase ( ) ; options . verbose = ( verbose === \"true\" || verbose === \"yes\" || verbose === \"1\" ) ; } if ( system . args [ 8 ] && system . args [ 8 ] !== \"undefined\" ) { options . module = system . args [ 8 ] ; } // ensure defaults, replaces false with false in two cases (useJQuery, verbose) Object . keys ( defaults ) . forEach ( function ( prop ) { if ( ! options [ prop ] ) { options [ prop ] = defaults [ prop ] ; } } ) ; } return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that options at least contains propties and values from must if they re not already defined and not null . Differs from underscore by replacing undefined * or null * falsies and only one defaults source allowed . [CODESPLIT] function ( options , must ) { if ( must ) { for ( var prop in must ) { if ( options [ prop ] === void 0 || options [ prop ] === null ) { options [ prop ] = must [ prop ] ; } } } return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepend a message to an Error message . [CODESPLIT] function ( error , message , quoteInput ) { var result , prepend , empty = \"\" , quote = \"'\" ; if ( error ) { if ( message ) { prepend = quoteInput ? empty . concat ( quote , message , quote ) : message ; } // Force Error instance, coerce given error to a string error = error instanceof Error ? error : new Error ( empty + error ) ; // If message supplied, prepend it error . message = prepend ? empty . concat ( prepend , \": \" , error . message ) : error . message ; result = error ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simple response checker for remote files . Expected use in robots . txt or sitemap . xml only . [CODESPLIT] function ( res , mediaTypes ) { var contentTypeOk , result = \"status: '\" + res . statusCode + \"', GET failed.\" ; mediaTypes = ! Array . isArray ( mediaTypes ) ? [ mediaTypes ] : mediaTypes ; if ( res . statusCode === 200 ) { // if content-type exists, and media type found then contentTypeOk contentTypeOk = res . headers [ \"content-type\" ] && // empty array and none found return true ! mediaTypes . every ( function ( mediaType ) { // flip -1 to 0 and NOT, so that true == NOT found, found stops loop w/false return ! ~ res . headers [ \"content-type\" ] . indexOf ( mediaType ) ; } ) ; result = contentTypeOk ? \"\" : \"content-type not one of '\" + mediaTypes . join ( \",\" ) + \"'\" ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility to promisify a Node function [CODESPLIT] function nodeCall ( nodeFunc /* args... */ ) { var nodeArgs = Array . prototype . slice . call ( arguments , 1 ) ; return new Promise ( function ( resolve , reject ) { /**\n     * Resolve a node callback\n     */ function nodeResolver ( err , value ) { if ( err ) { reject ( err ) ; } else { resolve ( value ) ; } } nodeArgs . push ( nodeResolver ) ; nodeFunc . apply ( nodeFunc , nodeArgs ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make sure path exists so a sitemap write can succeed . [CODESPLIT] function prepareWrite ( outputPath , callback ) { var path = pathLib . parse ( outputPath ) ; var dir = pathLib . join ( path . root , path . dir ) ; mkdirp ( dir , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a sitemap generate input and optionally update the local file for sitemapPolicy purposes . This writes the sitemap files out EVEN IF sitemapPolicy is false . The thinking is that it s better / cheaper to do this b / c if sitemapPolicy is enabled later then there is something to compare against for more savings . [CODESPLIT] function processSitemap ( options , document , callback ) { smLib . parse ( options , document , function ( err ) { var sitemapIndexOpts = options . __sitemapIndex ; var outputPath = base . outputFile ( sitemapIndexOpts , options . source ) ; if ( ! err && sitemapIndexOpts . sitemapOutputDir ) { prepareWrite ( outputPath , function ( err ) { if ( ! err ) { fs . writeFile ( outputPath , document , callback ) ; } else { callback ( common . prependMsgToErr ( err , outputPath , true ) ) ; } } ) ; } else { callback ( err ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a sitemap index document For each qualifying sitemap element download parse the sitemap . Stops processing if an error occurs . [CODESPLIT] function parse ( options , document , callback ) { xml2js . parseString ( document , { trim : true , normalizeTags : true , normalize : true } , function ( err , result ) { var sitemapUrls = [ ] ; var sitemapIndexOptions = Object . assign ( { } , options , { outputPath : undefined } ) ; if ( ! err ) { // Check if we should process each sitemap in the index. _ . forEach ( // if the sitemap index is malformed, just blow up result . sitemapindex . sitemap , function ( sitemapNode ) { // optionally ignore current sitemaps by sitemap policy var shouldProcess = ! options . sitemapPolicy || ! smLib . stillCurrent ( sitemapNode , sitemapIndexOptions ) ; if ( shouldProcess ) { // if sitemap index is malformed, just blow up sitemapUrls . push ( sitemapNode . loc [ 0 ] ) ; } } ) ; // Edge case message for clarity if ( sitemapUrls . length === 0 ) { console . log ( \"[*] No sitemaps qualified for processing\" ) ; } // Get all the sitemaps, parse them, and generate input for each Promise . all ( sitemapUrls . map ( function ( sitemapUrl ) { var sitemapOptions = Object . assign ( { } , options , { source : sitemapUrl , input : \"sitemap\" , sitemapOutputDir : false , __sitemapIndex : sitemapIndexOptions } ) ; console . log ( \"[+] Loading the sitemap: '\" + sitemapUrl + \"'\" ) ; return nodeCall ( smLib . getUrl , sitemapOptions , processSitemap ) ; } ) ) . then ( function ( ) { // Ignore the array of results to this function callback ( ) ; } ) . catch ( callback ) ; } else { callback ( err ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generateInput [CODESPLIT] function generateInput ( options ) { return nodeCall ( common . isUrl ( options . source ) ? smLib . getUrl : smLib . getFile , options , parse ) . catch ( function ( err ) { options . _abort ( err ) ; } ) . then ( function ( ) { base . EOI ( sitemapIndex ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the input arguments for snapshots from a robots . txt file . Each input argument generated calls the listener passing the input object . [CODESPLIT] function ( options , listener ) { var opts = Object . assign ( { } , base . defaults ( defaults ) , options ) ; return base . run ( opts , generateInput , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the snapshot arguments from a line oriented text file . Each line contains a single url we need a snapshot for . [CODESPLIT] function generateInput ( options ) { return nodeCall ( fs . readFile , options . source ) . catch ( function ( err ) { options . _abort ( err ) ; } ) . then ( function ( data ) { var error ; if ( data ) { data . toString ( ) . split ( '\\n' ) . every ( function ( line ) { var page = line . replace ( / ^\\s+|\\s+$ / g , \"\" ) ; if ( ! base . input ( options , page ) ) { error = common . prependMsgToErr ( base . generatorError ( ) , page , true ) ; return false ; } return true ; } ) ; if ( error ) { console . error ( error ) ; options . _abort ( error ) ; } } base . EOI ( textfile ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the snapshot arguments from an array of pages . Stops processing if one fails . [CODESPLIT] function generateInput ( options ) { var result = new Promise ( function ( resolve , reject ) { var all ; if ( Array . isArray ( options . source ) ) { all = options . source . every ( function ( sourceUrl ) { var url = urlm . parse ( sourceUrl ) ; var opts = Object . assign ( { } , options , { protocol : url . protocol , auth : url . auth , hostname : url . hostname , port : url . port } ) ; if ( ! base . input ( opts , sourceUrl ) ) { reject ( common . prependMsgToErr ( base . generatorError ( ) , sourceUrl , true ) ) ; return false ; } return true ; } ) ; if ( all ) { resolve ( ) ; } } else { reject ( new Error ( \"options.source must be an array\" ) ) ; } } ) ; return result . catch ( function ( error ) { options . _abort ( error ) ; } ) . then ( function ( ) { base . EOI ( array ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decorate the given WebPage with handlers to produce verbose output . Source : https : // newspaint . wordpress . com / 2013 / 04 / 25 / getting - to - the - bottom - of - why - a - phantomjs - page - load - fails / [CODESPLIT] function verbose ( page ) { page . onResourceError = function ( resourceError ) { system . stderr . writeLine ( '= onResourceError()' ) ; system . stderr . writeLine ( '  - unable to load url: \"' + resourceError . url + '\"' ) ; system . stderr . writeLine ( '  - error code: ' + resourceError . errorCode + ', description: ' + resourceError . errorString ) ; } ; page . onError = function ( msg , trace ) { system . stderr . writeLine ( '= onError()' ) ; var msgStack = [ '  ERROR: ' + msg ] ; if ( trace ) { msgStack . push ( '  TRACE:' ) ; trace . forEach ( function ( t ) { msgStack . push ( '    -> ' + t . file + ': ' + t . line + ( t . function ? ' (in function \"' + t . function + '\")' : '' ) ) ; } ) ; } system . stderr . writeLine ( msgStack . join ( '\\n' ) ) ; } ; page . onResourceRequested = function ( request ) { system . stderr . writeLine ( '= onResourceRequested()' ) ; system . stderr . writeLine ( '  request: ' + JSON . stringify ( request , undefined , 4 ) ) ; } ; page . onResourceReceived = function ( response ) { system . stderr . writeLine ( '= onResourceReceived()' ) ; system . stderr . writeLine ( '  id: ' + response . id + ', stage: \"' + response . stage + '\", response: ' + JSON . stringify ( response ) ) ; } ; page . onLoadStarted = function ( ) { system . stderr . writeLine ( '= onLoadStarted()' ) ; var currentUrl = page . evaluate ( function ( ) { return window . location . href ; } ) ; system . stderr . writeLine ( '  leaving url: ' + currentUrl ) ; } ; page . onNavigationRequested = function ( url , type , willNavigate , main ) { system . stderr . writeLine ( '= onNavigationRequested' ) ; system . stderr . writeLine ( '  destination_url: ' + url ) ; system . stderr . writeLine ( '  type (cause): ' + type ) ; system . stderr . writeLine ( '  will navigate: ' + willNavigate ) ; system . stderr . writeLine ( '  from page\\'s main frame: ' + main ) ; } ; page . onLoadFinished = function ( status ) { system . stderr . writeLine ( '= onLoadFinished()' ) ; system . stderr . writeLine ( '  status: ' + status ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create Creates the input generator based on the input string which must match a js file in this directory . So if input === robots then executes require ( . / robots ) ; Unsupported input generator types return a null generator . [CODESPLIT] function ( input ) { var result = { run : function ( ) { return [ ] ; } , __null : true } , hasInput ; if ( input ) { input = ( \"\" + input ) . replace ( \" \" , \"\" ) . toLowerCase ( ) ; hasInput = input && input . charAt ( 0 ) !== '_' && input !== \"index\" ; } try { if ( hasInput ) { result = require ( \"./\" + input ) ; } } catch ( e ) { console . error ( \"Input generator load failed '\" + input + \"'\" , e ) /* return the \"null\" generator on error */ } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize the given object to a function . [CODESPLIT] function normalize ( obj ) { var result = obj ; if ( typeof obj !== \"function\" ) { if ( typeof obj !== \"undefined\" ) { if ( Object . prototype . toString . call ( obj ) !== \"[object Object]\" ) { result = ( function ( value ) { return function ( ) { return value ; } ; } ( obj ) ) ; } else { result = ( function ( o ) { return function ( key , passthru ) { if ( o [ key ] === void 0 ) { return o . __default || ( passthru ? key : undefined ) ; } else { return o [ key ] ; } } ; } ( obj ) ) ; } } else { result = function ( passthru ) { return passthru ; } ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a normalized option was overriden but a default still undefined supply one . The result could still be undefined but only if the default is undefined . [CODESPLIT] function supplyMissingDefault ( options , name ) { if ( options [ name ] ( ) === void 0 ) { options [ name ] = _ . wrap ( options [ name ] , function ( func , key ) { var res = func ( key ) ; return res === void 0 ? defaults [ name ] : res ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare options for use by an input generator . [CODESPLIT] function prepOptions ( options , listener ) { // Ensure defaults are represented common . ensure ( options , defaults ) ; // Normalize certain arguments if they are not functions. // The certain arguments are per-page options. // However, outputPath is a special case [ \"selector\" , \"timeout\" , \"useJQuery\" , \"verbose\" , \"phantomjsOptions\" ] . forEach ( function ( perPageOption ) { options [ perPageOption ] = normalize ( options [ perPageOption ] ) ; supplyMissingDefault ( options , perPageOption ) ; } ) ; options . _inputEmitter = new EventEmitter ( ) ; options . _inputEmitter . on ( \"input\" , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an output path for a page . [CODESPLIT] function getOutputPath ( options , page , parse ) { var pagePart = urlm . parse ( page ) , // if outputPath was normalized with an object, let the key passthru outputPath = options . outputPath ( page , true ) ; // check for bad output path if ( ! outputPath ) { return false ; } // if the outputPath is really still a url, fix it to path+hash if ( common . isUrl ( outputPath ) ) { outputPath = pagePart . path + ( pagePart . hash ? pagePart . hash : \"\" ) ; } // if the caller wants the url parse output, return it if ( parse ) { parse . url = pagePart ; } return outputPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Using the options map the given page to an output path . [CODESPLIT] function mapOutputFile ( options , page , parse ) { if ( ! _ . isFunction ( options . outputPath ) ) { options . outputPath = normalize ( options . outputPath ) ; } var outputPath = getOutputPath ( options , page , parse ) ; var outputDir = options . outputDir ; var fileName = \"index.html\" ; if ( options . sitemapOutputDir ) { outputDir = path . join ( options . outputDir , options . sitemapOutputDir ) ; fileName = \"\" ; } return ( outputPath && path . join ( outputDir , outputPath , fileName ) ) || false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the input generator . [CODESPLIT] function ( options , generator , listener ) { options = options || { } ; prepOptions ( options , listener ) ; return generator ( options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the input Emit the event that contains the input hash [CODESPLIT] function ( options , page ) { var parse = { } ; var outputFile = mapOutputFile ( options , page , parse ) ; if ( outputFile ) { options . _inputEmitter . emit ( \"input\" , { outputFile : outputFile , // make the url url : urlm . format ( { protocol : options . protocol , auth : options . auth , hostname : options . hostname , port : options . port , pathname : parse . url . pathname , search : parse . url . search , hash : parse . url . hash } ) , // map the input page to a selector selector : options . selector ( page ) , // map the input page to a timeout timeout : options . timeout ( page ) , checkInterval : options . checkInterval , // map the input page to a useJQuery flag useJQuery : options . useJQuery ( page ) , // map the input page to a verbose flag verbose : options . verbose ( page ) , // map the input page to phantomJS options phantomjsOptions : options . phantomjsOptions ( page ) , // useful for testing, debugging __page : page } ) ; } return outputFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a path exists . [CODESPLIT] function pathExists ( path , options ) { options = options || { returnFile : false } ; // Defaults to F_OK return nodeCall ( fs . access , path ) . then ( function ( ) { return options . returnFile ? path : true ; } ) . catch ( function ( ) { if ( fs . existsSync ( path ) ) { return options . returnFile ? path : true ; } return false ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the default phantomJS module path . This is overridden by the phatomjs option . [CODESPLIT] function ( ) { // If the path we're given by phantomjs is to a .cmd, it is pointing to a global copy. // Using the cmd as the process to execute causes problems cleaning up the processes // so we walk from the cmd to the phantomjs.exe and use that instead. var phantomSource = require ( \"phantomjs-prebuilt\" ) . path ; if ( path . extname ( phantomSource ) . toLowerCase ( ) === \".cmd\" ) { return path . join ( path . dirname ( phantomSource ) , \"//node_modules//phantomjs-prebuilt//lib//phantom//bin//phantomjs.exe\" ) ; } return phantomSource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The worker task that launches phantomjs . [CODESPLIT] function worker ( input , options , notifier , qcb ) { var cp , customModule , snapshotScript = options . snapshotScript , phantomjsOptions = Array . isArray ( input . phantomjsOptions ) ? input . phantomjsOptions : [ input . phantomjsOptions ] ; // If the outputFile has NOT already been seen by the notifier, process. if ( ! notifier . known ( input . outputFile ) ) { // map snapshotScript object script to a real path if ( _ . isObject ( options . snapshotScript ) ) { snapshotScript = path . join ( __dirname , phantomDir , options . snapshotScript . script ) + \".js\" ; customModule = options . snapshotScript . module ; } cp = spawn ( options . phantomjs , phantomjsOptions . concat ( [ snapshotScript , input . outputFile , input . url , input . selector , input . timeout , input . checkInterval , input . useJQuery , input . verbose , customModule ] ) , { cwd : process . cwd ( ) , stdio : \"inherit\" , detached : true } ) ; cp . on ( \"error\" , function ( e ) { notifier . remove ( input . outputFile ) ; notifier . setError ( e ) ; console . error ( e ) ; qcb ( e ) ; } ) ; cp . on ( \"exit\" , function ( code ) { qcb ( code ) ; } ) ; // start counting notifier . add ( input . outputFile , input . timeout ) ; } else { // The input.outputFile is being or has been processed this run. qcb ( 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare html snapshots options . [CODESPLIT] function prepOptions ( options ) { // ensure this module's defaults are represented in the options. common . ensure ( options , defaults ) ; // if array data source, ensure input type is \"array\". if ( Array . isArray ( options . source ) ) { options . input = \"array\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run all the snapshots using the requested inputGenerator [CODESPLIT] function ( options , listener ) { var inputGenerator , notifier , started , result , q , emitter , completion ; options = options || { } ; prepOptions ( options ) ; // create the inputGenerator, default to robots inputGenerator = inputFactory . create ( options . input ) ; // clean the snapshot output directory if ( options . outputDirClean ) { rimraf ( options . outputDir ) ; } // start async completion notification. notifier = new Notifier ( ) ; emitter = new EventEmitter ( ) ; started = notifier . start ( options . pollInterval , inputGenerator , function ( err , completed ) { emitter . emit ( \"complete\" , err , completed ) ; } ) ; if ( started ) { // create the completion Promise. completion = new Promise ( function ( resolve , reject ) { function completionResolver ( err , completed ) { try { _ . isFunction ( listener ) && listener ( err , completed ) ; } catch ( e ) { console . error ( \"User supplied listener exception\" , e ) ; } if ( err ) { err . notCompleted = notifier . filesNotDone ; err . completed = completed ; reject ( err ) ; } else { resolve ( completed ) ; } } emitter . addListener ( \"complete\" , completionResolver ) ; } ) ; // create a worker queue with a parallel process limit. q = asyncLib . queue ( function ( task , callback ) { task ( _ . once ( callback ) ) ; } , options . processLimit ) ; // have the queue call notifier.empty when last item //  from the queue is given to a worker. q . empty = notifier . qEmpty . bind ( notifier ) ; // expose abort callback to input generators via options. options . _abort = function ( err ) { notifier . abort ( q , err ) ; } ; // generate input for the snapshots. result = inputGenerator . run ( options , function ( input ) { // give the worker the input and place into the queue q . push ( _ . partial ( worker , input , options , notifier ) ) ; } ) // after input generation, resolve on browser completion. . then ( function ( ) { return completion ; } ) ; } else { result = Promise . reject ( \"failed to start async notifier\" ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the lock factory . [CODESPLIT] function createLockFactory ( ) { // Create the per instance async lock. var lock = new AsyncLock ( ) ; // Make a random id var rid = crypto . randomBytes ( 16 ) . toString ( \"hex\" ) ; /**\n   * Force a serial execution context.\n   *\n   * @param {Function} fn - The function to guard.\n   * @param {Number} timeout - The max time to wait for the lock.\n   */ return function lockFactory ( fn , timeout ) { return function protectedContext ( ) { lock . acquire ( \"cs-guard-\" + rid , function ( done ) { fn ( function ( ) { done ( null , 0 ) ; } ) ; } , NOOP , { timeout : timeout } ) ; } ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notifier Constructor Polls the outputDir and when all the files exist calls the listener indicating the snapshots are done . [CODESPLIT] function Notifier ( ) { // Create the serial execution context mechanism. this . csFactory = createLockFactory ( ) ; // The private files collection // Contains a file and timer: \"filename\": {timer: timerid} // Used for tracking work left to do. When empty, work is done. this . files = { } ; // Contains files successfully processed this . filesDone = [ ] ; // Contains files unsuccessfully processed this . filesNotDone = [ ] ; // true if a timeout occurred, or set by abort this . errors = [ ] ; // the holder of the current failure timeout padding this . padTimeout = TIMEOUT_PAD_FLOOR ; // our reference to the listener this . callback = null ; // our reference to the watcher (an interval id) // initial value undefined is important // this.watcher; // the working pollInterval for this run // this.interval // flag set by qEmpty callback // when the last item from the queue is given to a worker this . qempty = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start a watch interval when a file exists remove it from our files array . If the files array is empty call the listener and stop the watch interval . [CODESPLIT] function start ( pollInterval , input , listener ) { var result = ( pollInterval > 0 && typeof listener === \"function\" && ( ! ! input ) ) ; if ( result ) { if ( this . isStarted ( ) ) { throw new Error ( \"Notifier already started\" ) ; } this . callback = listener ; this . interval = parseInt ( pollInterval , 10 ) ; // Poll the filesystem for the files to exist // Checks the child process expected output to determine success or failure // if the file exists, then it succeeded. this . watcher = setInterval ( this . csFactory ( function ( done ) { var self = this ; var eoi = typeof input . EOI === \"function\" && input . EOI ( ) ; if ( eoi ) { Promise . all ( Object . keys ( self . files ) . map ( function ( file ) { return pathExists ( file , { returnFile : true } ) ; } ) ) . then ( function ( files ) { var callback = self . callback ; try { files . forEach ( function ( file ) { file && self . _remove ( file , true ) ; } ) ; if ( self . _isDone ( ) ) { self . _closeWatcher ( ) ; if ( self . callback ) { self . callback = null ; setImmediate ( function ( ) { callback ( self . getError ( ) , self . filesDone ) ; } ) ; } } } catch ( e ) { console . error ( e ) ; } done ( ) ; } ) ; } else { done ( ) ; } } . bind ( this ) , L_WAIT ) , this . interval ) ; } else { console . error ( \"Bad poll interval, async listener, or input generator supplied\" ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a file to the files array if it s not there . [CODESPLIT] function add ( outputFile , timeout ) { var failTimeout = timeout ; var timer ; if ( ! this . isStarted ( ) ) { throw new Error ( \"MUST call `start` before `add`\" ) ; } if ( ! this . _exists ( outputFile ) ) { // make sure we evaluate after the child process failTimeout = parseInt ( timeout , 10 ) + parseInt ( this . padTimeout , 10 ) ; // Stagger and grow the failure timeout padding, add 1s every 10 processes this . padTimeout += 100 ; // setup a timeout handler to detect failure timer = setTimeout ( this . csFactory ( function ( done ) { var self = this ; // if the output file has not already been removed if ( self . _exists ( outputFile ) ) { pathExists ( outputFile ) . then ( function ( fsExists ) { var callback = self . callback ; try { if ( ! fsExists ) { self . _setError ( new Error ( \"'\" + outputFile + \"' did not get a snapshot before timeout\" ) ) ; } self . _remove ( outputFile , fsExists ) ; if ( self . _isDone ( ) ) { self . _closeWatcher ( ) ; if ( self . callback ) { self . callback = null ; setImmediate ( function ( ) { callback ( self . getError ( ) , self . filesDone ) ; } ) ; } } } catch ( e ) { console . error ( e ) ; } done ( ) ; } ) ; } else { done ( ) ; } } . bind ( this ) , L_WAIT ) , parseInt ( failTimeout , 10 ) ) ; // add the file tracking object this . files [ outputFile ] = { timer : timer } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a file is being processed or has already been processed . [CODESPLIT] function known ( outputFile ) { var result = false ; this . csFactory ( function ( done ) { result = this . _exists ( outputFile ) || this . filesDone . indexOf ( outputFile ) > - 1 ; done ( ) ; } . bind ( this ) , L_WAIT ) ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a file from the files array if it s there . Unprotected version . [CODESPLIT] function _remove ( outputFile , done ) { if ( this . _exists ( outputFile ) ) { if ( done ) { this . filesDone . push ( outputFile ) ; } else { this . filesNotDone . push ( outputFile ) ; } clearTimeout ( this . files [ outputFile ] . timer ) ; delete this . files [ outputFile ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a file from the files array if it s there . Protected version . [CODESPLIT] function remove ( outputFile , done ) { this . csFactory ( function ( _done ) { this . _remove ( outputFile , done ) ; _done ( ) ; } . bind ( this ) , L_WAIT ) ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a way to abort what this is doing . Causes conditions so that if isStarted the poll interval will exit cleanup and call the listener back . If not started the listener does not get called . This relationship is set in html - snapshots . js : listener == notifier . start [CODESPLIT] function abort ( q , err ) { this . csFactory ( function ( done ) { try { // for each file, clearTimeout and delete the object Object . keys ( this . files ) . forEach ( function ( file ) { clearTimeout ( this . files [ file ] . timer ) ; delete this . files [ file ] ; } , this ) ; // if nothing is waiting, make sure empty is set this . qempty = ! q . length ( ) ; // set the error this . _setError ( err ) ; } catch ( e ) { console . error ( e ) ; } done ( ) ; } . bind ( this ) , L_WAIT ) ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "waitFor [CODESPLIT] function waitFor ( testFx , onReady , onTimeout , timeout , checkInterval ) { var condition = false , interval = setInterval ( function ( ) { if ( ( new Date ( ) . getTime ( ) - start < timeout ) && ! condition ) { // If not timeout yet and condition not yet fulfilled condition = testFx ( ) ; } else { clearInterval ( interval ) ; // Stop this interval if ( ! condition ) { // If condition still not fulfilled (timeout but condition is 'false') onTimeout ( ) ; } else { // Condition fulfilled (timeout and/or condition is 'true') onReady ( ( new Date ( ) . getTime ( ) - start ) ) ; } } } , checkInterval ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "snapshot [CODESPLIT] function snapshot ( options , detector , filter ) { filter = filter || function ( content ) { return content ; } ; console . log ( \"Creating snapshot for \" + options . url + \"...\" ) ; // https://github.com/ariya/phantomjs/issues/10930 page . customHeaders = { \"Accept-Encoding\" : \"identity\" } ; // add optional verbose output if ( options . verbose ) { verbose ( page ) ; } // create the snapshot page . open ( options . url , { resourceTimeout : options . timeout - 300 // a little space to report problems. } , function ( status ) { if ( status !== \"success\" ) { // if phantomJS could not load the page, so end right now globals . exit ( 2 , \"Unable to load page \" + options . url ) ; } else { // phantomJS loaded the page, so wait for it to be ready waitFor ( // The test to determine readiness function ( ) { return page . evaluate ( detector , { selector : options . selector , url : options . url } ) ; } , // The onReady callback function ( time ) { fs . write ( options . outputFile , filter ( page . content ) , \"w\" ) ; globals . exit ( 0 , \"snapshot for \" + options . url + \" finished in \" + time + \" ms\\n  written to \" + options . outputFile ) ; } , // The onTimeout callback function ( ) { globals . exit ( 1 , \"timed out waiting for \" + options . selector + \" to become visible for \" + options . url ) ; } , options . timeout , options . checkInterval ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The onReady callback [CODESPLIT] function ( time ) { fs . write ( options . outputFile , filter ( page . content ) , \"w\" ) ; globals . exit ( 0 , \"snapshot for \" + options . url + \" finished in \" + time + \" ms\\n  written to \" + options . outputFile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate input for one line of a simple robots . txt file Does not support wildcards . [CODESPLIT] function oneline ( line , options ) { var key = \"Allow: \" , index = line . indexOf ( key ) ; if ( index !== - 1 ) { var page = line . substr ( index + key . length ) . replace ( / ^\\s+|\\s+$ / g , \"\" ) ; return page . indexOf ( \"*\" ) === - 1 && base . input ( options , page ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves robots . txt from url and parses it . [CODESPLIT] function getRobotsUrl ( options , callback ) { request ( { url : options . source , timeout : options . timeout ( ) } , function ( err , res , body ) { var error = err || common . checkResponse ( res , \"text/plain\" ) ; if ( error ) { callback ( common . prependMsgToErr ( error , options . source , true ) ) ; } else { body . toString ( ) . split ( '\\n' ) . every ( function ( line ) { // Process the line input, but break if base.input returns false. // For now, this can only happen if no outputDir is defined, //   which is a fatal bad option problem and will happen immediately. if ( ! oneline ( line , options ) ) { error = common . prependMsgToErr ( base . generatorError ( ) , line , true ) ; return false ; } return true ; } ) ; callback ( error ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the robots . txt file and parses it . [CODESPLIT] function getRobotsFile ( options , callback ) { fs . readFile ( options . source , function ( err , data ) { if ( ! err ) { data . toString ( ) . split ( '\\n' ) . every ( function ( line ) { // Process the line input, but break if base.input returns false. // For now, this can only happen if no outputDir is defined, //   which is a fatal bad option problem and will happen immediately. if ( ! oneline ( line , options ) ) { err = common . prependMsgToErr ( base . generatorError ( ) , line , true ) ; return false ; } return true ; } ) ; } callback ( err ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the snapshot arguments from a robots . txt file . Each line that has Allow : contains a url we need a snapshot for . This can return true on error for true async . An async error is supplied to listener in this case via _abort . [CODESPLIT] function generateInput ( options ) { return nodeCall ( common . isUrl ( options . source ) ? getRobotsUrl : getRobotsFile , options ) . catch ( function ( err ) { options . _abort ( err ) ; } ) . then ( function ( ) { base . EOI ( robots ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use plain Web API detection with standard selectors https : // developer . mozilla . org / en - US / docs / Web / Guide / CSS / Getting_Started / Selectors Returns true on element visibility [CODESPLIT] function ( options ) { var result = false ; var el = document . querySelector ( options . selector ) ; if ( el ) { // el must be an HTMLElement that is visible result = el . offsetWidth && el . offsetHeight ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bubbles up values that do not nest to the furthest key . [CODESPLIT] function bubble ( values ) { return values . map ( d => { if ( d . key && d . values ) { if ( d . values [ 0 ] . key === \"undefined\" ) return d . values [ 0 ] . values [ 0 ] ; else d . values = bubble ( d . values ) ; } return d ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "exclude b from a and return remainder cidrs [CODESPLIT] function exclude ( a , b , v ) { const aStart = a . start ( { type : \"bigInteger\" } ) ; const bStart = b . start ( { type : \"bigInteger\" } ) ; const aEnd = a . end ( { type : \"bigInteger\" } ) ; const bEnd = b . end ( { type : \"bigInteger\" } ) ; const parts = [ ] ; // compareTo returns negative if left is less than right //       aaa //   bbb //   aaa //       bbb if ( aStart . compareTo ( bEnd ) > 0 || aEnd . compareTo ( bStart ) < 0 ) { return [ a . cidr ] ; } //   aaa //   bbb if ( aStart . compareTo ( bStart ) === 0 && aEnd . compareTo ( bEnd ) === 0 ) { return [ ] ; } //   aa //  bbbb if ( aStart . compareTo ( bStart ) > 0 && aEnd . compareTo ( bEnd ) < 0 ) { return [ ] ; } // aaaa //   bbbb // aaaa //   bb if ( aStart . compareTo ( bStart ) < 0 && aEnd . compareTo ( bEnd ) <= 0 ) { parts . push ( { start : aStart , end : bStart . subtract ( one ) , } ) ; } //    aaa //   bbb //   aaaa //   bbb if ( aStart . compareTo ( bStart ) >= 0 && aEnd . compareTo ( bEnd ) > 0 ) { parts . push ( { start : bEnd . add ( one ) , end : aEnd , } ) ; } //  aaaa //   bb if ( aStart . compareTo ( bStart ) < 0 && aEnd . compareTo ( bEnd ) > 0 ) { parts . push ( { start : aStart , end : bStart . subtract ( one ) , } ) ; parts . push ( { start : bEnd . add ( one ) , end : aEnd , } ) ; } const remaining = [ ] ; for ( const part of parts ) { for ( const subpart of subparts ( part , v ) ) { remaining . push ( formatPart ( subpart , v ) ) ; } } return cidrTools . merge ( remaining ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "heart beat [CODESPLIT] function heartBeat ( ) { var isEmpty = true ; //process event queue var eventChanges = false ; for ( var device_id in eventQueue ) { if ( eventQueue [ device_id ] . length > 0 ) { eventChanges = true ; if ( eventQueue [ device_id ] . length <= conf . max_events ) { self . add_request ( { device_id : device_id , events : eventQueue [ device_id ] } ) ; eventQueue [ device_id ] = [ ] ; } else { var events = eventQueue [ device_id ] . splice ( 0 , conf . max_events ) ; self . add_request ( { device_id : device_id , events : events } ) ; } } } if ( eventChanges ) { isEmpty = false ; storeSet ( \"cly_bulk_event\" , eventQueue ) ; } //process request queue into bulk requests if ( requestQueue . length > 0 ) { isEmpty = false ; if ( requestQueue . length <= conf . bulk_size ) { toBulkRequestQueue ( { app_key : conf . app_key , requests : JSON . stringify ( requestQueue ) } ) ; requestQueue = [ ] ; } else { var requests = requestQueue . splice ( 0 , conf . bulk_size ) ; toBulkRequestQueue ( { app_key : conf . app_key , requests : JSON . stringify ( requests ) } ) ; } storeSet ( \"cly_req_queue\" , requestQueue ) ; } //process bulk request queue if ( bulkQueue . length > 0 && readyToProcess && getTimestamp ( ) > failTimeout ) { isEmpty = false ; readyToProcess = false ; var params = bulkQueue . shift ( ) ; log ( \"Processing request\" , params ) ; makeRequest ( params , function ( err , params ) { log ( \"Request Finished\" , params , err ) ; if ( err ) { bulkQueue . unshift ( params ) ; failTimeout = getTimestamp ( ) + conf . fail_timeout ; } storeSet ( \"cly_bulk_queue\" , bulkQueue ) ; readyToProcess = true ; } ) ; } if ( isEmpty ) { empty_count ++ ; if ( empty_count === 3 ) { empty_count = 0 ; if ( empty_queue_callback ) { empty_queue_callback ( ) ; } } } if ( initiated ) { setTimeout ( heartBeat , conf . interval ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "log stuff [CODESPLIT] function log ( ) { if ( conf . debug && typeof console !== \"undefined\" ) { if ( arguments [ 1 ] && typeof arguments [ 1 ] === \"object\" ) { arguments [ 1 ] = JSON . stringify ( arguments [ 1 ] ) ; } console . log ( Array . prototype . slice . call ( arguments ) . join ( \"\\n\" ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get unique timestamp in miliseconds [CODESPLIT] function getMsTimestamp ( ) { var ts = new Date ( ) . getTime ( ) ; if ( lastMsTs >= ts ) { lastMsTs ++ ; } else { lastMsTs = ts ; } return lastMsTs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parsing host and port information from url [CODESPLIT] function parseUrl ( url ) { var serverOptions = { host : \"localhost\" , port : 80 } ; if ( url . indexOf ( \"https\" ) === 0 ) { serverOptions . port = 443 ; } var host = url . split ( \"://\" ) . pop ( ) ; serverOptions . host = host ; var lastPos = host . indexOf ( \":\" ) ; if ( lastPos > - 1 ) { serverOptions . host = host . slice ( 0 , lastPos ) ; serverOptions . port = Number ( host . slice ( lastPos + 1 , host . length ) ) ; } return serverOptions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert JSON object to query params [CODESPLIT] function prepareParams ( params ) { var str = [ ] ; for ( var i in params ) { str . push ( i + \"=\" + encodeURIComponent ( params [ i ] ) ) ; } return str . join ( \"&\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "removing trailing slashes [CODESPLIT] function stripTrailingSlash ( str ) { if ( str . substr ( str . length - 1 ) === \"/\" ) { return str . substr ( 0 , str . length - 1 ) ; } return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "retrieve only specific properties from object [CODESPLIT] function getProperties ( orig , props ) { var ob = { } ; var prop ; for ( var i = 0 ; i < props . length ; i ++ ) { prop = props [ i ] ; if ( typeof orig [ prop ] !== \"undefined\" ) { ob [ prop ] = orig [ prop ] ; } } return ob ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "internal method for events in case there is no consent for custom events but internal events has consents [CODESPLIT] function add_cly_events ( event ) { if ( ! event . key ) { log ( \"Event must have key property\" ) ; return ; } if ( cluster . isMaster ) { if ( ! event . count ) { event . count = 1 ; } var props = [ \"key\" , \"count\" , \"sum\" , \"dur\" , \"segmentation\" ] ; var e = getProperties ( event , props ) ; e . timestamp = getMsTimestamp ( ) ; var date = new Date ( ) ; e . hour = date . getHours ( ) ; e . dow = date . getDay ( ) ; log ( \"Adding event: \" , event ) ; eventQueue . push ( e ) ; storeSet ( \"cly_event\" , eventQueue ) ; } else { process . send ( { cly : { event : event } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PRIVATE METHODS [CODESPLIT] function reportViewDuration ( ) { if ( lastView ) { if ( ! platform ) { getMetrics ( ) ; } var segments = { \"name\" : lastView , \"segment\" : platform } ; //track pageview if ( Countly . check_consent ( \"views\" ) ) { add_cly_events ( { \"key\" : \"[CLY]_view\" , \"dur\" : getTimestamp ( ) - lastViewTime , \"segmentation\" : segments } ) ; } lastView = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prepare request by adding basic info to it [CODESPLIT] function prepareRequest ( request ) { request . app_key = Countly . app_key ; request . device_id = Countly . device_id ; request . sdk_name = SDK_NAME ; request . sdk_version = SDK_VERSION ; if ( Countly . check_consent ( \"location\" ) ) { if ( Countly . country_code ) { request . country_code = Countly . country_code ; } if ( Countly . city ) { request . city = Countly . city ; } if ( Countly . ip_address !== null ) { request . ip_address = Countly . ip_address ; } } else { request . location = \"\" ; } request . timestamp = getMsTimestamp ( ) ; var date = new Date ( ) ; request . hour = date . getHours ( ) ; request . dow = date . getDay ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "insert request to queue [CODESPLIT] function toRequestQueue ( request ) { if ( cluster . isMaster ) { if ( ! Countly . app_key || ! Countly . device_id ) { log ( \"app_key or device_id is missing\" ) ; return ; } prepareRequest ( request ) ; if ( requestQueue . length > queueSize ) { requestQueue . shift ( ) ; } requestQueue . push ( request ) ; storeSet ( \"cly_queue\" , requestQueue ) ; } else { process . send ( { cly : { cly_queue : request } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "heart beat [CODESPLIT] function heartBeat ( ) { //extend session if needed if ( sessionStarted && autoExtend && trackTime ) { var last = getTimestamp ( ) ; if ( last - lastBeat > sessionUpdate ) { Countly . session_duration ( last - lastBeat ) ; lastBeat = last ; } } //process event queue if ( eventQueue . length > 0 ) { if ( eventQueue . length <= maxEventBatch ) { toRequestQueue ( { events : JSON . stringify ( eventQueue ) } ) ; eventQueue = [ ] ; } else { var events = eventQueue . splice ( 0 , maxEventBatch ) ; toRequestQueue ( { events : JSON . stringify ( events ) } ) ; } storeSet ( \"cly_event\" , eventQueue ) ; } //process request queue with event queue if ( requestQueue . length > 0 && readyToProcess && getTimestamp ( ) > failTimeout ) { readyToProcess = false ; var params = requestQueue . shift ( ) ; //check if any consent to sync if ( Object . keys ( syncConsents ) . length ) { if ( consentTimer ) { clearTimeout ( consentTimer ) ; consentTimer = null ; } params . consent = JSON . stringify ( syncConsents ) ; syncConsents = { } ; } log ( \"Processing request\" , params ) ; makeRequest ( Countly . url , apiPath , params , function ( err , params ) { log ( \"Request Finished\" , params , err ) ; if ( err ) { requestQueue . unshift ( params ) ; failTimeout = getTimestamp ( ) + failTimeoutAmount ; } storeSet ( \"cly_queue\" , requestQueue ) ; readyToProcess = true ; } ) ; } setTimeout ( heartBeat , beatInterval ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get metrics of the browser [CODESPLIT] function getMetrics ( ) { var m = JSON . parse ( JSON . stringify ( metrics ) ) ; //getting app version m . _app_version = m . _app_version || Countly . app_version ; m . _os = m . _os || os . type ( ) ; m . _os_version = m . _os_version || os . release ( ) ; platform = os . type ( ) ; log ( \"Got metrics\" , m ) ; return m ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sending HTTP request [CODESPLIT] function makeRequest ( url , path , params , callback ) { try { log ( \"Sending HTTP request\" ) ; var serverOptions = parseUrl ( url ) ; var data = prepareParams ( params ) ; var method = \"GET\" ; var options = { host : serverOptions . host , port : serverOptions . port , path : path + \"?\" + data , method : \"GET\" } ; if ( data . length >= 2000 ) { method = \"POST\" ; } else if ( Countly . force_post ) { method = \"POST\" ; } if ( method === \"POST\" ) { options . method = \"POST\" ; options . path = path ; options . headers = { \"Content-Type\" : \"application/x-www-form-urlencoded\" , \"Content-Length\" : Buffer . byteLength ( data ) } ; } var protocol = http ; if ( url . indexOf ( \"https\" ) === 0 ) { protocol = https ; } var req = protocol . request ( options , function ( res ) { var str = \"\" ; res . on ( \"data\" , function ( chunk ) { str += chunk ; } ) ; res . on ( \"end\" , function ( ) { if ( res . statusCode >= 200 && res . statusCode < 300 ) { callback ( false , params , str ) ; } else { callback ( true , params ) ; } } ) ; } ) ; if ( method === \"POST\" ) { // write data to request body req . write ( data ) ; } req . on ( \"error\" , function ( err ) { log ( \"Connection failed.\" , err ) ; if ( typeof callback === \"function\" ) { callback ( true , params ) ; } } ) ; req . end ( ) ; } catch ( e ) { // fallback log ( \"Failed HTTP request\" , e ) ; if ( typeof callback === \"function\" ) { callback ( true , params ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a promise that is resolved when all input promises have been settled . The returned Promise is resolved with an array of Promise . Inspection objects . [CODESPLIT] function allSettled ( promises ) { \"use strict\" ; const wrappedPromises = promises . map ( ( curPromise ) => curPromise . reflect ( ) ) ; return Promise . all ( wrappedPromises ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if there’s no word before index . [CODESPLIT] function firstWord ( parent , index ) { var siblings = parent . children while ( index -- ) { if ( is ( 'WordNode' , siblings [ index ] ) ) { return false } } return true }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the next word . [CODESPLIT] function after ( parent , index ) { var siblings = parent . children var sibling = siblings [ ++ index ] var other if ( is ( 'WhiteSpaceNode' , sibling ) ) { sibling = siblings [ ++ index ] if ( is ( 'PunctuationNode' , sibling ) && punctuation . test ( toString ( sibling ) ) ) { sibling = siblings [ ++ index ] } if ( is ( 'WordNode' , sibling ) ) { other = sibling } } return other }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Classify a word . [CODESPLIT] function classify ( value ) { var type = null var normal value = value . replace ( digits , toWords ) . split ( split , 1 ) [ 0 ] normal = lower ( value ) if ( requiresA ( value ) ) { type = 'a' } if ( requiresAn ( value ) ) { type = type === 'a' ? 'a-or-an' : 'an' } if ( ! type && normal === value ) { type = vowel . test ( normal . charAt ( 0 ) ) ? 'an' : 'a' } return type }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a test based on a list of phrases . [CODESPLIT] function factory ( list ) { var expressions = [ ] var sensitive = [ ] var insensitive = [ ] construct ( ) return test function construct ( ) { var length = list . length var index = - 1 var value var normal while ( ++ index < length ) { value = list [ index ] normal = value === lower ( value ) if ( value . charAt ( value . length - 1 ) === '*' ) { // Regexes are insensitive now, once we need them this should check for // `normal` as well. expressions . push ( new RegExp ( '^' + value . slice ( 0 , - 1 ) , 'i' ) ) } else if ( normal ) { insensitive . push ( value ) } else { sensitive . push ( value ) } } } function test ( value ) { var normal = lower ( value ) var length var index if ( sensitive . indexOf ( value ) !== - 1 || insensitive . indexOf ( normal ) !== - 1 ) { return true } length = expressions . length index = - 1 while ( ++ index < length ) { if ( expressions [ index ] . test ( value ) ) { return true } } return false } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "bind collections controllers dbctrl - db controller forcerebind - if <code > true< / code > force rebind all collection controllers otherwise check added / deleted collections [CODESPLIT] function ( dbctrl , forcerebind ) { var octrls = forcerebind ? [ ] : cchistory ; var nctrls = [ ] ; var dbMeta = cdb . jb . getDBMeta ( ) ; if ( dbMeta && dbMeta . collections ) { for ( var j = 0 ; j < dbMeta . collections . length ; ++ j ) { var collection = dbMeta . collections [ j ] ; var ci ; if ( ( ci = octrls . indexOf ( collection . name ) ) != - 1 ) { nctrls . push ( collection . name ) ; octrls . splice ( ci , 1 ) ; } else if ( ! dbctrl [ collection . name ] ) { nctrls . push ( collection . name ) ; dbctrl [ collection . name ] = colctl ( dbctrl , collection . name ) ; } } } for ( var i = 0 ; i < octrls . length ; ++ i ) { delete dbctrl [ octrls [ i ] ] ; } // save current known collections cchistory = nctrls ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "collection controller ( creation function ) [CODESPLIT] function ( db , cname ) { // build arguments function: add <cname> as first argument var buildargs = function ( args ) { var result = [ cname ] ; // args is Object, we need to iterate all fields with numeric key for collecting arguments for ( var i = 0 ; args [ i ] ; ++ i ) { result . push ( args [ i ] ) ; } return result ; } ; // method names for creating aliases (db.<method>(cname, ...) -> db.cname.<method>(...)) var mnames = [ \"save\" , \"load\" , \"remove\" , \"find\" , \"findOne\" , \"update\" , \"count\" , \"dropCollection\" , \"dropIndexes\" , \"optimizeIndexes\" , \"ensureStringIndex\" , \"rebuildStringIndex\" , \"dropStringIndex\" , \"ensureIStringIndex\" , \"rebuildIStringIndex\" , \"dropIStringIndex\" , \"ensureNumberIndex\" , \"rebuildNumberIndex\" , \"dropNumberIndex\" , \"ensureArrayIndex\" , \"rebuildArrayIndex\" , \"dropArrayIndex\" ] ; // bind method alias var mbind = function ( mname ) { return function ( ) { return db [ mname ] . apply ( db , buildargs ( arguments ) ) ; } } ; // collection controller impl var colctlimpl = { inspect : function ( ) { return '\\u001b[' + 36 + 'm' + \"[Collection]\" + '\\u001b[' + 39 + 'm' ; } } ; var mname ; // wrap methods for ( var i = 0 ; i < mnames . length ; ++ i ) { mname = mnames [ i ] ; colctlimpl [ mname ] = mbind ( mname ) ; if ( helpGetters [ mname ] ) { Object . defineProperty ( colctlimpl [ mname ] , '_help_' , { value : helpGetters [ mname ] ( true ) } ) ; } } return colctlimpl }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build arguments function : add <cname > as first argument [CODESPLIT] function ( args ) { var result = [ cname ] ; // args is Object, we need to iterate all fields with numeric key for collecting arguments for ( var i = 0 ; args [ i ] ; ++ i ) { result . push ( args [ i ] ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "db - db controller mname - method name frc - force rebind collections controllers . if <code > false< / code > db meta will be reloaded only if method executes on unknown collection . argl - arguments count ( for register callback as last argument ) [CODESPLIT] function ( db , mname , frc ) { return function ( ) { var cname = arguments [ 0 ] ; var args = [ cname ] ; // copy all arguments except first and last for ( var i = 1 ; i < arguments . length - 1 ; ++ i ) { args . push ( arguments [ i ] ) ; } // creating callback with collection rebuilding var ccb = function ( rcb ) { return function ( ) { if ( frc || ! db [ cname ] ) { bindColCtls ( db ) ; } if ( rcb ) { rcb . apply ( this , arguments ) ; } } } ; if ( arguments . length > 1 ) { if ( typeof arguments [ arguments . length - 1 ] === 'function' ) { // wrap existing callback args . push ( ccb ( arguments [ arguments . length - 1 ] ) ) ; } else { // adding registering callback after last argument args . push ( arguments [ arguments . length - 1 ] ) ; args . push ( ccb ( ) ) ; } } else { args . push ( ccb ( ) ) ; } return cdb . jb [ mname ] . apply ( cdb . jb , args ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creating callback with collection rebuilding [CODESPLIT] function ( rcb ) { return function ( ) { if ( frc || ! db [ cname ] ) { bindColCtls ( db ) ; } if ( rcb ) { rcb . apply ( this , arguments ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The nodejs database wrapper . [CODESPLIT] function ( ) { Object . defineProperty ( this , \"_impl\" , { value : new EJDBImpl ( ) , configurable : false , enumerable : false , writable : false } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * - ( cname [ cb ] ) - ( cname qobj [ cb ] ) - ( cname qobj hints [ cb ] ) - ( cname qobj qobjarr [ cb ] ) - ( cname qobj qobjarr hints [ cb ] ) [CODESPLIT] function parseQueryArgs ( args ) { var cname , qobj , orarr , hints , cb ; var i = 0 ; cname = args [ i ++ ] ; if ( typeof cname !== \"string\" ) { throw new Error ( \"Collection name 'cname' argument must be specified\" ) ; } var next = args [ i ++ ] ; if ( typeof next === \"function\" ) { cb = next ; } else { qobj = next ; } next = args [ i ++ ] ; if ( next !== undefined ) { if ( Array . isArray ( next ) ) { orarr = next ; next = args [ i ++ ] ; } else if ( typeof next === \"object\" ) { hints = next ; orarr = null ; next = args [ i ++ ] ; } if ( ! hints && typeof next === \"object\" ) { hints = next ; next = args [ i ++ ] ; } if ( typeof next === \"function\" ) { cb = next ; } } return [ cname , ( qobj || { } ) , ( orarr || [ ] ) , ( hints || { } ) , ( cb || null ) ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "used to start at 0 each time . [CODESPLIT] function dummyText ( opts ) { var corpus = opts . corpus || 'lorem' , i = opts . start , isRandom = typeof ( i ) === 'undefined' , mustReset = typeof ( origin ) === 'undefined' , skip = opts . skip || 1 , sentences = opts . sentences || 1 , words = opts . words , text = texts [ corpus ] || texts . lorem , len = text . length , output = [ ] , s ; if ( isRandom ) { i = Math . floor ( Math . random ( ) * len ) ; } if ( mustReset ) { origin = i ; } if ( isRandom ) { // possible modulo of a negative number, so take care here. i = ( ( i + len - origin ) % len + len ) % len ; } while ( sentences -- ) { s = text [ i ] ; if ( words ) { s = s . split ( ' ' ) . slice ( 0 , words ) . join ( ' ' ) ; } output . push ( s ) ; i = ( i + skip ) % len ; } return output . join ( ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a set of reconnect options defined in README [CODESPLIT] function Back ( options ) { if ( ! ( this instanceof Back ) ) { return new Back ( options ) ; } this . settings = extend ( options ) ; this . reconnect = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### setup Called when a Map constructor is defined / extended to perform any initialization behavior for the new constructor function . [CODESPLIT] function ( baseMap ) { Construct . setup . apply ( this , arguments ) ; // A cached list of computed properties on the prototype. this . _computedPropertyNames = [ ] ; // Do not run if we are defining can.Map. if ( Map ) { addTypeEvents ( this ) ; this [ canSymbol . for ( \"can.defineInstanceKey\" ) ] = function ( prop , definition ) { if ( definition . value !== undefined ) { this . defaults [ prop ] = definition . value ; } if ( definition . enumerable === false ) { this . enumerable [ prop ] = false ; } } ; // Provide warnings if can.Map is used incorrectly. //!steal-remove-start if ( process . env . NODE_ENV !== 'production' ) { if ( this . prototype . define && ! mapHelpers . define ) { dev . warn ( \"can/map/define is not included, yet there is a define property \" + \"used. You may want to add this plugin.\" ) ; } if ( this . define && ! mapHelpers . define ) { dev . warn ( \"The define property should be on the map's prototype properties, \" + \"not the static properties. Also, can/map/define is not included.\" ) ; } } //!steal-remove-end // Create a placeholder for default values. if ( ! this . defaults ) { this . defaults = { } ; } if ( ! this . enumerable ) { this . enumerable = { } ; } // Go through everything on the prototype.  If it's a primitive, // treat it as a default value.  If it's a compute, identify it so // it can be setup as a computed property. for ( var prop in this . prototype ) { if ( prop !== \"define\" && prop !== \"constructor\" && ( typeof this . prototype [ prop ] !== \"function\" || this . prototype [ prop ] . prototype instanceof Construct ) ) { this . defaults [ prop ] = this . prototype [ prop ] ; } else if ( canReflect . isObservableLike ( this . prototype [ prop ] ) ) { this . _computedPropertyNames . push ( prop ) ; } } // If define is a function, call it with this can.Map if ( mapHelpers . define ) { mapHelpers . define ( this , baseMap . prototype . define ) ; } } // If we inherit from can.Map, but not can.List, create a can.List that // creates instances of this Map type. // This is something List should weave in. /*if (can.List && !(this.prototype instanceof can.List)) {\n\t\t\t\tthis.List = Map.List.extend({\n\t\t\t\t\tMap: this\n\t\t\t\t}, {});\n\t\t\t}*/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### setup Initializes the map instance s behavior . [CODESPLIT] function ( obj ) { if ( canReflect . isObservableLike ( obj ) && typeof obj . serialize === \"function\" ) { obj = obj . serialize ( ) ; } // Where we keep the values of the compute. this . _data = Object . create ( null ) ; // The namespace this `object` uses to listen to events. CID ( this , \".map\" ) ; this . _setupComputedProperties ( ) ; var teardownMapping = obj && mapHelpers . addToMap ( obj , this ) ; var defaultValues = this . _setupDefaults ( obj ) ; var data = assign ( canReflect . assignDeep ( { } , defaultValues ) , obj ) ; this . attr ( data ) ; if ( teardownMapping ) { teardownMapping ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### _setupComputes Sets up computed properties on a Map . Stores information for each computed property on this . _computedAttrs that looks like : { // the number of bindings on this property count : 1 // a handler that forwards events on the compute // to the map instance handler : handler compute : compute // the compute } [CODESPLIT] function ( ) { this . _computedAttrs = Object . create ( null ) ; var computes = this . constructor . _computedPropertyNames ; for ( var i = 0 , len = computes . length ; i < len ; i ++ ) { var attrName = computes [ i ] ; mapHelpers . addComputedAttr ( this , attrName , this [ attrName ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### attr The primary get / set interface for can . Map . Calls _get _set or _attrs depending on how it is called . [CODESPLIT] function ( attr , val ) { var type = typeof attr ; if ( attr === undefined ) { return this . _getAttrs ( ) ; } else if ( type !== \"string\" && type !== \"number\" ) { // Get or set multiple attributes. return this . _setAttrs ( attr , val ) ; } else if ( arguments . length === 1 ) { // Get a single attribute. return this . _get ( attr ) ; } else { // Set an attribute. this . _set ( attr + \"\" , val ) ; return this ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### _get Handles reading nested properties like foo . bar by getting the value of foo and recursively calling _get for the value of bar . To read the actual values _get calls ___get . [CODESPLIT] function ( attr ) { attr = attr + \"\" ; var dotIndex = attr . indexOf ( '.' ) ; if ( dotIndex >= 0 ) { // Attempt to get the value anyway in case // somone wrote `new can.Map({\"foo.bar\": 1})`. var value = this . ___get ( attr ) ; if ( value !== undefined ) { ObservationRecorder . add ( this , attr ) ; return value ; } var first = attr . substr ( 0 , dotIndex ) , second = attr . substr ( dotIndex + 1 ) ; var current = this . __get ( first ) ; return current && canReflect . getKeyValue ( current , second ) ; } else { return this . __get ( attr ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### __get Signals can . compute that an observable property is being read . [CODESPLIT] function ( attr ) { if ( ! unobservable [ attr ] && ! this . _computedAttrs [ attr ] ) { ObservationRecorder . add ( this , attr ) ; } return this . ___get ( attr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### ___get When called with an argument returns the value of this property . If that property is represented by a computed attribute return the value of that compute . If no argument is provided return the raw data . [CODESPLIT] function ( attr ) { if ( attr !== undefined ) { var computedAttr = this . _computedAttrs [ attr ] ; if ( computedAttr ) { // return computedAttr.compute(); return canReflect . getValue ( computedAttr . compute ) ; } else { return hasOwnProperty . call ( this . _data , attr ) ? this . _data [ attr ] : undefined ; } } else { return this . _data ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### _set Handles setting nested properties by finding the nested observable and recursively calling _set on it . Eventually it calls __set with the __type converted value to set and the current value . The current value is passed for two reasons : - so __set can trigger an event if the value has changed . - for advanced setting behavior that define . set can do . If the map is initializing the current value does not need to be read because no change events are dispatched anyway . [CODESPLIT] function ( attr , value , keepKey ) { attr = attr + \"\" ; var dotIndex = attr . indexOf ( '.' ) , current ; if ( dotIndex >= 0 && ! keepKey ) { var first = attr . substr ( 0 , dotIndex ) , second = attr . substr ( dotIndex + 1 ) ; current = this [ inSetupSymbol ] ? undefined : this . ___get ( first ) ; if ( canReflect . isMapLike ( current ) ) { canReflect . setKeyValue ( current , second , value ) ; } else { current = this [ inSetupSymbol ] ? undefined : this . ___get ( attr ) ; // //Convert if there is a converter.  Remove in 3.0. if ( this . __convert ) { value = this . __convert ( attr , value ) ; } this . __set ( attr , this . __type ( value , attr ) , current ) ; } } else { current = this [ inSetupSymbol ] ? undefined : this . ___get ( attr ) ; // //Convert if there is a converter.  Remove in 3.0. if ( this . __convert ) { value = this . __convert ( attr , value ) ; } this . __set ( attr , this . __type ( value , attr ) , current ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "## __type Converts set values to another type . By default this converts Objects to can . Maps and Arrays to can . Lists . This also makes it so if a plain JavaScript object has already been converted to a list or map that same list or map instance is used . [CODESPLIT] function ( value , prop ) { if ( typeof value === \"object\" && ! canReflect . isObservableLike ( value ) && mapHelpers . canMakeObserve ( value ) && ! canReflect . isListLike ( value ) ) { var cached = mapHelpers . getMapFromObject ( value ) ; if ( cached ) { return cached ; } var MapConstructor = this . constructor . Map || Map ; return new MapConstructor ( value ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "## __set Handles firing events if the value has changed and works with the bubble helpers to setup bubbling . Calls ___set to do the actual setting . [CODESPLIT] function ( prop , value , current ) { if ( value !== current || ! Object . prototype . hasOwnProperty . call ( this . _data , prop ) ) { var computedAttr = this . _computedAttrs [ prop ] ; // Dispatch an \"add\" event if adding a new property. var changeType = computedAttr || current !== undefined || hasOwnProperty . call ( this . ___get ( ) , prop ) ? \"set\" : \"add\" ; // Set the value on `_data` and set up bubbling. this . ___set ( prop , typeof value === \"object\" ? bubble . set ( this , prop , value , current ) : value ) ; // Computed properties change events are already forwarded except if // no one is listening to them. if ( ! computedAttr || ! computedAttr . count ) { this . _triggerChange ( prop , changeType , value , current ) ; } // Stop bubbling old nested maps. if ( typeof current === \"object\" ) { bubble . teardownFromParent ( this , current ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### ___set Directly saves the set value as a property on _data or sets the computed attribute . [CODESPLIT] function ( prop , val ) { var computedAttr = this . _computedAttrs [ prop ] ; if ( computedAttr ) { canReflect . setValue ( computedAttr . compute , val ) ; } else { this . _data [ prop ] = val ; } // Adds the property directly to the map instance. But first, // checks that it's not overwriting a method. This should be removed // in 3.0. if ( typeof this . constructor . prototype [ prop ] !== 'function' && ! computedAttr ) { this [ prop ] = val ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### _remove Handles removing nested observes . [CODESPLIT] function ( attr ) { // If this is List. var parts = mapHelpers . attrParts ( attr ) , // The actual property to remove. prop = parts . shift ( ) , // The current value. current = this . ___get ( prop ) ; // If we have more parts, call `removeAttr` on that part. if ( parts . length && current ) { return canReflect . deleteKeyValue ( current , parts . join ( \".\" ) ) ; } else { // If attr does not have a `.` if ( typeof attr === 'string' && ! ! ~ attr . indexOf ( '.' ) ) { prop = attr ; } this . __remove ( prop , current ) ; return current ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### __remove Handles triggering an event if a property could be removed . [CODESPLIT] function ( prop , current ) { if ( prop in this . _data ) { this . ___remove ( prop ) ; // Let others now this property has been removed. this . _triggerChange ( prop , \"remove\" , undefined , current ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### ___serialize Serializes a property . Uses map helpers to recursively serialize nested observables . [CODESPLIT] function ( name , val ) { if ( this . _legacyAttrBehavior ) { return mapHelpers . getValue ( this , name , val , \"serialize\" ) ; } else { return canReflect . serialize ( val , CIDMap ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### _setAttrs Sets multiple properties on this object at once . First goes through all current properties and either merges or removes old properties . Then it goes through the remaining ones to be added and sets those properties . [CODESPLIT] function ( props , remove ) { if ( this . _legacyAttrBehavior ) { return this . __setAttrs ( props , remove ) ; } if ( remove === true || remove === \"true\" ) { this [ canSymbol . for ( \"can.updateDeep\" ) ] ( props ) ; } else { this [ canSymbol . for ( \"can.assignDeep\" ) ] ( props ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### _triggerChange A helper function used to trigger events on this map . If the map is bubbling this will fire a change event . Otherwise it only fires a named event . Triggers a __keys event if a property has been added or removed . [CODESPLIT] function ( attr , how , newVal , oldVal , batchNum ) { canQueues . batch . start ( ) ; if ( bubble . isBubbling ( this , \"change\" ) ) { canEvent . dispatch . call ( this , { type : \"change\" , target : this , batchNum : batchNum } , [ attr , how , newVal , oldVal ] ) ; } canEvent . dispatch . call ( this , { type : attr , target : this , batchNum : batchNum , patches : [ { type : \"set\" , key : attr , value : newVal } ] } , [ newVal , oldVal ] ) ; if ( how === \"remove\" || how === \"add\" ) { canEvent . dispatch . call ( this , { type : \"__keys\" , target : this , batchNum : batchNum } ) ; } canQueues . batch . stop ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### compute Creates a compute that represents a value on this map . If the property is a function on the prototype a function compute wil be created . Otherwise a compute will be created that reads the observable attributes [CODESPLIT] function ( prop ) { if ( typeof this . constructor . prototype [ prop ] === \"function\" ) { return canCompute ( this [ prop ] , this ) ; } else { var reads = ObserveReader . reads ( prop ) ; var last = reads . length - 1 ; return canCompute ( function ( newVal ) { if ( arguments . length ) { ObserveReader . write ( this , reads [ last ] . key , newVal , { } ) ; } else { return ObserveReader . get ( this , prop ) ; } } , this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### each loops through all the key - value pairs on this map . [CODESPLIT] function ( callback , context ) { var key , item ; var keys = canReflect . getOwnEnumerableKeys ( this ) ; for ( var i = 0 , len = keys . length ; i < len ; i ++ ) { key = keys [ i ] ; item = this . attr ( key ) ; if ( callback . call ( context || item , item , key , this ) === false ) { break ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### _each Iterator that does not trigger live binding . [CODESPLIT] function ( callback ) { var data = this . ___get ( ) ; for ( var prop in data ) { if ( hasOwnProperty . call ( data , prop ) ) { callback ( data [ prop ] , prop ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- shape [CODESPLIT] function ( ) { if ( ! this [ inSetupSymbol ] ) { ObservationRecorder . add ( this , '__keys' ) ; } var enumerable = this . constructor . enumerable ; if ( enumerable ) { return Object . keys ( this . _data ) . filter ( function ( key ) { return enumerable [ key ] !== false ; } , this ) ; } else { return Object . keys ( this . _data ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- shape get / set - [CODESPLIT] function ( source ) { canQueues . batch . start ( ) ; // TODO: we should probably just throw an error instead of cleaning canReflect . assignDeepMap ( this , mapHelpers . removeSpecialKeys ( canReflect . assignMap ( { } , source ) ) ) ; canQueues . batch . stop ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "observable [CODESPLIT] function ( key , handler , queue ) { var translationHandler = function ( ev , newValue , oldValue ) { handler . call ( this , newValue , oldValue ) ; } ; singleReference . set ( handler , this , translationHandler , key ) ; this . addEventListener ( key , translationHandler , queue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See https : // github . com / broofa / node - uuid for API details [CODESPLIT] function v1 ( options , buf , offset ) { var i = buf && offset || 0 ; var b = buf || [ ] ; options = options || { } ; var clockseq = options . clockseq !== undefined ? options . clockseq : _clockseq ; // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00).  JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs = options . msecs !== undefined ? options . msecs : new Date ( ) . getTime ( ) ; // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs = options . nsecs !== undefined ? options . nsecs : _lastNSecs + 1 ; // Time since last uuid creation (in msecs) var dt = ( msecs - _lastMSecs ) + ( nsecs - _lastNSecs ) / 10000 ; // Per 4.2.1.2, Bump clockseq on clock regression if ( dt < 0 && options . clockseq === undefined ) { clockseq = clockseq + 1 & 0x3fff ; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ( ( dt < 0 || msecs > _lastMSecs ) && options . nsecs === undefined ) { nsecs = 0 ; } // Per 4.2.1.2 Throw error if too many uuids are requested if ( nsecs >= 10000 ) { throw new Error ( 'uuid.v1(): Can\\'t create more than 10M uuids/sec' ) ; } _lastMSecs = msecs ; _lastNSecs = nsecs ; _clockseq = clockseq ; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000 ; // `time_low` var tl = ( ( msecs & 0xfffffff ) * 10000 + nsecs ) % 0x100000000 ; b [ i ++ ] = tl >>> 24 & 0xff ; b [ i ++ ] = tl >>> 16 & 0xff ; b [ i ++ ] = tl >>> 8 & 0xff ; b [ i ++ ] = tl & 0xff ; // `time_mid` var tmh = ( msecs / 0x100000000 * 10000 ) & 0xfffffff ; b [ i ++ ] = tmh >>> 8 & 0xff ; b [ i ++ ] = tmh & 0xff ; // `time_high_and_version` b [ i ++ ] = tmh >>> 24 & 0xf | 0x10 ; // include version b [ i ++ ] = tmh >>> 16 & 0xff ; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b [ i ++ ] = clockseq >>> 8 | 0x80 ; // `clock_seq_low` b [ i ++ ] = clockseq & 0xff ; // `node` var node = options . node || _nodeId ; for ( var n = 0 ; n < 6 ; n ++ ) { b [ i + n ] = node [ n ] ; } return buf ? buf : unparse ( b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create css build function [CODESPLIT] function css ( files , output , options ) { options = Object . assign ( { banner : false } , options ) ; return ( ) => { var build = gulp . src ( files ) if ( options . banner ) build = build . pipe ( $ . header ( banner , { pkg } ) ) ; build = build . pipe ( $ . rename ( 'd3.compose.css' ) ) . pipe ( gulp . dest ( output ) ) ; return build ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Approximate gulp 4 . 0 series [CODESPLIT] function series ( ) { const tasks = Array . prototype . slice . call ( arguments ) ; var fn = cb => cb ( ) ; if ( typeof tasks [ tasks . length - 1 ] === 'function' ) fn = tasks . pop ( ) ; return ( cb ) => { const tasks_with_cb = tasks . concat ( [ ( err ) => { if ( err ) return cb ( err ) ; fn ( cb ) ; } ] ) ; runSequence . apply ( this , tasks_with_cb ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Placeholder until formal constraints / layouts are added [CODESPLIT] function toSurround ( description ) { if ( ! Array . isArray ( description ) ) { description = [ layered ( description ) ] ; } var positions = extractSurroundPositions ( description ) ; var top = positions . top ; var right = positions . right ; var bottom = positions . bottom ; var left = positions . left ; var middle = positions . middle ; var container = { _id : '_container' } ; var topEdge = top [ top . length - 1 ] && constraint . eq ( top [ top . length - 1 ] , 'bottom' ) || 0 ; var rightEdge = right [ 0 ] && constraint . eq ( right [ 0 ] , 'left' ) || constraint . eq ( container , 'right' ) ; var bottomEdge = bottom [ 0 ] && constraint . eq ( bottom [ 0 ] , 'top' ) || constraint . eq ( container , 'bottom' ) ; var leftEdge = left [ left . length - 1 ] && constraint . eq ( left [ left . length - 1 ] , 'right' ) || 0 ; top = top . map ( function ( item , i , items ) { var layout = { _position : 'top' , top : items [ i - 1 ] && constraint . eq ( items [ i - 1 ] , 'bottom' ) || 0 , left : leftEdge , right : rightEdge , width : constraint . flex ( ) } ; item = assign ( { } , item ) ; item . props = assign ( layout , item . props ) ; return item ; } ) ; right = right . map ( function ( item , i , items ) { var layout = { _position : 'right' , right : items [ i + 1 ] && constraint . eq ( items [ i + 1 ] , 'left' ) || constraint . eq ( container , 'right' ) , top : topEdge , bottom : bottomEdge , height : constraint . flex ( ) } ; item = assign ( { } , item ) ; item . props = assign ( layout , item . props ) ; return item ; } ) ; bottom = bottom . map ( function ( item , i , items ) { var layout = { _position : 'bottom' , bottom : items [ i + 1 ] && constraint . eq ( items [ i + 1 ] , 'top' ) || constraint . eq ( container , 'bottom' ) , left : leftEdge , right : rightEdge , width : constraint . flex ( ) } ; item = assign ( { } , item ) ; item . props = assign ( layout , item . props ) ; return item ; } ) ; left = left . map ( function ( item , i , items ) { var layout = { _position : 'left' , left : items [ i - 1 ] && constraint . eq ( items [ i - 1 ] , 'right' ) || 0 , top : topEdge , bottom : bottomEdge , height : constraint . flex ( ) } ; item = assign ( { } , item ) ; item . props = assign ( layout , item . props ) ; return item ; } ) ; middle = middle . map ( function ( item ) { var layout = { _position : 'middle' , top : topEdge , right : rightEdge , bottom : bottomEdge , left : leftEdge , width : constraint . flex ( ) , height : constraint . flex ( ) } ; item = assign ( { } , item ) ; item . props = assign ( layout , item . props ) ; return item ; } ) ; var allItems = top . concat ( left ) . concat ( middle ) . concat ( right ) . concat ( bottom ) ; var byId = { } ; var ordered = [ ] ; allItems . forEach ( function ( item ) { byId [ item . _id ] = item ; ordered . push ( item . _id ) ; } ) ; return { byId : byId , ordered : ordered } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This sync function for Couchbase Sync Gateway was generated by synctos : https : // github . com / Kashoo / synctos [CODESPLIT] function synctos ( doc , oldDoc ) { // Whether the given value is either null or undefined function isValueNullOrUndefined ( value ) { return value === void 0 || value === null ; } // Whether the given document is missing/nonexistant (i.e. null or undefined) or deleted (its \"_deleted\" property is true) function isDocumentMissingOrDeleted ( candidate ) { return isValueNullOrUndefined ( candidate ) || candidate . _deleted ; } // A property validator that is suitable for use on type identifier properties. Ensures the value is a string, is neither null nor // undefined, is not an empty string and cannot be modified. var typeIdValidator = { type : 'string' , required : true , mustNotBeEmpty : true , immutable : true } ; // A type filter that matches on the document's type property function simpleTypeFilter ( doc , oldDoc , candidateDocType ) { if ( oldDoc ) { if ( doc . _deleted ) { return oldDoc . type === candidateDocType ; } else { return doc . type === oldDoc . type && oldDoc . type === candidateDocType ; } } else { return doc . type === candidateDocType ; } } // Retrieves the old doc's effective value. If it is null, undefined or its \"_deleted\" property is true, returns null. Otherwise, returns // the value of the \"oldDoc\" parameter. function resolveOldDoc ( ) { return ! isDocumentMissingOrDeleted ( oldDoc ) ? oldDoc : null ; } // Add the specified padding to the right of the given string value until its length matches the desired length function padRight ( value , desiredLength , padding ) { while ( value . length < desiredLength ) { value += padding ; } return value ; } // Determine if a given value is an integer. Exists because Number.isInteger is not supported by Sync Gateway's JavaScript engine. function isValueAnInteger ( value ) { return typeof value === 'number' && isFinite ( value ) && Math . floor ( value ) === value ; } // Retrieves the effective value of a top-level document constraint (e.g. \"channels\", \"documentIdRegexPattern\", \"accessAssignments\") function resolveDocumentConstraint ( constraintDefinition ) { if ( typeof constraintDefinition === 'function' ) { return constraintDefinition ( doc , resolveOldDoc ( ) ) ; } else { return constraintDefinition ; } } // Converts a given value to a JSON string. Exists because JSON.stringify is not supported by all versions of Sync // Gateway's JavaScript engine. var jsonStringify = ( typeof JSON !== 'undefined' && JSON . stringify ) ? JSON . stringify : importSyncFunctionFragment ( 'json-stringify-module.js' ) ; var utils = { isDocumentMissingOrDeleted : isDocumentMissingOrDeleted , isValueAnInteger : isValueAnInteger , isValueNullOrUndefined : isValueNullOrUndefined , jsonStringify : jsonStringify , padRight : padRight , resolveOldDoc : resolveOldDoc , resolveDocumentConstraint : resolveDocumentConstraint } ; // The document authorization module is responsible for verifying the user's permissions (e.g. roles, channels) var authorizationModule = importSyncFunctionFragment ( './authorization-module.js' ) ( utils ) ; // The document validation module is responsible for verifying the document's contents var validationModule = importSyncFunctionFragment ( './validation-module.js' ) ( utils , simpleTypeFilter , typeIdValidator ) ; // The access assignment module is responsible for dynamically assigning channels and roles to users var accessAssignmentModule = importSyncFunctionFragment ( './access-assignment-module.js' ) ( utils ) ; // The expiry module is responsible for controlling when the document will expire and be purged from the DB var expiryModule = importSyncFunctionFragment ( './expiry-module.js' ) ( utils ) ; var rawDocDefinitions = $DOCUMENT_DEFINITIONS_PLACEHOLDER$ ; var docDefinitions ; if ( typeof rawDocDefinitions === 'function' ) { docDefinitions = rawDocDefinitions ( ) ; } else { docDefinitions = rawDocDefinitions ; } function getDocumentType ( ) { var effectiveOldDoc = resolveOldDoc ( ) ; for ( var docType in docDefinitions ) { var docDefn = docDefinitions [ docType ] ; if ( docDefn . typeFilter ( doc , effectiveOldDoc , docType ) ) { return docType ; } } // The document type does not exist return null ; } // Now put the pieces together var theDocType = getDocumentType ( ) ; if ( isValueNullOrUndefined ( theDocType ) ) { if ( doc . _deleted ) { // Attempting to delete a document whose type is unknown. This may occur when bucket access/sharing // (https://developer.couchbase.com/documentation/mobile/current/guides/sync-gateway/shared-bucket-access.html) // is enabled and the document was deleted via the Couchbase SDK or if the document belongs to a type that existed // in a previous version of the document definitions but has since been removed. Verify that the user has // administrator access and then simply assign the public channel // (https://developer.couchbase.com/documentation/mobile/current/guides/sync-gateway/channels/index.html#special-channels) // to the document so that other users will get a 404 Not Found if they attempt to fetch (i.e. \"view\") the deleted // document rather than a 403 Forbidden. requireAccess ( [ ] ) ; // This test can only be satisfied via the admin API channel ( '!' ) ; return ; } else { var errorMessage = 'Unknown document type' ; var error = new Error ( errorMessage ) ; error . forbidden = errorMessage ; throw error ; } } var theDocDefinition = docDefinitions [ theDocType ] ; var customActionMetadata = { documentTypeId : theDocType , documentDefinition : theDocDefinition } ; if ( theDocDefinition . customActions && typeof theDocDefinition . customActions . onTypeIdentificationSucceeded === 'function' ) { theDocDefinition . customActions . onTypeIdentificationSucceeded ( doc , oldDoc , customActionMetadata ) ; } customActionMetadata . authorization = authorizationModule . authorize ( doc , oldDoc , theDocDefinition ) ; if ( theDocDefinition . customActions && typeof theDocDefinition . customActions . onAuthorizationSucceeded === 'function' ) { theDocDefinition . customActions . onAuthorizationSucceeded ( doc , oldDoc , customActionMetadata ) ; } validationModule . validateDoc ( doc , oldDoc , theDocDefinition , theDocType ) ; if ( theDocDefinition . customActions && typeof theDocDefinition . customActions . onValidationSucceeded === 'function' ) { theDocDefinition . customActions . onValidationSucceeded ( doc , oldDoc , customActionMetadata ) ; } if ( theDocDefinition . accessAssignments && ! doc . _deleted ) { var accessAssignments = accessAssignmentModule . assignUserAccess ( doc , oldDoc , theDocDefinition ) ; if ( accessAssignments . length > 0 ) { customActionMetadata . accessAssignments = accessAssignments ; if ( theDocDefinition . customActions && typeof theDocDefinition . customActions . onAccessAssignmentsSucceeded === 'function' ) { theDocDefinition . customActions . onAccessAssignmentsSucceeded ( doc , oldDoc , customActionMetadata ) ; } } } if ( ! isValueNullOrUndefined ( theDocDefinition . expiry ) && ! doc . _deleted ) { customActionMetadata . expiryDate = expiryModule . setDocExpiry ( doc , oldDoc , theDocDefinition . expiry ) ; if ( theDocDefinition . customActions && typeof theDocDefinition . customActions . onExpiryAssignmentSucceeded === 'function' ) { theDocDefinition . customActions . onExpiryAssignmentSucceeded ( doc , oldDoc , customActionMetadata ) ; } } // Getting here means the document revision is authorized and valid, and the appropriate channel(s) should now be assigned var allDocChannels = authorizationModule . getAllDocChannels ( theDocDefinition ) ; channel ( allDocChannels ) ; customActionMetadata . documentChannels = allDocChannels ; if ( theDocDefinition . customActions && typeof theDocDefinition . customActions . onDocumentChannelAssignmentSucceeded === 'function' ) { theDocDefinition . customActions . onDocumentChannelAssignmentSucceeded ( doc , oldDoc , customActionMetadata ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A type filter that matches on the document s type property [CODESPLIT] function simpleTypeFilter ( doc , oldDoc , candidateDocType ) { if ( oldDoc ) { if ( doc . _deleted ) { return oldDoc . type === candidateDocType ; } else { return doc . type === oldDoc . type && oldDoc . type === candidateDocType ; } } else { return doc . type === candidateDocType ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the specified padding to the right of the given string value until its length matches the desired length [CODESPLIT] function padRight ( value , desiredLength , padding ) { while ( value . length < desiredLength ) { value += padding ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms the given item or items into a new list of items with the specified prefix ( if any ) appended to each element [CODESPLIT] function resolveCollectionItems ( originalItems , itemPrefix ) { if ( utils . isValueNullOrUndefined ( originalItems ) ) { return [ ] ; } else if ( Array . isArray ( originalItems ) ) { var resultItems = [ ] ; for ( var i = 0 ; i < originalItems . length ; i ++ ) { var item = originalItems [ i ] ; if ( utils . isValueNullOrUndefined ( item ) ) { continue ; } resultItems . push ( prefixItem ( item , itemPrefix ) ) ; } return resultItems ; } else { // Represents a single item return [ prefixItem ( originalItems , itemPrefix ) ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms the given collection definition which may have been defined as a single item a list of items or a function that returns a list of items into a simple list where each item has the specified prefix if any [CODESPLIT] function resolveCollectionDefinition ( doc , oldDoc , collectionDefinition , itemPrefix ) { if ( utils . isValueNullOrUndefined ( collectionDefinition ) ) { return [ ] ; } else { if ( typeof collectionDefinition === 'function' ) { var fnResults = collectionDefinition ( doc , oldDoc ) ; return resolveCollectionItems ( fnResults , itemPrefix ) ; } else { return resolveCollectionItems ( collectionDefinition , itemPrefix ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assigns channel access to users / roles [CODESPLIT] function assignChannelsToUsersAndRoles ( doc , oldDoc , accessAssignmentDefinition ) { var usersAndRoles = [ ] ; var users = resolveCollectionDefinition ( doc , oldDoc , accessAssignmentDefinition . users ) ; for ( var userIndex = 0 ; userIndex < users . length ; userIndex ++ ) { usersAndRoles . push ( users [ userIndex ] ) ; } var roles = resolveRoleCollectionDefinition ( doc , oldDoc , accessAssignmentDefinition . roles ) ; for ( var roleIndex = 0 ; roleIndex < roles . length ; roleIndex ++ ) { usersAndRoles . push ( roles [ roleIndex ] ) ; } var channels = resolveCollectionDefinition ( doc , oldDoc , accessAssignmentDefinition . channels ) ; access ( usersAndRoles , channels ) ; return { type : 'channel' , usersAndRoles : usersAndRoles , channels : channels } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assigns role access to users [CODESPLIT] function assignRolesToUsers ( doc , oldDoc , accessAssignmentDefinition ) { var users = resolveCollectionDefinition ( doc , oldDoc , accessAssignmentDefinition . users ) ; var roles = resolveRoleCollectionDefinition ( doc , oldDoc , accessAssignmentDefinition . roles ) ; role ( users , roles ) ; return { type : 'role' , users : users , roles : roles } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assigns role access to users and / or channel access to users / roles according to the given access assignment definitions [CODESPLIT] function assignUserAccess ( doc , oldDoc , documentDefinition ) { var effectiveOldDoc = utils . resolveOldDoc ( ) ; var accessAssignmentDefinitions = resolveAccessAssignmentsDefinition ( doc , effectiveOldDoc , documentDefinition . accessAssignments ) ; var effectiveAssignments = [ ] ; for ( var assignmentIndex = 0 ; assignmentIndex < accessAssignmentDefinitions . length ; assignmentIndex ++ ) { var definition = accessAssignmentDefinitions [ assignmentIndex ] ; if ( definition . type === 'role' ) { effectiveAssignments . push ( assignRolesToUsers ( doc , effectiveOldDoc , definition ) ) ; } else if ( definition . type === 'channel' || utils . isValueNullOrUndefined ( definition . type ) ) { effectiveAssignments . push ( assignChannelsToUsersAndRoles ( doc , effectiveOldDoc , definition ) ) ; } } return effectiveAssignments ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A document definition may define its authorizations ( channels roles or users ) for each operation type ( view add replace delete or write ) as either a string or an array of strings . In either case add them to the list if they are not already present . [CODESPLIT] function appendToAuthorizationList ( allAuthorizations , authorizationsToAdd ) { if ( ! utils . isValueNullOrUndefined ( authorizationsToAdd ) ) { if ( Array . isArray ( authorizationsToAdd ) ) { for ( var i = 0 ; i < authorizationsToAdd . length ; i ++ ) { var authorization = authorizationsToAdd [ i ] ; if ( allAuthorizations . indexOf ( authorization ) < 0 ) { allAuthorizations . push ( authorization ) ; } } } else if ( allAuthorizations . indexOf ( authorizationsToAdd ) < 0 ) { allAuthorizations . push ( authorizationsToAdd ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a list of channels the document belongs to based on its specified type [CODESPLIT] function getAllDocChannels ( docDefinition ) { var docChannelMap = utils . resolveDocumentConstraint ( docDefinition . channels ) ; var allChannels = [ ] ; if ( docChannelMap ) { appendToAuthorizationList ( allChannels , docChannelMap . view ) ; appendToAuthorizationList ( allChannels , docChannelMap . write ) ; appendToAuthorizationList ( allChannels , docChannelMap . add ) ; appendToAuthorizationList ( allChannels , docChannelMap . replace ) ; appendToAuthorizationList ( allChannels , docChannelMap . remove ) ; } return allChannels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a list of authorizations ( e . g . channels roles users ) for the current document write operation type ( add replace or remove ) [CODESPLIT] function getRequiredAuthorizations ( doc , oldDoc , authorizationDefinition ) { var authorizationMap = utils . resolveDocumentConstraint ( authorizationDefinition ) ; if ( utils . isValueNullOrUndefined ( authorizationMap ) ) { // This document type does not define any authorizations (channels, roles, users) at all return null ; } var requiredAuthorizations = [ ] ; var writeAuthorizationFound = false ; if ( authorizationMap . write ) { writeAuthorizationFound = true ; appendToAuthorizationList ( requiredAuthorizations , authorizationMap . write ) ; } if ( doc . _deleted ) { if ( authorizationMap . remove ) { writeAuthorizationFound = true ; appendToAuthorizationList ( requiredAuthorizations , authorizationMap . remove ) ; } } else if ( ! utils . isDocumentMissingOrDeleted ( oldDoc ) && authorizationMap . replace ) { writeAuthorizationFound = true ; appendToAuthorizationList ( requiredAuthorizations , authorizationMap . replace ) ; } else if ( utils . isDocumentMissingOrDeleted ( oldDoc ) && authorizationMap . add ) { writeAuthorizationFound = true ; appendToAuthorizationList ( requiredAuthorizations , authorizationMap . add ) ; } if ( writeAuthorizationFound ) { return requiredAuthorizations ; } else { // This document type does not define any authorizations (channels, roles, users) that apply to this particular write operation type return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures the user is authorized to create / replace / delete this document [CODESPLIT] function authorize ( doc , oldDoc , docDefinition ) { var authorizedChannels = getRequiredAuthorizations ( doc , oldDoc , docDefinition . channels ) ; var authorizedRoles = getRequiredAuthorizations ( doc , oldDoc , docDefinition . authorizedRoles ) ; var authorizedUsers = getRequiredAuthorizations ( doc , oldDoc , docDefinition . authorizedUsers ) ; var channelMatch = false ; if ( authorizedChannels ) { try { requireAccess ( authorizedChannels ) ; channelMatch = true ; } catch ( ex ) { // The user has none of the authorized channels if ( ! authorizedRoles && ! authorizedUsers ) { // ... and the document definition does not specify any authorized roles or users throw ex ; } } } var roleMatch = false ; if ( authorizedRoles ) { try { requireRole ( authorizedRoles ) ; roleMatch = true ; } catch ( ex ) { // The user belongs to none of the authorized roles if ( ! authorizedChannels && ! authorizedUsers ) { // ... and the document definition does not specify any authorized channels or users throw ex ; } } } var userMatch = false ; if ( authorizedUsers ) { try { requireUser ( authorizedUsers ) ; userMatch = true ; } catch ( ex ) { // The user does not match any of the authorized usernames if ( ! authorizedChannels && ! authorizedRoles ) { // ... and the document definition does not specify any authorized channels or roles throw ex ; } } } if ( ! authorizedChannels && ! authorizedRoles && ! authorizedUsers ) { // The document type does not define any channels, roles or users that apply to this particular write operation type, so fall back to // Sync Gateway's default behaviour for an empty channel list: 403 Forbidden for requests via the public API and either 200 OK or 201 // Created for requests via the admin API. That way, the admin API will always be able to create, replace or remove documents, // regardless of their authorized channels, roles or users, as intended. requireAccess ( [ ] ) ; } else if ( ! channelMatch && ! roleMatch && ! userMatch ) { // None of the authorization methods (e.g. channels, roles, users) succeeded var errorMessage = 'missing channel access' ; var error = new Error ( errorMessage ) ; error . forbidden = errorMessage ; throw error ; } return { channels : authorizedChannels , roles : authorizedRoles , users : authorizedUsers } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Output help information if necessary [CODESPLIT] function outputHelpIfNecessary ( cmd , options ) { options = options || [ ] ; for ( var i = 0 ; i < options . length ; i ++ ) { if ( options [ i ] === '--help' || options [ i ] === '-h' ) { cmd . outputHelp ( ) ; process . exit ( 0 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes an argument an returns its human readable equivalent for help usage . [CODESPLIT] function humanReadableArgName ( arg ) { var nameOutput = arg . name + ( arg . variadic === true ? '...' : '' ) ; return arg . required ? '<' + nameOutput + '>' : '[' + nameOutput + ']' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The following functions are nested within this function so they can share access to the doc oldDoc and validationErrors params and the attachmentReferenceValidators and itemStack variables [CODESPLIT] function validateObjectProperties ( propertyValidators , allowUnknownProperties , ignoreInternalProperties ) { var currentItemEntry = itemStack [ itemStack . length - 1 ] ; var objectValue = currentItemEntry . itemValue ; var oldObjectValue = currentItemEntry . oldItemValue ; var supportedProperties = [ ] ; for ( var propertyValidatorName in propertyValidators ) { var validator = propertyValidators [ propertyValidatorName ] ; if ( utils . isValueNullOrUndefined ( validator ) || utils . isValueNullOrUndefined ( resolveItemConstraint ( validator . type ) ) ) { // Skip over non-validator fields/properties continue ; } var propertyValue = objectValue [ propertyValidatorName ] ; var oldPropertyValue ; if ( ! utils . isValueNullOrUndefined ( oldObjectValue ) ) { oldPropertyValue = oldObjectValue [ propertyValidatorName ] ; } supportedProperties . push ( propertyValidatorName ) ; itemStack . push ( { itemValue : propertyValue , oldItemValue : oldPropertyValue , itemName : propertyValidatorName } ) ; validateItemValue ( validator ) ; itemStack . pop ( ) ; } // Verify there are no unsupported properties in the object if ( ! allowUnknownProperties ) { for ( var propertyName in objectValue ) { if ( ignoreInternalProperties && propertyName . indexOf ( '_' ) === 0 ) { // These properties are special cases that should always be allowed - generally only applied at the root // level of the document continue ; } if ( supportedProperties . indexOf ( propertyName ) < 0 ) { var objectPath = buildItemPath ( itemStack ) ; var fullPropertyPath = objectPath ? objectPath + '.' + propertyName : propertyName ; validationErrors . push ( 'property \"' + fullPropertyPath + '\" is not supported' ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs the fully qualified path of the item at the top of the given stack [CODESPLIT] function buildItemPath ( itemStack ) { var nameComponents = [ ] ; for ( var i = 0 ; i < itemStack . length ; i ++ ) { var itemName = itemStack [ i ] . itemName ; if ( ! itemName ) { // Skip null or empty names (e.g. the first element is typically the root of the document, which has no name) continue ; } else if ( nameComponents . length < 1 || itemName . indexOf ( '[' ) === 0 ) { nameComponents . push ( itemName ) ; } else { nameComponents . push ( '.' + itemName ) ; } } return nameComponents . join ( '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defined as a function rather than a plain object because it contains lazy references that result in recursive references between the complex types ( e . g . array object hashtable ) and the main propertyValidators schema [CODESPLIT] function typeSpecificConstraintSchemas ( ) { return { any : { } , string : { mustNotBeEmpty : dynamicConstraintSchema ( joi . boolean ( ) ) , mustBeTrimmed : dynamicConstraintSchema ( joi . boolean ( ) ) , regexPattern : dynamicConstraintSchema ( regexSchema ) , minimumLength : dynamicConstraintSchema ( integerSchema . min ( 0 ) ) , maximumLength : maximumSizeConstraintSchema ( 'minimumLength' ) , minimumValue : dynamicConstraintSchema ( joi . string ( ) ) , minimumValueExclusive : dynamicConstraintSchema ( joi . string ( ) ) , maximumValue : dynamicConstraintSchema ( joi . string ( ) ) , maximumValueExclusive : dynamicConstraintSchema ( joi . string ( ) ) , mustEqualIgnoreCase : dynamicConstraintSchema ( joi . string ( ) ) } , integer : { minimumValue : dynamicConstraintSchema ( integerSchema ) , minimumValueExclusive : dynamicConstraintSchema ( integerSchema ) , maximumValue : maximumValueInclusiveNumberConstraintSchema ( integerSchema ) , maximumValueExclusive : maximumValueExclusiveNumberConstraintSchema ( integerSchema ) } , float : { minimumValue : dynamicConstraintSchema ( joi . number ( ) ) , minimumValueExclusive : dynamicConstraintSchema ( joi . number ( ) ) , maximumValue : maximumValueInclusiveNumberConstraintSchema ( joi . number ( ) ) , maximumValueExclusive : maximumValueExclusiveNumberConstraintSchema ( joi . number ( ) ) } , boolean : { } , datetime : { minimumValue : dynamicConstraintSchema ( datetimeSchema ) , minimumValueExclusive : dynamicConstraintSchema ( datetimeSchema ) , maximumValue : dynamicConstraintSchema ( datetimeSchema ) , maximumValueExclusive : dynamicConstraintSchema ( datetimeSchema ) } , date : { minimumValue : dynamicConstraintSchema ( dateOnlySchema ) , minimumValueExclusive : dynamicConstraintSchema ( dateOnlySchema ) , maximumValue : dynamicConstraintSchema ( dateOnlySchema ) , maximumValueExclusive : dynamicConstraintSchema ( dateOnlySchema ) } , time : { minimumValue : dynamicConstraintSchema ( timeOnlySchema ) , minimumValueExclusive : dynamicConstraintSchema ( timeOnlySchema ) , maximumValue : dynamicConstraintSchema ( timeOnlySchema ) , maximumValueExclusive : dynamicConstraintSchema ( timeOnlySchema ) } , timezone : { minimumValue : dynamicConstraintSchema ( timezoneSchema ) , minimumValueExclusive : dynamicConstraintSchema ( timezoneSchema ) , maximumValue : dynamicConstraintSchema ( timezoneSchema ) , maximumValueExclusive : dynamicConstraintSchema ( timezoneSchema ) } , enum : { predefinedValues : dynamicConstraintSchema ( joi . array ( ) . required ( ) . min ( 1 ) . items ( [ integerSchema , joi . string ( ) ] ) ) } , uuid : { minimumValue : dynamicConstraintSchema ( uuidSchema ) , minimumValueExclusive : dynamicConstraintSchema ( uuidSchema ) , maximumValue : dynamicConstraintSchema ( uuidSchema ) , maximumValueExclusive : dynamicConstraintSchema ( uuidSchema ) } , attachmentReference : { maximumSize : dynamicConstraintSchema ( integerSchema . min ( 1 ) . max ( 20971520 ) ) , supportedExtensions : dynamicConstraintSchema ( joi . array ( ) . min ( 1 ) . items ( joi . string ( ) ) ) , supportedContentTypes : dynamicConstraintSchema ( joi . array ( ) . min ( 1 ) . items ( joi . string ( ) . min ( 1 ) ) ) , regexPattern : dynamicConstraintSchema ( regexSchema ) } , array : { mustNotBeEmpty : dynamicConstraintSchema ( joi . boolean ( ) ) , minimumLength : dynamicConstraintSchema ( integerSchema . min ( 0 ) ) , maximumLength : maximumSizeConstraintSchema ( 'minimumLength' ) , arrayElementsValidator : dynamicConstraintSchema ( joi . lazy ( ( ) => schema ) ) } , object : { allowUnknownProperties : dynamicConstraintSchema ( joi . boolean ( ) ) , propertyValidators : dynamicConstraintSchema ( joi . object ( ) . min ( 1 ) . pattern ( / ^.+$ / , joi . lazy ( ( ) => schema ) ) ) } , hashtable : { minimumSize : dynamicConstraintSchema ( integerSchema . min ( 0 ) ) , maximumSize : maximumSizeConstraintSchema ( 'minimumSize' ) , hashtableKeysValidator : dynamicConstraintSchema ( joi . object ( ) . keys ( { mustNotBeEmpty : dynamicConstraintSchema ( joi . boolean ( ) ) , regexPattern : dynamicConstraintSchema ( regexSchema ) } ) ) , hashtableValuesValidator : dynamicConstraintSchema ( joi . lazy ( ( ) => schema ) ) } , conditional : { validationCandidates : dynamicConstraintSchema ( conditionalValidationCandidatesSchema ( ) ) . required ( ) } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that a business ID is valid ( an integer greater than 0 ) and is not changed from the old version of the document [CODESPLIT] function validateBusinessIdProperty ( doc , oldDoc , currentItemEntry , validationItemStack ) { var parentObjectElement = validationItemStack [ validationItemStack . length - 1 ] ; var businessId = currentItemEntry . itemValue ; var oldBusinessId = currentItemEntry . oldItemValue ; var validationErrors = [ ] ; if ( parentObjectElement . oldItemValue && oldBusinessId !== businessId ) { validationErrors . push ( 'cannot change \"businessId\" property' ) ; } return validationErrors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the ID of the business to which the document belongs [CODESPLIT] function getBusinessId ( doc , oldDoc ) { var regex = / ^biz\\.([A-Za-z0-9_-]+)(?:\\..+)?$ / ; var matchGroups = regex . exec ( doc . _id ) ; if ( matchGroups ) { return matchGroups [ 1 ] ; } else if ( oldDoc && oldDoc . businessId ) { // The document ID doesn't contain a business ID, so use the property from the old document return oldDoc . businessId || null ; } else { // Neither the document ID nor the old document's contents contain a business ID, so use the property from the new document return doc . businessId || null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a function that returns the view add replace remove channels extrapolated from the specified base privilege name which is formatted according to the de facto Books convention of VIEW_FOOBAR ADD_FOOBAR CHANGE_FOOBAR and REMOVE_FOOBAR assuming the base privilege name is FOOBAR [CODESPLIT] function toDefaultSyncChannels ( doc , oldDoc , basePrivilegeName ) { var businessId = getBusinessId ( doc , oldDoc ) ; return function ( doc , oldDoc ) { return { view : [ toSyncChannel ( businessId , 'VIEW_' + basePrivilegeName ) ] , add : [ toSyncChannel ( businessId , 'ADD_' + basePrivilegeName ) ] , replace : [ toSyncChannel ( businessId , 'CHANGE_' + basePrivilegeName ) ] , remove : [ toSyncChannel ( businessId , 'REMOVE_' + basePrivilegeName ) ] } ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check that a given value is a valid ISO 8601 format date string with optional time and time zone components [CODESPLIT] function isIso8601DateTimeString ( value ) { var dateAndTimePieces = splitDateAndTime ( value ) ; var date = extractDateStructureFromDateAndTime ( dateAndTimePieces ) ; if ( date ) { var timeAndTimezone = extractTimeStructuresFromDateAndTime ( dateAndTimePieces ) ; var time = timeAndTimezone . time ; var timezone = timeAndTimezone . timezone ; return isValidDateStructure ( date ) && isValidTimeStructure ( time ) && ( timezone === null || isValidTimeZoneStructure ( timezone ) ) ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the given time to the number of milliseconds since hour 0 [CODESPLIT] function normalizeIso8601Time ( time , timezoneOffsetMinutes ) { var msPerSecond = 1000 ; var msPerMinute = 60000 ; var msPerHour = 3600000 ; var effectiveTimezoneOffset = timezoneOffsetMinutes || 0 ; var rawTimeMs = ( time . hour * msPerHour ) + ( time . minute * msPerMinute ) + ( time . second * msPerSecond ) + time . millisecond ; return rawTimeMs - ( effectiveTimezoneOffset * msPerMinute ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares the given time strings . Returns a negative number if a is less than b a positive number if a is greater than b or zero if a and b are equal . [CODESPLIT] function compareTimes ( a , b ) { if ( typeof a !== 'string' || typeof b !== 'string' ) { return NaN ; } return normalizeIso8601Time ( parseIso8601Time ( a ) ) - normalizeIso8601Time ( parseIso8601Time ( b ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares the given date representations . Returns a negative number if a is less than b a positive number if a is greater than b or zero if a and b are equal . [CODESPLIT] function compareDates ( a , b ) { var aPieces = extractDatePieces ( a ) ; var bPieces = extractDatePieces ( b ) ; if ( aPieces === null || bPieces === null ) { return NaN ; } for ( var pieceIndex = 0 ; pieceIndex < aPieces . length ; pieceIndex ++ ) { if ( aPieces [ pieceIndex ] < bPieces [ pieceIndex ] ) { return - 1 ; } else if ( aPieces [ pieceIndex ] > bPieces [ pieceIndex ] ) { return 1 ; } } // If we got here, the two parameters represent the same date/point in time return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an ISO 8601 time zone into the number of minutes offset from UTC [CODESPLIT] function normalizeIso8601TimeZone ( value ) { return value ? value . multiplicationFactor * ( ( value . hour * 60 ) + value . minute ) : - ( new Date ( ) . getTimezoneOffset ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////////////////////// Only Function Definitions Beyond This Point The main process of starting an xGraph System . [CODESPLIT] async function initiate ( ) { log . i ( '--Nexus/Initiate' ) ; let Setup = { } ; let Start = { } ; cacheInterface = new CacheInterface ( { path : __options . cache , log } ) ; let cache = await cacheInterface . loadCache ( ) ; Start = cache . start ; Setup = cache . setup ; Stop = Object . assign ( Stop , cache . stop ) ; await setup ( ) ; await start ( ) ; run ( ) ; ///////////////////////////////////////////////////////////////////////////////////////// // // Only Helper Functions Beyond This Point // // /**\n\t\t\t\t * Call setup on the required Module Apexes\n\t\t\t\t */ async function setup ( ) { log . i ( '--Nexus/Setup' ) ; //build the setup promise array let setupArray = [ ] ; for ( let pid in Setup ) { setupArray . push ( new Promise ( ( resolve , _reject ) => { let com = { } ; com . Cmd = Setup [ pid ] ; com . Passport = { } ; com . Passport . To = pid ; com . Passport . Pid = genPid ( ) ; sendMessage ( com , resolve ) ; } ) ) ; } await Promise . all ( setupArray ) ; log . v ( '--Nexus: All Setups Complete' ) ; } /**\n\t\t\t\t * Call Start on the required Module Apexes\n\t\t\t\t */ async function start ( ) { log . i ( '--Nexus/Start' ) ; //build the setup promise array let startArray = [ ] ; for ( let pid in Start ) { startArray . push ( new Promise ( ( resolve , _reject ) => { let com = { } ; com . Cmd = Start [ pid ] ; com . Passport = { } ; com . Passport . To = pid ; com . Passport . Pid = genPid ( ) ; sendMessage ( com , resolve ) ; } ) ) ; } await Promise . all ( startArray ) ; log . v ( '--Nexus: All Starts Complete' ) ; } /**\n\t\t\t\t * Send Finished command if the process was generated\n\t\t\t\t */ function run ( ) { log . i ( '--Nexus/Run' ) ; if ( 'send' in process ) { process . send ( '{\"Cmd\":\"Finished\"}' ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////////////// Only Helper Functions Beyond This Point Call setup on the required Module Apexes [CODESPLIT] async function setup ( ) { log . i ( '--Nexus/Setup' ) ; //build the setup promise array let setupArray = [ ] ; for ( let pid in Setup ) { setupArray . push ( new Promise ( ( resolve , _reject ) => { let com = { } ; com . Cmd = Setup [ pid ] ; com . Passport = { } ; com . Passport . To = pid ; com . Passport . Pid = genPid ( ) ; sendMessage ( com , resolve ) ; } ) ) ; } await Promise . all ( setupArray ) ; log . v ( '--Nexus: All Setups Complete' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call Start on the required Module Apexes [CODESPLIT] async function start ( ) { log . i ( '--Nexus/Start' ) ; //build the setup promise array let startArray = [ ] ; for ( let pid in Start ) { startArray . push ( new Promise ( ( resolve , _reject ) => { let com = { } ; com . Cmd = Start [ pid ] ; com . Passport = { } ; com . Passport . To = pid ; com . Passport . Pid = genPid ( ) ; sendMessage ( com , resolve ) ; } ) ) ; } await Promise . all ( startArray ) ; log . v ( '--Nexus: All Starts Complete' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper Functions as well as Entity definition [CODESPLIT] async function exit ( code = 0 ) { log . i ( '--Nexus/Stop' ) ; //build the Stop promise array let stopTasks = [ ] ; log . i ( 'Nexus unloading node modules' ) ; log . v ( Object . keys ( require . cache ) . join ( '\\n' ) ) ; for ( let pid in Stop ) { stopTasks . push ( new Promise ( ( resolve , _reject ) => { let com = { } ; com . Cmd = Stop [ pid ] ; com . Passport = { } ; com . Passport . To = pid ; com . Passport . Pid = genPid ( ) ; sendMessage ( com , resolve ) ; } ) ) ; } await Promise . all ( stopTasks ) ; log . v ( '--Nexus: All Stops Complete' ) ; dispatchEvent ( 'exit' , { exitCode : code } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a message from an entity to an Apex entity . If a callback is provided return when finished [CODESPLIT] function sendMessage ( com , fun = _ => _ ) { if ( ! ( 'Passport' in com ) ) { log . w ( 'Message has no Passport, ignored' ) ; log . w ( '    ' + JSON . stringify ( com ) ) ; fun ( 'No Passport' ) ; return ; } if ( ! ( 'To' in com . Passport ) || ! com . Passport . To ) { log . w ( 'Message has no destination entity, ignored' ) ; log . w ( '    ' + JSON . stringify ( com ) ) ; fun ( 'No recipient in message' , com ) ; return ; } if ( ! ( 'Pid' in com . Passport ) ) { log . w ( 'Message has no message id, ignored' ) ; log . w ( '    ' + JSON . stringify ( com ) ) ; fun ( 'No message id' , com ) ; return ; } let pid = com . Passport . To ; let apx = com . Passport . Apex || pid ; if ( pid in EntCache ) { done ( null , EntCache [ pid ] ) ; return ; } else { getEntityContext ( pid , done ) ; } async function done ( err , entContextVolatile ) { let entApex = await new Promise ( res => entContextVolatile . lock ( ( val ) => { res ( val . Apex ) ; return val ; } ) ) ; if ( err ) { log . w ( err ) ; log . w ( JSON . stringify ( com , null , 2 ) ) ; fun ( err , com ) ; return ; } //TODO pid instanceOf ApexEntity if ( ( EntCache [ pid ] . Apex == EntCache [ pid ] . Pid ) || ( entApex == apx ) ) { let entContext = await new Promise ( res => entContextVolatile . lock ( ( context ) => { res ( context ) ; return context ; } ) ) ; entContext . instance . dispatch ( com , reply ) ; } else { let err = 'Trying to send a message to a non-Apex' + 'entity outside of the sending module' ; log . w ( err ) ; log . w ( JSON . stringify ( com , null , 2 ) ) ; fun ( err , com ) ; } } function reply ( err , q ) { // log.i('NEXUS MESSAGE:', com) fun ( err , q ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an Entity in the module which is defined by the apx from the given entity definition The entity is then stored in EntCache ( the location of all in Memory entities ) [CODESPLIT] async function genEntity ( par , fun = _ => log . e ( _ ) ) { if ( ! ( 'Entity' in par ) ) { fun ( 'No Entity defined in Par' ) ; return ; } par . Pid = par . Pid || genPid ( ) ; let impkey = ( par . Module + '/' + par . Entity ) ; let mod = ModCache [ par . Module ] ; if ( ! ( par . Entity in mod . files ) ) { log . e ( '<' + par . Entity + '> not in module <' + par . Module + '>' ) ; fun ( 'Null entity' ) ; return ; } if ( ! ( impkey in ImpCache ) ) { let entString = await new Promise ( async ( res , _rej ) => { mod . file ( par . Entity ) . async ( 'string' ) . then ( ( string ) => res ( string ) ) ; } ) ; ImpCache [ impkey ] = indirectEvalImp ( impkey , entString , log , createRequireFromModuleType ( par . Module ) ) ; } EntCache [ par . Pid ] = new Volatile ( new Entity ( Nxs , ImpCache [ impkey ] , par , log ) ) ; fun ( null , par . Pid ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete an entity from the module s memory . If the entity is an Apex of a Module then delete all the entities found in that module as well . [CODESPLIT] function deleteEntity ( pid , fun = ( err , _pid ) => { if ( err ) log . e ( err ) ; } ) { cacheInterface . deleteEntity ( pid , ( err , removedPidArray ) => { //remove ent from EntCache (in RAM) for ( let i = 0 ; i < removedPidArray . length ; i ++ ) { let entPid = removedPidArray [ i ] ; if ( entPid in EntCache ) { delete EntCache [ entPid ] ; } } log . v ( ` ${ ( removedPidArray . length == 1 ) ? 'Entity' : 'Entities' } ${ removedPidArray . join ( ' ' ) } ` ) ; fun ( err , pid ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save an entity file . Make sure that all nested files exist in the cache prior to saving said file [CODESPLIT] async function saveEntity ( par , fun = ( err , _pid ) => { if ( err ) log . e ( err ) ; } ) { let saveEntity = ( async ( par ) => { await new Promise ( ( res , rej ) => { cacheInterface . saveEntityPar ( par , ( err , pid ) => { if ( err ) { log . e ( err , 'saving ' , pid ) ; rej ( err ) ; } log . v ( ` ${ par . Pid } ` ) ; res ( ) ; } ) ; } ) ; } ) ; //check if the entity is the modules Apex if ( par . Pid != par . Apex ) { //check if the Apex exists in the cache cacheInterface . getEntityPar ( par . Apex , async ( err ) => { if ( err ) { //get the Apex's par from the EntCache let apexPar = await new Promise ( ( res , _rej ) => { EntCache [ par . Apex ] . lock ( ( entityContext ) => { res ( entityContext . Par ) ; return entityContext ; } ) ; } ) ; log . v ( 'Must first save the Apex -- Saving...' ) ; await saveEntity ( apexPar ) ; await saveEntity ( par ) ; fun ( null , par . Pid ) ; } else { //this entity is not the apex and the apex is alread in the cache await saveEntity ( par ) ; fun ( null , par . Pid ) ; } } ) ; } else { await saveEntity ( par ) ; fun ( null , par . Pid ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a module into the in memory Module Cache ( ModCache ) [CODESPLIT] async function addModule ( modName , modZip , fun ) { //modZip is the uint8array that can be written directly to the cache directory if ( checkFlag ( 'allow-add-module' ) ) { try { let newModname = await cacheInterface . addModule ( modName , modZip ) ; fun ( null , newModname ) ; } catch ( e ) { fun ( e , modName ) ; } } else { let err = 'addModule not permitted in current xGraph process\\n' + 'run xgraph with --allow-add-module to enable' ; log . w ( err ) ; fun ( err ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Access a file that exists in the module . json [CODESPLIT] function getFile ( module , filename , fun = _ => _ ) { let mod = ModCache [ module ] ; if ( filename in mod . files ) { mod . file ( filename ) . async ( 'string' ) . then ( ( dat ) => { fun ( null , dat ) ; } ) ; return ; } let err = ` ${ filename } ${ module } ` ; log . e ( err ) ; fun ( err ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Spin up an entity from cache into memory and retrievd its context otherwise just return it s context from memory [CODESPLIT] async function getEntityContext ( pid , fun = _ => _ ) { EntCache [ pid ] = new Volatile ( { } ) ; await EntCache [ pid ] . lock ( ( _entityContext ) => { return new Promise ( ( res , _rej ) => { cacheInterface . getEntityPar ( pid , ( err , data ) => { let par = JSON . parse ( data . toString ( ) ) ; if ( err ) { log . e ( ` ${ data . moduleType } ${ pid } ` ) ; log . e ( err ) ; fun ( 'Unavailable' ) ; return ; } let impkey = par . Module + '/' + par . Entity ; if ( impkey in ImpCache ) { BuildEnt ( ) ; return ; } GetModule ( par . Module , async function ( err , mod ) { if ( err ) { log . e ( 'Module <' + par . Module + '> not available' ) ; fun ( 'Module not available' ) ; return ; } if ( ! ( par . Entity in mod . files ) ) { log . e ( '<' + par . Entity + '> not in module <' + par . Module + '>' ) ; fun ( 'Null entity' ) ; return ; } let entString = await new Promise ( async ( res , _rej ) => { mod . file ( par . Entity ) . async ( 'string' ) . then ( ( string ) => res ( string ) ) ; } ) ; log . v ( ` ${ par . Module } ${ par . Entity . split ( '.' ) [ 0 ] } ` ) ; ImpCache [ impkey ] = indirectEvalImp ( impkey , entString , log , createRequireFromModuleType ( par . Module ) ) ; BuildEnt ( ) ; } ) ; function BuildEnt ( ) { // TODO: rethink the whole process of having to call out a setup and start res ( new Entity ( Nxs , ImpCache [ impkey ] , par , log ) ) ; } } ) ; } ) ; } ) ; fun ( null , EntCache [ pid ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts an instance of a module that exists in the cache . After generating the instance Apex receives a setup and start command synchronously [CODESPLIT] async function genModule ( moduleDefinition , fun = _ => _ ) { moduleDefinition = JSON . parse ( JSON . stringify ( moduleDefinition ) ) ; let moduleDefinitions = moduleDefinition ; if ( 'Module' in moduleDefinition && ( typeof moduleDefinition . Module == 'string' ) ) { moduleDefinitions = { 'Top' : moduleDefinition } ; } let Setup = { } ; let Start = { } ; let PromiseArray = [ ] ; let symbols = { } ; // loop over the keys to assign pids to the local dictionary and the // module definitions (moduleDefinitions) for ( let key in moduleDefinitions ) { symbols [ key ] = genPid ( ) ; } //compile each module for ( let moduleKey in moduleDefinitions ) { //do a GetModule and compile instance for each  PromiseArray . push ( new Promise ( ( res , _rej ) => { let inst = moduleDefinitions [ moduleKey ] ; GetModule ( inst . Module , async function ( err , mod ) { if ( err ) { log . e ( 'GenModule err -' , err ) ; fun ( err ) ; return ; } let pidapx = symbols [ moduleKey ] ; for ( let key in inst . Par ) { let val = inst . Par [ key ] ; if ( typeof val == 'string' ) { if ( val . startsWith ( '$' ) ) { let symbol = val . substr ( 1 ) ; if ( symbol in symbols ) { inst . Par [ key ] = symbols [ symbol ] ; } else { log . w ( ` ${ symbol } ` ) ; log . v ( ` ${ Object . keys ( symbols ) } ` ) ; } } if ( val . startsWith ( '\\\\' ) ) { let escaping = val . charAt ( 1 ) ; if ( escaping == '$' || escaping == '\\\\' ) { //these are valid escape character inst . Par [ key ] = val . substr ( 1 ) ; } else { //invalid log . w ( ` \\\\ ${ escaping } ` ) ; } } } else { inst . Par [ key ] = val ; } } await compileInstance ( pidapx , inst ) ; let schema = await new Promise ( async ( res , _rej ) => { if ( 'schema.json' in mod . files ) { mod . file ( 'schema.json' ) . async ( 'string' ) . then ( function ( schemaString ) { res ( JSON . parse ( schemaString ) ) ; } ) ; } else { log . e ( 'Module <' + inst . Module + '> schema not in ModCache' ) ; res ( ) ; return ; } } ) ; if ( '$Setup' in schema . Apex ) Setup [ pidapx ] = schema . Apex [ '$Setup' ] ; if ( '$Start' in schema . Apex ) Start [ pidapx ] = schema . Apex [ '$Start' ] ; res ( ) ; } ) ; } ) ) ; } await Promise . all ( PromiseArray ) ; log . v ( 'Modules' , JSON . stringify ( symbols , null , 2 ) ) ; log . v ( 'Setup' , JSON . stringify ( Setup , null , 2 ) ) ; log . v ( 'Start' , JSON . stringify ( Start , null , 2 ) ) ; await setup ( ) ; await start ( ) ; fun ( null , ( 'Top' in symbols ) ? symbols [ 'Top' ] : null , symbols ) ; /**\n\t\t\t * Call setup on the required Module Apexes\n\t\t\t */ async function setup ( ) { //build the setup promise array let setupArray = [ ] ; for ( let pid in Setup ) { setupArray . push ( new Promise ( ( resolve , _reject ) => { let com = { } ; com . Cmd = Setup [ pid ] ; com . Passport = { } ; com . Passport . To = pid ; com . Passport . Pid = genPid ( ) ; sendMessage ( com , resolve ) ; } ) ) ; } await Promise . all ( setupArray ) ; } /**\n\t\t\t\t * Call Start on the required Module Apexes\n\t\t\t\t */ async function start ( ) { //build the setup promise array let startArray = [ ] ; for ( let pid in Start ) { startArray . push ( new Promise ( ( resolve , _reject ) => { let com = { } ; com . Cmd = Start [ pid ] ; com . Passport = { } ; com . Passport . To = pid ; com . Passport . Pid = genPid ( ) ; sendMessage ( com , resolve ) ; } ) ) ; } await Promise . all ( startArray ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate array of entities from module Module must be in cache [CODESPLIT] async function compileInstance ( pidapx , inst , saveRoot = false ) { log . v ( 'compileInstance' , pidapx , JSON . stringify ( inst , null , 2 ) ) ; let Local = { } ; let modnam = ( typeof inst . Module == 'object' ) ? inst . Module . Module : inst . Module ; let mod ; let ents = [ ] ; modnam = modnam . replace ( / :\\/ / g , '.' ) ; if ( modnam in ModCache ) { mod = ModCache [ modnam ] ; } else { log . e ( 'Module <' + modnam + '> not in ModCache' ) ; process . exit ( 1 ) ; return ; } let schema = await new Promise ( async ( res , rej ) => { if ( 'schema.json' in mod . files ) { mod . file ( 'schema.json' ) . async ( 'string' ) . then ( function ( schemaString ) { res ( JSON . parse ( schemaString ) ) ; } ) ; } else { log . e ( 'Module <' + modnam + '> schema not in ModCache' ) ; process . exit ( 1 ) ; rej ( ) ; return ; } } ) ; let entkeys = Object . keys ( schema ) ; //set Pids for each entity in the schema for ( let j = 0 ; j < entkeys . length ; j ++ ) { let entkey = entkeys [ j ] ; if ( entkey === 'Apex' ) { Local [ entkey ] = pidapx ; } else { Local [ entkey ] = genPid ( ) ; } } //unpack the par of each ent for ( let j = 0 ; j < entkeys . length ; j ++ ) { let entkey = entkeys [ j ] ; //start with the pars from the schema let ent = schema [ entkey ] ; ent . Pid = Local [ entkey ] ; ent . Module = modnam ; ent . Apex = pidapx ; //unpack the inst pars to the par of the apex of the instance if ( entkey == 'Apex' && 'Par' in inst ) { let pars = Object . keys ( inst . Par ) ; for ( let ipar = 0 ; ipar < pars . length ; ipar ++ ) { let par = pars [ ipar ] ; ent [ par ] = inst . Par [ par ] ; } } //pars all values for symbols let pars = Object . keys ( ent ) ; for ( let ipar = 0 ; ipar < pars . length ; ipar ++ ) { let par = pars [ ipar ] ; let val = ent [ par ] ; if ( entkey == 'Apex' && saveRoot ) { // if (par == '$Setup') { Setup[ent.Pid] = val; } // if (par == '$Start') { Start[ent.Pid] = val; } } ent [ par ] = await symbol ( val ) ; } ents . push ( ent ) ; } let entsPromise = [ ] ; for ( let par of ents ) { entsPromise . push ( ( async function ( ) { let impkey = modnam + '/' + par . Entity ; if ( ! ( impkey in ImpCache ) ) { let entString = await new Promise ( async ( res , _rej ) => { if ( ! ( par . Entity in mod . files ) ) { log . e ( 'Entity <' + par . Entity + '> not in Module <' + modnam + '>' ) ; process . exit ( 1 ) ; return ; } mod . file ( par . Entity ) . async ( 'string' ) . then ( ( string ) => res ( string ) ) ; } ) ; ImpCache [ impkey ] = indirectEvalImp ( impkey , entString , log , createRequireFromModuleType ( modnam ) ) ; } EntCache [ par . Pid ] = new Volatile ( new Entity ( Nxs , ImpCache [ impkey ] , par , log ) ) ; cacheInterface . EntIndex [ par . Pid ] = par . Apex ; } ) ( ) ) ; } await Promise . all ( entsPromise ) ; async function symbol ( val ) { if ( typeof val === 'object' ) { if ( Array . isArray ( val ) ) { val . map ( v => symbol ( v ) ) ; val = await Promise . all ( val ) ; } else { for ( let key in val ) { val [ key ] = await symbol ( val [ key ] ) ; } } return val ; } if ( typeof val !== 'string' ) return val ; let sym = val . substr ( 1 ) ; if ( val . charAt ( 0 ) === '#' && sym in Local ) return Local [ sym ] ; if ( val . charAt ( 0 ) === '\\\\' ) return sym ; return val ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For retrieving modules Modules come from the cache directory on the harddrive or the ModCache if its already been read to RAM . [CODESPLIT] function GetModule ( ModName , fun = _ => _ ) { ModName = ModName . replace ( / :\\/ / g , '.' ) ; if ( ModName in ModCache ) return fun ( null , ModCache [ ModName ] ) ; else cacheInterface . getModule ( ModName , ( err , moduleZip ) => { if ( err ) return fun ( err ) ; ModCache [ ModName ] = moduleZip ; return fun ( null , ModCache [ ModName ] ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strategy constructor . [CODESPLIT] function Strategy ( options , verify ) { var supportedApiVersions = [ '1' , '2' ] , defaultOptionsByApiVersion = { 1 : { authorizationURL : 'https://www.dropbox.com/1/oauth2/authorize' , tokenURL : 'https://api.dropbox.com/1/oauth2/token' , scopeSeparator : ',' , customHeaders : { } } , 2 : { authorizationURL : 'https://www.dropbox.com/oauth2/authorize' , tokenURL : 'https://api.dropbox.com/oauth2/token' , scopeSeparator : ',' , customHeaders : { 'Content-Type' : 'application/json' } } } ; options = options || { } ; if ( options . apiVersion != null && supportedApiVersions . indexOf ( options . apiVersion . toString ( ) ) === - 1 ) { throw new Error ( 'Unsupported Dropbox API version. Supported versions are \"1\" and \"2\".' ) ; } this . _apiVersion = options . apiVersion || '1' ; options . authorizationURL = options . authorizationURL || defaultOptionsByApiVersion [ this . _apiVersion ] . authorizationURL ; options . tokenURL = options . tokenURL || defaultOptionsByApiVersion [ this . _apiVersion ] . tokenURL ; options . scopeSeparator = options . scopeSeparator || defaultOptionsByApiVersion [ this . _apiVersion ] . scopeSeparator ; options . customHeaders = options . customHeaders || defaultOptionsByApiVersion [ this . _apiVersion ] . customHeaders ; OAuth2Strategy . call ( this , options , verify ) ; this . name = 'dropbox-oauth2' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////// Only helper functions defined below in this scope [CODESPLIT] async function retrieveModules ( modules ) { modules = JSON . parse ( JSON . stringify ( modules ) ) ; const xgrls = [ ] ; for ( const moduleName in modules ) { const xgrl = Config . Sources [ modules [ moduleName ] . Source ] ; if ( xgrls . indexOf ( xgrl ) === - 1 ) xgrls . push ( xgrl ) ; modules [ moduleName ] . Source = xgrl } // console.dir(xgrls); let promises = [ ] ; for ( const xgrl of xgrls ) { promises . push ( new Promise ( async ( res ) => { let broker ; if ( xgrl in BrokerCache ) { broker = BrokerCache [ xgrl ] ; } else { const timer = log . time ( 'Booting Broker' ) ; broker = new Broker ( xgrl , { ... __options } ) ; BrokerCache [ xgrl ] = broker ; await broker . startup ; log . timeEnd ( timer ) ; } const modulePromises = [ ] ; for ( const moduleName in modules ) { if ( modules [ moduleName ] . Source === xgrl ) { // console.log(`${moduleName} => ${xgrl}`); modulePromises . push ( new Promise ( async ( res ) => { ModCache [ moduleName ] = await broker . getModule ( { Module : moduleName , Version : modules [ moduleName ] . Version || undefined } ) ; res ( ) ; } ) ) } } await Promise . all ( modulePromises ) ; res ( ) ; } ) ) } await Promise . all ( promises ) ; return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads in the given config and fills in the Sources Macros [CODESPLIT] function processSources ( cfg ) { if ( typeof cfg [ 'Sources' ] === 'undefined' ) { log . e ( 'You must defined a Sources object.\\n' ) ; rejectSetup ( 'You must defined a Sources object.' ) ; return ; } let val , sources , subval ; for ( let key in cfg ) { val = cfg [ key ] ; if ( key == 'Sources' ) { Config . Sources = { } ; sources = cfg [ 'Sources' ] ; for ( let subkey in sources ) { subval = sources [ subkey ] ; switch ( typeof subval ) { case 'string' : { Config . Sources [ subkey ] = Macro ( subval ) ; break ; } case 'object' : { Config . Sources [ subkey ] = { } ; for ( let id in subval ) { Config . Sources [ subkey ] [ id . toLowerCase ( ) ] = ( typeof subval [ id ] == 'string' ) ? Macro ( subval [ id ] ) : subval [ id ] ; } if ( ! ( 'port' in Config . Sources [ subkey ] ) ) { Config . Sources [ subkey ] [ 'port' ] = 27000 ; } break ; } default : { log . e ( ` ${ subkey } ${ typeof subval } ` + 'Must be of type string or object' ) ; } } } } else { Config [ key ] = val ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a list of all required modules and their brokers [CODESPLIT] function generateModuleCatalog ( ) { // Create new cache and install high level // module subdirectories. Each of these also // has a link to the source of that module (Module.json). let keys = Object . keys ( Config . Modules ) ; for ( let i = 0 ; i < keys . length ; i ++ ) { let key = keys [ i ] ; if ( key == 'Deferred' ) { let arr = Config . Modules [ 'Deferred' ] ; for ( let idx = 0 ; idx < arr . length ; idx ++ ) { let mod = arr [ idx ] ; log . v ( ` ${ mod . Module || mod } ` ) ; if ( typeof mod == 'string' ) { log . w ( 'Adding Module names directly to Deferred is deprecated' ) ; log . w ( ` ${ mod } ` ) ; mod = { Module : mod } ; } if ( ! ( 'Module' in mod ) ) { log . e ( 'Malformed Deferred Module listing' , mod ) ; rejectSetup ( 'Malformed Deferred Module listing' ) ; return ; } logModule ( key , mod ) ; } } else { if ( typeof Config . Modules [ key ] . Module != 'string' ) { log . e ( 'Malformed Module Definition' ) ; log . e ( JSON . stringify ( Config . Modules [ key ] , null , 2 ) ) ; } logModule ( key , Config . Modules [ key ] ) ; } } /**\n\t\t\t\t\t * Add the module to the Modules object if unique\n\t\t\t\t\t * @param {object} mod \t\tThe module object\n\t\t\t\t\t * @param {string} mod.Module\tThe name of the module\n\t\t\t\t\t * @param {object, string} mod.Source The Module broker or path reference\n\t\t\t\t\t */ function logModule ( key , mod ) { let folder = mod . Module . replace ( / [/:] / g , '.' ) ; if ( ! ( 'Source' in mod ) ) { log . e ( ` ${ key } ${ mod . Module } ` ) ; rejectSetup ( ` ${ key } ` ) ; return ; } let source = { Source : mod . Source , Version : mod . Version } ; if ( ! ( folder in Modules ) ) { Modules [ folder ] = source ; } else { if ( Modules [ folder ] . Source != source . Source || ( Modules [ folder ] . Version != source . Version ) ) { log . e ( ` ${ key } \\n ` + ` ${ JSON . stringify ( Modules [ folder ] , null , 2 ) } ` + ` \\n ${ JSON . stringify ( source , null , 2 ) } ` ) ; rejectSetup ( 'Broker Mismatch Exception' ) ; return ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the module to the Modules object if unique [CODESPLIT] function logModule ( key , mod ) { let folder = mod . Module . replace ( / [/:] / g , '.' ) ; if ( ! ( 'Source' in mod ) ) { log . e ( ` ${ key } ${ mod . Module } ` ) ; rejectSetup ( ` ${ key } ` ) ; return ; } let source = { Source : mod . Source , Version : mod . Version } ; if ( ! ( folder in Modules ) ) { Modules [ folder ] = source ; } else { if ( Modules [ folder ] . Source != source . Source || ( Modules [ folder ] . Version != source . Version ) ) { log . e ( ` ${ key } \\n ` + ` ${ JSON . stringify ( Modules [ folder ] , null , 2 ) } ` + ` \\n ${ JSON . stringify ( source , null , 2 ) } ` ) ; rejectSetup ( 'Broker Mismatch Exception' ) ; return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the modules and all instances to the cache [CODESPLIT] async function buildApexInstances ( processPidReferences ) { if ( processPidReferences ) { // Assign pids to all instance in Config.Modules for ( let instname in Config . Modules ) { if ( instname == 'Deferred' ) continue ; Apex [ instname ] = genPid ( ) ; } log . v ( 'Apex List' , JSON . stringify ( Apex , null , 2 ) ) ; } // Now populate all of the modules from config.json for ( let instname in Config . Modules ) { if ( instname === 'Deferred' ) continue ; await processApexPar ( Apex [ instname ] , Config . Modules [ instname ] , processPidReferences ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------- CompileModule [CODESPLIT] async function processApexPar ( apx , inst , processPidReferences ) { inst = symbolPhase0 ( inst ) ; if ( processPidReferences ) inst . Par = await symbolPhase1 ( inst . Par ) ; inst . Par = await symbolPhase2 ( inst . Par ) ; inst . Par = await symbolPhase3 ( inst . Par ) ; return ; //process {} references function symbolPhase0 ( obj ) { for ( let key in obj ) { if ( typeof obj [ key ] == 'string' ) obj [ key ] = Macro ( obj [ key ] ) ; else if ( typeof obj [ key ] == 'object' ) obj [ key ] = symbolPhase0 ( obj [ key ] ) ; } return obj ; } //process $ references  async function symbolPhase1 ( val ) { if ( typeof val === 'object' ) { if ( Array . isArray ( val ) ) { val = await Promise . all ( val . map ( v => symbolPhase1 ( v ) ) ) ; } else { for ( let key in val ) { val [ key ] = await symbolPhase1 ( val [ key ] ) ; } } return val ; } if ( typeof val !== 'string' ) return val ; let sym = val . substr ( 1 ) ; if ( val . charAt ( 0 ) === '$' ) { if ( sym in Apex ) return Apex [ sym ] ; else { log . v ( sym , Apex ) ; log . e ( ` ${ val } ` ) ; rejectSetup ( ` ${ val } ` ) ; return ; } } return val ; } //process @ system directives async function symbolPhase2 ( val ) { if ( typeof val === 'object' ) { if ( Array . isArray ( val ) ) { val = await Promise . all ( val . map ( v => symbolPhase2 ( v ) ) ) ; } else { for ( let key in val ) { val [ key ] = await symbolPhase2 ( val [ key ] ) ; } } return val ; } if ( typeof val !== 'string' || ( ! val . startsWith ( '@' ) ) ) return val ; let [ directive , path ] = val . split ( ':' ) . map ( v => v . toLocaleLowerCase ( ) . trim ( ) ) ; if ( directive == '@system' ) { let directiveTimer = log . time ( val ) ; let stepTimer = log . time ( 'fs' ) ; let systemPath = Params . config ? Path . dirname ( Params . config ) : CWD ; if ( ! ( Path . isAbsolute ( path ) ) ) { path = Path . join ( Path . resolve ( systemPath ) , path ) ; } let tempConfig ; if ( ! fs . existsSync ( path ) ) { rejectSetup ( ` ${ path } ` ) ; return ; } try { tempConfig = JSON . parse ( fs . readFileSync ( path ) ) ; } catch ( e ) { rejectSetup ( 'Specified configuration file is in an unparsable format.' ) ; return ; } log . timeEnd ( stepTimer ) ; //TODO parse out all $'s, replace with \\\\$ let systemObject ; try { systemObject = await setup ( tempConfig , false ) ; } catch ( e ) { rejectSetup ( ` ${ path } ` ) ; return ; } try { fs . mkdirSync ( Path . join ( CWD , 'Static' ) ) ; } catch ( e ) { log . v ( e ) ; } stepTimer = log . time ( 'bower' ) ; await new Promise ( async resolve => { // let zip = new jszip(); // let cacheBuffer = Buffer.from(systemObject.Cache, 'base64'); // zip.loadAsync(cacheBuffer).then(async (a) => { // \tfor (let key in a.files) { // \t\tif (key === 'manifest.json') continue; for ( let moduleType in systemObject . ModCache ) { let modZip = new jszip ( ) ; // let moduleZipBinary = await zip.file(key).async('base64'); modZip = await new Promise ( ( res ) => { let modZipBuffer = Buffer . from ( systemObject . ModCache [ moduleType ] , 'base64' ) ; modZip . loadAsync ( modZipBuffer ) . then ( zip => { res ( zip ) ; } ) ; } ) ; if ( ! ( 'bower.json' in modZip . files ) ) continue ; let bowerjson = await modZip . file ( 'bower.json' ) . async ( 'string' ) ; let dependencies = JSON . parse ( bowerjson ) . dependencies ; let packageArray = [ ] ; for ( let bowerModuleName in dependencies ) { if ( dependencies [ bowerModuleName ] . indexOf ( '/' ) > 0 ) { packageArray . push ( ` ${ dependencies [ bowerModuleName ] } ` ) ; } else { packageArray . push ( ` ${ bowerModuleName } ` + ` ${ dependencies [ bowerModuleName ] } ` ) ; } await new Promise ( res => { proc . execSync ( 'bower install \"--config.directory=' + ` ${ Path . join ( CWD , 'Static' , 'bower_components' ) } ${ packageArray . join ( '\" \"' ) } ` ) ; log . v ( ` ${ packageArray . join ( ', ' ) } ` ) ; res ( ) ; } ) ; } let bowerComponentsDir = Path . join ( CWD , 'Static' , 'bower_components' ) ; proc . execSync ( 'bower install \"--config.directory=' + ` ${ bowerComponentsDir } ${ packageArray . join ( '\" \"' ) } ` ) ; log . v ( ` ${ packageArray . join ( ', ' ) } ` ) ; } resolve ( ) ; } ) ; log . timeEnd ( stepTimer ) ; stepTimer = log . time ( 'zip it' ) ; //zip up the ModCache for export to the browser or other subsystems let zip = await new Promise ( resolveZip => { let zip = new jszip ( ) ; let man = [ ] ; for ( let folder in systemObject . ModCache ) { let mod = Buffer . from ( systemObject . ModCache [ folder ] , 'base64' ) ; man . push ( folder ) ; zip . file ( folder , mod , { date : new Date ( 'April 2, 2010 00:00:01' ) //the date is required for zip consistency } ) ; } zip . file ( 'manifest.json' , JSON . stringify ( man ) , { date : new Date ( 'April 2, 2010 00:00:01' ) //the date is required for zip consistency } ) ; zip . generateAsync ( { type : 'base64' } ) . then ( function ( data ) { resolveZip ( { 'Config' : systemObject . Config , 'Cache' : data } ) ; } ) ; } ) ; log . timeEnd ( stepTimer ) ; log . timeEnd ( directiveTimer ) ; return zip ; } return val ; } //process @ files and directories  async function symbolPhase3 ( val ) { if ( typeof val === 'object' ) { if ( Array . isArray ( val ) ) { val = await Promise . all ( val . map ( v => symbolPhase3 ( v ) ) ) ; } else { for ( let key in val ) { val [ key ] = await symbolPhase3 ( val [ key ] ) ; } } return val ; } if ( typeof val !== 'string' || ( ! val . startsWith ( '@' ) ) ) return val ; if ( val . charAt ( 0 ) === '@' ) { let directive = val . substr ( 0 ) ; val = val . split ( ':' ) ; let key = val [ 0 ] . toLocaleLowerCase ( ) . trim ( ) ; let encoding = undefined ; if ( key . split ( ',' ) . length == 2 ) { key = key . split ( ',' ) [ 0 ] . trim ( ) ; let _encoding = key . split ( ',' ) [ 1 ] . trim ( ) ; } val = val . slice ( 1 ) . join ( ':' ) . trim ( ) ; let directiveTimer = log . time ( directive ) ; switch ( key ) { case '@filename' : case '@file' : { log . v ( ` ${ directive } ` ) ; let path ; try { let systemPath = Params . config ? Path . dirname ( Params . config ) : CWD ; if ( Path . isAbsolute ( val ) ) path = val ; else { path = Path . join ( Path . resolve ( systemPath ) , val ) ; } log . timeEnd ( directiveTimer ) ; return fs . readFileSync ( path ) . toString ( encoding ) ; } catch ( err ) { log . e ( '@file: (compileInstance) Error reading file ' , path ) ; log . w ( ` ${ inst . Module } ` ) ; } break ; } case '@folder' : case '@directory' : { log . v ( ` ${ directive } ` ) ; let dir ; try { let systemPath = Params . config ? Path . dirname ( Params . config ) : CWD ; if ( Path . isAbsolute ( val ) ) dir = val ; else dir = Path . join ( Path . resolve ( systemPath ) , val ) ; let _return = await buildDir ( dir ) ; log . timeEnd ( directiveTimer ) ; return _return ; } catch ( err ) { og . e ( 'Error reading directory ' , dir ) ; og . w ( ` ${ inst . Module } ` ) ; } break ; } default : { log . w ( ` ${ key } ` + ` ${ inst . Module } ` ) ; } } log . timeEnd ( directiveTimer ) ; } return val ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "process {} references [CODESPLIT] function symbolPhase0 ( obj ) { for ( let key in obj ) { if ( typeof obj [ key ] == 'string' ) obj [ key ] = Macro ( obj [ key ] ) ; else if ( typeof obj [ key ] == 'object' ) obj [ key ] = symbolPhase0 ( obj [ key ] ) ; } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "process $ references [CODESPLIT] async function symbolPhase1 ( val ) { if ( typeof val === 'object' ) { if ( Array . isArray ( val ) ) { val = await Promise . all ( val . map ( v => symbolPhase1 ( v ) ) ) ; } else { for ( let key in val ) { val [ key ] = await symbolPhase1 ( val [ key ] ) ; } } return val ; } if ( typeof val !== 'string' ) return val ; let sym = val . substr ( 1 ) ; if ( val . charAt ( 0 ) === '$' ) { if ( sym in Apex ) return Apex [ sym ] ; else { log . v ( sym , Apex ) ; log . e ( ` ${ val } ` ) ; rejectSetup ( ` ${ val } ` ) ; return ; } } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "process [CODESPLIT] async function symbolPhase2 ( val ) { if ( typeof val === 'object' ) { if ( Array . isArray ( val ) ) { val = await Promise . all ( val . map ( v => symbolPhase2 ( v ) ) ) ; } else { for ( let key in val ) { val [ key ] = await symbolPhase2 ( val [ key ] ) ; } } return val ; } if ( typeof val !== 'string' || ( ! val . startsWith ( '@' ) ) ) return val ; let [ directive , path ] = val . split ( ':' ) . map ( v => v . toLocaleLowerCase ( ) . trim ( ) ) ; if ( directive == '@system' ) { let directiveTimer = log . time ( val ) ; let stepTimer = log . time ( 'fs' ) ; let systemPath = Params . config ? Path . dirname ( Params . config ) : CWD ; if ( ! ( Path . isAbsolute ( path ) ) ) { path = Path . join ( Path . resolve ( systemPath ) , path ) ; } let tempConfig ; if ( ! fs . existsSync ( path ) ) { rejectSetup ( ` ${ path } ` ) ; return ; } try { tempConfig = JSON . parse ( fs . readFileSync ( path ) ) ; } catch ( e ) { rejectSetup ( 'Specified configuration file is in an unparsable format.' ) ; return ; } log . timeEnd ( stepTimer ) ; //TODO parse out all $'s, replace with \\\\$ let systemObject ; try { systemObject = await setup ( tempConfig , false ) ; } catch ( e ) { rejectSetup ( ` ${ path } ` ) ; return ; } try { fs . mkdirSync ( Path . join ( CWD , 'Static' ) ) ; } catch ( e ) { log . v ( e ) ; } stepTimer = log . time ( 'bower' ) ; await new Promise ( async resolve => { // let zip = new jszip(); // let cacheBuffer = Buffer.from(systemObject.Cache, 'base64'); // zip.loadAsync(cacheBuffer).then(async (a) => { // \tfor (let key in a.files) { // \t\tif (key === 'manifest.json') continue; for ( let moduleType in systemObject . ModCache ) { let modZip = new jszip ( ) ; // let moduleZipBinary = await zip.file(key).async('base64'); modZip = await new Promise ( ( res ) => { let modZipBuffer = Buffer . from ( systemObject . ModCache [ moduleType ] , 'base64' ) ; modZip . loadAsync ( modZipBuffer ) . then ( zip => { res ( zip ) ; } ) ; } ) ; if ( ! ( 'bower.json' in modZip . files ) ) continue ; let bowerjson = await modZip . file ( 'bower.json' ) . async ( 'string' ) ; let dependencies = JSON . parse ( bowerjson ) . dependencies ; let packageArray = [ ] ; for ( let bowerModuleName in dependencies ) { if ( dependencies [ bowerModuleName ] . indexOf ( '/' ) > 0 ) { packageArray . push ( ` ${ dependencies [ bowerModuleName ] } ` ) ; } else { packageArray . push ( ` ${ bowerModuleName } ` + ` ${ dependencies [ bowerModuleName ] } ` ) ; } await new Promise ( res => { proc . execSync ( 'bower install \"--config.directory=' + ` ${ Path . join ( CWD , 'Static' , 'bower_components' ) } ${ packageArray . join ( '\" \"' ) } ` ) ; log . v ( ` ${ packageArray . join ( ', ' ) } ` ) ; res ( ) ; } ) ; } let bowerComponentsDir = Path . join ( CWD , 'Static' , 'bower_components' ) ; proc . execSync ( 'bower install \"--config.directory=' + ` ${ bowerComponentsDir } ${ packageArray . join ( '\" \"' ) } ` ) ; log . v ( ` ${ packageArray . join ( ', ' ) } ` ) ; } resolve ( ) ; } ) ; log . timeEnd ( stepTimer ) ; stepTimer = log . time ( 'zip it' ) ; //zip up the ModCache for export to the browser or other subsystems let zip = await new Promise ( resolveZip => { let zip = new jszip ( ) ; let man = [ ] ; for ( let folder in systemObject . ModCache ) { let mod = Buffer . from ( systemObject . ModCache [ folder ] , 'base64' ) ; man . push ( folder ) ; zip . file ( folder , mod , { date : new Date ( 'April 2, 2010 00:00:01' ) //the date is required for zip consistency } ) ; } zip . file ( 'manifest.json' , JSON . stringify ( man ) , { date : new Date ( 'April 2, 2010 00:00:01' ) //the date is required for zip consistency } ) ; zip . generateAsync ( { type : 'base64' } ) . then ( function ( data ) { resolveZip ( { 'Config' : systemObject . Config , 'Cache' : data } ) ; } ) ; } ) ; log . timeEnd ( stepTimer ) ; log . timeEnd ( directiveTimer ) ; return zip ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "process [CODESPLIT] async function symbolPhase3 ( val ) { if ( typeof val === 'object' ) { if ( Array . isArray ( val ) ) { val = await Promise . all ( val . map ( v => symbolPhase3 ( v ) ) ) ; } else { for ( let key in val ) { val [ key ] = await symbolPhase3 ( val [ key ] ) ; } } return val ; } if ( typeof val !== 'string' || ( ! val . startsWith ( '@' ) ) ) return val ; if ( val . charAt ( 0 ) === '@' ) { let directive = val . substr ( 0 ) ; val = val . split ( ':' ) ; let key = val [ 0 ] . toLocaleLowerCase ( ) . trim ( ) ; let encoding = undefined ; if ( key . split ( ',' ) . length == 2 ) { key = key . split ( ',' ) [ 0 ] . trim ( ) ; let _encoding = key . split ( ',' ) [ 1 ] . trim ( ) ; } val = val . slice ( 1 ) . join ( ':' ) . trim ( ) ; let directiveTimer = log . time ( directive ) ; switch ( key ) { case '@filename' : case '@file' : { log . v ( ` ${ directive } ` ) ; let path ; try { let systemPath = Params . config ? Path . dirname ( Params . config ) : CWD ; if ( Path . isAbsolute ( val ) ) path = val ; else { path = Path . join ( Path . resolve ( systemPath ) , val ) ; } log . timeEnd ( directiveTimer ) ; return fs . readFileSync ( path ) . toString ( encoding ) ; } catch ( err ) { log . e ( '@file: (compileInstance) Error reading file ' , path ) ; log . w ( ` ${ inst . Module } ` ) ; } break ; } case '@folder' : case '@directory' : { log . v ( ` ${ directive } ` ) ; let dir ; try { let systemPath = Params . config ? Path . dirname ( Params . config ) : CWD ; if ( Path . isAbsolute ( val ) ) dir = val ; else dir = Path . join ( Path . resolve ( systemPath ) , val ) ; let _return = await buildDir ( dir ) ; log . timeEnd ( directiveTimer ) ; return _return ; } catch ( err ) { og . e ( 'Error reading directory ' , dir ) ; og . w ( ` ${ inst . Module } ` ) ; } break ; } default : { log . w ( ` ${ key } ` + ` ${ inst . Module } ` ) ; } } log . timeEnd ( directiveTimer ) ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build an object to represent a directory [CODESPLIT] async function buildDir ( path ) { let dirObj = { } ; if ( fs . existsSync ( path ) ) { let files = fs . readdirSync ( path ) ; let itemPromises = [ ] ; for ( let file of files ) { itemPromises . push ( new Promise ( async ( resolve ) => { let curPath = path + '/' + file ; if ( fs . lstatSync ( curPath ) . isDirectory ( ) ) { // recurse dirObj [ file ] = await buildDir ( curPath ) ; resolve ( ) ; } else { fs . readFile ( curPath , function ( err , data ) { // log.v(curPath.length > 80 ? curPath.substr(0, 35)  // + ' ... ' + curPath.substr(-40, 40) : curPath); dirObj [ file ] = data . toString ( ) ; resolve ( ) ; } ) ; // dirObj[file] = fs.readFileSync(curPath).toString(encoding); } } ) ) ; } await Promise . all ( itemPromises ) ; return dirObj ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generate a 32 character hexidecimal pid [CODESPLIT] function genPid ( ) { if ( ! Uuid ) { // module.paths = [Path.join(Path.resolve(CacheDir), 'node_modules')]; Uuid = require ( 'uuid/v4' ) ; } let str = Uuid ( ) ; let pid = str . replace ( / - / g , '' ) . toUpperCase ( ) ; return pid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "replace the {} macros passed throught the xgraph cli or __options object [CODESPLIT] function Macro ( str ) { str = str . substr ( 0 ) ; // copy for ( let option in __options ) { str = str . replace ( ` ${ option } ` , __options [ option ] ) ; } return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the system to the cache [CODESPLIT] async function genesis ( system ) { log . i ( ' [Save Cache]' . padStart ( 80 , '=' ) ) ; log . i ( 'Genesis Compile Start:' ) ; let cacheState = null ; if ( fs . existsSync ( CacheDir ) ) cacheState = 'exists' ; cacheInterface = new CacheInterface ( { path : CacheDir , log } ) ; cleanCache ( ) ; log . i ( 'Saving modules and updating dependencies ...' ) ; await cacheModules ( system . ModCache ) ; if ( ! ( __options . state == 'updateOnly' ) ) { log . i ( 'Saving entities ...' ) ; await cacheApexes ( system . Apex , system . Config . Modules ) ; } Stop ( ) ; ///////////////////////////////////////////////////////////// // //\tOnly helper functions beyond this point of this scope // /**\n\t\t\t*  Remove the cache if it currently exists in the given directory\t\n\t\t\t*/ function cleanCache ( ) { // Remove the provided cache directory if ( __options . state == 'development' && cacheState ) { __options . state = 'updateOnly' ; return ; } log . v ( 'Removing the old cache.' ) ; cacheInterface . clean ( ) ; } /**\n\t\t\t * Write the modules to the cache\n\t\t\t * @param {Object} ModCache \t//the set of module zips required for this system\n\t\t\t */ async function cacheModules ( ModCache ) { let timer = log . time ( 'cacheModules' ) ; let ModulePromiseArray = [ ] ; for ( let folder in ModCache ) { ModulePromiseArray . push ( new Promise ( async ( res ) => { await cacheInterface . addModule ( folder , ModCache [ folder ] ) ; log . v ( ` ${ folder } ` ) ; res ( ) ; } ) ) ; } await Promise . all ( ModulePromiseArray ) ; log . timeEnd ( timer ) ; } /**\n\t\t\t * Write the module Apexes to the cache\n\t\t\t * @param {Object} Apexes \t\t\t\t\t\t//The id:Pid of each apex\n\t\t\t * @param {Object} ModuleDefinitions \t//the id:ModuleDefinition from Config\n\t\t\t */ async function cacheApexes ( Apexes , ModuleDefinitions ) { let ModulePromiseArray = [ ] ; for ( let moduleId in Apexes ) { ModulePromiseArray . push ( await cacheInterface . createInstance ( ModuleDefinitions [ moduleId ] , Apexes [ moduleId ] ) ) ; } await Promise . all ( ModulePromiseArray ) ; } /**\n\t\t\t * Resolves the main promise created during genesis call\n\t\t\t */ async function Stop ( ) { log . i ( ` ${ new Date ( ) . toString ( ) } ` ) ; log . i ( ' [Finished]' . padStart ( 80 , '=' ) ) ; for ( const xgrl in BrokerCache ) { const broker = BrokerCache [ xgrl ] ; broker . cleanup ( ) ; } log . timeEnd ( compileTimer ) ; resolveMain ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////// Only helper functions beyond this point of this scope Remove the cache if it currently exists in the given directory [CODESPLIT] function cleanCache ( ) { // Remove the provided cache directory if ( __options . state == 'development' && cacheState ) { __options . state = 'updateOnly' ; return ; } log . v ( 'Removing the old cache.' ) ; cacheInterface . clean ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the modules to the cache [CODESPLIT] async function cacheModules ( ModCache ) { let timer = log . time ( 'cacheModules' ) ; let ModulePromiseArray = [ ] ; for ( let folder in ModCache ) { ModulePromiseArray . push ( new Promise ( async ( res ) => { await cacheInterface . addModule ( folder , ModCache [ folder ] ) ; log . v ( ` ${ folder } ` ) ; res ( ) ; } ) ) ; } await Promise . all ( ModulePromiseArray ) ; log . timeEnd ( timer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the module Apexes to the cache [CODESPLIT] async function cacheApexes ( Apexes , ModuleDefinitions ) { let ModulePromiseArray = [ ] ; for ( let moduleId in Apexes ) { ModulePromiseArray . push ( await cacheInterface . createInstance ( ModuleDefinitions [ moduleId ] , Apexes [ moduleId ] ) ) ; } await Promise . all ( ModulePromiseArray ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves the main promise created during genesis call [CODESPLIT] async function Stop ( ) { log . i ( ` ${ new Date ( ) . toString ( ) } ` ) ; log . i ( ' [Finished]' . padStart ( 80 , '=' ) ) ; for ( const xgrl in BrokerCache ) { const broker = BrokerCache [ xgrl ] ; broker . cleanup ( ) ; } log . timeEnd ( compileTimer ) ; resolveMain ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "load protocol to access modules [CODESPLIT] function getProtocolModule ( protocol ) { return new Promise ( function ( resolve , reject ) { let cacheFilepath = path . join ( appdata , protocol ) ; if ( fs . existsSync ( cacheFilepath ) ) { return resolve ( JSON . parse ( fs . readFileSync ( cacheFilepath ) . toString ( ) ) ) ; } let options = { host : 'protocols.xgraphdev.com' , port : 443 , path : '/' + protocol , method : 'GET' , rejectUnauthorized : false , } ; let req = https . request ( options , function ( res ) { res . setEncoding ( 'utf8' ) ; let response = '' ; res . on ( 'data' , function ( chunk ) { response += chunk ; } ) ; res . on ( 'end' , _ => { try { resolve ( JSON . parse ( response ) ) ; try { fs . writeFileSync ( cacheFilepath , response ) ; } catch ( e ) { reject ( { code : 1 , text : ` ${ cacheFilepath } ` + '\\n delete file and try again' } ) ; } } catch ( e ) { reject ( { code : 0 , text : 'try and retrieve locally' } ) ; } } ) ; } ) ; req . on ( 'error' , function ( e ) { log . e ( 'problem with request: ' + e . message ) ; reject ( { code : 1 , text : 'problem with request: ' + e . message } ) ; } ) ; // write data to request body req . end ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive directory deletion [CODESPLIT] function remDir ( path ) { return ( new Promise ( async ( resolve , _reject ) => { if ( fs . existsSync ( path ) ) { let files = fs . readdirSync ( path ) ; let promiseArray = [ ] ; for ( let fileIndex = 0 ; fileIndex < files . length ; fileIndex ++ ) { promiseArray . push ( new Promise ( async ( resolve2 , _reject2 ) => { let curPath = path + '/' + files [ fileIndex ] ; if ( fs . lstatSync ( curPath ) . isDirectory ( ) ) { // recurse await remDir ( curPath ) ; resolve2 ( ) ; } else { // delete file log . v ( 'Removing Entity ' , files [ fileIndex ] . split ( '.' ) [ 0 ] ) ; fs . unlinkSync ( curPath ) ; resolve2 ( ) ; } } ) ) ; } //make sure all the sub files and directories have been removed; await Promise . all ( promiseArray ) ; log . v ( 'Removing Module Directory ' , path ) ; fs . rmdirSync ( path ) ; resolve ( ) ; } else { log . v ( 'trying to remove nonexistant path ' , path ) ; resolve ( ) ; } } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get mouse position [CODESPLIT] function getMousePosition ( e ) { var mouseObj = void 0 , originalEvent = e . originalEvent ? e . originalEvent : e ; mouseObj = 'changedTouches' in originalEvent && originalEvent . changedTouches ? originalEvent . changedTouches [ 0 ] : originalEvent ; // clientX, Y 쓰면 스크롤에서 문제 발생 return { clientX : mouseObj . pageX , clientY : mouseObj . pageY } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "injects any LAN proxy servers into the request [CODESPLIT] function proxyRequest ( req , res , rule ) { var router , target , path ; injectProxyHeaders ( req , rule ) ; // rewrite the base path of the requested URL path = req . url . replace ( rule . regexp , rule . target . path ) ; if ( useGateway ) { // for HTTP LAN proxies, rewrite the request URL from a relative URL to an absolute URL // also add a header that can be inspected by the unit tests req . url = url . parse ( util . format ( '%s//%s:%s%s' , rule . target . protocol , rule . target . host , rule . target . port , path ) ) . href ; req . headers [ 'X-Forwarded-Url' ] = req . url ; // the proxy target is really the HTTP LAN proxy target = config . gateway ; logger . info ( 'proxy: %s %s --> %s:%s --> %s//%s:%s%s' , req . method , req . url , config . gateway . host , config . gateway . port , rule . target . protocol , rule . target . host , rule . target . port , path ) ; } else { target = rule . target ; logger . info ( 'proxy: %s %s --> %s//%s:%s%s' , req . method , req . url , rule . target . protocol , rule . target . host , rule . target . port , path ) ; req . url = path ; } var errorCallback = function errorCallback ( err , proxyRequest , proxyResponse ) { var status = 500 ; if ( proxyResponse !== undefined && proxyResponse !== null && proxyResponse . statusCode >= 400 ) { status = proxyResponse . statusCode ; } logger . error ( 'proxy: error - %s %s - %s' , proxyRequest . method , proxyRequest . url , err . message ) ; if ( res . status && typeof res . status === 'function' ) { res . status ( status ) . json ( { error : status , message : err . message } ) ; } } ; // get a ProxyServer from the cache router = createRouter ( target ) ; // proxy the request router . web ( req , res , errorCallback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "factory method to cache / fetch HttpProxy instances [CODESPLIT] function createRouter ( target ) { var key = util . format ( '%s//%s:%s' , target . protocol , target . host , target . port ) , router = routers [ key ] , options ; // httpProxy.createProxyServer options // { //   target : <url string to be parsed with the url module> //   forward: <url string to be parsed with the url module> //   agent  : <object to be passed to http(s).request> //   ssl    : <object to be passed to https.createServer()> //   ws     : <true/false, if you want to proxy websockets> //   xfwd   : <true/false, adds x-forward headers> //   secure : <true/false, verify SSL certificate> //   toProxy: passes the absolute URL as the path (useful for proxying to proxies) // } if ( router === undefined || router === null ) { options = { xfwd : true , secure : ( target . protocol && target . protocol === 'https://' ) , target : key , prependPath : ( useGateway === true ) , toProxy : ( useGateway === true ) } ; router = httpProxy . createProxyServer ( options ) ; routers [ key ] = router ; } return router ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "support basic auth for LAN HTTP proxied connections if needed HACK : http - proxy uses node s http . request () . pipe () which doesn t properly support the options . auth setting like http . request . write () as of Node v0 . 10 . 24 so this copies the implementation of request . write () from http . request () SOURCE : https : // github . com / joyent / node / blob / 828f14556e0daeae7fdac08fceaa90952de63f73 / lib / _http_client . js#L84 - L88 [CODESPLIT] function injectAuthHeader ( req ) { if ( useGateway === true && typeof ( config . gateway . auth ) === 'string' && req . headers [ 'authorization' ] === undefined ) { req . headers [ 'authorization' ] = 'Basic ' + new Buffer ( config . gateway . auth ) . toString ( 'base64' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "inject any custom header values into a proxy request along with the x - forwarded - for x - forwarded - port and via headers [CODESPLIT] function injectProxyHeaders ( req , rule ) { // the HTTP host header is often needed by the target webserver config req . headers [ 'host' ] = rule . target . host + ( rule . target . originalPort ? util . format ( ':%d' , rule . target . originalPort ) : '' ) ; // document that this request was proxied req . headers [ 'via' ] = util . format ( 'http://%s:%s' , req . connection . address ( ) . address , req . connection . address ( ) . port ) ; // inject any custom headers as configured config . headers . forEach ( function ( header ) { var value = header . value , name = header . name ; if ( typeof ( value ) === 'function' ) { value = value . call ( undefined , req ) ; } if ( typeof ( value ) !== 'string' ) { value = '' ; } if ( typeof ( name ) === 'string' ) { req . headers [ name . toLowerCase ( ) ] = value ; } } ) ; injectAuthHeader ( req ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reads a config file from either the config file specified on the command line or fallback to a file name json - proxy . config in the working directory return true if the file can be read otherwise return false [CODESPLIT] function parseFile ( filepath , config ) { var contents ; filepath = filepath || path . join ( process . cwd ( ) , '/json-proxy.json' ) ; // if we were passed a config file, read and parse it if ( fs . existsSync ( filepath ) ) { try { var data = fs . readFileSync ( filepath ) ; contents = JSON . parse ( data . toString ( ) ) ; config = parseConfig ( contents , config ) ; // replace the token $config_dir in the webroot arg if ( config . server . webroot && config . server . webroot . length > 0 ) { config . server . webroot = config . server . webroot . replace ( \"$config_dir\" , path . dirname ( filepath ) ) ; } } catch ( ex ) { throw new Error ( 'Cannot parse the config file \"' + filepath + '\": ' + ex ) ; } } return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse a config structure overriding any values in config [CODESPLIT] function parseConfig ( contents , config ) { contents . server = contents . server || { } ; contents . proxy = contents . proxy || { } ; if ( contents . proxy . gateway && typeof ( contents . proxy . gateway ) === \"string\" && contents . proxy . gateway . length > 0 ) { contents . proxy . gateway = parseGateway ( contents . proxy . gateway ) ; } contents . proxy . forward = parseConfigMap ( contents . proxy . forward , parseForwardRule ) ; contents . proxy . headers = parseConfigMap ( contents . proxy . headers , parseHeaderRule ) ; // override any values in the config object with values specified in the file; config . server . port = contents . server . port || config . server . port ; config . server . webroot = contents . server . webroot || config . server . webroot ; config . server . html5mode = contents . server . html5mode || config . server . html5mode ; config . proxy . gateway = contents . proxy . gateway || config . proxy . gateway ; config . proxy . forward = contents . proxy . forward || config . proxy . forward ; config . proxy . headers = contents . proxy . headers || config . proxy . headers ; return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "transform a config hash object into an array [CODESPLIT] function parseConfigMap ( map , callback ) { var result = [ ] ; if ( ! ( map instanceof Object ) ) { return map ; } for ( var property in map ) { if ( map . hasOwnProperty ( property ) ) { result . push ( callback ( property , map [ property ] ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reads command line parameters [CODESPLIT] function parseCommandLine ( argv , config ) { if ( argv ) { // read the command line arguments if no config file was given parseCommandLineArgument ( argv . port , function ( item ) { config . server . port = item ; } ) ; parseCommandLineArgument ( argv . html5mode , function ( item ) { config . server . html5mode = item ; } ) ; parseCommandLineArgument ( argv . _ , function ( item ) { config . server . webroot = path . normalize ( item ) ; } ) ; parseCommandLineArgument ( argv . gateway , function ( item ) { config . proxy . gateway = parseGateway ( item ) ; } ) ; parseCommandLineArgument ( argv . forward , function ( item ) { var rule = parseForwardRule ( item ) ; var match = false ; config . proxy . forward . forEach ( function ( item ) { if ( item . regexp . source === rule . regexp . source ) { item . target = rule . target ; match = true ; } } ) ; if ( ! match ) { config . proxy . forward . push ( rule ) ; } } ) ; parseCommandLineArgument ( argv . header , function ( item ) { var rule = parseHeaderRule ( item ) ; var match = false ; config . proxy . headers . forEach ( function ( item ) { if ( item . name === rule . name ) { item . value = rule . value ; match = true ; } } ) ; if ( ! match ) { config . proxy . headers . push ( rule ) ; } } ) ; } return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "argv . X will be an array if multiple - X options are provided otherwise argv . X will just be a scalar value [CODESPLIT] function parseCommandLineArgument ( arg , fn ) { if ( typeof ( fn ) !== 'function' ) return ; if ( Array . isArray ( arg ) ) { arg . forEach ( function ( item ) { fn . call ( null , item ) ; } ) ; } else { if ( arg !== null && arg !== undefined ) { fn . call ( null , arg ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parses rule syntax to create forwarding rules [CODESPLIT] function parseForwardRule ( ) { var token , rule ; if ( arguments [ 0 ] === undefined || arguments [ 0 ] === null ) { return ; } if ( typeof ( arguments [ 0 ] ) === \"object\" ) { return arguments [ 0 ] ; } try { token = tokenize . apply ( null , arguments ) ; rule = { regexp : new RegExp ( '^' + token . name , 'i' ) , target : parseTargetServer ( token . value ) } ; } catch ( e ) { throw new Error ( 'cannot parse the forwarding rule ' + arguments [ 0 ] + ' - ' + e ) ; } return rule ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parses a simple hostname : port argument defaulting to port 80 if not specified [CODESPLIT] function parseTargetServer ( value ) { var target , path ; // insert a http protocol handler if not found in the string if ( value . indexOf ( 'http://' ) !== 0 && value . indexOf ( 'https://' ) !== 0 ) { value = 'http://' + value + '/' ; } target = url . parse ( value ) ; path = target . path ; // url.parse() will default to '/' as the path // we can safely strip this for regexp matches to function properly if ( path === '/' ) { path = '' ; } // support an explict set of regexp unnamed captures (prefixed with `$`) // if the pattern doesn't include a match operator like '$1', '$2', '$3', // then use the RegExp lastMatch operator `$&` if the rewrite rule if ( / \\$\\d / . test ( path ) === false ) { path = [ path , '$&' ] . join ( '' ) ; } return { host : target . hostname , // inject a default port if one wasn't specified port : target . port || ( ( target . protocol === 'https:' ) ? 443 : 80 ) , originalPort : target . port , protocol : target . protocol , path : path } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reads name / value tokens for command line parameters [CODESPLIT] function tokenize ( ) { var token = { name : null , value : null } , temp = null ; if ( arguments . length !== 1 ) { token . name = arguments [ 0 ] ; token . value = arguments [ 1 ] ; return token ; } temp = arguments [ 0 ] ; if ( undefined !== temp && null !== temp ) { temp = temp . split ( '=' ) ; } if ( Array . isArray ( temp ) && temp . length > 1 ) { token . name = temp [ 0 ] ; token . value = temp [ 1 ] ; } return token ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an error with a specific code [CODESPLIT] function withCode ( code , msg ) { const err = new Error ( msg ) ; err . code = code ; return err ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change workinState for a specific branch [CODESPLIT] function updateWorkingState ( repoState , branch , newWorkingState ) { let workingStates = repoState . getWorkingStates ( ) ; const key = branch . getFullName ( ) ; if ( newWorkingState === null ) { // Delete workingStates = workingStates . delete ( key ) ; } else { // Update the entry in the map workingStates = workingStates . set ( key , newWorkingState ) ; } return repoState . set ( 'workingStates' , workingStates ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches the given branch s tree from its SHA and __resets any WorkingState for it__ [CODESPLIT] function fetchTree ( repoState , driver , branch ) { // Fetch a working tree for this branch return WorkingUtils . fetch ( driver , branch ) . then ( ( newWorkingState ) => { return updateWorkingState ( repoState , branch , newWorkingState ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change current branch in the repository ( sync ) . Requires to have fetched the branch . [CODESPLIT] function checkout ( repoState , branch ) { let _branch = branch ; if ( ! ( branch instanceof Branch ) ) { _branch = repoState . getBranch ( branch ) ; if ( branch === null ) { throw Error ( 'Unknown branch ' + branch ) ; } } if ( ! repoState . isFetched ( _branch ) ) { throw Error ( 'Tree for branch ' + _branch . getFullName ( ) + ' must be fetched first' ) ; } return repoState . set ( 'currentBranchName' , _branch . getFullName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch the list of branches in the repository and update them all . Will clear the WorkingStates of all branches that have updated . [CODESPLIT] function fetchBranches ( repoState , driver ) { const oldBranches = repoState . getBranches ( ) ; return driver . fetchBranches ( ) . then ( ( branches ) => { return repoState . set ( 'branches' , branches ) ; } ) . then ( function refreshWorkingStates ( repoState ) { // Remove outdated WorkingStates return oldBranches . reduce ( ( repoState , oldBranch ) => { const fullName = oldBranch . getFullName ( ) ; const newBranch = repoState . getBranch ( fullName ) ; if ( newBranch === null || newBranch . getSha ( ) !== oldBranch . getSha ( ) ) { // Was removed OR updated return updateWorkingState ( repoState , oldBranch , null ) ; } else { // Unchanged return repoState ; } } , repoState ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new RepositoryState from the repo of a Driver . Fetch the branches and checkout master or the first available branch . [CODESPLIT] function initialize ( driver ) { const repoState = RepositoryState . createEmpty ( ) ; return fetchBranches ( repoState , driver ) . then ( ( repoState ) => { const branches = repoState . getBranches ( ) ; const master = branches . find ( function isMaster ( branch ) { return branch . getFullName ( ) === 'master' ; } ) ; const branch = master || branches . first ( ) ; return fetchTree ( repoState , driver , branch ) . then ( ( repoState ) => { return checkout ( repoState , branch ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Force conversion to an arraybuffer [CODESPLIT] function enforceArrayBuffer ( b , encoding ) { if ( isArrayBuffer ( b ) ) return b ; else if ( isBuffer ( b ) ) return fromBuffer ( b ) ; else return fromString ( b , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Force conversion to string with specific encoding [CODESPLIT] function enforceString ( b , encoding ) { if ( is . string ( b ) ) return b ; if ( isArrayBuffer ( b ) ) b = toBuffer ( b ) ; return b . toString ( encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests equality of two ArrayBuffer [CODESPLIT] function equals ( buf1 , buf2 ) { if ( buf1 . byteLength != buf2 . byteLength ) return false ; const dv1 = new Int8Array ( buf1 ) ; const dv2 = new Int8Array ( buf2 ) ; for ( let i = 0 ; i != buf1 . byteLength ; i ++ ) { if ( dv1 [ i ] != dv2 [ i ] ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---- utils ---- [CODESPLIT] function getChange ( parent , sha ) { if ( parent === sha ) { return CHANGE . IDENTICAL ; } else if ( parent === null ) { return CHANGE . ADDED ; } else if ( sha === null ) { return CHANGE . DELETED ; } else { // Both are not null but different return CHANGE . MODIFIED ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Seq of tree mixing changes and the fetched tree [CODESPLIT] function getMergedFileSet ( workingState ) { return Immutable . Set . fromKeys ( getMergedTreeEntries ( workingState ) . filter ( treeEntry => treeEntry . getType ( ) === TreeEntry . TYPES . BLOB ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Map of TreeEntry with sha null when the content is not available as sha . [CODESPLIT] function getMergedTreeEntries ( workingState ) { const removedOrModified = workingState . getChanges ( ) . groupBy ( ( change , path ) => { if ( change . getType ( ) === CHANGES . REMOVE ) { return 'remove' ; } else { // Must be UDPATE or CREATE return 'modified' ; } } ) ; const setToRemove = Immutable . Set . fromKeys ( removedOrModified . get ( 'remove' , [ ] ) ) ; const withoutRemoved = workingState . getTreeEntries ( ) . filter ( ( treeEntry , path ) => { return ! setToRemove . contains ( path ) ; } ) ; const addedTreeEntries = removedOrModified . get ( 'modified' , [ ] ) . map ( function toTreeEntry ( change ) { return new TreeEntry ( { sha : change . hasSha ( ) ? change . getSha ( ) : null , mode : '100644' } ) ; } ) ; return withoutRemoved . concat ( addedTreeEntries ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the file differs from initial tree ( including removed ) [CODESPLIT] function hasPendingChanges ( workingState , filepath ) { // Lookup potential changes const change = workingState . getChanges ( ) . get ( filepath ) ; if ( change ) { return true ; } else { // Else lookup tree const treeEntry = workingState . getTreeEntries ( ) . get ( filepath ) ; if ( ! treeEntry ) { throw error . fileNotFound ( filepath ) ; } else { return false ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to find a SHA if available for the given file [CODESPLIT] function findSha ( workingState , filepath ) { // Lookup potential changes const change = workingState . getChanges ( ) . get ( filepath ) ; // Else lookup tree const treeEntry = workingState . getTreeEntries ( ) . get ( filepath ) ; if ( change ) { if ( change . getType ( ) == CHANGES . REMOVE ) { throw error . fileNotFound ( filepath ) ; } else { return change . getSha ( ) ; } } else if ( treeEntry ) { return treeEntry . getSha ( ) ; } else { throw error . fileNotFound ( filepath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a commit builder from the changes on current branch [CODESPLIT] function prepare ( repoState , opts ) { const workingState = repoState . getCurrentState ( ) ; const changes = workingState . getChanges ( ) ; // Is this an empty commit ? opts . empty = workingState . isClean ( ) ; // Parent SHA opts . parents = new Immutable . List ( [ workingState . getHead ( ) ] ) ; // Get merged tree (with applied changes) opts . treeEntries = WorkingUtils . getMergedTreeEntries ( workingState ) ; // Create map of blobs that needs to be created opts . blobs = changes . filter ( ( change ) => { return ! change . hasSha ( ) ; } ) . map ( ( change ) => { return change . getContent ( ) ; } ) ; return CommitBuilder . create ( opts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flush a commit from the current branch using a driver Then update the reference and pull new workingState [CODESPLIT] function flush ( repoState , driver , commitBuilder , options = { } ) { options = Object . assign ( { branch : repoState . getCurrentBranch ( ) , ignoreEmpty : true } , options ) ; if ( options . ignoreEmpty && commitBuilder . isEmpty ( ) && commitBuilder . getParents ( ) . count ( ) < 2 ) { return Q ( repoState ) ; } // Create new commit return driver . flushCommit ( commitBuilder ) // Forward the branch . then ( ( commit ) => { return driver . forwardBranch ( options . branch , commit . getSha ( ) ) // Fetch new workingState and replace old one . then ( function updateBranch ( ) { const updated = options . branch . merge ( { commit } ) ; return repoState . updateBranch ( options . branch , updated ) ; } , function nonFF ( err ) { if ( err . code === ERRORS . NOT_FAST_FORWARD ) { // Provide the created commit to allow merging it back. err . commit = commit ; } throw err ; } ) ; } ) . then ( function updateWorkingState ( forwardedRepoState ) { const forwardedBranch = forwardedRepoState . getBranch ( options . branch . getFullName ( ) ) ; return RepoUtils . fetchTree ( forwardedRepoState , driver , forwardedBranch ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "colorize strings and send to console . log [CODESPLIT] function format ( color , messages ) { var length = messages . length ; if ( length === 0 || typeof ( color ) !== 'string' ) { return ; } return ( util . format . apply ( null , messages ) [ color ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push a local branch to a remote repository [CODESPLIT] function push ( repoState , driver , opts = { } ) { opts = Object . assign ( { branch : repoState . getCurrentBranch ( ) , force : false , remote : { name : 'origin' } } , opts ) ; return driver . push ( opts ) // Can fail with NOT_FAST_FORWARD // TODO update remote branch in repoState list of branches . thenResolve ( repoState ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pulls changes for local branch from remote repository . Loses any pending changes on it . [CODESPLIT] function pull ( repoState , driver , opts = { } ) { opts = Object . assign ( { branch : repoState . getCurrentBranch ( ) , force : false , remote : { name : 'origin' } } , opts ) ; return driver . pull ( opts ) // Update branch SHA . then ( ( ) => { return driver . fetchBranches ( ) ; } ) . then ( ( branches ) => { const updatedBranch = branches . find ( ( br ) => { return br . name === opts . branch . name ; } ) ; repoState = repoState . updateBranch ( opts . branch , updatedBranch ) ; return RepoUtils . fetchTree ( repoState , driver , updatedBranch ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sync repository with remote by pulling / pushing to the remote . [CODESPLIT] function sync ( repoState , driver , opts = { } ) { opts = Object . assign ( { branch : repoState . getCurrentBranch ( ) , force : false , remote : { name : 'origin' } } , opts ) ; return pull ( repoState , driver , opts ) . fail ( ( err ) => { if ( err . code === ERRORS . REF_NOT_FOUND ) { return Promise ( repoState ) ; } return Promise . reject ( err ) ; } ) . then ( ( newRepoState ) => { return push ( newRepoState , driver , opts ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes a TreeConflict between to tree references . Fetches the trees from the repo . The list of conflicts is the minimal set of conflicts . [CODESPLIT] function compareRefs ( driver , base , head ) { const baseRef = base instanceof Branch ? base . getFullName ( ) : base ; const headRef = head instanceof Branch ? head . getFullName ( ) : head ; return driver . findParentCommit ( baseRef , headRef ) . then ( ( parentCommit ) => { // There can be no parent commit return Q . all ( [ parentCommit ? parentCommit . getSha ( ) : null , baseRef , headRef ] . map ( ( ref ) => { return ref ? driver . fetchWorkingState ( ref ) : WorkingState . createEmpty ( ) ; } ) ) ; } ) . spread ( ( parent , base , head ) => { const conflicts = _compareTrees ( parent . getTreeEntries ( ) , base . getTreeEntries ( ) , head . getTreeEntries ( ) ) ; return new TreeConflict ( { base , head , parent , conflicts } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge solved Conflicts back into a TreeConflict . Unsolved conflicts default to keep base . [CODESPLIT] function solveTree ( treeConflict , solved ) { solved = treeConflict . getConflicts ( ) . merge ( solved ) // Solve unresolved conflicts . map ( function defaultSolve ( conflict ) { if ( ! conflict . isSolved ( ) ) { return conflict . keepBase ( ) ; } else { return conflict ; } } ) ; return treeConflict . set ( 'conflicts' , solved ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a merge commit builder [CODESPLIT] function mergeCommit ( treeConflict , parents , options ) { options = options || { } ; const opts = { } ; // Assume the commit is not empty opts . empty = false ; // Parent SHAs opts . parents = new Immutable . List ( parents ) ; opts . author = options . author ; opts . message = options . message || 'Merged commit' ; // Get the solved tree entries const solvedEntries = _getSolvedEntries ( treeConflict ) ; opts . treeEntries = solvedEntries ; // Create map of blobs that needs to be created const solvedConflicts = treeConflict . getConflicts ( ) ; opts . blobs = solvedEntries . filter ( ( treeEntry ) => { return ! treeEntry . hasSha ( ) ; } ) . map ( ( treeEntry , path ) => { return solvedConflicts . get ( path ) . getSolvedContent ( ) ; } ) ; return CommitBuilder . create ( opts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---- Auxiliaries ---- [CODESPLIT] function _compareTrees ( parentEntries , baseEntries , headEntries ) { const headDiff = _diffEntries ( parentEntries , headEntries ) ; const baseDiff = _diffEntries ( parentEntries , baseEntries ) ; // Conflicting paths are paths... // ... modified by both branches const headSet = Immutable . Set . fromKeys ( headDiff ) ; const baseSet = Immutable . Set . fromKeys ( baseDiff ) ; const conflictSet = headSet . intersect ( baseSet ) . filter ( ( filepath ) => { // ...in different manners return ! Immutable . is ( headDiff . get ( filepath ) , baseDiff . get ( filepath ) ) ; } ) ; // Create the map of Conflict return ( new Immutable . Map ( ) ) . withMutations ( ( map ) => { return conflictSet . reduce ( ( map , filepath ) => { const shas = [ parentEntries , baseEntries , headEntries ] . map ( function getSha ( entries ) { if ( ! entries . has ( filepath ) ) return null ; return entries . get ( filepath ) . getSha ( ) || null ; } ) ; return map . set ( filepath , Conflict . create . apply ( undefined , shas ) ) ; } , map ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the final TreeEntries for a solved TreeConflict . [CODESPLIT] function _getSolvedEntries ( treeConflict ) { const parentEntries = treeConflict . getParent ( ) . getTreeEntries ( ) ; const baseEntries = treeConflict . getBase ( ) . getTreeEntries ( ) ; const headEntries = treeConflict . getHead ( ) . getTreeEntries ( ) ; const baseDiff = _diffEntries ( parentEntries , baseEntries ) ; const headDiff = _diffEntries ( parentEntries , headEntries ) ; const resolvedEntries = treeConflict . getConflicts ( ) . map ( ( solvedConflict ) => { // Convert to TreeEntries (or null for deletion) if ( solvedConflict . isDeleted ( ) ) { return null ; } else { return new TreeEntry ( { sha : solvedConflict . getSolvedSha ( ) || null } ) ; } } ) ; return parentEntries . merge ( baseDiff , headDiff , resolvedEntries ) // Remove deleted entries . filter ( function nonNull ( entry ) { return entry !== null ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new blob to a cache instance [CODESPLIT] function addBlob ( cache , sha , blob ) { const blobs = cache . getBlobs ( ) ; const newBlobs = blobs . set ( sha , blob ) ; const newCache = cache . set ( 'blobs' , newBlobs ) ; return newCache ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utils to create tree structures for files . Convert a filepath to a Seq<String > to use as key path [CODESPLIT] function pathToKeySeq ( path ) { // Remove trailing '/' etc. path = Path . join ( path , '.' ) ; if ( path === '.' ) { return Immutable . Seq ( [ ] ) ; } else { return Immutable . Seq ( path . split ( '/' ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a files tree from the current branch taking pending changes into account . [CODESPLIT] function get ( repoState , dirPath ) { // Remove trailing '/' etc. const normDirPath = Path . join ( dirPath , '.' ) ; const filepaths = DirUtils . readFilenamesRecursive ( repoState , normDirPath ) ; const tree = { value : File . createDir ( normDirPath ) , children : { } } ; for ( let i = 0 ; i < filepaths . length ; i ++ ) { const relativePath = Path . relative ( normDirPath , filepaths [ i ] ) ; const parts = relativePath . split ( '/' ) ; let node = tree ; let prefix = normDirPath ; for ( let j = 0 ; j < parts . length ; j ++ ) { const head = parts [ j ] ; const isLeaf = ( j === parts . length - 1 ) ; prefix = Path . join ( prefix , head ) ; // Create node if doesn't exist if ( ! node . children [ head ] ) { if ( isLeaf ) { node . children [ head ] = { value : FileUtils . stat ( repoState , filepaths [ i ] ) } ; } else { node . children [ head ] = { value : File . createDir ( prefix ) , children : { } } ; } } node = node . children [ head ] ; } } return TreeNode . fromJS ( tree ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize a commit coming from the GitHub commit creation API [CODESPLIT] function normCreatedCommit ( ghCommit ) { const commit = Commit . create ( { sha : ghCommit . sha , message : ghCommit . message , author : getSimpleAuthor ( ghCommit . author ) , date : ghCommit . author . date , parents : ghCommit . parents . map ( function getSha ( o ) { return o . sha ; } ) } ) ; return commit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize a commit coming from the GitHub commit listing API [CODESPLIT] function normListedCommit ( ghCommit ) { const commit = Commit . create ( { sha : ghCommit . sha , message : ghCommit . commit . message , author : getCompleteAuthor ( ghCommit ) , date : ghCommit . commit . author . date , files : ghCommit . files , parents : ghCommit . parents . map ( c => c . sha ) } ) ; return commit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get author from created commit ( no avatar ) [CODESPLIT] function getSimpleAuthor ( author ) { return Author . create ( { name : author . name , email : author . email , date : author . date } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get author from a listed commit ( with avatar ) [CODESPLIT] function getCompleteAuthor ( commit ) { const author = getSimpleAuthor ( commit . commit . author ) ; const avatar = commit . author ? commit . author . avatar_url : gravatar . url ( author . getEmail ( ) ) ; return author . set ( 'avatar' , avatar ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch a file blob . Required for content access with stat / read . No - op if the file is already fetched . [CODESPLIT] function fetch ( repoState , driver , filepath ) { if ( isFetched ( repoState , filepath ) ) { // No op if already fetched return Q ( repoState ) ; } const workingState = repoState . getCurrentState ( ) ; const blobSha = WorkingUtils . findSha ( workingState , filepath ) ; return BlobUtils . fetch ( repoState , driver , blobSha ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stat details about a file . [CODESPLIT] function stat ( repoState , filepath ) { const workingState = repoState . getCurrentState ( ) ; // Lookup potential changes const change = workingState . getChanges ( ) . get ( filepath ) ; // Lookup file entry const treeEntry = workingState . getTreeEntries ( ) . get ( filepath ) ; // Determine SHA of the blob let blobSHA ; if ( change ) { blobSHA = change . getSha ( ) ; } else { blobSHA = treeEntry . getSha ( ) ; } // Get the blob from change or cache let blob ; if ( blobSHA ) { // Get content from cache blob = repoState . getCache ( ) . getBlob ( blobSHA ) ; } else { // No sha, so it must be in changes blob = change . getContent ( ) ; } let fileSize ; if ( blob ) { fileSize = blob . getByteLength ( ) ; } else { // It might have been moved (but not fetched) const originalEntry = workingState . getTreeEntries ( ) . find ( ( entry ) => { return entry . getSha ( ) === blobSHA ; } ) ; fileSize = originalEntry . getBlobSize ( ) ; } return new File ( { type : FILETYPE . FILE , fileSize , path : filepath , content : blob } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read content of a file returns a String [CODESPLIT] function readAsString ( repoState , filepath , encoding ) { const blob = read ( repoState , filepath ) ; return blob . getAsString ( encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if file exists in working tree false otherwise [CODESPLIT] function exists ( repoState , filepath ) { const workingState = repoState . getCurrentState ( ) ; const mergedFileSet = WorkingUtils . getMergedTreeEntries ( workingState ) ; return mergedFileSet . has ( filepath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new file ( must not exists already ) [CODESPLIT] function create ( repoState , filepath , content ) { content = content || '' ; if ( exists ( repoState , filepath ) ) { throw error . fileAlreadyExist ( filepath ) ; } const change = Change . createCreate ( content ) ; return ChangeUtils . setChange ( repoState , filepath , change ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a file ( must exists ) [CODESPLIT] function write ( repoState , filepath , content ) { if ( ! exists ( repoState , filepath ) ) { throw error . fileNotFound ( filepath ) ; } const change = Change . createUpdate ( content ) ; return ChangeUtils . setChange ( repoState , filepath , change ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a file [CODESPLIT] function remove ( repoState , filepath ) { if ( ! exists ( repoState , filepath ) ) { throw error . fileNotFound ( filepath ) ; } const change = Change . createRemove ( ) ; return ChangeUtils . setChange ( repoState , filepath , change ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rename a file [CODESPLIT] function move ( repoState , filepath , newFilepath ) { if ( filepath === newFilepath ) { return repoState ; } const initialWorkingState = repoState . getCurrentState ( ) ; // Create new file, with Sha if possible const sha = WorkingUtils . findSha ( initialWorkingState , filepath ) ; let changeNewFile ; if ( sha ) { changeNewFile = Change . createCreateFromSha ( sha ) ; } else { // Content not available as blob const blob = read ( repoState , filepath ) ; const contentBuffer = blob . getAsBuffer ( ) ; changeNewFile = Change . createCreate ( contentBuffer ) ; } // Remove old file const removedRepoState = remove ( repoState , filepath ) ; // Add new file return ChangeUtils . setChange ( removedRepoState , newFilepath , changeNewFile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the given file has the same content in both RepositoryState s current working state or is absent from both . [CODESPLIT] function hasChanged ( previousState , newState , filepath ) { const previouslyExists = exists ( previousState , filepath ) ; const newExists = exists ( newState , filepath ) ; if ( ! previouslyExists && ! newExists ) { // Still non existing return false ; } else if ( exists ( previousState , filepath ) !== exists ( newState , filepath ) ) { // The file is absent from one return true ; } else { // Both files exist const prevWorking = previousState . getCurrentState ( ) ; const newWorking = newState . getCurrentState ( ) ; const prevSha = WorkingUtils . findSha ( prevWorking , filepath ) ; const newSha = WorkingUtils . findSha ( newWorking , filepath ) ; if ( prevSha === null && newSha === null ) { // Both have are in pending changes. We can compare their contents return read ( previousState , filepath ) . getAsString ( ) !== read ( newState , filepath ) . getAsString ( ) ; } else { // Content changed if Shas are different, or one of them is null return prevSha !== newSha ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the testing infrastructure needed for verifying the behavior of the core proxy library - nock express and httpServer . [CODESPLIT] function setup ( connection , done ) { var config = createDefaultConfig ( ) , options = { proxy : false , headers : { } } ; // reset the global variable with handles to port numbers handles = { } ; if ( connection !== 'direct' ) { options . proxy = true ; config . proxy . gateway = { protocol : 'http:' , host : 'localhost' , port : 0 , auth : 'proxyuser:C0mp13x_!d0rd$$@P!' } ; // optionally test a non-RFC proxy that expects explicit values // for the  Via and/or Host request headers if ( connection === 'non-rfc-proxy' ) { config . proxy . headers [ 'Via' ] = 'http://jedi.example.com' ; config . proxy . headers [ 'Host' ] = 'force.example.com' ; } // the config map will be mutated by the json-proxy library, so clone it options . headers = require ( 'util' ) . _extend ( config . proxy . headers ) ; configureLanProxy ( options , config , function ( ) { configureNock ( options , config ) ; configureExpress ( config , done ) ; } ) } else { configureNock ( options , config ) ; configureExpress ( config , done ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "configures nock globally for a test run [CODESPLIT] function configureNock ( options , config ) { var result = { } ; // deny all real net connections except for localhost nock . disableNetConnect ( ) ; nock . enableNetConnect ( 'localhost' ) ; function createNock ( url ) { var instance = nock ( url ) , expectedViaHeader = options . headers [ 'Via' ] || 'http://localhost:' + config . proxy . gateway . port , expectedHostHeader = options . headers [ 'Host' ] || / .* / ; if ( options . proxy === true ) { // verify that the request was actually proxied // optionally support downstream proxies with non-RFC expectations on // the Host and Via request headers instance . matchHeader ( 'via' , expectedViaHeader ) ; instance . matchHeader ( 'host' , expectedHostHeader ) ; } // verify the injected header instance . matchHeader ( 'x-test-header' , 'John Doe' ) ; return instance ; } rules = [ createNock ( 'http://api.example.com' ) . get ( '/api/hello' ) . reply ( 200 , '{ \"hello\": \"world\" }' ) . get ( '/account?id=1&email=2&sort=asc' ) . reply ( 200 , '{ \"email\": \"john.doe@example.com\" }' ) . get ( '/api/notfound' ) . reply ( 404 ) , createNock ( 'http://rewrite.example.com' ) . get ( '/hello' ) . reply ( 200 , '{ \"hello\": \"world\" }' ) . get ( '/foo/bar' ) . reply ( 200 , '{ \"foo\": \"bar\" }' ) , createNock ( 'http://www.example.com' ) . get ( '/foo/12345/bar' ) . reply ( 200 , '{ \"foo\": \"bar\" }' ) . get ( '/subapp/junction/customer/1' ) . reply ( 200 , '{ \"id\": 1 }' ) , createNock ( 'https://api.example.biz' ) . get ( '/issue/8' ) . reply ( 200 , '{ \"reporter\": \"@heygrady\" }' ) , createNock ( 'https://secure.example.com' ) . get ( '/secure/api/hello' ) . reply ( 200 , '{ \"hello\": \"world\" }' ) . get ( '/secure/api/notfound' ) . reply ( 404 ) , createNock ( 'https://authorization.example.com' ) . matchHeader ( 'X-Test-Header-Function' , 'Bearer 0123456789abcdef' ) . get ( '/token' ) . reply ( 200 , '{ \"author\": \"ehtb\" }' ) ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures an express instance on a dynamically assigned port for serving static files and proxying requests based on the config . [CODESPLIT] function configureExpress ( config , done ) { var portfinder = require ( 'portfinder' ) ; tmp . dir ( function ( err , filepath ) { handles . filepath = filepath ; portfinder . getPort ( function ( err , port ) { if ( err ) throw ( err ) ; handles . port = port ; fs . writeFileSync ( path . join ( handles . filepath , 'index.txt' ) , 'hello, world' ) ; app . use ( proxy . initialize ( config ) ) ; app . use ( express . static ( handles . filepath ) ) ; handles . server = require ( 'http' ) . createServer ( app ) ; handles . server . listen ( handles . port , function ( ) { done ( null , handles . port ) ; } ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a simple LAN proxy using a vanilla HTTP server that verifies the state of the proxy credentials and the x - forwarded - url are correct . [CODESPLIT] function configureLanProxy ( options , config , done ) { var portfinder = require ( 'portfinder' ) , request = require ( 'request' ) , credentials = config . proxy . gateway . auth , gatewayPort , expectedAuthorizationHeader , requestViaHeader , responseViaHeader ; handles = handles || { } ; handles . gatewayServer = require ( 'http' ) . createServer ( function ( req , res ) { expectedAuthorizationHeader = 'Basic ' + new Buffer ( credentials ) . toString ( 'base64' ) ; // HACK: node 0.12.x appears to inject a slash at the front //       of absolute URLs //       ex., GET http://www.example.com --> GET /http://www.exampel.com if ( req . url . charAt ( 0 ) === '/' ) { req . url = req . url . substr ( 1 ) ; } // validate the proxy target if ( req . url !== req . headers [ 'x-forwarded-url' ] ) { res . writeHead ( 500 ) ; res . end ( '{ \"error\": 500, \"message\": \"invalid proxy request, expected X-Forwarded-Url header ' + req . headers [ 'x-forwarded-url' ] + '\" }' ) ; return ; } // validate the proxy credentials if ( req . headers [ 'authorization' ] !== expectedAuthorizationHeader ) { res . writeHead ( 401 ) ; res . end ( '{ \"error\": 401, \"message\": \"invalid proxy credentials, expected ' + expectedAuthorizationHeader + '\" }' ) ; return ; } // determine if we are using a proxy that is not RFC compliant requestViaHeader = options . headers [ 'Via' ] || '127.0.0.1:' + handles . port ; responseHostHeader = options . headers [ 'Host' ] || req . headers [ 'host' ] ; responseViaHeader = options . headers [ 'Via' ] || 'http://localhost:' + gatewayPort ; // validate the via header was injected and points to 127.0.0.1 in either ipv4 or ipv6 format if ( req . headers [ 'via' ] === undefined || req . headers [ 'via' ] === null || req . headers [ 'via' ] . indexOf ( requestViaHeader ) === - 1 ) { res . writeHead ( 400 ) ; res . end ( '{ \"error\": 400, \"message\": \"invalid via header, expected ' + requestViaHeader + '\" }' ) ; return ; } // strip the proxy credentials header req . headers [ 'authorization' ] = null ; // simulate the behavior of x-forwarded-for with multiple proxies req . headers [ 'x-forwarded-for' ] = [ req . headers [ 'x-forwarded-for' ] , req . headers [ 'via' ] ] . join ( ', ' ) ; // change the via header to this server req . headers [ 'via' ] = responseViaHeader ; req . headers [ 'host' ] = responseHostHeader ; var errorCallback = function errorCallback ( err , repsonse , body ) { if ( err ) { res . writeHead ( 500 ) ; res . end ( JSON . stringify ( { \"error\" : 500 , \"message\" : err . message } ) ) ; return ; } } request ( req , errorCallback ) . pipe ( res ) ; } ) ; portfinder . getPort ( function ( err , port ) { if ( err ) done ( err ) ; config . proxy . gateway . port = port ; gatewayPort = port ; handles . gatewayServer . listen ( port , function ( ) { done ( null ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Teardown logic for the reusable test suites [CODESPLIT] function cleanup ( done ) { config = null ; rules . forEach ( function ( rule ) { rule . done ( ) ; } ) ; nock . cleanAll ( ) ; handles . server . close ( ) ; if ( handles . gatewayServer !== undefined && handles . gatewayServer !== null ) { handles . gatewayServer . close ( ) ; } fs . unlinkSync ( path . join ( handles . filepath , '/index.txt' ) ) ; handles = null ; done ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a new change to the current WorkingState . Attempt to resolve some cases like removing a file that was added in the first place . [CODESPLIT] function setChange ( repoState , filepath , change ) { let workingState = repoState . getCurrentState ( ) ; let changes = workingState . getChanges ( ) ; const type = change . getType ( ) ; // Simplify change when possible if ( type === CHANGE_TYPE . REMOVE && ! workingState . getTreeEntries ( ) . has ( filepath ) ) { // Removing a file that did not exist before changes = changes . delete ( filepath ) ; } else if ( type === CHANGE_TYPE . CREATE && workingState . getTreeEntries ( ) . has ( filepath ) ) { // Adding back a file that existed already changes = changes . set ( filepath , change . set ( 'type' , CHANGE_TYPE . UPDATE ) ) ; } else { // Push changes to list changes = changes . set ( filepath , change ) ; } // Update workingState and repoState workingState = workingState . set ( 'changes' , changes ) ; return RepoUtils . updateCurrentWorkingState ( repoState , workingState ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Revert all changes [CODESPLIT] function revertAll ( repoState ) { let workingState = repoState . getCurrentState ( ) ; // Create empty list of changes const changes = new Immutable . OrderedMap ( ) ; // Update workingState and repoState workingState = workingState . set ( 'changes' , changes ) ; return RepoUtils . updateCurrentWorkingState ( repoState , workingState ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Revert change for a specific file [CODESPLIT] function revertForFile ( repoState , filePath ) { let workingState = repoState . getCurrentState ( ) ; // Remove file from changes map const changes = workingState . getChanges ( ) . delete ( filePath ) ; // Update workingState and repoState workingState = workingState . set ( 'changes' , changes ) ; return RepoUtils . updateCurrentWorkingState ( repoState , workingState ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Revert changes for a specific directory [CODESPLIT] function revertForDir ( repoState , dirPath ) { let workingState = repoState . getCurrentState ( ) ; let changes = workingState . getChanges ( ) ; // Remove all changes that are in the directory changes = changes . filter ( ( change , filePath ) => { return ! PathUtils . contains ( dirPath , filePath ) ; } ) ; // Update workingState and repoState workingState = workingState . set ( 'changes' , changes ) ; return RepoUtils . updateCurrentWorkingState ( repoState , workingState ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Revert all removed files [CODESPLIT] function revertAllRemoved ( repoState ) { let workingState = repoState . getCurrentState ( ) ; const changes = workingState . getChanges ( ) . filter ( // Remove all changes that are in the directory ( change ) => { return change . getType ( ) === CHANGE_TYPE . REMOVE ; } ) ; // Update workingState and repoState workingState = workingState . set ( 'changes' , changes ) ; return RepoUtils . updateCurrentWorkingState ( repoState , workingState ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize a path [CODESPLIT] function normPath ( p ) { p = path . normalize ( p ) ; if ( p [ 0 ] == '/' ) p = p . slice ( 1 ) ; if ( p [ p . length - 1 ] == '/' ) p = p . slice ( 0 , - 1 ) ; if ( p == '.' ) p = '' ; return p ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the path is under dir [CODESPLIT] function pathContains ( dir , path ) { dir = dir ? normPath ( dir ) + '/' : dir ; path = normPath ( path ) ; return path . indexOf ( dir ) === 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List files in a directory ( shallow ) [CODESPLIT] function read ( repoState , dirName ) { dirName = PathUtils . norm ( dirName ) ; const workingState = repoState . getCurrentState ( ) ; const changes = workingState . getChanges ( ) ; const treeEntries = WorkingUtils . getMergedTreeEntries ( workingState ) ; const files = [ ] ; treeEntries . forEach ( ( treeEntry , filepath ) => { // Ignore git submodules if ( treeEntry . getType ( ) !== TreeEntry . TYPES . BLOB ) return ; if ( ! PathUtils . contains ( dirName , filepath ) ) return ; const innerPath = PathUtils . norm ( filepath . replace ( dirName , '' ) ) ; const isDirectory = innerPath . indexOf ( '/' ) >= 0 ; // Make it shallow const name = innerPath . split ( '/' ) [ 0 ] ; const file = new File ( { path : Path . join ( dirName , name ) , type : isDirectory ? FILETYPE . DIRECTORY : FILETYPE . FILE , change : changes . get ( filepath ) , fileSize : treeEntry . blobSize } ) ; files . push ( file ) ; } ) ; // Remove duplicate from entries within directories return uniqueBy ( files , ( file ) => { return file . getName ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List files and directories in a directory ( recursive ) . Warning : This recursive implementation is very costly . [CODESPLIT] function readRecursive ( repoState , dirName ) { // TODO improve performance and don't use .read() directly const files = read ( repoState , dirName ) ; let filesInDirs = files . filter ( ( file ) => { return file . isDirectory ( ) ; } ) . map ( ( dir ) => { return readRecursive ( repoState , dir . path ) ; } ) ; filesInDirs = flatten ( filesInDirs ) ; return Array . prototype . concat ( files , filesInDirs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List files in a directory ( shallow ) [CODESPLIT] function readFilenames ( repoState , dirName ) { const files = read ( repoState , dirName ) ; return files . map ( ( file ) => { return file . getPath ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List files recursively in a directory [CODESPLIT] function readFilenamesRecursive ( repoState , dirName ) { dirName = PathUtils . norm ( dirName ) ; const workingState = repoState . getCurrentState ( ) ; const fileSet = WorkingUtils . getMergedFileSet ( workingState ) ; return fileSet . filter ( ( path ) => { return PathUtils . contains ( dirName , path ) ; } ) . toArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rename a directory [CODESPLIT] function move ( repoState , dirName , newDirName ) { // List entries to move const filesToMove = readFilenamesRecursive ( repoState , dirName ) ; // Push change to remove all entries return filesToMove . reduce ( ( repoState , oldPath ) => { const newPath = Path . join ( newDirName , Path . relative ( dirName , oldPath ) ) ; return FileUtils . move ( repoState , oldPath , newPath ) ; } , repoState ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a directory : push REMOVE changes for all entries in the directory [CODESPLIT] function remove ( repoState , dirName ) { // List entries to move const filesToRemove = readFilenamesRecursive ( repoState , dirName ) ; // Push change to remove all entries return filesToRemove . reduce ( ( repoState , path ) => { return FileUtils . remove ( repoState , path ) ; } , repoState ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new branch with the given name . [CODESPLIT] function create ( repositoryState , driver , name , opts = { } ) { const { // Base branch for the new branch base = repositoryState . getCurrentBranch ( ) , // Fetch the working state and switch to it ? checkout = true , // Drop changes from base branch the new working state ? clean = true , // Drop changes from the base branch ? cleanBase = false } = opts ; let createdBranch ; return driver . createBranch ( base , name ) // Update list of branches . then ( ( branch ) => { createdBranch = branch ; let branches = repositoryState . getBranches ( ) ; branches = branches . push ( createdBranch ) ; return repositoryState . set ( 'branches' , branches ) ; } ) // Update working state or fetch it if needed . then ( ( repoState ) => { let baseWk = repoState . getWorkingStateForBranch ( base ) ; if ( ! baseWk ) { return checkout ? RepoUtils . fetchTree ( repoState , driver , createdBranch ) : repoState ; } // Reuse base WorkingState clean const headWk = clean ? baseWk . asClean ( ) : baseWk ; repoState = RepoUtils . updateWorkingState ( repoState , createdBranch , headWk ) ; // Clean base WorkingState baseWk = cleanBase ? baseWk . asClean ( ) : baseWk ; repoState = RepoUtils . updateWorkingState ( repoState , base , baseWk ) ; return repoState ; } ) // Checkout the branch . then ( ( repoState ) => { if ( ! checkout ) { return repoState ; } return RepoUtils . checkout ( repoState , createdBranch ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch the list of branches and update the given branch only . Will update the WorkingState of the branch ( and discard previous [CODESPLIT] function update ( repoState , driver , branchName ) { branchName = Normalize . branchName ( branchName || repoState . getCurrentBranch ( ) ) ; return driver . fetchBranches ( ) . then ( ( branches ) => { const newBranch = branches . find ( ( branch ) => { return branch . getFullName ( ) === branchName ; } ) ; if ( ! newBranch ) { return repoState ; } else { return RepoUtils . fetchTree ( repoState , driver , newBranch ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the given branch from the repository . [CODESPLIT] function remove ( repoState , driver , branch ) { return driver . deleteBranch ( branch ) . then ( ( ) => { return repoState . updateBranch ( branch , null ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge a branch / commit into a branch and update that branch s tree . [CODESPLIT] function merge ( repoState , driver , from , into , options = { } ) { options = Object . assign ( { fetch : true } , options ) ; let updatedInto ; // closure return driver . merge ( from , into , { message : options . message } ) // Can fail here with ERRORS.CONFLICT . then ( function updateInto ( mergeCommit ) { if ( ! mergeCommit ) { // Was a no op return repoState ; } else { updatedInto = into . merge ( { commit : mergeCommit } ) ; repoState = repoState . updateBranch ( into , updatedInto ) ; // invalidate working state return RepoUtils . updateWorkingState ( repoState , into , null ) ; } } ) . then ( function fetchTree ( repositoryState ) { if ( ! options . fetch ) { return repositoryState ; } else { return RepoUtils . fetchTree ( repositoryState , driver , updatedInto ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch a blob from SHA . [CODESPLIT] function fetch ( repoState , driver , sha ) { if ( isFetched ( repoState , sha ) ) { // No op if already fetched return Q ( repoState ) ; } const cache = repoState . getCache ( ) ; // Fetch the blob return driver . fetchBlob ( sha ) // Then store it in the cache . then ( ( blob ) => { const newCache = CacheUtils . addBlob ( cache , sha , blob ) ; return repoState . set ( 'cache' , newCache ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a private function to automatically refresh the access token when receiving a 401 . Adds rejected requests to a queue to be processed [CODESPLIT] function ( context , options , callback ) { // add the current request to the queue context . retryQueue . push ( [ options , callback ] ) ; // bail if the token is currently being refreshed if ( context . refreshActive ) { return false ; } // ready to refresh context . refreshActive = true ; return request ( { uri : baseUrl + '/oauth2/token' , method : 'POST' , headers : { 'Authorization' : 'Basic ' + new Buffer ( context . clientId + ':' + context . clientSecret ) . toString ( 'base64' ) , 'User-Agent' : userAgent } , form : { grant_type : 'client_credentials' } } , function ( err , res , body ) { context . refreshActive = false ; // if anything but a 200 is returned from the token refresh call, we return the error to the // caller and blow out the retry queue if ( res . statusCode != 200 ) { context . retryQueue = [ ] ; return callback && callback ( res . body , res ) ; } // set the access token on the connection var token = JSON . parse ( body ) ; context . accessToken = token . access_token ; // process the queue of requests for the current connection while ( 0 < context . retryQueue . length ) { var reqArgs = context . retryQueue . pop ( ) ; context . apiRequest ( reqArgs [ 0 ] , reqArgs [ 1 ] ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a connection to the pokitdok API . The version defaults to v4 . You must enter your client ID and client secret or all requests made with your connection will return errors . [CODESPLIT] function PokitDok ( clientId , clientSecret , version ) { this . clientId = clientId ; this . clientSecret = clientSecret ; this . version = version || 'v4' ; this . refreshActive = false ; this . retryQueue = [ ] ; this . accessToken = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : check react - router version assume that router . js is already created [CODESPLIT] function findRouterNode ( root ) { return root . find ( j . JSXElement , { openingElement : { name : { name : 'Router' } } } ) . nodes ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private [CODESPLIT] function _action ( type , payload , checklist , optional = [ ] ) { for ( let checkitem of [ 'namespace' , ... checklist ] ) { if ( optional . indexOf ( checkitem ) === - 1 ) { assert ( payload [ checkitem ] , ` ${ type } ${ checkitem } ` ) ; } } const filePath = join ( payload . sourcePath , payload . filePath ) ; const source = readFile ( filePath ) ; const root = j ( source ) ; const models = root . findModels ( payload . namespace ) ; const args = checklist . map ( checkitem => payload [ checkitem ] ) ; models [ type ] . apply ( models , args ) ; writeFile ( filePath , root . toSource ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert an array of features to a single line in SVM - light format . The line starts with a space . [CODESPLIT] function featureArrayToFeatureString ( features , bias , firstFeatureNumber ) { if ( ! Array . isArray ( features ) ) throw new Error ( \"Expected an array, but got \" + JSON . stringify ( features ) ) var line = ( bias ? \" \" + firstFeatureNumber + \":\" + bias : \"\" ) ; for ( var feature = 0 ; feature < features . length ; ++ feature ) { var value = features [ feature ] ; if ( value ) line += ( \" \" + ( feature + firstFeatureNumber + ( bias ? 1 : 0 ) ) + \":\" + value . toPrecision ( 5 ) ) ; } return line ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add a single feature if it does not exist [CODESPLIT] function ( feature ) { if ( ! ( feature in this . featureNameToFeatureIndex ) ) { var newIndex = this . featureIndexToFeatureName . length ; this . featureIndexToFeatureName . push ( feature ) ; this . featureNameToFeatureIndex [ feature ] = newIndex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add all features in the given hash or array [CODESPLIT] function ( hash ) { if ( hash instanceof Array ) { for ( var index in hash ) this . addFeature ( hash [ index ] ) ; } else if ( hash instanceof Object ) { for ( var feature in hash ) this . addFeature ( feature ) ; } else throw new Error ( \"FeatureLookupTable.addFeatures expects a hash or an array, but got: \" + JSON . stringify ( hash ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the given hash of features to a numeric array using 0 for padding . If some features in the hash do not exist - they will be added . [CODESPLIT] function ( hash ) { this . addFeatures ( hash ) ; var array = [ ] ; for ( var featureIndex = 0 ; featureIndex < this . featureIndexToFeatureName . length ; ++ featureIndex ) array [ featureIndex ] = 0 ; if ( hash instanceof Array ) { for ( var i in hash ) array [ this . featureNameToFeatureIndex [ hash [ i ] ] ] = true ; } else if ( hash instanceof Object ) { for ( var feature in hash ) array [ this . featureNameToFeatureIndex [ feature ] ] = hash [ feature ] ; } else throw new Error ( \"Unsupported type: \" + JSON . stringify ( hash ) ) ; return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert all the given hashes of features to numeric arrays using 0 for padding . If some features in some of the hashes do not exist - they will be added . [CODESPLIT] function ( hashes ) { this . addFeaturess ( hashes ) ; var arrays = [ ] ; for ( var i = 0 ; i < hashes . length ; ++ i ) { arrays [ i ] = [ ] ; for ( var feature in this . featureNameToFeatureIndex ) arrays [ i ] [ this . featureNameToFeatureIndex [ feature ] ] = hashes [ i ] [ feature ] || 0 ; } return arrays ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the given numeric array to a hash of features ignoring zero values . [CODESPLIT] function ( array ) { var hash = { } ; for ( var feature in this . featureNameToFeatureIndex ) { if ( array [ this . featureNameToFeatureIndex [ feature ] ] ) hash [ feature ] = array [ this . featureNameToFeatureIndex [ feature ] ] ; } return hash ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the given numeric arrays to array of hashes of features ignoring zero values . [CODESPLIT] function ( arrays ) { var hashes = [ ] ; for ( var i = 0 ; i < arrays . length ; ++ i ) hashes [ i ] = this . arrayToHash ( arrays [ i ] ) ; return hashes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "HOMER - Hierarchy Of Multilabel classifiERs . See : [CODESPLIT] function ( opts ) { opts = opts || { } ; if ( ! opts . multilabelClassifierType ) { console . dir ( opts ) ; throw new Error ( \"opts.multilabelClassifierType is null\" ) ; } this . multilabelClassifierType = opts . multilabelClassifierType ; this . splitLabel = opts . splitLabel || function ( label ) { return label . split ( / @ / ) ; } this . joinLabel = opts . joinLabel || function ( superlabel ) { return superlabel . join ( \"@\" ) ; } this . root = { superlabelClassifier : this . newMultilabelClassifier ( ) , mapSuperlabelToBranch : { } } this . allClasses = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tell the classifier that the given sample belongs to the given classes . [CODESPLIT] function ( sample , labels ) { labels = multilabelutils . normalizeOutputLabels ( labels ) ; for ( var i in labels ) this . allClasses [ labels [ i ] ] = true ; return this . trainOnlineRecursive ( sample , labels . map ( this . splitLabel ) , this . root ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive internal subroutine of trainOnline . [CODESPLIT] function ( sample , splitLabels , treeNode ) { var superlabels = { } ; // the first parts of each of the splitLabels var mapSuperlabelToRest = { } ; // each value is a list of continuations of the key.  for ( var i in splitLabels ) { var splitLabel = splitLabels [ i ] ; var superlabel = splitLabel [ 0 ] ; superlabels [ superlabel ] = true ; if ( splitLabel . length > 1 ) { if ( ! mapSuperlabelToRest [ superlabel ] ) mapSuperlabelToRest [ superlabel ] = [ ] ; mapSuperlabelToRest [ superlabel ] . push ( splitLabel . slice ( 1 ) ) ; } } treeNode . superlabelClassifier . trainOnline ( sample , Object . keys ( superlabels ) ) ; for ( var superlabel in mapSuperlabelToRest ) { if ( ! ( superlabel in treeNode . mapSuperlabelToBranch ) ) { treeNode . mapSuperlabelToBranch [ superlabel ] = { superlabelClassifier : this . newMultilabelClassifier ( ) , mapSuperlabelToBranch : { } } } this . trainOnlineRecursive ( sample , mapSuperlabelToRest [ superlabel ] , treeNode . mapSuperlabelToBranch [ superlabel ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Train the classifier with all the given documents . [CODESPLIT] function ( dataset ) { dataset = dataset . map ( function ( datum ) { var normalizedLabels = multilabelutils . normalizeOutputLabels ( datum . output ) ; for ( var i in normalizedLabels ) this . allClasses [ normalizedLabels [ i ] ] = true ; return { input : datum . input , output : normalizedLabels . map ( this . splitLabel ) } } , this ) ; // [ [ 'Offer', 'Leased Car', 'Without leased car' ], [ 'Offer', 'Working Hours', '9 hours' ] ] return this . trainBatchRecursive ( dataset , this . root ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive internal subroutine of trainBatch . [CODESPLIT] function ( dataset , treeNode ) { var superlabelsDataset = [ ] ; var mapSuperlabelToRestDataset = { } ; dataset . forEach ( function ( datum ) { var splitLabels = datum . output ; // [ [ 'Offer', 'Leased Car', 'Without leased car' ], [ 'Offer', 'Working Hours', '9 hours' ] ] var superlabels = { } ; // the first parts of each of the splitLabels var mapSuperlabelToRest = { } ; // each value is a list of continuations of the key.  for ( var i in splitLabels ) { var splitLabel = splitLabels [ i ] ; //[ 'Offer', 'Leased Car', 'Without leased car' ] var superlabel = splitLabel [ 0 ] ; superlabels [ superlabel ] = true ; //superlabels['Offer'] = true if ( splitLabel . length > 1 ) { // if it have more than one label (superlabel) if ( ! mapSuperlabelToRest [ superlabel ] ) mapSuperlabelToRest [ superlabel ] = [ ] ; mapSuperlabelToRest [ superlabel ] . push ( splitLabel . slice ( 1 ) ) ; //['Leased Car', 'Without leased car'] } } /*\t\t\tSample of mapSuperlabelToRest\n\t\t\t{ Offer: \n\t\t\t[ [ 'Leased Car', 'Without leased car' ],\n   \t\t\t  [ 'Working Hours', '9 hours' ] ] }\n\n\t\t\tSample of superlabelsDataset, initial dataset with superlabel instead of entire output\n\t\t\t'. [end]': 0.965080896043587 },\n\t\t\toutput: [ 'Offer' ] } ]\n*/ superlabelsDataset . push ( { input : datum . input , output : Object . keys ( superlabels ) } ) ; for ( var superlabel in mapSuperlabelToRest ) { if ( ! ( superlabel in mapSuperlabelToRestDataset ) ) mapSuperlabelToRestDataset [ superlabel ] = [ ] ; mapSuperlabelToRestDataset [ superlabel ] . push ( { input : datum . input , output : mapSuperlabelToRest [ superlabel ] } ) ; } } , this ) ; /*\t\tSample of mapSuperlabelToRestDataset\n\t\t{ Offer: [ { input: [Object], output: [[\"Leased Car\",\"Without leased car\"],[\"Working Hours\",\"9 hours\"]] } ] }\n*/ // train the classifier only on superlabels treeNode . superlabelClassifier . trainBatch ( superlabelsDataset ) ; for ( var superlabel in mapSuperlabelToRestDataset ) { if ( ! ( superlabel in treeNode . mapSuperlabelToBranch ) ) { treeNode . mapSuperlabelToBranch [ superlabel ] = { superlabelClassifier : this . newMultilabelClassifier ( ) , mapSuperlabelToBranch : { } } } /*\t\t\ttrain the next level classifier for a give superlabel classifier superlabel (from loop)\n\t\t\twith the dataset from new structure mapSuperlabelToRestDataset (see above)\n*/ this . trainBatchRecursive ( mapSuperlabelToRestDataset [ superlabel ] , treeNode . mapSuperlabelToBranch [ superlabel ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use the model trained so far to classify a new sample . [CODESPLIT] function ( sample , explain ) { var splitLabels = this . classifyRecursive ( sample , explain , this . root ) ; //console.log(\"splitLabels:\"+JSON.stringify(splitLabels)); if ( explain > 0 ) { splitLabels . classes = splitLabels . classes . map ( this . joinLabel ) ; } else { splitLabels = splitLabels . map ( this . joinLabel ) ; } return splitLabels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive internal subroutine of classify . [CODESPLIT] function ( sample , explain , treeNode , depth ) { if ( ! depth ) depth = 1 ; // classify the superlabel  var superlabelsWithExplain = treeNode . superlabelClassifier . classify ( sample , explain ) ; var superlabels = ( explain > 0 ? superlabelsWithExplain . classes : superlabelsWithExplain ) ; var splitLabels = [ ] ; if ( explain > 0 ) { var explanations = [ \"depth=\" + depth + \": \" + superlabels , superlabelsWithExplain . explanation ] ; } // for all superlabels that were classified, may be there are more than one that were classified with it for ( var i in superlabels ) { var superlabel = superlabels [ i ] ; var splitLabel = [ superlabel ] ; // classifier of [Offer] types / second level / classifies Offer's parameters var branch = treeNode . mapSuperlabelToBranch [ superlabel ] ; if ( branch ) { // [ [ 'Without leased car' ] ] var branchLabelsWithExplain = this . classifyRecursive ( sample , explain , branch , depth + 1 ) ; var branchLabels = ( explain > 0 ? branchLabelsWithExplain . classes : branchLabelsWithExplain ) ; for ( var j in branchLabels ) splitLabels . push ( splitLabel . concat ( branchLabels [ j ] ) ) ; if ( explain > 0 ) explanations = explanations . concat ( branchLabelsWithExplain . explanation ) ; } else { splitLabels . push ( splitLabel ) ; } } return ( explain > 0 ? { classes : splitLabels , explanation : explanations } : splitLabels ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Link to a FeatureLookupTable from a higher level in the hierarchy ( typically from an EnhancedClassifier ) used ONLY for generating meaningful explanations . [CODESPLIT] function ( featureLookupTable , treeNode ) { if ( treeNode . superlabelClassifier && treeNode . superlabelClassifier . setFeatureLookupTable ) treeNode . superlabelClassifier . setFeatureLookupTable ( featureLookupTable ) ; for ( var superlabel in treeNode . mapSuperlabelToBranch ) this . setFeatureLookupTableRecursive ( featureLookupTable , treeNode . mapSuperlabelToBranch [ superlabel ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "BinarySegmentation - Multi - label text classifier based on a segmentation scheme using base binary classifiers . [CODESPLIT] function ( opts ) { if ( ! ( 'binaryClassifierType' in opts ) ) { console . dir ( opts ) ; throw new Error ( \"opts must contain binaryClassifierType\" ) ; } if ( ! opts . binaryClassifierType ) { console . dir ( opts ) ; throw new Error ( \"opts.binaryClassifierType is null\" ) ; } this . binaryClassifierType = opts . binaryClassifierType ; this . classifier = new this . binaryClassifierType ( ) ; switch ( opts . segmentSplitStrategy ) { case 'shortestSegment' : this . segmentSplitStrategy = this . shortestSegmentSplitStrategy ; break ; case 'longestSegment' : this . segmentSplitStrategy = this . longestSegmentSplitStrategy ; break ; case 'cheapestSegment' : this . segmentSplitStrategy = this . cheapestSegmentSplitStrategy ; break ; default : this . segmentSplitStrategy = null ; } this . mapClassnameToClassifier = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Tell the classifier that the given sample belongs to the given classes . [CODESPLIT] function ( sample , classes ) { sample = this . sampleToFeatures ( sample , this . featureExtractors ) ; classes = hash . normalized ( classes ) ; for ( var positiveClass in classes ) { this . makeSureClassifierExists ( positiveClass ) ; this . mapClassnameToClassifier [ positiveClass ] . trainOnline ( sample , 1 ) ; } for ( var negativeClass in this . mapClassnameToClassifier ) { if ( ! classes [ negativeClass ] ) this . mapClassnameToClassifier [ negativeClass ] . trainOnline ( sample , 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Train the classifier with all the given documents . [CODESPLIT] function ( dataset ) { // add ['start'] and ['end'] as a try to resolve Append:previous FP _ . map ( dataset , function ( num ) { num [ 'input' ] = \"['start'] \" + num [ 'input' ] + \" ['end']\" return num } ) ; this . classifier . trainBatch ( dataset ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function - use the model trained so far to classify a single segment of a sentence . [CODESPLIT] function ( segment , explain ) { var classes = this . classifySegment ( segment , explain ) ; if ( classes . classes . length == 0 ) { // FEATURES return [ '' , 0 , '' ] ; // return ['', 0]; } else { // HERE // console.log([classes.classes[0], classes.scores[classes.classes[0]]]) // FEATURES return [ classes . classes [ 0 ] , classes . scores [ classes . classes [ 0 ] ] , classes [ 'explanation' ] [ 'positive' ] ] ; // return [classes.classes[0], classes.scores[classes.classes[0]]]; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "protected function : Strategy of finding the cheapest segmentation ( - most probable segmentation ) using a dynamic programming algorithm . Based on : Morbini Fabrizio Sagae Kenji . Joint Identification and Segmentation of Domain - Specific Dialogue Acts for Conversational Dialogue Systems . ACL - HLT 2011 http : // www . citeulike . org / user / erelsegal - halevi / article / 10259046 [CODESPLIT] function ( words , accumulatedClasses , explain , explanations ) { //for (var start=0; start<=words.length; ++start) { //\tfor (var end=start+1; end<=words.length; ++end) { //\t\tvar segment = words.slice(start,end).join(\" \"); //\t\tvar bestClassAndProbability = this.bestClassOfSegment(segment, explain); //\t\tif (bestClassAndProbability[1] != Infinity) //\t\t{ //\t\t\tvar bestClass = bestClassAndProbability[0]; //\t\t\tvar bestClassProbability = bestClassAndProbability[1]; //\t\tdigraph.add(start, end, -bestClassProbability); //\t\t} //\t} //} var cheapest_paths = require ( \"graph-paths\" ) . cheapest_paths ; var mini = Infinity _ ( words . length ) . times ( function ( nn ) { cheapestSegmentClassificationCosts = cheapest_paths ( segmentClassificationCosts , nn ) ; _ . each ( cheapestSegmentClassificationCosts , function ( value , key , list ) { if ( value . cost < mini ) { mini = value . cost cheapestSentenceClassificationCost = value } } , this ) } , this ) cheapestSegmentClassificationCosts = cheapest_paths ( segmentClassificationCosts , 0 ) ; cheapestSentenceClassificationCost = cheapestSegmentClassificationCosts [ words . length ] ; var path = cheapestSentenceClassificationCost . path ; for ( var i = 0 ; i < path . length - 1 ; ++ i ) { // var segment = words.slice(cheapestClassificationPath[i],cheapestClassificationPath[i+1]).join(\" \"); var segment = words . slice ( path [ i ] , path [ i + 1 ] ) . join ( \" \" ) ; //HERE var segmentClassesWithExplain = this . classifySegment ( segment , explain ) ; var segmentClasses = ( segmentClassesWithExplain . classes ? segmentClassesWithExplain . classes : segmentClassesWithExplain ) ; if ( segmentClasses . length > 0 ) accumulatedClasses [ segmentClasses [ 0 ] ] = true ; // explanations = [] if ( explain > 0 ) { if ( segmentClasses . length > 0 ) explanations . push ( [ segmentClasses [ 0 ] , segment , [ path [ i ] , path [ i + 1 ] ] , segmentClassesWithExplain [ 'explanation' ] [ 'positive' ] ] ) } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "protected function : Strategy of classifying the shortest segments with a single class . [CODESPLIT] function ( words , accumulatedClasses , explain , explanations ) { var currentStart = 0 ; for ( var currentEnd = 1 ; currentEnd <= words . length ; ++ currentEnd ) { var segment = words . slice ( currentStart , currentEnd ) . join ( \" \" ) ; var segmentClassesWithExplain = this . classifySegment ( segment , explain ) ; var segmentClasses = ( segmentClassesWithExplain . classes ? segmentClassesWithExplain . classes : segmentClassesWithExplain ) ; if ( segmentClasses . length == 1 ) { // greedy algorithm: found a section with a single class - cut it and go on accumulatedClasses [ segmentClasses [ 0 ] ] = true ; currentStart = currentEnd ; if ( explain > 0 ) { explanations . push ( segment ) ; explanations . push ( segmentClassesWithExplain . explanation ) ; } ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "protected function : Strategy of classifying the longest segments with a single class . [CODESPLIT] function ( words , accumulatedClasses , explain , explanations ) { var currentStart = 0 ; var segment = null ; var segmentClassesWithExplain = null ; var segmentClasses = null ; for ( var currentEnd = 1 ; currentEnd <= words . length ; ++ currentEnd ) { var nextSegment = words . slice ( currentStart , currentEnd ) . join ( \" \" ) ; var nextSegmentClassesWithExplain = this . classifySegment ( nextSegment , explain ) ; var nextSegmentClasses = ( nextSegmentClassesWithExplain . classes ? nextSegmentClassesWithExplain . classes : nextSegmentClassesWithExplain ) ; //console.log(\"\\t\"+JSON.stringify(nextSegment) +\" -> \"+nextSegmentClasses) nextSegmentClasses . sort ( ) ; if ( segmentClasses && segmentClasses . length == 1 && ( nextSegmentClasses . length > 1 || ! _ ( nextSegmentClasses ) . isEqual ( segmentClasses ) ) ) { // greedy algorithm: found a section with a single class - cut it and go on accumulatedClasses [ segmentClasses [ 0 ] ] = true ; currentStart = currentEnd - 1 ; if ( explain > 0 ) { explanations . push ( segment ) ; explanations . push ( segmentClassesWithExplain . explanation ) ; } ; } segment = nextSegment ; segmentClassesWithExplain = nextSegmentClassesWithExplain ; segmentClasses = nextSegmentClasses ; } // add the classes of the last section: for ( var i in segmentClasses ) accumulatedClasses [ segmentClasses [ i ] ] = true ; if ( explain > 0 ) { explanations . push ( segment ) ; explanations . push ( segmentClassesWithExplain . explanation ) ; } ; /*if (words.length>20)  {\n\t\t\tconsole.dir(explanations);\n\t\t\tprocess.exit(1);\n\t\t}*/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use the model trained so far to classify a new sample . [CODESPLIT] function ( sentence , explain ) { // sentence = \"['start'] \" + sentence + \" ['end']\" var minWordsToSplit = 2 ; var words = sentence . split ( /   / ) ; // var words = tokenizer.tokenize(sentence); if ( this . segmentSplitStrategy && words . length >= minWordsToSplit ) { var accumulatedClasses = { } ; var explanations = [ ] ; this . segmentSplitStrategy ( words , accumulatedClasses , explain , explanations ) ; var classes = Object . keys ( accumulatedClasses ) ; return ( explain > 0 ? { classes : classes , explanation : explanations } : classes ) ; } else { classification = this . bestClassOfSegment ( sentence , explain ) // classification = this.classifySegment(sentence, explain); //HERER // console.log(sentence) // console.log(classification) // process.exit(0) // process.exit(0) return ( explain > 0 ? { classes : classification [ 0 ] , // FEATURES explanation : [ [ classification [ 0 ] , sentence , [ 0 , sentence . length - 1 ] , classification [ 2 ] ] ] // explanation: [[classification[0], sentence, [0,sentence.length-1]]] } : classification [ 0 ] ) ; // return {classes: classification[0], // explanation: [[classification[0], sentence, [0,sentence.length-1]]]} // return {classes: classification.classes[0]} } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multilabel online classifier based on Perceptron and Passive - Aggressive . [CODESPLIT] function ( opts ) { this . retrain_count = opts . retrain_count || 10 ; this . Constant = opts . Constant || 5.0 ; this . weights = { //DUMMY_CLASS:{} } ; this . weights_sum = { //DUMMY_CLASS:{} } ; this . seenFeatures = { } ; this . num_iterations = 0 }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tell the classifier that the given sample belongs to the given classes . [CODESPLIT] function ( sample , classes ) { var classesSet = hash . normalized ( classes ) ; var ranks = this . predict ( sample , /*averaging=*/ false ) ; // pairs of [class,score] sorted by decreasing score // find the lowest ranked relevant label r: var r = 0 var r_score = Number . MAX_VALUE ranks . forEach ( function ( labelAndScore ) { var label = labelAndScore [ 0 ] ; var score = labelAndScore [ 1 ] ; if ( ( label in classesSet ) && score < r_score ) { r = label r_score = score } } ) ; // find the highest ranked irrelevant label s var s = 0 var s_score = - Number . MAX_VALUE ranks . reverse ( ) ; ranks . forEach ( function ( labelAndScore ) { var label = labelAndScore [ 0 ] ; var score = labelAndScore [ 1 ] ; if ( ! ( label in classesSet ) && score > s_score ) { s = label ; s_score = score ; } } ) ; var loss = Math . max ( 1.0 - r_score , 0.0 ) + Math . max ( 1.0 + s_score , 0.0 ) ; if ( loss > 0 ) { var sample_norm2 = hash . sum_of_square_values ( sample ) ; var tau = Math . min ( this . Constant , loss / sample_norm2 ) ; if ( r_score < Number . MAX_VALUE ) hash . addtimes ( this . weights [ r ] , tau , sample ) ; // weights[r] += tau*sample if ( s_score > - Number . MAX_VALUE ) hash . addtimes ( this . weights [ s ] , - tau , sample ) ; // weights[s] -= tau*sample } // this.weights_sum = (this.weights + this.weights_sum); for ( category in this . weights ) hash . add ( this . weights_sum [ category ] , this . weights [ category ] ) ; hash . add ( this . seenFeatures , sample ) ; this . num_iterations += 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Train the classifier with all the given documents . [CODESPLIT] function ( dataset ) { // preprocessing: add all the classes in the dataset to the weights vector; dataset . forEach ( function ( datum ) { this . addClasses ( datum . output ) ; this . editFeatureValues ( datum . input , /*remove_unknown_features=*/ false ) ; } , this ) ; for ( var i = 0 ; i < this . retrain_count ; ++ i ) dataset . forEach ( function ( datum ) { this . update ( datum . input , datum . output ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use the model trained so far to classify a new sample . [CODESPLIT] function ( features , explain , withScores ) { this . editFeatureValues ( features , /*remove_unknown_features=*/ true ) ; var scoresVector = this . predict ( features , /*averaging=*/ true , explain ) ; return multilabelutils . mapScoresVectorToMultilabelResult ( scoresVector , explain , withScores , /*threshold=*/ 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tell the classifier that the given classes will be used for the following samples so that it will know to add negative samples to classes that do not appear . [CODESPLIT] function ( classes ) { classes = hash . normalized ( classes ) ; for ( var aClass in classes ) { if ( ! ( aClass in this . weights ) ) { this . weights [ aClass ] = { } ; this . weights_sum [ aClass ] = { } ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PartialClassification is a test classifier that learns and classifies the components of the labels separately according to the splitLabel routine . One of the examples could be classifying intent attribute value separately by three different classifiers . When performing test by trainAndTest module there is a check for toFormat routine if it exists then pretest format converting occurs . [CODESPLIT] function ( opts ) { opts = opts || { } ; if ( ! opts . multilabelClassifierType ) { console . dir ( opts ) ; throw new Error ( \"opts.multilabelClassifierType is null\" ) ; } if ( ! opts . numberofclassifiers ) { console . dir ( opts ) ; throw new Error ( \"opts.numberofclassifiers is null\" ) ; } // this.splitLabel = opts.splitLabel || function(label)      {return label.split(/@/);} this . classifier = this . intializeClassifiers ( opts . numberofclassifiers , opts . multilabelClassifierType ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "github . com / erelsgl / limdu / blob / d61166c91a81daee62e3d67d5fff2b06cee8191f / utils / PrecisionRecall . js [CODESPLIT] function ( ) { this . count = 0 ; this . TP = 0 ; this . TN = 0 ; this . FP = 0 ; this . FN = 0 ; this . TRUE = 0 ; this . startTime = new Date ( ) ; this . labels = { } this . dep = { } this . confusion = { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Record the result of a new binary experiment . [CODESPLIT] function ( expected , actual ) { this . count ++ ; if ( expected && actual ) this . TP ++ ; if ( ! expected && actual ) this . FP ++ ; if ( expected && ! actual ) this . FN ++ ; if ( ! expected && ! actual ) this . TN ++ ; if ( expected == actual ) this . TRUE ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Record the result of a new classes experiment per labels . [CODESPLIT] function ( expectedClasses , actualClasses ) { var explanations = [ ] ; actualClasses = hash . normalized ( actualClasses ) ; expectedClasses = hash . normalized ( expectedClasses ) ; var allTrue = true ; if ( ! ( Object . keys ( expectedClasses ) [ 0 ] in this . confusion ) ) this . confusion [ Object . keys ( expectedClasses ) [ 0 ] ] = { } if ( ! ( Object . keys ( actualClasses ) [ 0 ] in this . confusion [ Object . keys ( expectedClasses ) [ 0 ] ] ) ) this . confusion [ Object . keys ( expectedClasses ) [ 0 ] ] [ Object . keys ( actualClasses ) [ 0 ] ] = 0 this . confusion [ Object . keys ( expectedClasses ) [ 0 ] ] [ Object . keys ( actualClasses ) [ 0 ] ] += 1 for ( var actualClass in actualClasses ) { if ( ! ( actualClass in this . confusion ) ) this . confusion [ actualClass ] = { } if ( ! ( actualClass in this . labels ) ) { this . labels [ actualClass ] = { } this . labels [ actualClass ] [ 'TP' ] = 0 this . labels [ actualClass ] [ 'FP' ] = 0 this . labels [ actualClass ] [ 'FN' ] = 0 } if ( actualClass in expectedClasses ) { this . labels [ actualClass ] [ 'TP' ] += 1 } else { this . labels [ actualClass ] [ 'FP' ] += 1 } } for ( var expectedClass in expectedClasses ) { if ( ! ( expectedClass in this . labels ) ) { this . labels [ expectedClass ] = { } this . labels [ expectedClass ] [ 'TP' ] = 0 this . labels [ expectedClass ] [ 'FP' ] = 0 this . labels [ expectedClass ] [ 'FN' ] = 0 } if ( ! ( expectedClass in actualClasses ) ) { this . labels [ expectedClass ] [ 'FN' ] += 1 } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Record the result of a new classes experiment . [CODESPLIT] function ( expectedClasses , actualClasses , logTruePositives ) { var explanations = [ ] ; actualClasses = hash . normalized ( actualClasses ) ; expectedClasses = hash . normalized ( expectedClasses ) ; var allTrue = true ; for ( var actualClass in actualClasses ) { if ( actualClass in expectedClasses ) { if ( logTruePositives ) explanations . push ( \"\\t\\t+++ TRUE POSITIVE: \" + actualClass ) ; this . TP ++ ; } else { explanations . push ( \"\\t\\t--- FALSE POSITIVE: \" + actualClass ) ; this . FP ++ ; allTrue = false ; } } for ( var expectedClass in expectedClasses ) { if ( ! ( expectedClass in actualClasses ) ) { explanations . push ( \"\\t\\t--- FALSE NEGATIVE: \" + expectedClass ) ; this . FN ++ ; allTrue = false ; } } if ( allTrue ) { if ( logTruePositives ) explanations . push ( \"\\t\\t*** ALL TRUE!\" ) ; this . TRUE ++ ; } this . count ++ ; return explanations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Record the result of a new classes experiment in a hash manner . Doesn t allowed to do a inner output all stats are put in hash [CODESPLIT] function ( expectedClasses , actualClasses , logTruePositives ) { var explanations = { } ; explanations [ 'TP' ] = [ ] ; explanations [ 'FP' ] = [ ] ; explanations [ 'FN' ] = [ ] ; actualClasses = hash . normalized ( actualClasses ) ; expectedClasses = hash . normalized ( expectedClasses ) ; var allTrue = true ; for ( var actualClass in actualClasses ) { if ( actualClass in expectedClasses ) { if ( logTruePositives ) explanations [ 'TP' ] . push ( actualClass ) ; this . TP ++ ; } else { explanations [ 'FP' ] . push ( actualClass ) ; this . FP ++ ; allTrue = false ; } } for ( var expectedClass in expectedClasses ) { if ( ! ( expectedClass in actualClasses ) ) { explanations [ 'FN' ] . push ( expectedClass ) ; this . FN ++ ; allTrue = false ; } } if ( allTrue ) { // if ((logTruePositives)&& (!only_false_cases)) explanations.push(\"\\t\\t*** ALL TRUE!\"); this . TRUE ++ ; } this . count ++ ; _ . each ( explanations , function ( value , key , list ) { // explanations[key] = _.sortBy(explanations[key], function(num){ num }); explanations [ key ] . sort ( ) } , this ) if ( explanations [ 'FP' ] . length == 0 ) delete explanations [ 'FP' ] if ( explanations [ 'FN' ] . length == 0 ) delete explanations [ 'FN' ] return explanations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "example of usage see in test [CODESPLIT] function ( expectedClasses , actualClasses , logTruePositives ) { var ex = [ ] var ac = [ ] var matchlist = [ ] // clean up expected list _ . each ( expectedClasses , function ( expected , key , list ) { if ( ( expected . length == 2 ) || ( expected . length == 3 ) ) ex . push ( expected ) } , this ) // ac = actualClasses // // filtering actual classes\t\t // _.each(actualClasses, function(actual, key, list){  // \tvar found = _.filter(ac, function(num){ return ((num[0] == actual[0]) && (this.intersection(num[1], actual[1]) == true)) }, this); // \tif (found.length == 0) // \t\tac.push(actual) // }, this) // console.log(JSON.stringify(actualClasses, null, 4)) // var ac = this.uniquecandidate(this.uniqueaggregate(actualClasses)) var ac = actualClasses // filling interdependencies between labels  // for every candidate (actual) it looks for intersection between actual labels with different  // intents, intersection means that different intents came to the common substring, then arrange  // all the data in the hash, and mention only keyphrases. _ . each ( ac , function ( actual , key , list ) { if ( actual . length > 3 ) { label = actual [ 0 ] // keyphrase str = actual [ 2 ] if ( ! ( label in this . dep ) ) { this . dep [ label ] = { } this . dep [ label ] [ label ] = [ ] } this . dep [ label ] [ label ] . push ( str ) // intersection, different intents but actual intersection var found = _ . filter ( ac , function ( num ) { return ( ( num [ 0 ] != actual [ 0 ] ) && ( this . intersection ( num [ 1 ] , actual [ 1 ] ) == true ) ) } , this ) ; _ . each ( found , function ( sublabel , key , list ) { if ( ! ( sublabel [ 0 ] in this . dep [ label ] ) ) this . dep [ label ] [ sublabel [ 0 ] ] = [ ] this . dep [ label ] [ sublabel [ 0 ] ] . push ( [ [ actual [ 2 ] , actual [ 4 ] ] , [ sublabel [ 2 ] , sublabel [ 4 ] ] ] ) } , this ) } } , this ) var explanations = { } ; explanations [ 'TP' ] = [ ] ; explanations [ 'FP' ] = [ ] ; explanations [ 'FN' ] = [ ] ; var explanations_detail = { } ; explanations_detail [ 'TP' ] = [ ] ; explanations_detail [ 'FP' ] = [ ] ; explanations_detail [ 'FN' ] = [ ] ; var allTrue = true ; for ( var actualClassindex in ac ) { if ( ! ( ac [ actualClassindex ] [ 0 ] in this . labels ) ) { this . labels [ ac [ actualClassindex ] [ 0 ] ] = { } this . labels [ ac [ actualClassindex ] [ 0 ] ] [ 'TP' ] = 0 this . labels [ ac [ actualClassindex ] [ 0 ] ] [ 'FP' ] = 0 this . labels [ ac [ actualClassindex ] [ 0 ] ] [ 'FN' ] = 0 } var found = false _ . each ( ex , function ( exc , key , list ) { if ( ac [ actualClassindex ] [ 0 ] == exc [ 0 ] ) { if ( ( exc [ 1 ] . length == 0 ) || ( ac [ actualClassindex ] [ 1 ] [ 0 ] == - 1 ) ) { found = true matchlist . push ( ac [ actualClassindex ] ) } else { if ( this . intersection ( ac [ actualClassindex ] [ 1 ] , exc [ 1 ] ) ) { found = true matchlist . push ( ac [ actualClassindex ] ) } } } } , this ) if ( found ) { if ( logTruePositives ) { explanations [ 'TP' ] . push ( ac [ actualClassindex ] [ 0 ] ) ; explanations_detail [ 'TP' ] . push ( ac [ actualClassindex ] ) ; this . labels [ ac [ actualClassindex ] [ 0 ] ] [ 'TP' ] += 1 this . TP ++ } } else { explanations [ 'FP' ] . push ( ac [ actualClassindex ] [ 0 ] ) ; explanations_detail [ 'FP' ] . push ( ac [ actualClassindex ] ) ; this . labels [ ac [ actualClassindex ] [ 0 ] ] [ 'FP' ] += 1 this . FP ++ allTrue = false ; } } for ( var expectedClassindex in ex ) { var found = false if ( ! ( ex [ expectedClassindex ] [ 0 ] in this . labels ) ) { this . labels [ ex [ expectedClassindex ] [ 0 ] ] = { } this . labels [ ex [ expectedClassindex ] [ 0 ] ] [ 'TP' ] = 0 this . labels [ ex [ expectedClassindex ] [ 0 ] ] [ 'FP' ] = 0 this . labels [ ex [ expectedClassindex ] [ 0 ] ] [ 'FN' ] = 0 } _ . each ( ac , function ( acc , key , list ) { if ( ex [ expectedClassindex ] [ 0 ] == acc [ 0 ] ) { if ( ( ex [ expectedClassindex ] [ 1 ] . length == 0 ) || ( acc [ 1 ] [ 0 ] == - 1 ) ) found = true else { if ( this . intersection ( ex [ expectedClassindex ] [ 1 ] , acc [ 1 ] ) ) found = true } } } , this ) if ( ! found ) { explanations [ 'FN' ] . push ( ex [ expectedClassindex ] [ 0 ] ) ; explanations_detail [ 'FN' ] . push ( ex [ expectedClassindex ] ) ; this . labels [ ex [ expectedClassindex ] [ 0 ] ] [ 'FN' ] += 1 this . FN ++ ; allTrue = false ; } } if ( allTrue ) { // if ((logTruePositives)&& (!only_false_cases)) explanations.push(\"\\t\\t*** ALL TRUE!\"); this . TRUE ++ ; } this . count ++ ; // _.each(explanations, function(value, key, list){  // explanations[key] = _.sortBy(explanations[key], function(num){ num }); // explanations[key].sort() // }, this) // console.log(explanations) // console.log(matchlist) // if (expectedClasses.length > 1) // process.exit(0) return { 'explanations' : explanations , 'match' : matchlist , 'explanations_detail' : explanations_detail } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "simple intersection [CODESPLIT] function ( begin , end ) { if ( ( begin [ 0 ] <= end [ 0 ] ) && ( begin [ 1 ] >= end [ 0 ] ) ) return true if ( ( begin [ 0 ] >= end [ 0 ] ) && ( begin [ 0 ] <= end [ 1 ] ) ) return true return false }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for explanations [CODESPLIT] function WinnowHash ( opts ) { if ( ! opts ) opts = { } this . debug = opts . debug || false ; // Default values are based on Carvalho and Cohen, 2006, section 4.2:\t this . default_positive_weight = opts . default_positive_weight || 2.0 ; this . default_negative_weight = opts . default_negative_weight || 1.0 ; this . do_averaging = opts . do_averaging || false ; this . threshold = ( 'threshold' in opts ? opts . threshold : 1 ) ; this . promotion = opts . promotion || 1.5 ; this . demotion = opts . demotion || 0.5 ; this . margin = ( 'margin' in opts ? opts . margin : 1.0 ) ; this . retrain_count = opts . retrain_count || 0 ; this . detailed_explanations = opts . detailed_explanations || false ; this . bias = ( 'bias' in opts ? opts . bias : 1.0 ) ; this . positive_weights = { } ; this . negative_weights = { } ; this . positive_weights_sum = { } ; // for averaging; count only weight vectors with successful predictions (Carvalho and Cohen, 2006). this . negative_weights_sum = { } ; // for averaging; count only weight vectors with successful predictions (Carvalho and Cohen, 2006). }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Batch training ( a set of samples ) . Uses the option this . retrain_count . [CODESPLIT] function ( dataset ) { //\t\t\tvar normalized_inputs = []; for ( var i = 0 ; i < dataset . length ; ++ i ) this . editFeatureValues ( dataset [ i ] . input , /*remove_unknown_features=*/ false ) ; //\t\t\t\tnormalized_inputs[i] = this.normalized_features(dataset[i].input, /*remove_unknown_features=*/false); for ( var r = 0 ; r <= this . retrain_count ; ++ r ) for ( var i = 0 ; i < dataset . length ; ++ i ) this . train_features ( dataset [ i ] . input , dataset [ i ] . output ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send the given dataset to svm_perf_learn . [CODESPLIT] function ( dataset ) { if ( this . debug ) console . log ( \"trainBatch start\" ) ; var timestamp = new Date ( ) . getTime ( ) + \"_\" + process . pid var learnFile = svmcommon . writeDatasetToFile ( dataset , this . bias , /*binarize=*/ true , this . model_file_prefix + \"_\" + timestamp , \"SvmPerf\" , FIRST_FEATURE_NUMBER ) ; var modelFile = learnFile . replace ( / [.]learn / , \".model\" ) ; var command = \"svm_perf_learn \" + this . learn_args + \" \" + learnFile + \" \" + modelFile ; if ( this . debug ) console . log ( \"running \" + command ) ; console . log ( command ) var result = execSync ( command ) ; if ( result . code > 0 ) { console . dir ( result ) ; console . log ( fs . readFileSync ( learnFile , 'utf-8' ) ) ; throw new Error ( \"Failed to execute: \" + command ) ; } this . setModel ( fs . readFileSync ( modelFile , \"utf-8\" ) ) ; if ( this . debug ) console . log ( \"trainBatch end\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "weights smaller than this are ignored to save space A utility that converts a model in the SVMPerf format to a map of feature weights . [CODESPLIT] function modelStringToModelMap ( modelString ) { var matches = SVM_PERF_MODEL_PATTERN . exec ( modelString ) ; if ( ! matches ) { console . log ( modelString ) ; throw new Error ( \"Model does not match SVM-perf format\" ) ; } ; //var threshold = parseFloat(matches[1]);  // not needed - we use our own bias var featuresAndWeights = matches [ 2 ] . split ( \" \" ) ; var mapFeatureToWeight = { } ; //mapFeatureToWeight.threshold = threshold; // not needed - we use our own bias //String alphaTimesY = featuresAndWeights[0]; // always 1 in svmperf for ( var i = 1 ; i < featuresAndWeights . length ; ++ i ) { var featureAndWeight = featuresAndWeights [ i ] ; var featureWeight = featureAndWeight . split ( \":\" ) ; if ( featureWeight . length != 2 ) throw new Error ( \"Model featureAndWeight doesn't match svm-perf pattern: featureAndWeight=\" + featureAndWeight ) ; var feature = parseInt ( featureWeight [ 0 ] ) ; if ( feature <= 0 ) throw new IllegalArgumentException ( \"Non-positive feature id: featureAndWeight=\" + featureAndWeight ) ; var weight = parseFloat ( featureWeight [ 1 ] ) ; if ( Math . abs ( weight ) >= MIN_WEIGHT ) mapFeatureToWeight [ feature - FIRST_FEATURE_NUMBER ] = weight ; // start feature values from 0. // Note: if there is bias, then mapFeatureToWeight[0] is its weight. } return mapFeatureToWeight ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert a single dataset to Weka ARFF string . [CODESPLIT] function ( dataset , relationName , featureLookupTable ) { var arff = \"% Automatically generated by Node.js\\n\" ; arff += \"@relation \" + relationName + \"\\n\" ; featureLookupTable . featureIndexToFeatureName . forEach ( function ( featureName ) { if ( _ . isUndefined ( featureName ) ) arff += \"@attribute undefined {0,1}\" + \"\\n\" ; else if ( ! _ . isString ( featureName ) ) throw new Error ( \"Expected featureName to be a string, but found \" + JSON . stringify ( featureName ) ) ; else arff += \"@attribute \" + featureName . replace ( / [^a-zA-Z0-9] / g , \"_\" ) + \" \" + \"{0,1}\" + \"\\n\" ; } ) ; arff += \"\\n@data\\n\" ; dataset . forEach ( function ( datum ) { var datumArff = _ . clone ( datum . input , { } ) ; for ( var i = 0 ; i < datum . output . length ; ++ i ) datumArff [ datum . output [ i ] ] = 1 ; //console.dir(datumArff); var array = featureLookupTable . hashToArray ( datumArff ) ; arff += array + \"\\n\" ; } ) ; return arff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "in lib linear feature numbers start with 1 [CODESPLIT] function SvmLinear ( opts ) { this . learn_args = opts . learn_args || \"\" ; this . model_file_prefix = opts . model_file_prefix || null ; this . bias = opts . bias || 1.0 ; this . multiclass = opts . multiclass || false ; this . debug = opts . debug || false ; this . train_command = opts . train_command || 'liblinear_train' ; this . test_command = opts . test_command || 'liblinear_test' ; this . timestamp = \"\" if ( ! SvmLinear . isInstalled ( ) ) { var msg = \"Cannot find the executable 'liblinear_train'. Please download it from the LibLinear website, and put a link to it in your path.\" ; console . error ( msg ) throw new Error ( msg ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send the given dataset to liblinear_train . [CODESPLIT] function ( dataset ) { this . timestamp = new Date ( ) . getTime ( ) + \"_\" + process . pid // check for multilabel _ . each ( dataset , function ( datum , key , list ) { if ( _ . isArray ( datum . output ) ) if ( datum . output . length > 1 ) { console . log ( \"Multi-label is not allowed\" ) console . log ( JSON . stringify ( darum . output , null , 4 ) ) process . exit ( 0 ) } } , this ) //  convert all arraay-like outputs to just values dataset = _ . map ( dataset , function ( datum ) { if ( _ . isArray ( datum . output ) ) datum . output = datum . output [ 0 ] return datum } ) ; this . allLabels = _ ( dataset ) . map ( function ( datum ) { return datum . output } ) ; this . allLabels = _ . uniq ( _ . flatten ( this . allLabels ) ) // dataset = _.map(dataset, function(datum){ // \tdatum.output = this.allLabels.indexOf(datum.output) // \treturn datum }); if ( this . allLabels . length == 1 ) // a single label return ; //console.log(util.inspect(dataset,{depth:1})); if ( this . debug ) console . log ( \"trainBatch start\" ) ; var learnFile = svmcommon . writeDatasetToFile ( dataset , this . bias , /*binarize=*/ false , this . model_file_prefix + \"_\" + this . timestamp , \"SvmLinear\" , FIRST_FEATURE_NUMBER ) ; var modelFile = learnFile . replace ( / [.]learn / , \".model\" ) ; var command = this . train_command + \" \" + this . learn_args + \" \" + learnFile + \" \" + modelFile ; console . log ( \"running \" + command ) ; var result = child_process . execSync ( command ) ; if ( result . code > 0 ) { console . dir ( result ) ; console . log ( fs . readFileSync ( learnFile , 'utf-8' ) ) ; throw new Error ( \"Failed to execute: \" + command ) ; } this . modelFileString = modelFile ; if ( this . debug ) console . log ( \"trainBatch end\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "weights smaller than this are ignored to save space A utility that converts a model in the SvmLinear format to a matrix of feature weights per label . [CODESPLIT] function modelStringToModelMap ( modelString ) { var matches = LIB_LINEAR_MODEL_PATTERN . exec ( modelString ) ; if ( ! matches ) { console . log ( modelString ) ; throw new Error ( \"Model does not match SVM-Linear format\" ) ; } ; var labels = matches [ 1 ] . split ( / \\s+ / ) ; var mapLabelToMapFeatureToWeight = { } ; for ( var iLabel in labels ) { var label = labels [ iLabel ] ; mapLabelToMapFeatureToWeight [ label ] = { } ; } var weightsMatrix = matches [ 3 ] ; // each line represents a feature; each column represents a label: var weightsLines = weightsMatrix . split ( NEWLINE ) ; for ( var feature in weightsLines ) { var weights = weightsLines [ feature ] . split ( / \\s+ / ) ; weights . pop ( ) ; // ignore lal]st weight, which is empty (-space) if ( weights . length == 0 ) continue ; // ignore empty lines //\t\tif (isNaN(parseFloat(weights[weights.length-1]))) //\t\t\tweights.pop(); if ( weights . length == 1 && labels . length == 2 ) weights [ 1 ] = - weights [ 0 ] ; if ( weights . length != labels . length ) throw new Error ( \"Model does not match SVM-Linear format: there are \" + labels . length + \" labels (\" + labels + \") and \" + weights . length + \" weights (\" + weights + \")\" ) ; for ( var iLabel in labels ) { var label = labels [ iLabel ] ; var weight = parseFloat ( weights [ iLabel ] ) ; if ( Math . abs ( weight ) >= MIN_WEIGHT ) mapLabelToMapFeatureToWeight [ label ] [ feature ] = weight ; } } return mapLabelToMapFeatureToWeight ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "MetaLabeler - Multi - label classifier based on : [CODESPLIT] function ( opts ) { if ( ! opts . rankerType ) { console . dir ( opts ) ; throw new Error ( \"opts.rankerType not found\" ) ; } if ( ! opts . counterType ) { console . dir ( opts ) ; throw new Error ( \"opts.counterType not found\" ) ; } this . ranker = new opts . rankerType ( ) ; this . counter = new opts . counterType ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tell the classifier that the given sample belongs to the given classes . [CODESPLIT] function ( sample , labels ) { // The ranker is just trained by the given set of relevant labels: this . ranker . trainOnline ( sample , labels ) ; // The counter is trained by the *number* of relevant labels: var labelCount = ( Array . isArray ( labels ) ? labels : Object . keys ( labels ) ) . length ; this . counter . trainOnline ( sample , labelCount ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Train the classifier with all the given documents . [CODESPLIT] function ( dataset ) { // The ranker is just trained by the given set of labels relevant to each sample: this . ranker . trainBatch ( dataset ) ; // The counter is trained by the *number* of labels relevant to each sample: var labelCountDataset = dataset . map ( function ( datum ) { var labelCount = ( Array . isArray ( datum . output ) ? datum . output . length : 1 ) ; return { input : datum . input , output : labelCount } ; } ) ; this . counter . trainBatch ( labelCountDataset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use the model trained so far to classify a new sample . [CODESPLIT] function ( sample , explain ) { var rankedLabelsWithExplain = this . ranker . classify ( sample , explain , /*withScores=*/ true ) ; var rankedLabels = ( explain > 0 ? rankedLabelsWithExplain . classes : rankedLabelsWithExplain ) ; var labelCountWithExplain = this . counter . classify ( sample , explain , /*withScores=*/ true ) ; var labelCount = ( explain > 0 ? labelCountWithExplain . classes [ 0 ] [ 0 ] : labelCountWithExplain [ 0 ] [ 0 ] ) ; if ( _ . isString ( labelCount ) ) labelCount = parseInt ( labelCount ) ; // Pick the labelCount most relevant labels from the list returned by the ranker:    var positiveLabelsWithScores = rankedLabels . slice ( 0 , labelCount ) ; var positiveLabels = positiveLabelsWithScores if ( positiveLabelsWithScores . length != 0 ) if ( _ . isArray ( positiveLabelsWithScores [ 0 ] ) ) var positiveLabels = positiveLabelsWithScores . map ( function ( labelWithScore ) { return labelWithScore [ 0 ] } ) ; return ( explain > 0 ? { classes : positiveLabels , explanation : { ranking : rankedLabelsWithExplain . explanation , counting : labelCountWithExplain . explanation } } : positiveLabels ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Link to a FeatureLookupTable from a higher level in the hierarchy ( typically from an EnhancedClassifier ) used ONLY for generating meaningful explanations . [CODESPLIT] function ( featureLookupTable ) { if ( this . ranker . setFeatureLookupTable ) this . ranker . setFeatureLookupTable ( featureLookupTable ) ; if ( this . counter . setFeatureLookupTable ) this . counter . setFeatureLookupTable ( featureLookupTable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "var fs = require ( fs ) ; BinaryRelevance - Multi - label classifier based on a collection of binary classifiers . Also known as : One - vs - All . [CODESPLIT] function ( opts ) { if ( ! opts . binaryClassifierType ) { console . dir ( opts ) ; throw new Error ( \"opts.binaryClassifierType not found\" ) ; } this . binaryClassifierType = opts . binaryClassifierType ; this . debug = opts . debug || false this . mapClassnameToClassifier = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tell the classifier that the given sample belongs to the given labels . [CODESPLIT] function ( sample , labels ) { labels = multilabelutils . normalizeOutputLabels ( labels ) ; for ( var l in labels ) { var positiveLabel = labels [ l ] ; this . makeSureClassifierExists ( positiveLabel ) ; this . mapClassnameToClassifier [ positiveLabel ] . trainOnline ( sample , 1 ) ; } for ( var negativeLabel in this . mapClassnameToClassifier ) { if ( labels . indexOf ( negativeLabel ) < 0 ) this . mapClassnameToClassifier [ negativeLabel ] . trainOnline ( sample , 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Train the classifier with all the given documents . [CODESPLIT] function ( dataset ) { // this variable will hold a dataset for each binary classifier: var mapClassnameToDataset = { } ; // create positive samples for each class: for ( var d in dataset ) { var sample = dataset [ d ] . input ; dataset [ d ] . output = multilabelutils . normalizeOutputLabels ( dataset [ d ] . output ) ; var labels = dataset [ d ] . output ; for ( var l in labels ) { var positiveLabel = labels [ l ] ; this . makeSureClassifierExists ( positiveLabel ) ; if ( ! ( positiveLabel in mapClassnameToDataset ) ) // make sure dataset for this class exists mapClassnameToDataset [ positiveLabel ] = [ ] ; mapClassnameToDataset [ positiveLabel ] . push ( { input : sample , output : 1 } ) } } // create negative samples for each class (after all labels are in the array): for ( var d in dataset ) { var sample = dataset [ d ] . input ; var labels = dataset [ d ] . output ; for ( var negativeLabel in this . mapClassnameToClassifier ) { if ( ! ( negativeLabel in mapClassnameToDataset ) ) // make sure dataset for this class exists mapClassnameToDataset [ negativeLabel ] = [ ] ; if ( labels . indexOf ( negativeLabel ) < 0 ) mapClassnameToDataset [ negativeLabel ] . push ( { input : sample , output : 0 } ) ; } } // train all classifiers: for ( var label in mapClassnameToDataset ) { if ( this . debug ) console . dir ( \"TRAIN class=\" + label ) ; this . mapClassnameToClassifier [ label ] . trainBatch ( mapClassnameToDataset [ label ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use the model trained so far to classify a new sample . [CODESPLIT] function ( sample , explain , withScores ) { var labels = [ ] var scores = [ ] var explanations = [ ] ; var positive_explanations = { } ; var negative_explanations = [ ] for ( var label in this . mapClassnameToClassifier ) { var classifier = this . mapClassnameToClassifier [ label ] ; if ( this . debug ) console . dir ( \"Classify for class=\" + label ) // fs.writeFileSync('/tmp/labels/'+label, JSON.stringify(classifier.getFeatures(), null, 4), 'utf8'); var scoreWithExplain = classifier . classify ( sample , explain , withScores ) ; if ( this . debug ) console . log ( JSON . stringify ( scoreWithExplain , null , 4 ) ) var score = scoreWithExplain . explanation ? scoreWithExplain . classification : scoreWithExplain ; if ( this . debug ) console . dir ( \"score=\" + score ) explanations_string = scoreWithExplain . explanation // if (score>0.5) if ( score > 0 ) { labels . push ( [ label , score ] ) if ( explanations_string ) positive_explanations [ label ] = explanations_string ; } else { if ( explanations_string ) negative_explanations . push ( [ label , score , explanations_string ] ) } scores . push ( [ label , score ] ) } if ( this . debug ) console . dir ( scores ) if ( explain > 0 ) { scores = _ . sortBy ( scores , function ( num ) { return num [ 1 ] } ) . reverse ( ) var scores_hash = _ . object ( scores ) negative_explanations = _ . sortBy ( negative_explanations , function ( num ) { return num [ 1 ] } ) . reverse ( ) negative_explanations = _ . map ( negative_explanations , function ( num ) { return [ num [ 0 ] , num [ 2 ] ] } ) ; var negative_explanations_hash = _ . object ( negative_explanations ) } labels = _ . sortBy ( labels , function ( num ) { return num [ 1 ] } ) ; labels = _ . map ( labels . reverse ( ) , function ( num ) { return num [ 0 ] } ) ; return ( explain > 0 ? { classes : labels , scores : scores_hash , explanation : { positive : positive_explanations , negative : negative_explanations_hash , } } : labels ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Link to a FeatureLookupTable from a higher level in the hierarchy ( typically from an EnhancedClassifier ) used ONLY for generating meaningful explanations . [CODESPLIT] function ( featureLookupTable ) { //console.log(\"BR setFeatureLookupTable \"+featureLookupTable); this . featureLookupTable = featureLookupTable ; for ( var label in this . mapClassnameToClassifier ) if ( featureLookupTable && this . mapClassnameToClassifier [ label ] . setFeatureLookupTable ) this . mapClassnameToClassifier [ label ] . setFeatureLookupTable ( featureLookupTable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private function : [CODESPLIT] function ( label ) { if ( ! this . mapClassnameToClassifier [ label ] ) { // make sure classifier exists this . mapClassnameToClassifier [ label ] = new this . binaryClassifierType ( ) ; if ( this . featureLookupTable && this . mapClassnameToClassifier [ label ] . setFeatureLookupTable ) this . mapClassnameToClassifier [ label ] . setFeatureLookupTable ( this . featureLookupTable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ThresholdClassifier - classifier that converts multi - class classifier to multi - label classifier by finding the best appropriate threshold . [CODESPLIT] function ( opts ) { opts = opts || { } ; if ( ! ( 'multiclassClassifierType' in opts ) ) { console . dir ( opts ) ; throw new Error ( \"opts must contain multiclassClassifierType\" ) ; } if ( ! opts . multiclassClassifierType ) { console . dir ( opts ) ; throw new Error ( \"opts.multiclassClassifierType is null\" ) ; } if ( ! ( 'evaluateMeasureToMaximize' in opts ) ) { console . dir ( opts ) ; throw new Error ( \"opts must contain evaluateMeasureToMaximize\" ) ; } if ( ! opts . evaluateMeasureToMaximize ) { console . dir ( opts ) ; throw new Error ( \"opts.evaluateMeasureToMaximize is null\" ) ; } if ( ! opts . numOfFoldsForThresholdCalculation ) { console . dir ( opts ) ; throw new Error ( \"opts.numOfFoldsForThresholdCalculation is null\" ) ; } this . multiclassClassifier = new opts . multiclassClassifierType ( ) ; // [F1, Accuracy]\t this . evaluateMeasureToMaximize = opts . evaluateMeasureToMaximize ; // constant size of validation set this . devsetsize = 0.1 // > 1, n - fold cross - validation, otherwise validation set this . numOfFoldsForThresholdCalculation = opts . numOfFoldsForThresholdCalculation }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Train the classifier with all the given documents and identify the best possible threshold simply by running over all relevant scores and determining the value of feedback function ( F1 by default ) [CODESPLIT] function ( dataset ) { _ . times ( 3 , function ( n ) { dataset = _ . shuffle ( dataset ) } ) if ( this . numOfFoldsForThresholdCalculation > 1 ) { thresholds = [ ] best_performances = [ ] average_performances = [ ] median_performances = [ ] partitions . partitions_consistent ( dataset , this . numOfFoldsForThresholdCalculation , ( function ( trainSet , testSet , index ) { this . multiclassClassifier . trainBatch ( trainSet ) ; result = this . receiveScores ( testSet ) performance = this . CalculatePerformance ( result [ 0 ] , testSet , result [ 1 ] ) best_performances . push ( performance ) } ) . bind ( this ) ) this . stats = best_performances threshold_average = ulist . average ( _ . pluck ( best_performances , 'Threshold' ) ) threshold_median = ulist . median ( _ . pluck ( best_performances , 'Threshold' ) ) Threshold = threshold_median } else { dataset = partitions . partition ( dataset , 1 , Math . round ( dataset . length * this . devsetsize ) ) trainSet = dataset [ 'train' ] testSet = dataset [ 'test' ] this . multiclassClassifier . trainBatch ( trainSet ) ; result = this . receiveScores ( testSet ) performance = this . CalculatePerformance ( result [ 0 ] , testSet , result [ 1 ] ) Threshold = performance [ 'Threshold' ] } this . multiclassClassifier . threshold = Threshold }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Classify dataset and return the scored result in sorted list [CODESPLIT] function ( dataset ) { list_of_scores = [ ] ; FN = 0 for ( var i = 0 ; i < dataset . length ; ++ i ) { var scoresVector = this . multiclassClassifier . classify ( dataset [ i ] . input , false , true ) ; for ( score in scoresVector ) { if ( dataset [ i ] . output . indexOf ( scoresVector [ score ] [ 0 ] ) > - 1 ) { scoresVector [ score ] . push ( \"+\" ) FN += 1 } else { scoresVector [ score ] . push ( \"-\" ) } scoresVector [ score ] . push ( i ) } list_of_scores = list_of_scores . concat ( scoresVector ) } // list_of_scores = [['d',4],['b',2],['a',1],['c',3]] list_of_scores . sort ( ( function ( index ) { return function ( a , b ) { return ( a [ index ] === b [ index ] ? 0 : ( a [ index ] < b [ index ] ? 1 : - 1 ) ) ; } ; } ) ( 1 ) ) return [ list_of_scores , FN ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Calculate the bst threshold with the highest evaluateMeasureToMaximize [CODESPLIT] function ( list_of_scores , testSet , FN ) { current_set = [ ] TRUE = 0 FP = 0 TP = 0 result = [ ] for ( var th = 0 ; th < list_of_scores . length ; ++ th ) { if ( list_of_scores [ th ] [ 2 ] == \"+\" ) { TP += 1 ; FN -= 1 } if ( list_of_scores [ th ] [ 2 ] == \"-\" ) { FP += 1 ; } // console.log(list_of_scores[th]) // console.log(\"TP \"+TP+\" FP \"+FP+\" FN \"+FN) index_in_testSet = list_of_scores [ th ] [ 3 ] if ( _ . isEqual ( current_set [ index_in_testSet ] , testSet [ index_in_testSet ] [ 'output' ] ) ) { TRUE -= 1 } if ( ! current_set [ index_in_testSet ] ) { current_set [ index_in_testSet ] = [ list_of_scores [ th ] [ 0 ] ] } else { current_set [ index_in_testSet ] . push ( list_of_scores [ th ] [ 0 ] ) } if ( _ . isEqual ( current_set [ index_in_testSet ] , testSet [ index_in_testSet ] [ 'output' ] ) ) { TRUE += 1 } PRF = calculate_PRF ( TP , FP , FN ) PRF [ 'Accuracy' ] = TRUE / testSet . length PRF [ 'Threshold' ] = list_of_scores [ th ] [ 1 ] result [ list_of_scores [ th ] [ 1 ] ] = PRF } optial_measure = 0 index = Object . keys ( result ) [ 0 ] for ( i in result ) { if ( result [ i ] [ this . evaluateMeasureToMaximize ] >= optial_measure ) { index = i optial_measure = result [ i ] [ this . evaluateMeasureToMaximize ] } } return result [ index ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "MulticlassSegmentation - Multi - label text classifier based on a segmentation scheme using a base multi - class classifier . [CODESPLIT] function ( opts ) { if ( ! opts . multiclassClassifierType ) { console . dir ( opts ) ; throw new Error ( \"opts.multiclassClassifierType not found\" ) ; } this . multiclassClassifierType = opts . multiclassClassifierType ; this . featureExtractor = FeaturesUnit . normalize ( opts . featureExtractor ) ; this . multiclassClassifier = new this . multiclassClassifierType ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tell the classifier that the given sample belongs to the given classes . [CODESPLIT] function ( sample , classes ) { sample = this . sampleToFeatures ( sample , this . featureExtractor ) ; var category = ( Array . isArray ( classes ) ? classes [ 0 ] : classes ) ; this . multiclassClassifier . trainOnline ( sample , category ) ; /*for (var positiveClass in classes) {\n\t\t\tthis.makeSureClassifierExists(positiveClass);\n\t\t\tthis.mapClassnameToClassifier[positiveClass].trainOnline(sample, 1);\n\t\t}\n\t\tfor (var negativeClass in this.mapClassnameToClassifier) {\n\t\t\tif (!classes[negativeClass])\n\t\t\t\tthis.mapClassnameToClassifier[negativeClass].trainOnline(sample, 0);\n\t\t}*/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Train the classifier with all the given documents . [CODESPLIT] function ( dataset ) { for ( var i = 0 ; i < dataset . length ; ++ i ) { dataset [ i ] = { input : this . sampleToFeatures ( dataset [ i ] . input , this . featureExtractor ) , output : ( Array . isArray ( dataset [ i ] . output ) ? dataset [ i ] . output [ 0 ] : dataset [ i ] . output ) } ; } this . multiclassClassifier . trainBatch ( dataset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function - use the model trained so far to classify a single segment of a sentence . [CODESPLIT] function ( segment , explain ) { var sample = this . sampleToFeatures ( segment , this . featureExtractor ) ; return this . multiclassClassifier . classify ( sample , explain ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "protected function : Strategy of finding the cheapest segmentation ( - most probable segmentation ) using a dynamic programming algorithm . Based on : Morbini Fabrizio Sagae Kenji . Joint Identification and Segmentation of Domain - Specific Dialogue Acts for Conversational Dialogue Systems . ACL - HLT 2011 http : // www . citeulike . org / user / erelsegal - halevi / article / 10259046 [CODESPLIT] function ( words , accumulatedClasses , explain , explanations ) { // Calculate the cost of classification of the segment from i to j. // (Cost = - log probability). var segmentClassificationCosts = [ ] ; // best cost to classify segment [i,j] for ( var start = 0 ; start <= words . length ; ++ start ) { segmentClassificationCosts [ start ] = [ ] ; for ( var end = 0 ; end < start ; ++ end ) segmentClassificationCosts [ start ] [ end ] = Infinity ; segmentClassificationCosts [ start ] [ start ] = 0 ; for ( var end = start + 1 ; end <= words . length ; ++ end ) { var segment = words . slice ( start , end ) . join ( \" \" ) ; var classification = this . bestClassOfSegment ( segment ) ; segmentClassificationCosts [ start ] [ end ] = - Math . log ( classification . probability ) ; } } //console.log(words+\":  \");\t\tconsole.log(\"segmentClassificationCosts\");\t\tconsole.dir(segmentClassificationCosts); var cheapest_paths = require ( \"graph-paths\" ) . cheapest_paths ; cheapestSegmentClassificationCosts = cheapest_paths ( segmentClassificationCosts , 0 ) ; cheapestSentenceClassificationCost = cheapestSegmentClassificationCosts [ words . length ] ; if ( ! cheapestSentenceClassificationCost ) throw new Error ( \"cheapestSegmentClassificationCosts[\" + words . length + \"] is empty\" ) ; //console.log(\"cheapestSentenceClassificationCost\");\t\tconsole.dir(cheapestSentenceClassificationCost); var cheapestClassificationPath = cheapestSentenceClassificationCost . path ; explanations . push ( cheapestSentenceClassificationCost ) ; for ( var i = 0 ; i < cheapestClassificationPath . length - 1 ; ++ i ) { var segment = words . slice ( cheapestClassificationPath [ i ] , cheapestClassificationPath [ i + 1 ] ) . join ( \" \" ) ; //console.log(segment+\":  \"); var segmentCategoryWithExplain = this . classifySegment ( segment , explain ) ; //console.dir(segmentCategoryWithExplain); var segmentCategory = ( segmentCategoryWithExplain . category ? segmentCategoryWithExplain . category : segmentCategoryWithExplain ) ; accumulatedClasses [ segmentCategory ] = true ; if ( explain > 0 ) { explanations . push ( segment ) ; explanations . push ( segmentCategoryWithExplain . explanation ) ; } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use the model trained so far to classify a new sample . [CODESPLIT] function ( sentence , explain ) { var minWordsToSplit = 2 ; var words = sentence . split ( /   / ) ; if ( words . length >= minWordsToSplit ) { var accumulatedClasses = { } ; var explanations = [ ] ; this . cheapestSegmentSplitStrategy ( words , accumulatedClasses , explain , explanations ) ; var classes = Object . keys ( accumulatedClasses ) ; return ( explain > 0 ? { classes : classes , explanation : explanations } : classes ) ; } else { return this . classifySegment ( sentence , explain ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private function : [CODESPLIT] function ( sample , featureExtractor ) { var features = sample ; if ( featureExtractor ) { try { features = { } ; featureExtractor ( sample , features ) ; } catch ( err ) { throw new Error ( \"Cannot extract features from '\" + JSON . stringify ( sample ) + \"': \" + JSON . stringify ( err ) ) ; } } return features ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the package definition ( if it exists ) and picks specific properties to expose . These properties are later merged into the options object as default values . [CODESPLIT] function loadPackageProperties ( grunt ) { var packageFile = 'package.json' ; if ( grunt . file . exists ( packageFile ) ) { return _ . pick ( grunt . file . readJSON ( packageFile ) , [ 'name' , 'version' , 'description' ] ) ; } return { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the prop property on options to the concatenation of that property from both options and data if both exist . Otherwise if either exist exclusively that array will be set to the options . When neither exist nothing is done to the options object . [CODESPLIT] function concatOptionDataArrays ( options , data , prop ) { if ( ! _ . has ( options , prop ) && ! _ . has ( data , prop ) ) { return ; } var combined = [ ] ; if ( _ . isArray ( options [ prop ] ) ) { combined = combined . concat ( options [ prop ] ) ; } if ( _ . isArray ( data [ prop ] ) ) { combined = combined . concat ( data [ prop ] ) ; } options [ prop ] = combined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies properties from the options object to the spec object . This is done explicitly to mitigate pollution from the options object and allow for notification of default assignments . [CODESPLIT] function applySpecSettings ( grunt , options , spec ) { spec . tags . name = options . name || spec . tags . name ; if ( ! _ . has ( options , 'version' ) ) { _defaultOptionNotice ( grunt , 'version' , '0.0.0' ) ; } spec . tags . version = options . version || '0.0.0' ; if ( ! _ . has ( options , 'release' ) ) { _defaultOptionNotice ( grunt , 'release' , '1' ) ; } spec . tags . release = options . release || '1' ; if ( ! _ . has ( options , 'buildArch' ) ) { _defaultOptionNotice ( grunt , 'buildArch' , 'noarch' ) ; } spec . tags . buildArch = options . buildArch || 'noarch' ; if ( ! _ . has ( options , 'description' ) ) { _defaultOptionNotice ( grunt , 'description' , 'No Description' ) ; } spec . tags . description = options . description || 'No Description' ; if ( ! _ . has ( options , 'summary' ) ) { _defaultOptionNotice ( grunt , 'summary' , 'No Summary' ) ; } spec . tags . summary = options . summary || 'No Summary' ; if ( ! _ . has ( options , 'license' ) ) { _defaultOptionNotice ( grunt , 'license' , 'MIT' ) ; } spec . tags . license = options . license || 'MIT' ; spec . tags . epoch = options . epoch || spec . tags . epoch ; spec . tags . distribution = options . distribution || spec . tags . distribution ; if ( ! _ . has ( options , 'vendor' ) ) { _defaultOptionNotice ( grunt , 'vendor' , 'Vendor' ) ; } spec . tags . vendor = options . vendor || 'Vendor' ; spec . tags . url = options . url || spec . tags . url ; if ( ! _ . has ( options , 'group' ) ) { _defaultOptionNotice ( grunt , 'group' , 'Development/Tools' ) ; } spec . tags . group = options . group || 'Development/Tools' ; spec . tags . packager = options . packager || spec . tags . packager ; if ( _ . has ( options , 'defines' ) ) { spec . addDefines . apply ( spec , options . defines ) ; } // To maintain backwards compatability with the older API, the arrays // `dependencies` and `requires` are synonymous. if ( _ . has ( options , 'dependencies' ) ) { // TODO deprecate post 1.5.0 grunt . log . writelns ( chalk . gray ( '[Notice] Deprecation warning: ' + 'the use of \"dependencies\" is deprecated in favour of ' + 'the RPM \"requires\" and \"conflicts\" tags.' ) ) ; spec . addRequirements . apply ( spec , options . dependencies ) ; } if ( _ . has ( options , 'requires' ) ) { spec . addRequirements . apply ( spec , options . requires ) ; } if ( _ . has ( options , 'buildRequires' ) ) { spec . addBuildRequirements . apply ( spec , options . buildRequires ) ; } if ( _ . has ( options , 'provides' ) ) { spec . addProvides . apply ( spec , options . provides ) ; } if ( options . autoReq === false ) { spec . tags . autoReq = options . autoReq ; } if ( options . autoProv === false ) { spec . tags . autoProv = options . autoProv ; } if ( options . hasOwnProperty ( 'excludeArchs' ) ) { spec . addExcludeArchs . apply ( spec , options . excludeArchs ) ; } if ( options . hasOwnProperty ( 'exclusiveArchs' ) ) { spec . addExclusiveArchs . apply ( spec , options . exclusiveArchs ) ; } if ( options . hasOwnProperty ( 'excludeOS' ) ) { spec . addExcludeOS . apply ( spec , options . excludeOS ) ; } if ( options . hasOwnProperty ( 'exclusiveOS' ) ) { spec . addExclusiveOS . apply ( spec , options . exclusiveOS ) ; } spec . tags . prefix = options . prefix || spec . tags . prefix ; spec . tags . buildRoot = options . buildRoot || spec . tags . buildRoot ; if ( options . hasOwnProperty ( 'sources' ) ) { spec . addSources . apply ( spec , options . sources ) ; } if ( options . hasOwnProperty ( 'noSources' ) ) { spec . addNoSources . apply ( spec , options . noSources ) ; } if ( options . hasOwnProperty ( 'patches' ) ) { spec . addPatches . apply ( spec , options . patches ) ; } if ( options . hasOwnProperty ( 'noPatches' ) ) { spec . addNoPatches . apply ( spec , options . noPatches ) ; } // Add scripts from options. if ( options . hasOwnProperty ( 'prepScript' ) ) { spec . addPrepScripts . apply ( spec , options . prepScript ) ; } if ( options . hasOwnProperty ( 'buildScript' ) ) { spec . addBuildScripts . apply ( spec , options . buildScript ) ; } if ( options . hasOwnProperty ( 'checkScript' ) ) { spec . addCheckScripts . apply ( spec , options . checkScript ) ; } if ( options . hasOwnProperty ( 'cleanScript' ) ) { spec . addCleanScripts . apply ( spec , options . cleanScript ) ; } if ( options . hasOwnProperty ( 'installScript' ) ) { spec . addInstallScripts . apply ( spec , options . installScript ) ; } if ( options . hasOwnProperty ( 'preInstallScript' ) ) { spec . addPreInstallScripts . apply ( spec , options . preInstallScript ) ; } if ( options . hasOwnProperty ( 'postInstallScript' ) ) { spec . addPostInstallScripts . apply ( spec , options . postInstallScript ) ; } if ( options . hasOwnProperty ( 'preUninstallScript' ) ) { spec . addPreUninstallScripts . apply ( spec , options . preUninstallScript ) ; } if ( options . hasOwnProperty ( 'postUninstallScript' ) ) { spec . addPostUninstallScripts . apply ( spec , options . postUninstallScript ) ; } if ( options . hasOwnProperty ( 'verifyScript' ) ) { spec . addVerifyScripts . apply ( spec , options . verifyScript ) ; } // Add the default file attributes from options. if ( options . hasOwnProperty ( 'defaultAttributes' ) ) { spec . setDefaultAttributes ( options . defaultAttributes ) ; } // Add the changelogs. if ( options . hasOwnProperty ( 'changelog' ) ) { var changelog ; if ( _ . isFunction ( options . changelog ) ) { changelog = options . changelog ( ) ; } else if ( _ . isArray ( options . changelog ) ) { changelog = options . changelog ; } spec . addChangelogs . apply ( spec , changelog ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "API [CODESPLIT] function Couch ( opts ) { var self = this ; self . url = ( typeof opts . url === 'string' ) ? opts . url : null ; self . userCtx = opts . userCtx || null ; self . time_C = opts . time_C || null ; self . known_dbs = null ; self . log = debug ( 'cqs:couch:' + self . url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utilities [CODESPLIT] function uuids_for ( couch ) { UUIDS [ couch . url ] = UUIDS [ couch . url ] || new UUIDGetter ( couch ) ; return UUIDS [ couch . url ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utilities [CODESPLIT] function templated_ddoc ( name ) { return stringify_functions ( TEMPLATE ) function stringify_functions ( obj ) { var copy = { } ; if ( Array . isArray ( obj ) ) return obj . map ( stringify_functions ) else if ( typeof obj === 'object' && obj !== null ) { Object . keys ( obj ) . forEach ( function ( key ) { copy [ key ] = stringify_functions ( obj [ key ] ) ; } ) return copy ; } else if ( typeof obj === 'function' ) return func_from_template ( obj ) else return lib . JDUP ( obj ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For example : 1 год 2 года 3 года 4 года 5 лет 6 лет … 11 лет 12 лет … 20 лет 21 год 31 год 22 года 32 года [CODESPLIT] function pluralize ( number , words ) { var magnitude = number % 100 ; var pluralWord = '' if ( ( magnitude > 10 && magnitude < 20 ) || ( number === 0 ) ) { pluralWord = words [ 2 ] ; } else { switch ( Math . abs ( number % 10 ) ) { case 1 : pluralWord = words [ 0 ] ; break case 2 : case 3 : case 4 : pluralWord = words [ 1 ] ; break default : pluralWord = words [ 2 ] ; break } } return [ number , pluralWord ] . join ( ' ' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "API [CODESPLIT] function Message ( opts ) { var self = this ; events . EventEmitter . call ( self ) ; lib . copy ( opts , self , 'uppercase' ) ; self . MessageId = opts . MessageId || opts . _id || null ; self . Body = opts . MessageBody || opts . Body || opts . _str || null ; self . MD5OfMessageBody = null ; self . IdExtra = opts . IdExtra || null ; self . queue = opts . queue || null ; self . is_heartbeat = opts . is_heartbeat || false ; self . seq = opts . seq || null ; self . log = debug ( 'cqs:message:' + ( self . MessageId || 'untitled' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "API [CODESPLIT] function Queue ( opts ) { var self = this ; if ( typeof opts == 'string' ) opts = { 'name' : opts } ; opts = defaultable . merge ( opts , DEFS ) ; self . name = opts . name || opts . QueueName || opts . _str || null ; self . time_C = opts . time_C || null ; self . db = new couch . Database ( { 'couch' : opts . couch , 'db' : opts . db , time_C : self . time_C } ) ; self . VisibilityTimeout = opts . DefaultVisibilityTimeout || opts . VisibilityTimeout || DEFS . visibility_timeout ; self . cache_confirmation = true ; self . browser_attachments = ! ! ( opts . browser_attachments ) ; self . allow_foreign_docs = opts . allow_foreign_docs self . log = debug ( 'cqs:queue:' + ( self . name || 'untitled' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check and remove nodes recursively in preorder . For each composite node modify its children array in - place . [CODESPLIT] function preorder ( node , nodeIndex , parent ) { var children var length var index var position var child if ( is ( test , node , nodeIndex , parent ) ) { return null } children = node . children if ( ! children || children . length === 0 ) { return node } // Move all living children to the beginning of the children array. position = 0 length = children . length index = - 1 while ( ++ index < length ) { child = preorder ( children [ index ] , index , node ) if ( child ) { children [ position ++ ] = child } } // Cascade delete. if ( cascade && position === 0 ) { return null } // Drop other nodes. children . length = position return node }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parse data into a IPV6 address string [CODESPLIT] function asAAAA ( consumer , packet ) { var data = '' ; for ( var i = 0 ; i < 7 ; i ++ ) { data += consumer . short ( ) . toString ( 16 ) + ':' ; } data += consumer . short ( ) . toString ( 16 ) ; packet . address = data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters models so they are formatted correctly . [CODESPLIT] function filterRelations ( relation ) { var mappedData = includedData . find ( function ( inc ) { return inc . id === relation . id ; } ) ; var RelationModel = getModel ( relation . type ) ; var modeledData = new RelationModel ( mappedData ) ; return checkForRelations ( modeledData , modeledData . data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Locator walks the filesystem and gives semantic meaning to files in the application . @module Locator @class Locator @constructor @param { object } [ options ] Options for how the configuration files are located . @param { string } [ options . applicationDirectory ] Where the application will be found . If not given it defaults to the current working directory . @param { [ string ] } [ options . exclude ] folder names that should not be analyzed @param { integer } options . maxPackageDepth Maximum depth in node_modules / to walk . Defaults to 9999 . @param { function } options . rulesetFn Function hook to compute rules per bundle dynamically . This hook allow to analyze the pkg and produce the proper rules when needed . [CODESPLIT] function BundleLocator ( options ) { this . _options = options || { } ; if ( this . _options . applicationDirectory ) { this . _options . applicationDirectory = libpath . resolve ( process . cwd ( ) , this . _options . applicationDirectory ) ; } else { this . _options . applicationDirectory = process . cwd ( ) ; } this . _options . maxPackageDepth = this . _options . maxPackageDepth || DEFAULT_MAX_PACKAGES_DEPTH ; this . _options . exclude = this . _options . exclude || [ ] ; this . _cacheRules = { } ; // rulename + package directory: rules this . _bundles = { } ; this . _bundlePaths = { } ; // path: name this . _bundleUpdates = { } ; // name: object describing why the update happened }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the directory to turn it into a bundle . @method parseBundle @param { string } dir The directory for the bundle . @param { object } [ options ] Options for processing the bundle . [CODESPLIT] function ( dir , options ) { var self = this , bundleSeeds ; // Normalize the root directory before storing its value. If it is // stored before normalizing, other paths created afterwards may be // normalized and fail comparisons against the root directory dir = libpath . normalize ( dir ) ; this . _rootDirectory = dir ; bundleSeeds = this . _walkNPMTree ( dir ) ; bundleSeeds = this . _filterBundleSeeds ( bundleSeeds ) ; bundleSeeds . forEach ( function ( bundleSeed ) { var opts = ( bundleSeed . baseDirectory === dir ) ? options : { } ; self . _walkBundle ( bundleSeed , opts ) ; } ) ; this . _rootBundleName = this . _bundlePaths [ libfs . realpathSync ( dir ) ] ; return this . _bundles [ this . _rootBundleName ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method for listing all files in a bundle . [CODESPLIT] function ( bundleName , filter ) { var bundle , files = [ ] ; bundle = this . _bundles [ bundleName ] ; if ( ! bundle ) { throw new Error ( 'Unknown bundle \"' + bundleName + '\"' ) ; } Object . keys ( bundle . files ) . forEach ( function ( fullpath ) { var res = { ext : libpath . extname ( fullpath ) . substr ( 1 ) } ; if ( this . _filterResource ( res , filter ) ) { files . push ( fullpath ) ; } } , this ) ; return files ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method for listing all resources in a bundle . [CODESPLIT] function ( bundleName , filter ) { var bundle = this . _bundles [ bundleName ] ; if ( ! bundle ) { throw new Error ( 'Unknown bundle \"' + bundleName + '\"' ) ; } return this . _walkBundleResources ( bundle , filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of resources in all the bundles . [CODESPLIT] function ( filter ) { var self = this , ress = [ ] ; Object . keys ( this . _bundles ) . forEach ( function ( bundleName ) { var bundle = self . _bundles [ bundleName ] ; self . _walkBundleResources ( bundle , filter ) . forEach ( function ( res ) { ress . push ( res ) ; } ) ; } ) ; return ress ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of all located bundle names . The names are not ordered . [CODESPLIT] function ( filter ) { var bundleName , bundles = this . _bundles , bundleNames = [ ] ; if ( 'function' !== typeof filter ) { return Object . keys ( this . _bundles ) ; } for ( bundleName in bundles ) { if ( bundles . hasOwnProperty ( bundleName ) ) { if ( filter ( bundles [ bundleName ] ) ) { bundleNames . push ( bundleName ) ; } } } return bundleNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the name of the bundle to which the path belongs . [CODESPLIT] function ( findPath ) { // FUTURE OPTIMIZATION:  use a more complicated datastructure for faster lookups var found = { } , // length: path longest ; // expands path in case of symlinks findPath = libfs . realpathSync ( findPath ) ; // searchs based on expanded path Object . keys ( this . _bundlePaths ) . forEach ( function ( bundlePath ) { if ( 0 === findPath . indexOf ( bundlePath ) && ( findPath . length === bundlePath . length || libpath . sep === findPath . charAt ( bundlePath . length ) ) ) { found [ bundlePath . length ] = bundlePath ; } } ) ; longest = Math . max . apply ( Math , Object . keys ( found ) ) ; return this . _bundlePaths [ found [ longest ] ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the seed of a potential bundle . [CODESPLIT] function ( baseDirectory , name , version , pkg , options ) { var seed ; seed = { baseDirectory : baseDirectory , name : name , version : version } ; if ( pkg ) { seed . name = ( pkg . locator && pkg . locator . name ? pkg . locator . name : pkg . name ) ; seed . version = pkg . version ; seed . options = pkg . locator ; seed . pkg = pkg ; } if ( options ) { if ( seed . options ) { // merge options under seed.options mix ( seed . options , options ) ; } else { seed . options = options ; } } return seed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a bundle out of a directory . [CODESPLIT] function ( seed , parent ) { var bundle , ruleset = this . _loadRuleset ( seed ) , msg ; if ( seed . options . location ) { // This is fairly legacy, and we might be able to remove it. seed . baseDirectory = libpath . resolve ( seed . baseDirectory , seed . options . location ) ; } if ( ! ruleset ) { msg = 'Bundle \"' + seed . name + '\" has unknown ruleset ' + JSON . stringify ( seed . options . ruleset ) ; if ( seed . options . rulesets ) { msg += ' in rulesets ' + JSON . stringify ( seed . options . rulesets ) ; } throw new Error ( msg ) ; } bundle = new Bundle ( seed . baseDirectory , seed . options ) ; bundle . name = seed . name ; bundle . version = seed . version ; bundle . type = ruleset . _name ; this . _bundles [ bundle . name ] = bundle ; this . _bundlePaths [ libfs . realpathSync ( bundle . baseDirectory ) ] = bundle . name ; // wire into parent if ( parent ) { if ( ! parent . bundles ) { parent . bundles = { } ; } parent . bundles [ bundle . name ] = bundle ; } return bundle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turns the path into a resource in the associated bundle if applicable . [CODESPLIT] function ( fullPath ) { var bundleName , bundle , ruleset , relativePath , pathParts , subBundleSeed , res ; bundleName = this . _getBundleNameByPath ( fullPath ) ; bundle = this . _bundles [ bundleName ] ; if ( bundle . baseDirectory === fullPath . substr ( 0 , bundle . baseDirectory . length ) ) { relativePath = fullPath . substr ( bundle . baseDirectory . length + 1 ) ; } // This mainly happens during watch(), since we skip node_modules // in _walkBundle(). if ( relativePath . indexOf ( 'node_modules' ) === 0 ) { pathParts = relativePath . split ( libpath . sep ) ; while ( pathParts [ 0 ] === 'node_modules' && pathParts . length >= 2 ) { pathParts . shift ( ) ; bundleName = pathParts . shift ( ) ; } relativePath = pathParts . join ( libpath . sep ) ; bundle = this . _bundles [ bundleName ] ; // The package's directory is not a resource (... and is mostly uninteresting). if ( ! relativePath ) { return ; } // unknown bundle if ( ! bundle ) { return ; } } ruleset = this . _loadRuleset ( bundle ) ; if ( ruleset . _skip && this . _ruleSkip ( fullPath , relativePath , ruleset . _skip ) ) { return ; } if ( ruleset . _bundles ) { subBundleSeed = this . _ruleBundles ( fullPath , relativePath , ruleset . _bundles , bundle ) ; if ( subBundleSeed ) { // sub-bundle inherits options.rulesets from parent if ( ! subBundleSeed . options ) { subBundleSeed . options = { } ; } if ( ! subBundleSeed . options . rulesets ) { subBundleSeed . options . rulesets = bundle . options . rulesets ; } this . _makeBundle ( subBundleSeed , bundle ) ; return ; } } // This is the base \"meta\" for a file.  If a rule matches we'll // augment this. res = { bundleName : bundleName , fullPath : fullPath , relativePath : relativePath , ext : libpath . extname ( fullPath ) . substr ( 1 ) } ; this . _onFile ( res , ruleset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the _skip rule to decide if the path should be skipped . [CODESPLIT] function ( fullPath , relativePath , rule ) { var r , regex ; relativePath = BundleLocator . _toUnixPath ( relativePath ) ; for ( r = 0 ; r < rule . length ; r += 1 ) { regex = rule [ r ] ; if ( regex . test ( relativePath ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the _bundles rule looking for child bundles . Returns a bundle seed as described by _makeBundleSeed () . [CODESPLIT] function ( fullPath , relativePath , rule , parent ) { var r , matches , defaultVersion = DEFAULT_VERSION , pkg ; if ( parent ) { defaultVersion = parent . version ; } relativePath = BundleLocator . _toUnixPath ( relativePath ) ; for ( r = 0 ; r < rule . length ; r += 1 ) { matches = relativePath . match ( rule [ r ] . regex ) ; if ( matches ) { try { pkg = require ( libpath . resolve ( fullPath , 'package.json' ) ) ; } catch ( packageErr ) { // It's OK for a sub-bundle to not have a package.json. } return this . _makeBundleSeed ( fullPath , libpath . normalize ( matches [ 1 ] ) , defaultVersion , pkg , rule [ r ] . options ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the file . [CODESPLIT] function ( res , ruleset ) { var bundle = this . _bundles [ res . bundleName ] , ruleName , rule , relativePath = BundleLocator . _toUnixPath ( res . relativePath ) , match ; bundle . files [ res . fullPath ] = true ; for ( ruleName in ruleset ) { if ( ruleset . hasOwnProperty ( ruleName ) ) { // Rules that start with \"_\" are special directives, // and have already been handle by the time we get here. if ( '_' !== ruleName . charAt ( 0 ) ) { rule = ruleset [ ruleName ] ; match = relativePath . match ( rule . regex ) ; if ( match ) { res . name = match [ rule . nameKey || 1 ] ; res . type = ruleName ; if ( rule . subtypeKey ) { res . subtype = match [ rule . subtypeKey ] || '' ; } if ( rule . selectorKey && match [ rule . selectorKey ] ) { res . selector = match [ rule . selectorKey ] ; } else { res . selector = DEFAULT_SELECTOR ; } // file will become a resource after the first match return this . _onResource ( res ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the resource . [CODESPLIT] function ( res ) { var bundle = this . _bundles [ res . bundleName ] , type = res . type , subtype , selector = res . selector , name = res . name ; if ( ! bundle . resources [ selector ] ) { bundle . resources [ selector ] = { } ; } if ( ! bundle . resources [ selector ] [ type ] ) { bundle . resources [ selector ] [ type ] = { } ; } if ( res . hasOwnProperty ( 'subtype' ) ) { subtype = res . subtype ; if ( ! bundle . resources [ selector ] [ type ] [ subtype ] ) { bundle . resources [ selector ] [ type ] [ subtype ] = { } ; } bundle . resources [ selector ] [ type ] [ subtype ] [ name ] = res ; } else { bundle . resources [ selector ] [ type ] [ name ] = res ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether a resource is filtered or not . [CODESPLIT] function ( res , filter ) { if ( ! filter || Object . keys ( filter ) . length === 0 ) { return true ; } var prop ; for ( prop in filter ) { if ( 'extensions' === prop ) { // sugar for users if ( 'string' === typeof filter . extensions ) { filter . extensions = filter . extensions . split ( ',' ) ; } if ( ! filter . extensions || filter . extensions . indexOf ( res . ext ) === - 1 ) { return false ; } } else if ( 'types' === prop ) { // sugar for users if ( 'string' === typeof filter . types ) { filter . types = filter . types . split ( ',' ) ; } if ( ! filter . types || filter . types . indexOf ( res . type ) === - 1 ) { return false ; } } else { return false ; // unknown filters should fail to pass } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walks a directory and returns a list of metadata about locator packages installed in that directory ( including the package for the directory itself ) . [CODESPLIT] function ( dir , _depth ) { var self = this , pkg , seed , seeds = [ ] , subdirs ; _depth = _depth || 0 ; try { pkg = require ( libpath . resolve ( dir , 'package.json' ) ) ; // top level package doesn't require a locator flag in package.json if ( ( 0 === _depth ) && ( ! pkg . locator ) ) { pkg . locator = { } ; } seed = this . _makeBundleSeed ( dir , libpath . basename ( dir ) , DEFAULT_VERSION , pkg ) ; if ( seed . options ) { seed . npmDepth = _depth ; seeds . push ( seed ) ; } } catch ( packageErr ) { // Some build environments leave extraneous directories in // node_modules and we should ignore them gracefully. // (trello board:Modown card:124) if ( 'MODULE_NOT_FOUND' !== packageErr . code ) { throw packageErr ; } return seeds ; } if ( _depth < this . _options . maxPackageDepth ) { try { subdirs = libfs . readdirSync ( libpath . join ( dir , 'node_modules' ) ) ; } catch ( readdirErr ) { if ( 'ENOENT' === readdirErr . code ) { // missing node_modules/ directory is OK return seeds ; } throw readdirErr ; } subdirs . reduce ( function ( memo , subdir ) { return memo . concat ( '@' === subdir . substring ( 0 , 1 ) ? libfs . readdirSync ( libpath . join ( dir , 'node_modules' , subdir ) ) . map ( function ( scopeddir ) { return libpath . join ( subdir , scopeddir ) ; } ) : [ subdir ] ) ; } , [ ] ) . forEach ( function ( subdir ) { var subpkgResults ; if ( '.' === subdir . substring ( 0 , 1 ) ) { return ; } subpkgResults = self . _walkNPMTree ( libpath . join ( dir , 'node_modules' , subdir ) , _depth + 1 ) ; // merge in found packages if ( subpkgResults && subpkgResults . length ) { seeds = seeds . concat ( subpkgResults ) ; } } ) ; } return seeds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Figures out which seed to use from the list of available packages . Select by depth then by semver . [CODESPLIT] function ( pkgDepths ) { // pkgDepths -> depth: [metas] var depths , minDepth , maxDepth , seeds ; depths = Object . keys ( pkgDepths ) ; minDepth = Math . min . apply ( Math , depths ) ; maxDepth = Math . max . apply ( Math , depths ) ; seeds = pkgDepths [ minDepth ] ; if ( 1 === seeds . length ) { if ( minDepth !== maxDepth ) { debug ( 'multiple \"' + seeds [ 0 ] . name + '\" packages found, using version ' + seeds [ 0 ] . version + ' from ' + seeds [ 0 ] . baseDirectory ) ; } return seeds [ 0 ] ; } seeds . sort ( function ( a , b ) { return libsemver . rcompare ( a . version , b . version ) ; } ) ; debug ( 'multiple \"' + seeds [ 0 ] . name + '\" packages found, using version ' + seeds [ 0 ] . version + ' from ' + seeds [ 0 ] . baseDirectory ) ; return seeds [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Figures out which bundles to use from the list . The returned list is sorted first by NPM package depth then by name . [CODESPLIT] function ( all ) { var byDepth = { } ; // name: depth: [metas] all . forEach ( function ( seed ) { if ( ! byDepth [ seed . name ] ) { byDepth [ seed . name ] = { } ; } if ( ! byDepth [ seed . name ] [ seed . npmDepth ] ) { byDepth [ seed . name ] [ seed . npmDepth ] = [ ] ; } byDepth [ seed . name ] [ seed . npmDepth ] . push ( seed ) ; } ) ; return Object . keys ( byDepth ) . map ( function ( name ) { return this . _dedupeSeeds ( byDepth [ name ] ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a bundle from an NPM package and queues up files in the package . [CODESPLIT] function ( bundleSeed ) { var self = this , parentName , parent , bundle , filters ; // TODO -- merge options (second arg) over bundleSeed.options parentName = this . _getBundleNameByPath ( libpath . dirname ( bundleSeed . baseDirectory ) ) ; parent = this . _bundles [ parentName ] ; bundle = this . _makeBundle ( bundleSeed , parent ) ; this . _bundles [ bundle . name ] = bundle ; filters = this . _options . exclude . concat ( [ 'node_modules' , / ^\\. / ] ) ; // adding the bundle dir itself for BC this . _processFile ( bundle . baseDirectory ) ; walk . walkSync ( bundle . baseDirectory , { filters : [ ] , listeners : { directories : function ( root , dirStatsArray , next ) { var i , dirStats , exclude ; function filterDir ( filter ) { if ( dirStats . name . match ( filter ) ) { return true ; } } for ( i = dirStatsArray . length - 1 ; i >= 0 ; i -= 1 ) { dirStats = dirStatsArray [ i ] ; exclude = filters . some ( filterDir ) ; if ( exclude ) { // the sync walk api is pretty bad, it requires to // mutate the actual dir array dirStatsArray . splice ( i , 1 ) ; } else { self . _processFile ( libpath . join ( root , dirStats . name ) ) ; } } next ( ) ; } , file : function ( root , fileStats , next ) { self . _processFile ( libpath . join ( root , fileStats . name ) ) ; next ( ) ; } , errors : function ( root , nodeStatsArray , next ) { next ( ) ; } } } ) ; return bundle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the rulesets for the bundle ( or seed ) . [CODESPLIT] function ( bundle ) { var name = ( bundle . options && bundle . options . ruleset ) || DEFAULT_RULESET , cacheKey = name + '@' + bundle . baseDirectory , rulesetsPath , rulesets , dir , rules ; rules = this . _cacheRules [ cacheKey ] ; if ( rules ) { return rules ; } if ( bundle . options && bundle . options . rulesets ) { try { rulesetsPath = libpath . resolve ( bundle . baseDirectory , bundle . options . rulesets ) ; rulesets = require ( rulesetsPath ) ; } catch ( errLocal ) { if ( 'MODULE_NOT_FOUND' !== errLocal . code ) { throw errLocal ; } } if ( ! rulesets ) { dir = bundle . baseDirectory ; while ( dir ) { try { rulesetsPath = libpath . resolve ( dir , bundle . options . rulesets ) ; rulesets = require ( rulesetsPath ) ; break ; } catch ( errDir ) { if ( 'MODULE_NOT_FOUND' !== errDir . code ) { throw errDir ; } } try { rulesetsPath = libpath . resolve ( dir , 'node_modules' , bundle . options . rulesets ) ; rulesets = require ( rulesetsPath ) ; break ; } catch ( errDep ) { if ( 'MODULE_NOT_FOUND' !== errDep . code ) { throw errDep ; } } // not found, iterate dir = libpath . dirname ( dir ) ; if ( 'node_modules' === libpath . basename ( dir ) ) { dir = libpath . dirname ( dir ) ; } if ( this . _rootDirectory && dir . length < this . _rootDirectory . length ) { // if we can find the ruleset anywhere near in the filesystem // we should try to rely on npm lookup process try { rulesetsPath = Module . _resolveFilename ( bundle . options . rulesets , Module . _cache [ __filename ] ) ; rulesets = require ( rulesetsPath ) ; } catch ( errLocalMod ) { return ; } } } } // a ruleset pkg can contain multiple rulesets rules = rulesets [ name ] ; } else if ( this . _options . rulesetFn ) { // using the rulesetFn() hook to produce custom rules rules = this . _options . rulesetFn ( bundle ) ; } else { rules = DEFAULT_RULESETS [ name ] ; } if ( rules ) { rules . _name = name ; this . _cacheRules [ cacheKey ] = rules ; } return rules ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new object with the certain keys excluded . This is used instead of delete since that has performance implications in V8 . [CODESPLIT] function ( srcObject , excludeKeys ) { var destObject = { } , key ; for ( key in srcObject ) { if ( srcObject . hasOwnProperty ( key ) ) { if ( - 1 === excludeKeys . indexOf ( key ) ) { destObject [ key ] = srcObject [ key ] ; } } } return destObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Locator walks the filesystem and gives semantic meaning to files in the application . [CODESPLIT] function Bundle ( baseDirectory , options ) { this . options = options || { } ; this . name = libpath . basename ( baseDirectory ) ; this . baseDirectory = baseDirectory ; this . type = undefined ; this . files = { } ; this . resources = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get a scale with logic for the x and y axis if the domain starts and finishes on the same number returns the mid range value [CODESPLIT] function getBaseScales ( type , domain , range , nice , tickCount ) { const factory = ( type === 'time' && scaleUtc ) || ( type === 'log' && scaleLog ) || scaleLinear const scale = createScale ( factory , domain , range ) if ( nice ) scale . nice ( tickCount ) return scale }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generate the array of render data [CODESPLIT] function getLineRenderData ( props , data , idx ) { if ( isEmpty ( data ) ) return undefined const path2D = getPath2D ( ) const values = getPlotValues ( props , head ( data ) , idx , { hoverAlpha : 0.2 } ) if ( props . interpolate ) { splineInterpolation ( props , data , path2D ) } else { path2D . moveTo ( values . x , values . y ) reduce ( data , ( shouldDrawPoint , d ) => { const x = plotValue ( props , d , idx , 'x' ) const y = plotValue ( props , d , idx , 'y' ) if ( notPlotNumber ( [ x , y ] ) ) return false if ( shouldDrawPoint ) path2D . lineTo ( x , y ) else path2D . moveTo ( x , y ) return true } , true ) } return { ... values , data , hoverSolver , path2D , type : 'line' , } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * points is used to generate render data for dots and similar . it handles x y radius and fill . [CODESPLIT] function getPointRenderData ( props , datum , idx ) { const values = getPlotValues ( props , datum , idx , { hoverAlpha : 0.75 , radius : 4 , x : getMidX ( props . plotRect ) , y : getMidY ( props . plotRect ) , } ) const path2D = getPath2D ( ) const hover2ndPath2D = getPath2D ( ) path2D . arc ( values . x , values . y , values . radius , 0 , 2 * Math . PI ) hover2ndPath2D . arc ( values . x , values . y , values . radius + 8 , 0 , 2 * Math . PI ) return { ... values , hover2ndPath2D , path2D , type : 'area' , } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start with the input props send them to the first transform merge the returned new props back to the props . Do again with the next transform . const rootProps = chartTransformFlow ( props t1 t2 t3 ) [CODESPLIT] function removeDimArrays ( props ) { const names = map ( props . groupedKeys , key => ` ${ key } ` ) return omit ( props , names ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generate the array of render data [CODESPLIT] function getTextRenderData ( props , datum , idx ) { const { plotRect , theme , width , height } = props const values = getPlotValues ( props , datum , idx , { x : getMidX ( props . plotRect ) , y : getMidY ( props . plotRect ) , } ) if ( values . textSnap === 'top' ) values . y = getMinY ( plotRect ) if ( values . textSnap === 'bottom' ) values . y = getMaxY ( plotRect ) if ( values . textSnap === 'left' ) values . x = getMinX ( plotRect ) if ( values . textSnap === 'right' ) values . x = getMaxX ( plotRect ) if ( values . textSnap === 'topLeft' ) { values . x = getMinX ( plotRect ) values . y = getMinY ( plotRect ) } if ( values . textSnap === 'topRight' ) { values . x = getMaxX ( plotRect ) values . y = getMinY ( plotRect ) } if ( values . textSnap === 'bottomLeft' ) { values . x = getMinX ( plotRect ) values . y = getMaxY ( plotRect ) } if ( values . textSnap === 'bottomRight' ) { values . x = getMaxX ( plotRect ) values . y = getMaxY ( plotRect ) } const newValues = fitCheckText ( values , width , height , theme ) return { ... newValues , type : 'text' } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Buffer traces and defer recording until maxTraces have been received or sendInterval has elapsed since the last trace was recorded . [CODESPLIT] function BufferingTracer ( tracer , options ) { options = options || { } ; var self = this ; this . _tracer = tracer ; this . _maxTraces = options . maxTraces || 50 ; this . _sendInterval = options . sendInterval ? ( options . sendInterval * 1000 ) : 10 * 1000 ; this . _lastSentTs = Date . now ( ) ; this . _buffer = [ ] ; this . _stopped = false ; this . _periodSendTimeoutId = setTimeout ( this . _periodicSendFunction . bind ( this ) , this . _sendInterval ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A tracer that records to zipkin through the RESTkin http interface . Requires a keystone client ( { node - keystone - client } ) . [CODESPLIT] function RawRESTkinHTTPTracer ( traceUrl , keystoneClient ) { if ( traceUrl . charAt ( traceUrl . length - 1 ) === '/' ) { traceUrl = traceUrl . slice ( 0 , - 1 ) ; } this . _traceUrl = traceUrl ; this . _keystoneClient = keystoneClient ; EndAnnotationTracer . call ( this , this . sendTraces ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A tracer that records to zipkin through the RESTkin http interface . Requires a keystone client ( { node - keystone - client } ) . [CODESPLIT] function RESTkinHTTPTracer ( traceUrl , keystoneClient , options ) { var rawTracer = new module . exports . RawRESTkinHTTPTracer ( traceUrl , keystoneClient ) ; this . _tracer = new module . exports . BufferingTracer ( rawTracer , options ) ; this . stop = this . _tracer . stop . bind ( this . _tracer ) ; EndAnnotationTracer . call ( this , this . sendTraces ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A tracer that records directly to Zipkin Query HTTP API . [CODESPLIT] function RawZipkinQueryServiceHTTPTracer ( traceUrl ) { if ( traceUrl . charAt ( traceUrl . length - 1 ) === '/' ) { traceUrl = traceUrl . slice ( 0 , - 1 ) ; } this . _traceUrl = traceUrl ; EndAnnotationTracer . call ( this , this . sendTraces ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A tracer that records directly to Zipkin Query HTTP API . [CODESPLIT] function ZipkinQueryServiceHTTPTracer ( serviceUrl , options ) { var rawTracer = new module . exports . RawZipkinQueryServiceHTTPTracer ( serviceUrl ) ; this . _tracer = new module . exports . BufferingTracer ( rawTracer , options ) ; this . stop = this . _tracer . stop . bind ( this . _tracer ) ; EndAnnotationTracer . call ( this , this . sendTraces ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A tracer that records to zipkin through scribe . Requires a scribe client ( { node - scribe } ) . [CODESPLIT] function RawZipkinTracer ( scribeClient , category ) { this . scribeClient = scribeClient ; this . category = ( category ) ? category : 'zipkin' ; EndAnnotationTracer . call ( this , this . sendTraces ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A tracer that records to zipkin through scribe . Requires a scribe client ( { node - scribe } ) . [CODESPLIT] function ZipkinTracer ( scribeClient , category , options ) { var rawTracer = new RawZipkinTracer ( scribeClient , category ) ; this . _tracer = new BufferingTracer ( rawTracer , options ) ; this . stop = this . _tracer . stop . bind ( this . _tracer ) ; EndAnnotationTracer . call ( this , this . sendTraces ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A tracer that records to RESTkin through scribe . Requires a scribe client ( { node - scribe } ) . [CODESPLIT] function RawRESTkinScribeTracer ( scribeClient , category ) { this . scribeClient = scribeClient ; this . category = ( category ) ? category : 'restkin' ; EndAnnotationTracer . call ( this , this . sendTraces ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A tracer that records to RESTkin through scribe . Requires a scribe client ( { node - scribe } ) . [CODESPLIT] function RESTkinScribeTracer ( scribeClient , category , options ) { var rawTracer = new RawRESTkinScribeTracer ( scribeClient , category ) ; this . _tracer = new module . exports . BufferingTracer ( rawTracer , options ) ; this . stop = this . _tracer . stop . bind ( this . _tracer ) ; EndAnnotationTracer . call ( this , this . sendTraces ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Analyzes given gulp instance and build internal cache for further printing [CODESPLIT] function build ( gulp ) { // make sure we don't lose anything from required files // @see https://github.com/Mikhus/gulp-help-doc/issues/2 // currently this is not supported for typescript var source = OPTIONS . isTypescript ? fs . readFileSync ( 'gulpfile.ts' ) . toString ( ) : OPTIONS . gulpfile ? fs . readFileSync ( OPTIONS . gulpfile ) . toString ( ) : Object . keys ( require . cache || { 'gulpfile.js' : '' } ) . map ( function ( file ) { if ( ! / node_modules|\\.json$ / . test ( file ) ) { return fs . readFileSync ( file ) . toString ( ) + '\\n' ; } } ) . join ( '' ) ; var rxDoc = '\\\\/\\\\*\\\\*\\\\r?\\n(((?!\\\\*\\\\/)[\\\\s\\\\S])*?)' + '@task\\\\s+\\\\{(.*)?\\\\}((?!\\\\*\\\\/)[\\\\s\\\\S])*?\\\\*\\\\/' ; var rxArgs = '@arg\\\\s+\\\\{(.*?)\\\\}(.*?)\\\\r?\\\\n' ; var rxOrder = '@order\\\\s+\\\\{(\\\\d+)\\\\}(.*?)\\\\r?\\\\n' ; var rxGroup = '@group\\\\s+\\\\{(.*?)\\\\}(.*?)\\\\r?\\\\n' ; var globalRxDoc = new RegExp ( rxDoc , 'g' ) ; var localRxDoc = new RegExp ( rxDoc ) ; var globalRxArgs = new RegExp ( rxArgs , 'g' ) ; var localRxArgs = new RegExp ( rxArgs ) ; var globalRxOrder = new RegExp ( rxOrder , 'g' ) ; var localRxOrder = new RegExp ( rxOrder ) ; var globalRxGroup = new RegExp ( rxGroup , 'g' ) ; var localRxGroup = new RegExp ( rxGroup ) ; var jsDoc = ( source . match ( globalRxDoc ) || [ ] ) ; var tasks = gulpTasks ( gulp ) ; Object . keys ( tasks ) . forEach ( function ( task ) { reflection [ task ] = { name : tasks [ task ] . name , desc : '' , dep : tasks [ task ] . dep } ; } ) ; jsDoc . map ( function ( block ) { var parts = block . match ( localRxDoc ) ; var name = parts [ 3 ] . trim ( ) ; var desc = parts [ 1 ] . replace ( / \\s*\\* / g , ' ' ) . replace ( / \\s{2,} / g , ' ' ) . trim ( ) ; if ( ! reflection [ name ] ) { return ; } reflection [ name ] . desc = desc ; reflection [ name ] . public = true ; reflection [ name ] . args = ( block . match ( globalRxArgs ) || [ ] ) . map ( function ( def ) { var argsParts = def . match ( localRxArgs ) ; return { name : argsParts [ 1 ] , desc : argsParts [ 2 ] . replace ( / \\s*\\* / g , ' ' ) . replace ( / \\s{2,} / g , ' ' ) . trim ( ) } ; } ) ; reflection [ name ] . order = ( function ( ) { var orderParts = block . match ( globalRxOrder ) ; if ( orderParts ) { return + orderParts [ 0 ] . match ( localRxOrder ) [ 1 ] ; } return Number . MAX_SAFE_INTEGER ; } ) ( ) ; reflection [ name ] . group = ( function ( ) { var groupParts = block . match ( globalRxGroup ) ; if ( groupParts ) { return groupParts [ 0 ] . match ( localRxGroup ) [ 1 ] ; } return OPTIONS . defaultGroupName ; } ) ( ) ; } ) ; // Re-group tasks using user-defined groups var tmp = { } ; Object . keys ( reflection ) . forEach ( function ( task ) { var group = reflection [ task ] . group || OPTIONS . defaultGroupName ; tmp [ group ] = tmp [ group ] || { } ; tmp [ group ] [ task ] = reflection [ task ] ; } ) ; reflection = tmp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Chunks given string into pieces making each chunk less or equal to OPTIONS . lineWidth taking into account safe word - break [CODESPLIT] function chunk ( str , maxLen ) { var len = maxLen || OPTIONS . lineWidth ; var curr = len ; var prev = 0 ; var out = [ ] ; while ( str [ curr ] ) { if ( str [ curr ++ ] == ' ' ) { out . push ( str . substring ( prev , curr ) ) ; prev = curr ; curr += len ; } } out . push ( str . substr ( prev ) ) ; return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints usage help information for the given gulp instance . Usually it is used as a task within gulpfile . js in your project Please make sure all your comments are properly annotated [CODESPLIT] function usage ( gulp , options ) { // re-define options if needed if ( options ) { Object . assign ( OPTIONS , options ) ; } return new Promise ( function ( resolve ) { build ( gulp ) ; print ( ) ; resolve ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@constructor [CODESPLIT] function ( options ) { // Call abstract constructor AbstractWriter . prototype . constructor . apply ( this , arguments ) ; this . name = 'eyeD3' ; this . methods = { clear : 'eyeD3' , write : 'eyeD3' } ; if ( ~ this . options . encoding . indexOf ( 'ISO-' ) ) { this . options . encoding = 'latin1' ; } if ( 'UTF-8' === this . options . encoding ) { this . options . encoding = 'utf8' ; } if ( 'UTF-16' === this . options . encoding ) { this . options . encoding = 'utf16' ; } this . version = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@constructor [CODESPLIT] function ( options ) { // Call abstract constructor AbstractWriter . prototype . constructor . apply ( this , arguments ) ; this . name = 'id3tag' ; this . methods = { clear : 'id3convert' , write : 'id3tag' } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@constructor [CODESPLIT] function ( information , images ) { // Initalize the meta information this . information = { } ; this . set ( information || { } , true ) ; // Initalize images this . images = [ ] ; this . addImages ( images || [ ] , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strategy constructor . [CODESPLIT] function Strategy ( options , verify ) { options = options || { } ; options . authorizationURL = options . authorizationURL || 'https://api.weibo.com/oauth2/authorize' ; options . tokenURL = options . tokenURL || 'https://api.weibo.com/oauth2/access_token' ; options . scopeSeparator = options . scopeSeparator || ',' ; options . customHeaders = options . customHeaders || { } ; if ( ! options . customHeaders [ 'User-Agent' ] ) { options . customHeaders [ 'User-Agent' ] = options . userAgent || 'passport-weibo' ; } OAuth2Strategy . call ( this , options , verify ) ; this . name = 'weibo' ; this . _getuidAPI = options . getuidAPI || 'https://api.weibo.com/2/account/get_uid.json' ; this . _getProfileAPI = options . getProfileAPI || 'https://api.weibo.com/2/users/show.json' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a filter implementation that mutates the original array [CODESPLIT] function filterArray ( arr , toKeep ) { var i = 0 while ( i < arr . length ) { if ( toKeep ( arr [ i ] ) ) { i ++ } else { arr . splice ( i , 1 ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get all adapter that validates with args with the highest score the result is a single adapter ( func validators ) [CODESPLIT] function filterAndSortOne ( args , adapters ) { var results = decorateAndFilter ( args , adapters ) if ( results . length === 0 ) { return } // sort stable . inplace ( results , compare ) if ( results . length > 1 && results [ 0 ] . toString ( ) === results [ 1 ] . toString ( ) ) { throw new Error ( 'Occamsrazor (get): More than one adapter fits' ) } // undecorate return undecorate ( results ) [ 0 ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get all the adapter that validates with args . Sorted by score the result is a list of adapters ( func validators ) [CODESPLIT] function filterAndSort ( args , adapters ) { var results = decorateAndFilter ( args , adapters ) // sort stable . inplace ( results , compare ) // undecorate return undecorate ( results ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private methods [CODESPLIT] function getAdd ( opts ) { opts = opts || { } var times = opts . times var doesConsume = opts . doesConsume return function add ( ) { var lastArg = arguments [ arguments . length - 1 ] var func = typeof lastArg === 'function' ? lastArg : function ( ) { return lastArg } var validators = arguments . length > 1 ? Array . prototype . slice . call ( arguments , 0 , - 1 ) : [ ] var newAdapter = { doesConsume : doesConsume , // calling this adapter will remove the event posted times : times , func : func , validators : ut . combineValidators ( validators ) , ns : _ns } _adapters . push ( newAdapter ) // trigger all published event matching this adapter ut . filterArray ( _events , function ( event ) { if ( newAdapter . times === 0 ) return true var filteredAdapters = ut . filterAndSort ( event . args , [ newAdapter ] ) filteredAdapters . forEach ( ut . countdown ) ut . filterArray ( _adapters , ut . notExausted ) ut . triggerAll ( event . context , event . args , filteredAdapters ) // if the adapter consume the event, this gets filtered out return ! ( doesConsume && filteredAdapters . length ) } ) return or } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public methods / * this function is posting an event : context this and arguments [CODESPLIT] function adapt ( ) { var context = this var args = ut . getArgs ( arguments ) var filteredAdapter = ut . filterAndSortOne ( args , _adapters ) // the most specific if ( filteredAdapter ) { ut . countdown ( filteredAdapter ) ut . filterArray ( _adapters , ut . notExausted ) return filteredAdapter . func . apply ( context , args ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * this function is posting an event : context this and arguments [CODESPLIT] function all ( ) { var context = this var args = ut . getArgs ( arguments ) var filteredAdapters = ut . filterAndSort ( args , _adapters ) // all matching adapters filteredAdapters . forEach ( ut . countdown ) ut . filterArray ( _adapters , ut . notExausted ) return ut . getAll ( context , args , filteredAdapters ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * this function is posting an event : context this and arguments [CODESPLIT] function trigger ( ) { var context = this var args = ut . getArgs ( arguments ) var filteredAdapters = ut . filterAndSort ( args , _adapters ) filteredAdapters . forEach ( ut . countdown ) ut . filterArray ( _adapters , ut . notExausted ) ut . triggerAll ( context , args , filteredAdapters ) return or }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * this function is posting an event : context this and arguments [CODESPLIT] function stick ( ) { var context = this var args = ut . getArgs ( arguments ) var filteredAdapters = ut . filterAndSort ( args , _adapters ) var consumeAdapters = filteredAdapters . filter ( function ( adapter ) { return adapter . doesConsume } ) // adapters published with \"consume\" trigger the removal of the registered event if ( ! consumeAdapters . length ) { ut . binaryInsert ( _events , { context : this , args : args } , comparator ) } filteredAdapters . forEach ( ut . countdown ) ut . filterArray ( _adapters , ut . notExausted ) ut . triggerAll ( context , args , filteredAdapters ) return or }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract CSS from a browserify bundle obj - > null [CODESPLIT] function cssExtract ( bundle , opts ) { opts = opts || { } var outFile = opts . out || opts . o || 'bundle.css' var sourceMap = d ( opts . sourceMap , bundle && bundle . _options && bundle . _options . debug , false ) assert . equal ( typeof bundle , 'object' , 'bundle should be an object' ) assert . equal ( typeof opts , 'object' , 'opts should be an object' ) // every time .bundle is called, attach hook bundle . on ( 'reset' , addHooks ) addHooks ( ) function addHooks ( ) { const extractStream = through . obj ( write , flush ) const writeStream = ( typeof outFile === 'function' ) ? outFile ( ) : bl ( writeComplete ) // run before the \"label\" step in browserify pipeline bundle . pipeline . get ( 'label' ) . unshift ( extractStream ) function write ( chunk , enc , cb ) { // Performance boost: don't do ast parsing unless we know it's needed if ( ! / (insert-css|sheetify\\/insert) / . test ( chunk . source ) ) { return cb ( null , chunk ) } var source = from2 ( chunk . source ) var sm = staticModule ( { 'insert-css' : function ( src ) { writeStream . write ( String ( src ) + '\\n' ) return from2 ( 'null' ) } , 'sheetify/insert' : function ( src ) { writeStream . write ( String ( src ) + '\\n' ) return from2 ( 'null' ) } } , { sourceMap : sourceMap } ) source . pipe ( sm ) . pipe ( bl ( complete ) ) function complete ( err , source ) { if ( err ) return extractStream . emit ( 'error' , err ) chunk . source = String ( source ) cb ( null , chunk ) } } // close stream and signal end function flush ( cb ) { writeStream . end ( ) cb ( ) } function writeComplete ( err , buffer ) { if ( err ) return extractStream . emit ( 'error' , err ) fs . writeFileSync ( outFile , buffer ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "no : adapt all size batch [CODESPLIT] function fakeOccamsrazor ( hiddenPropertyName , objectPropertyName , globalObj , customAttrs ) { return buildFakeObject ( hiddenPropertyName , objectPropertyName , globalObj , defaultAttrs . concat ( customAttrs ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "! [CODESPLIT] function githubCompareCommits ( options , parseOptions ) { return compareCommits ( options ) . then ( function ( commits ) { return massageGithubCommits ( commits , parseOptions ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "! @method compareCommits [CODESPLIT] function compareCommits ( options ) { assert ( \"You MUST include 'project' in the options passed to compareCommits.\" + \"It should be the path to the project's git root.\" , options . project ) ; assert ( \"You MUST include 'base' in the options passed to compareCommits. \" + \"It should be either a branch name or tag name.\" , options . base ) ; assert ( \"You MUST include 'head' in the options passed to compareCommits. \" + \"It should be either a branch name or tag name.\" , options . head ) ; assert ( \"Branch or Tag names passed to compareCommit via 'options.head' must be strings.\" , typeof options . head === 'string' ) ; assert ( \"Branch or Tag names passed to compareCommit via 'options.base' must be strings.\" , typeof options . base === 'string' ) ; return getRepository ( options . project ) . then ( function ( repository ) { return RSVP . hash ( { head : getReference ( repository , options . head ) , base : getReference ( repository , options . base ) , repository : repository } ) ; } ) . then ( function ( references ) { return RSVP . hash ( { head : getTargetCommit ( references . repository , references . head ) , base : getTargetCommit ( references . repository , references . base ) , repository : references . repository } ) ; } ) . then ( function ( heads ) { return walkCommits ( heads . repository , heads . head , heads . base ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "yhsd 接口返回的请求量 header stringify 参数 [CODESPLIT] function genStringify ( options ) { var stringifyFn ; if ( options . headers [ 'Content-Type' ] && options . headers [ 'Content-Type' ] . toLowerCase ( ) === 'application/x-www-form-urlencoded' ) { stringifyFn = querystring . stringify ; } else { switch ( options . method . toUpperCase ( ) ) { case 'POST' : case 'PUT' : stringifyFn = JSON . stringify ; break ; } } return stringifyFn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "释放1个请求 [CODESPLIT] function decrement ( count ) { count = count || 0 ; if ( count <= MINUEND ) { count = 0 ; } else { count -= MINUEND ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "请求操作 [CODESPLIT] function ( options , params ) { var self = this ; return this . onBeforeHandle ( ) . then ( function ( ) { // 请求 Promise return new Promise ( function ( resolve , reject ) { var client = this . protocol === 'http' ? require ( 'http' ) : require ( 'https' ) ; var req = client . request ( options , self . genResponseFn ( resolve , reject ) ) ; req . on ( 'error' , reject ) ; // 发送参数 if ( params ) { var stringify = genStringify ( options ) ; req . write ( stringify ( params ) ) ; } req . end ( ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "请求前的操作 [CODESPLIT] function ( ) { var self = this ; if ( this . counted ) { return this . getRequestCount ( ) . then ( function ( count ) { count = count || 0 ; //如果请求数超过限制则 setTimeout 排队 if ( count >= config . requestLimit ) { return Promise . delay ( config . requestTimeout ) . then ( self . onBeforeHandle ) ; } return count ; } ) . then ( increment ) . then ( this . saveRequestCount ) ; } return Promise . resolve ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "请求后的操作 [CODESPLIT] function ( count ) { var delayMs = count * config . requestTimeout ; if ( this . counted ) { if ( this . getRequestCount && this . saveRequestCount ) return this . saveRequestCount ( count ) . delay ( delayMs ) . then ( this . getRequestCount ) . then ( decrement ) . then ( this . saveRequestCount ) ; } return Promise . resolve ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "验证 Hmac [CODESPLIT] function ( hmac , bodyData ) { if ( arguments . length < 2 ) { throw paramError ; } var calculatedHmac = crypto . createHmac ( 'sha256' , this . token ) . update ( bodyData , 'utf8' ) . digest ( 'base64' ) ; return hmac === calculatedHmac ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "包装 token 函数 [CODESPLIT] function ( token , fn ) { return function ( ) { // arguments 转成数组 var args = Array . prototype . slice . call ( arguments ) ; // 插入 token args . unshift ( token ) ; return Promise . cast ( fn . call ( null , args ) ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "初始化 [CODESPLIT] function ( token , option ) { if ( arguments . length < 1 ) { throw paramError ; } check ( option ) ; this . token = token ; this . host = ( option && option . host ) || config . apiHost ; // 存取请求数的回调函数 this . getRequestCount = option && option . getRequestCount || getReqCountHandle ; this . saveRequestCount = option && option . saveRequestCount || saveReqCountHandle ; // 请求实例 this . _request = new Request ( { protocol : ( option && option . protocol ) || config . httpProtocol , getRequestCount : reqCountWrap ( this . token , this . getRequestCount ) , saveRequestCount : reqCountWrap ( this . token , this . saveRequestCount ) , } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "发送 GET 请求 [CODESPLIT] function ( path , query ) { if ( arguments . length < 1 ) { throw paramError ; } return this . request ( 'GET' , query ? path + '?' + querystring . stringify ( query ) : path , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "请求函数 [CODESPLIT] function ( method , path , params ) { return this . _request . request ( { hostname : this . host , path : '/v1/' + path , method : method , headers : { 'Content-Type' : 'application/json' , 'X-API-ACCESS-TOKEN' : this . token } } , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "构造函数 [CODESPLIT] function ( options ) { if ( arguments . length < 1 || ! options . appKey || ! options . appSecret ) { throw paramError ; } if ( ! options . private ) { if ( ! options . callbackUrl ) { throw paramError ; } options . scope || ( options . scope = [ 'read_basic' ] ) ; } this . app_key = options . appKey || '' ; this . app_secret = options . appSecret || '' ; this . private = options . private || false ; this . callback_url = options . callbackUrl || '' ; this . scope = options . scope || '' ; this . redirect_url = options . redirectUrl || '' ; this . protocol = options . protocol || config . httpProtocol ; this . host = options . host || config . appHost ; this . _request = new Request ( { protocol : this . protocol , } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "验证 Hmac [CODESPLIT] function ( queryObj ) { if ( arguments . length < 1 ) { throw paramError ; } var hmac = queryObj . hmac ; delete queryObj . hmac ; return ( Date . now ( ) - new Date ( queryObj . time_stamp ) . getTime ( ) < timeOffset ) && ( hmac === crypto . createHmac ( 'sha256' , this . app_secret ) . update ( decodeURIComponent ( querystring . stringify ( queryObj ) ) , 'utf8' ) . digest ( 'hex' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取应用授权页面地址，用于开放应用 [CODESPLIT] function ( shopKey , state ) { if ( arguments . length < 1 ) { throw paramError ; } return this . protocol + '://' + this . host + '/oauth2/authorize?' + querystring . stringify ( { response_type : 'code' , client_id : this . app_key , shop_key : shopKey , scope : this . scope . join ( ',' ) , state : state , redirect_uri : this . redirect_url } , null , null , { encodeURIComponent : null } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取 token [CODESPLIT] function ( code ) { var params ; var headers = { 'Content-Type' : 'application/x-www-form-urlencoded' } ; if ( this . private ) { headers . Authorization = 'Basic ' + Buffer . from ( this . app_key + ':' + this . app_secret ) . toString ( 'base64' ) ; params = { grant_type : 'client_credentials' } ; } else { if ( arguments . length < 1 ) { throw paramError ; } params = { grant_type : 'authorization_code' , code : code , client_id : this . app_key , redirect_uri : this . redirect_url ? this . redirect_url : this . callback_url } ; } var option = { hostname : this . host , path : '/oauth2/token' , method : 'POST' , headers : headers } ; return this . _request . request ( option , params ) . then ( function ( data ) { if ( ! data . token . length ) { throw new Error ( '无效的 token');   } return data . token ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the regular placeholders of an item . This possibly modifies the given validationErrors . [CODESPLIT] function validatePlaceholders ( { id , idPlural , translations } , validationErrors ) { // search for {{placeholderName}} // Also search for e.g. Chinese symbols in the placeholderName let pattern = / {{\\s*(\\S+?)\\s*?}} / g ; let placeholders = id . match ( pattern ) || [ ] ; // We also want to add placeholders from the plural string if ( idPlural ) { let pluralPlaceholders = idPlural . match ( pattern ) || [ ] ; pluralPlaceholders . forEach ( ( placeholder ) => { if ( ! placeholders . includes ( placeholder ) ) { placeholders . push ( placeholder ) ; } } ) ; } if ( ! placeholders . length ) { return ; } translations . forEach ( ( translation ) => { let translatedPlaceholders = translation . match ( pattern ) || [ ] ; // Search for placeholders in the translated string that are not in the original string let invalidPlaceholder = translatedPlaceholders . find ( ( placeholder ) => ! placeholders . includes ( placeholder ) ) ; if ( invalidPlaceholder ) { validationErrors . push ( { id , translation , message : ` ${ invalidPlaceholder } ${ placeholders . join ( ', ' ) } ` , level : 'ERROR' } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the translated ( complex ) placeholders of an item . This mutates the given validationErrors . [CODESPLIT] function validateTranslatedPlaceholders ( { id , translations } , validationErrors ) { // find all: {{placeholder 'also translated'}} // {{placeholder \"also translated\"}} // {{placeholder \\'also translated\\'}} // {{placeholder \\\"also translated\\\"}} let pattern = / {{\\s*([\\w]+)\\s+((\\\\')|(\\\\\")|\"|')(.*?)((\\\\')|(\\\\\")|\"|')\\s*}} / g ; // This only works in non-plural form, so we assume only one translation let [ translation ] = translations ; // If the item is not translated at all, ignore it if ( ! translation ) { return ; } // Build an object describing the complex placeholders from the original string let placeholders = id . match ( pattern ) || [ ] ; if ( ! placeholders . length ) { return ; } let placeholderConfig = placeholders . map ( ( str ) => { pattern . lastIndex = 0 ; let [ fullResult , placeholder , quoteSymbol1 , , , content , quoteSymbol2 ] = pattern . exec ( str ) ; return { fullResult , placeholder , quoteSymbol1 , quoteSymbol2 , content } ; } ) ; // Build an object describing the complex placeholders from the translated string let translatedPlaceholders = translation . match ( pattern ) || [ ] ; let translatedPlaceholderConfig = translatedPlaceholders . map ( ( str ) => { pattern . lastIndex = 0 ; let [ fullResult , placeholder , quoteSymbol1 , , , content , quoteSymbol2 ] = pattern . exec ( str ) ; return { fullResult , placeholder , quoteSymbol1 , quoteSymbol2 , content } ; } ) ; placeholderConfig . forEach ( ( { placeholder , content } ) => { // First we check for missing/invalid placeholders // This can happen e.g. if a translator changes {{placeholder 'test'}} to {{placeholder `test`}} // So we make sure that all originally defined placeholders actually still exist if ( ! translatedPlaceholderConfig . find ( ( config ) => config . placeholder === placeholder ) ) { validationErrors . push ( { id , translation , message : ` ${ placeholder } ` , level : 'ERROR' } ) ; return ; } // Then, we check if the placeholder content is correctly translated // If the whole string is not translated at all, we ignore it // Only if the string is translated but the placeholder part not will this show a warning // NOTE: This is just a warning (not an error), as it is theoretically possible this is done on purpose // E.g. a word _might_ be the same in translated form if ( id === translation ) { return ; } let invalidTranslatedPlaceholder = translatedPlaceholderConfig . find ( ( config ) => { return config . content === content ; } ) ; if ( invalidTranslatedPlaceholder ) { validationErrors . push ( { id , translation , message : ` ${ content } ${ placeholder } ` , level : 'WARNING' } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Group equal entries together The generated groups look like the given gettextItems only that they have locs instead of loc Where locs is an array of loc entries having a fileName line and column . [CODESPLIT] function groupGettextItems ( gettextItems ) { return gettextItems . filter ( ( item ) => item . messageId ) // filter out items without message id . sort ( ( item1 , item2 ) => { return ( item1 . loc . fileName . localeCompare ( item2 . loc . fileName ) || item1 . loc . line - item2 . loc . line ) ; } ) . reduce ( ( allGroups , item ) => { let group = allGroups . find ( ( group ) => { return ( group . messageId === item . messageId && group . messageContext === item . messageContext ) ; } ) ; if ( group ) { group . locs . push ( item . loc ) ; // Although it is an edge case, it is possible for two translations to have the same messageID // while only one of them has a plural // For example: {{t 'Find item'}} {{n 'Find item' 'Find items' count}} // For such a case, we make sure to also add the plural, if it was previously missing if ( ! group . messageIdPlural && item . messageIdPlural ) { group . messageIdPlural = item . messageIdPlural ; } } else { group = Object . assign ( { } , item ) ; group . locs = [ item . loc ] ; delete group . loc ; allGroups . push ( group ) ; } return allGroups ; } , [ ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This will traverse an l10n - JSON file and call the callback function for each translation item . [CODESPLIT] function traverseJson ( json , callback ) { let { translations } = json ; Object . keys ( translations ) . forEach ( ( namespace ) => { Object . keys ( translations [ namespace ] ) . forEach ( ( k ) => { callback ( translations [ namespace ] [ k ] , translations [ namespace ] , k ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "autoParse auto - parse any value you happen to send in ( String Number Boolean Array Object Function undefined and null ) . You send it we will try to find a way to parse it . We now support sending in a string of what type ( e . g . boolean ) or constructor ( e . g . Boolean ) [CODESPLIT] function autoParse ( value , type ) { if ( type ) { return parseType ( value , type ) } var orignalValue = value /**\n   *  PRE RULE - check for null be cause null can be typeof object which can  through off parsing\n   */ if ( value === null ) { return null } /**\n   * TYPEOF SECTION - Use to check and do specific things based off of know the type\n   * Check against undefined\n   */ if ( value === void 0 ) { return undefined } if ( value instanceof Date || value instanceof RegExp ) { return value } if ( typeof value === 'number' || typeof value === 'boolean' ) { return value } if ( typeof value === 'function' ) { return parseFunction ( value ) } if ( typeof value === 'object' ) { return parseObject ( value ) } /**\n   * STRING SECTION - If we made it this far that means it is a string that we must do something with to parse\n   */ if ( value === 'NaN' ) { return NaN } var jsonParsed = null try { jsonParsed = JSON . parse ( value ) } catch ( e ) { try { jsonParsed = JSON . parse ( value . trim ( ) . replace ( / (\\\\\\\\\")|(\\\\\") / gi , '\"' ) . replace ( / (\\\\n|\\\\\\\\n) / gi , '' ) . replace ( / (^\"|\"$)|(^'|'$) / gi , '' ) ) } catch ( e ) { } } if ( jsonParsed && typeof jsonParsed === 'object' ) { return autoParse ( jsonParsed ) } value = stripTrimLower ( value ) if ( value === 'undefined' || value === '' ) { return undefined } if ( value === 'null' ) { return null } /**\n   * Order Matter because if it is a one or zero boolean will come back with a awnser too. if you want it to be a boolean you must specify\n   */ var num = Number ( value ) if ( typpy ( num , Number ) ) { return num } var boo = checkBoolean ( value ) if ( typpy ( boo , Boolean ) ) { return boo } /**\n   * DEFAULT SECTION - bascially if we catch nothing we assume that you just have a string\n   */ return String ( orignalValue ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eslint - disable - line [CODESPLIT] function traceWebpackLoader ( file ) { var traceName = ( __webpack_require__ . p || '/' ) + '' + file + '.bundle.js' // eslint-disable-line var trace = serviceContainer . services . transactionService . startTrace ( traceName , 'resource.script' ) return trace }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize ArangoStore with the given options . Optional calls readyCallback when db connection is ready ( mainly for testing purposes ) . [CODESPLIT] function ArangoStore ( options , readyCallback ) { options = options || { } ; if ( options . hash ) { var defaultSalt = \"connect-arango\" ; var defaultAlgorithm = \"sha1\" ; this . hash = { } ; this . hash . salt = options . hash . salt ? options . hash . salt : defaultSalt ; this . hash . algorithm = options . hash . algorithm ? options . hash . algorithm : defaultAlgorithm ; } Store . call ( this , options ) ; if ( ! options . db ) { throw new Error ( 'Required ArangoStore option `db` missing' ) ; } this . db_collection_name = options . collection || defaultOptions . collection ; if ( options . stringify || ( ! ( 'stringify' in options ) && ! ( 'serialize' in options ) && ! ( 'unserialize' in options ) ) ) { this . _serialize_session = JSON . stringify ; this . _unserialize_session = JSON . parse ; } else { this . _serialize_session = options . serialize || defaultSerializer ; this . _unserialize_session = options . unserialize || identity ; } var self = this ; var host = options . host || defaultOptions . host ; var port = options . port || defaultOptions . port ; if ( typeof options . db === 'object' ) { this . dbHelper = new DatabaseHelper ( options . db , self . db_collection_name ) ; } else { this . dbHelper = new DatabaseHelper ( { host : host , port : port , username : options . username , password : options . password } ) ; self . dbHelper . use ( options . db ) ; } self . dbHelper . ensureCollection ( self . db_collection_name , function ( err , db ) { if ( err ) { if ( readyCallback ) { readyCallback ( err ) ; } else { throw e ; } } else { db . index . createSkipListIndex ( self . db_collection_name , [ \"expires\" ] , false ) . then ( function ( res ) { if ( readyCallback ) { readyCallback ( ) ; } } , function ( err ) { debug ( \"Unable to create skip-list\" ) ; if ( readyCallback ) { readyCallback ( err ) ; } } ) . catch ( function ( e ) { throw e ; } ) ; } } ) ; this . db_clear_expires_time = 0 ; this . db_clear_expires_interval = options . clear_interval || defaultOptions . clear_interval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Promise that returns a flat list of all the Elm files the given Elm file depends on based on the modules it loads via import . [CODESPLIT] function findAllDependencies ( file , knownDependencies , sourceDirectories , knownFiles ) { if ( ! knownDependencies ) { knownDependencies = [ ] ; } if ( typeof knownFiles === \"undefined\" ) { knownFiles = [ ] ; } else if ( knownFiles . indexOf ( file ) > - 1 ) { return knownDependencies ; } if ( sourceDirectories ) { return findAllDependenciesHelp ( file , knownDependencies , sourceDirectories , knownFiles ) . then ( function ( thing ) { return thing . knownDependencies ; } ) ; } else { return getBaseDir ( file ) . then ( getElmPackageSourceDirectories ) . then ( function ( newSourceDirs ) { return findAllDependenciesHelp ( file , knownDependencies , newSourceDirs , knownFiles ) . then ( function ( thing ) { return thing . knownDependencies ; } ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a source directory ( containing top - level Elm modules ) locate the elm . json file that includes it and get all its source directories . [CODESPLIT] function getElmPackageSourceDirectories ( baseDir , currentDir ) { if ( typeof currentDir === \"undefined\" ) { baseDir = path . resolve ( baseDir ) ; currentDir = baseDir ; } var elmPackagePath = path . join ( currentDir , 'elm.json' ) ; if ( fs . existsSync ( elmPackagePath ) ) { var sourceDirectories = getSourceDirectories ( elmPackagePath ) ; if ( _ . includes ( sourceDirectories , baseDir ) ) { return sourceDirectories ; } } if ( isRoot ( currentDir ) ) { return [ ] ; } return getElmPackageSourceDirectories ( baseDir , path . dirname ( currentDir ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Read imports from a given file and return them [CODESPLIT] function readImports ( file ) { return new Promise ( function ( resolve , reject ) { // read 60 chars at a time. roughly optimal: memory vs performance var stream = fs . createReadStream ( file , { encoding : 'utf8' , highWaterMark : 8 * 60 } ) ; var buffer = \"\" ; var parser = new Parser ( ) ; stream . on ( 'error' , function ( ) { // failed to process the file, so return null resolve ( null ) ; } ) ; stream . on ( 'data' , function ( chunk ) { buffer += chunk ; // when the chunk has a newline, process each line if ( chunk . indexOf ( '\\n' ) > - 1 ) { var lines = buffer . split ( '\\n' ) ; lines . slice ( 0 , lines . length - 1 ) . forEach ( parser . parseLine . bind ( parser ) ) ; buffer = lines [ lines . length - 1 ] ; // end the stream early if we're past the imports // to save on memory if ( parser . isPastImports ( ) ) { stream . destroy ( ) ; } } } ) ; stream . on ( 'close' , function ( ) { resolve ( parser . getImports ( ) ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "useless now [CODESPLIT] function inlineStyle ( fileContent , filePath ) { return fileContent . replace ( / styleUrls\\s*:\\s*\\[(.+)\\] / g , ( _match , templateUrl ) => { let styleContent = '' const styleList = templateUrl . replace ( / '|\\s / g , '' ) . split ( ',' ) styleList . forEach ( s => { const stylePath = path . join ( path . dirname ( filePath ) , s ) styleContent += loadResourceFile ( stylePath ) } ) return ` \\[ \\` ${ styleContent } \\` \\] ` } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "publish () ; Publisher should input the new version number . This script would check if the input is valid . [CODESPLIT] function changeVersion ( ) { log . info ( 'Updating version number...' ) ; const packageJson = path . join ( __dirname , '../components/package.json' ) ; const currentVersion = fs . readFileSync ( packageJson , 'utf-8' ) . match ( / \"version\": \"([0-9.]+)\" / ) [ 1 ] ; let versionNumberValid = false ; let version ; function checkVersionNumber ( cur , next ) { // Must be numbers and dots. if ( ! / ^[0-9][0-9.]{1,10}[0-9](\\-\\w+)*$ / . test ( next ) ) { return false ; } const curArr = cur . split ( '.' ) ; const nextArr = next . split ( '.' ) ; const length = curArr . length ; if ( nextArr . length !== nextArr . length ) { return false ; } for ( let i = 0 ; i < length ; i ++ ) { if ( curArr [ i ] < nextArr [ i ] ) { return true ; } if ( curArr [ i ] > nextArr [ i ] ) { return false ; } if ( i === length - 1 && curArr [ i ] === nextArr [ i ] ) { return false ; } } } while ( ! versionNumberValid ) { version = read . question ( chalk . bgYellow . black ( 'Please input the new version:' ) + '  ' ) ; if ( checkVersionNumber ( currentVersion , version ) ) { versionNumberValid = true ; nextVersion = version ; } else { log . error ( ` ${ version } ${ currentVersion } ` ) ; } } fs . writeFileSync ( packageJson , fs . readFileSync ( packageJson , 'utf-8' ) . replace ( / \"version\": \"[0-9.]+\" / g , ` ${ version } ` ) ) ; log . success ( 'Version updated!' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Check if whether tagNames is given a node is an element or an element matching tagNames . [CODESPLIT] function isElement ( node , tagNames ) { var name if ( ! ( tagNames === null || tagNames === undefined || typeof tagNames === 'string' || ( typeof tagNames === 'object' && tagNames . length !== 0 ) ) ) { throw new Error ( 'Expected `string` or `Array.<string>` for `tagNames`, not `' + tagNames + '`' ) } if ( ! node || typeof node !== 'object' || node . type !== 'element' || typeof node . tagName !== 'string' ) { return false } if ( tagNames === null || tagNames === undefined ) { return true } name = node . tagName if ( typeof tagNames === 'string' ) { return name === tagNames } return tagNames . indexOf ( name ) !== - 1 }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses URL query string . [CODESPLIT] function parse ( query ) { if ( query [ 0 ] == \"?\" ) query = query . slice ( 1 ) ; var pairs = query . split ( \"&\" ) , obj = { } ; for ( var i in pairs ) { var pair = pairs [ i ] . split ( \"=\" ) , key = decodeURIComponent ( pair [ 0 ] ) , value = pair [ 1 ] ? decodeURIComponent ( pair [ 1 ] ) : \"\" ; obj [ key ] = value ; } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stringifies an object to a URL query string . [CODESPLIT] function stringify ( obj ) { var arr = [ ] ; for ( var x in obj ) { arr . push ( encodeURIComponent ( x ) + \"=\" + encodeURIComponent ( obj [ x ] ) ) ; } return arr . join ( \"&\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add ?lang = [ lang ] in the URL * [CODESPLIT] function replaceLink ( target ) { var lang = QueryString . parse ( location . search ) . lang ; if ( lang ) { target = target || $ ( \"body\" ) ; target . find ( \"a\" ) . each ( function ( ) { var href = $ ( this ) . attr ( \"href\" ) , query = QueryString . parse ( href ) ; if ( href . indexOf ( \"javascript:\" ) !== 0 && href . indexOf ( \"http\" ) !== 0 && href . indexOf ( \"#\" ) !== 0 && ! query . lang ) { href = QueryString . setUrl ( href , { lang : lang } ) ; $ ( this ) . attr ( \"href\" , href ) ; } } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the server is created but before it starts to listening to incoming requests . N . B . gmeAuth safeStorage and workerManager are not ready to use until the start function is called . ( However inside an incoming request they are all ensured to have been initialized . ) [CODESPLIT] function initialize ( middlewareOpts ) { const logger = middlewareOpts . logger . fork ( 'BindingsDocs' ) , ensureAuthenticated = middlewareOpts . ensureAuthenticated ; function servePythonDocFile ( rootDir , fileName , res , logger ) { const options = { root : rootDir , dotfiles : 'deny' , headers : { 'x-timestamp' : Date . now ( ) , 'x-sent' : true } } ; res . sendFile ( fileName , options , function ( err ) { if ( err ) { logger . error ( 'Failed to send ' + fileName , err ) ; res . status ( err . status ) . end ( ) ; } } ) ; } // Ensure authenticated can be used only after this rule. router . use ( '*' , function ( req , res , next ) { res . setHeader ( 'X-WebGME-Media-Type' , 'webgme.v1' ) ; next ( ) ; } ) ; // Use ensureAuthenticated if the routes require authentication. (Can be set explicitly for each route.) router . use ( '*' , ensureAuthenticated ) ; function getFullUrl ( req , name ) { return req . protocol + '://' + req . headers . host + middlewareOpts . getMountedPath ( req ) + req . baseUrl + name ; } router . get ( '/' , function ( req , res ) { res . json ( { python : getFullUrl ( req , '/python/index.html' ) } ) ; } ) ; router . get ( '/python/' , function ( req , res ) { servePythonDocFile ( PYTHON_DOCS_DIR , 'index.html' , res , logger ) ; } ) ; router . get ( '/python/*' , function ( req , res ) { servePythonDocFile ( PYTHON_DOCS_DIR , req . params [ 0 ] , res , logger ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Source : https : // github . com / garycourt / murmurhash - js / blob / master / murmurhash2_gc . js [CODESPLIT] function murmurhash ( str ) { let l = str . length | 0 , h = l | 0 , i = 0 , k ; while ( l >= 4 ) { k = ( ( str . charCodeAt ( i ) & 0xff ) ) | ( ( str . charCodeAt ( ++ i ) & 0xff ) << 8 ) | ( ( str . charCodeAt ( ++ i ) & 0xff ) << 16 ) | ( ( str . charCodeAt ( ++ i ) & 0xff ) << 24 ) ; k = ( ( ( k & 0xffff ) * 0x5bd1e995 ) + ( ( ( ( k >>> 16 ) * 0x5bd1e995 ) & 0xffff ) << 16 ) ) ; k ^= k >>> 24 ; k = ( ( ( k & 0xffff ) * 0x5bd1e995 ) + ( ( ( ( k >>> 16 ) * 0x5bd1e995 ) & 0xffff ) << 16 ) ) ; h = ( ( ( h & 0xffff ) * 0x5bd1e995 ) + ( ( ( ( h >>> 16 ) * 0x5bd1e995 ) & 0xffff ) << 16 ) ) ^ k ; l -= 4 ; ++ i ; } switch ( l ) { case 3 : h ^= ( str . charCodeAt ( i + 2 ) & 0xff ) << 16 ; case 2 : h ^= ( str . charCodeAt ( i + 1 ) & 0xff ) << 8 ; case 1 : h ^= ( str . charCodeAt ( i ) & 0xff ) ; h = ( ( ( h & 0xffff ) * 0x5bd1e995 ) + ( ( ( ( h >>> 16 ) * 0x5bd1e995 ) & 0xffff ) << 16 ) ) ; } h ^= h >>> 13 ; h = ( ( ( h & 0xffff ) * 0x5bd1e995 ) + ( ( ( ( h >>> 16 ) * 0x5bd1e995 ) & 0xffff ) << 16 ) ) ; h ^= h >>> 15 ; return h >>> 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_setObject ( obj k1 k2 ... value ) : Set object deeply key by key ensure each part is an object [CODESPLIT] function _setObject ( obj ) { var args = arguments , o = obj , len = args . length , // keys are args ix: 1 to n-2 keys = 3 <= len ? slice . call ( args , 1 , len = len - 1 ) : ( len = 1 , [ ] ) , // value is last arg value = args [ len ++ ] , ix , k for ( ix = 0 ; ix < keys . length ; ix ++ ) { k = keys [ ix ] // Initialize key to empty object if necessary if ( typeof o [ k ] !== 'object' ) o [ k ] = { } // Set final value if this is the last key if ( ix === keys . length - 1 ) o [ k ] = value else // Continue deeper o = o [ k ] } return obj }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "uniqueSort : [CODESPLIT] function uniqueSort ( arr , isSorted ) { if ( isSorted == null ) isSorted = false if ( ! isSorted ) arr . sort ( ) var out = [ ] , ix , item for ( ix = 0 ; ix < arr . length ; ix ++ ) { item = arr [ ix ] if ( ix > 0 && arr [ ix - 1 ] === arr [ ix ] ) continue out . push ( item ) } return out }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_d ( args ... ) : initialization helper that returns first arg that isn t null [CODESPLIT] function _d ( ) { for ( var ix = 0 ; ix < arguments . length ; ix ++ ) if ( arguments [ ix ] != null ) return arguments [ ix ] return null }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_e : error by throwing msg with optional fn name [CODESPLIT] function _e ( fn , msg ) { msg = _d ( msg , fn , '' ) fn = _d ( fn , 0 ) var pfx = \"oj: \" if ( fn ) pfx = \"oj.\" + fn + \": \" throw new Error ( pfx + msg ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_v : validate argument n with fn name and message [CODESPLIT] function _v ( fn , n , v , type ) { n = { 1 : 'first' , 2 : 'second' , 3 : 'third' , 4 : 'fourth' } [ n ] _a ( ! type || ( typeof v === type ) , fn , \"\" + type + \" expected for \" + n + \" argument\" ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_splitAndTrim : Split string by seperator and trim result [CODESPLIT] function _splitAndTrim ( str , seperator , limit ) { return str . split ( seperator , limit ) . map ( function ( v ) { return v . trim ( ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_getInstanceOnElement : Get a oj instance on a given element [CODESPLIT] function _getInstanceOnElement ( el ) { if ( ( el != null ? el . oj : 0 ) != null ) return el . oj else return null }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_flattenCSSMap : Take an OJ cssMap and flatten it into the form plugin - > [CODESPLIT] function _flattenCSSMap ( cssMap ) { var flatMap = { } , plugin , cssMap_ for ( plugin in cssMap ) { cssMap_ = cssMap [ plugin ] _flattenCSSMap_ ( cssMap_ , flatMap , [ '' ] , [ '' ] , plugin ) } return flatMap }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive helper with accumulators ( it outputs flatMapAcc ) [CODESPLIT] function _flattenCSSMap_ ( cssMap , flatMapAcc , selectorsAcc , mediasAcc , plugin ) { // Built in media helpers var acc , cur , inner , isMedia , mediaJoined , mediasNext , next , outer , parts , rules , selector , selectorJoined , selectorsNext , o , i , medias = { 'widescreen' : 'only screen and (min-width: 1200px)' , 'monitor' : '' , 'tablet' : 'only screen and (min-width: 768px) and (max-width: 959px)' , 'phone' : 'only screen and (max-width: 767px)' } for ( selector in cssMap ) { rules = cssMap [ selector ] // Base Case: Record our selector when `rules` is a value if ( typeof rules !== 'object' ) { // Join selectors and media accumulators with commas selectorJoined = selectorsAcc . sort ( ) . join ( ',' ) mediaJoined = mediasAcc . sort ( ) . join ( ',' ) // Prepend @media as that was removed previously when spliting into parts if ( mediaJoined !== '' ) mediaJoined = \"@media \" + mediaJoined // Record the rule deeply in `flatMapAcc` _setObject ( flatMapAcc , plugin , mediaJoined , selectorJoined , selector , rules ) // Recursive Case: Recurse on `rules` when it is an object } else { // (r1) Media Query found: Generate the next media queries if ( selector . indexOf ( '@media' ) === 0 ) { isMedia = true mediasNext = next = [ ] selectorsNext = selectorsAcc selector = ( selector . slice ( '@media' . length ) ) . trim ( ) acc = mediasAcc // (r2) Selector found: Generate the next selectors } else { isMedia = false selectorsNext = next = [ ] mediasNext = mediasAcc acc = selectorsAcc } // Media queries and Selectors can be comma seperated parts = _splitAndTrim ( selector , ',' ) // Media queries have convience substitutions like 'phone', 'tablet' if ( isMedia ) { parts = parts . map ( function ( v ) { return _d ( medias [ v ] , v ) } ) } // Determine the next selectors or media queries for ( o = 0 ; o < acc . length ; o ++ ) { outer = acc [ o ] for ( i = 0 ; i < parts . length ; i ++ ) { inner = parts [ i ] // When `&` is not present just insert in front with the correct join operator cur = inner if ( ( inner . indexOf ( '&' ) ) === - 1 && outer !== '' ) cur = ( isMedia ? '& and ' : '& ' ) + cur next . push ( cur . replace ( / & / g , outer ) ) } } // Recurse through objects after calculating the next selectors _flattenCSSMap_ ( rules , flatMapAcc , selectorsNext , mediasNext , plugin ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_cssFromPluginObject : Convert flattened css selectors and rules to a string pluginMaps are of the form : pluginName = > mediaQuery = > selector = > rulesObject minify : false will output newlines tags : true will output the css in <style > tags [CODESPLIT] function _cssFromPluginObject ( flatCSSMap , options ) { options = _d ( options , { } ) var mediaMap , plugin , minify = options . minify != null ? options . minify : 0 , tags = options . tags != null ? options . tags : 0 , // Deterine what output characters are needed newline = minify ? '' : '\\n' , space = minify ? '' : ' ' , inline = minify , css = '' for ( plugin in flatCSSMap ) { mediaMap = flatCSSMap [ plugin ] if ( tags ) css += \"<style class=\\\"\" + plugin + \"-style\\\">\" + newline // Serialize CSS with potential minification css += _cssFromMediaObject ( mediaMap , options ) if ( tags ) css += \"\" + newline + \"</style>\" + newline } return css }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_compileAny Recursive helper for compiling ojml or any type [CODESPLIT] function _compileAny ( any , options ) { // Array if ( oj . isArray ( any ) ) _compileTag ( any , options ) // String else if ( oj . isString ( any ) ) { if ( options . html != null ) options . html . push ( any ) if ( any . length > 0 && any [ 0 ] === '<' ) { var root = document . createElement ( 'div' ) root . innerHTML = any if ( options . dom != null ) options . dom . appendChild ( root ) } else { if ( options . dom != null ) options . dom . appendChild ( document . createTextNode ( any ) ) } // Boolean or Number } else if ( oj . isBoolean ( any ) || oj . isNumber ( any ) ) { if ( options . html != null ) options . html . push ( \"\" + any ) if ( options . dom != null ) options . dom . appendChild ( document . createTextNode ( \"\" + any ) ) // Function } else if ( oj . isFunction ( any ) ) { // Wrap function call to allow full oj generation within any _compileAny ( oj ( any ) , options ) // Date } else if ( oj . isDate ( any ) ) { if ( options . html != null ) options . html . push ( \"\" + ( any . toLocaleString ( ) ) ) if ( options . dom != null ) options . dom . appendChild ( document . createTextNode ( \"\" + ( any . toLocaleString ( ) ) ) ) // OJ Type or Instance } else if ( oj . isOJ ( any ) ) { if ( options . types != null ) options . types . push ( any ) if ( options . html != null ) options . html . push ( any . toHTML ( options ) ) if ( options . dom != null ) options . dom . appendChild ( any . toDOM ( options ) ) if ( options . css != null ) _extend ( options . css , any . toCSSMap ( options ) ) } // Do nothing for: null, undefined, object }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_compileTag : Recursive helper for compiling ojml tags [CODESPLIT] function _compileTag ( ojml , options ) { // Empty list compiles to undefined if ( ojml . length === 0 ) return // The first part of ojml is the tag var tag = ojml [ 0 ] , tagType = typeof tag , u = oj . unionArguments ( ojml . slice ( 1 ) ) , attributes = u . options , children = u . args , styles , selector // Allow the tag parameter to be 'table' (string) or oj.table (function) or oj.Table (object) if ( ( tagType === 'function' || tagType === 'object' ) ) tag = _d ( _getTagName ( tag ) , tag ) // Fail if no tag found if ( ! ( oj . isString ( tag ) && tag . length > 0 ) ) _e ( 'compile' , 'tag name is missing' ) // Record tag as encountered options . tags [ tag ] = true // Instance oj object if tag is capitalized if ( _isCapitalLetter ( tag [ 0 ] ) ) return _compileDeeper ( _compileAny , new oj [ tag ] ( ojml . slice ( 1 ) ) , options ) // Compile to css if requested if ( options . css && tag === 'css' ) { // Extend options.css with rules for ( selector in attributes ) { styles = attributes [ selector ] options . css [ 'oj' ] = _d ( options . css [ 'oj' ] , { } ) options . css [ 'oj' ] [ selector ] = _d ( options . css [ 'oj' ] [ selector ] , { } ) _extend ( options . css [ 'oj' ] [ selector ] , styles ) } } // Compile DOCTYPE as special case because it is not really an element // It has attributes with spaces and cannot be created by dom manipulation // In this way it is HTML generation only. if ( tag === '!DOCTYPE' ) { _v ( 'compile' , 1 , ojml [ 1 ] , 'string' ) if ( ! options . ignore [ tag ] ) { if ( options . html ) options . html . push ( \"<\" + tag + \" \" + ojml [ 1 ] + \">\" ) // options.dom is purposely ignored } return } if ( ! options . ignore [ tag ] ) { var events = _attributesProcessedForOJ ( attributes ) , el // Compile to dom if requested // Add dom element with attributes if ( options . dom && ( typeof document !== _udf && document !== null ) ) { // Create element el = document . createElement ( tag ) // Add self to parent if ( oj . isDOMElement ( options . dom ) ) options . dom . appendChild ( el ) // Push ourselves on the dom stack (to handle children) options . dom = el // Set attributes in sorted order for consistency if ( oj . isPlainObject ( attributes ) ) { var keys = _keys ( attributes ) . sort ( ) , ix , attrName , attrValue for ( ix = 0 ; ix < keys . length ; ix ++ ) { attrName = keys [ ix ] attrValue = attributes [ attrName ] // Boolean attributes have no value if ( attrValue === true ) el . setAttributeNode ( document . createAttribute ( attrName ) ) else el . setAttribute ( attrName , attrValue ) } } // Bind events _attributesBindEventsToDOM ( events , el , options . inserts ) } // Compile to html if requested // Add tag with attributes if ( options . html ) { var attr = _d ( _attributesFromObject ( attributes ) , '' ) , space = attr === '' ? '' : ' ' options . html . push ( \"<\" + tag + space + attr + \">\" ) // Recurse through children if this tag isn't ignored deeply } } if ( options . ignore [ tag ] !== 'deep' ) { for ( ix = 0 ; ix < children . length ; ix ++ ) { var child = children [ ix ] // Skip indention if there is only one child if ( options . html != null && ! options . minify && children . length > 1 ) options . html . push ( \"\\n\\t\" + options . indent ) _compileDeeper ( _compileAny , child , options ) } } // Skip indention if there is only one child if ( options . html != null && ! options . minify && children . length > 1 ) options . html . push ( \"\\n\" + options . indent ) // End html tag if you have children or your tag closes if ( ! options . ignore [ tag ] ) { // Close tag if html if ( options . html != null && ( children . length > 0 || oj . tag . isClosed ( tag ) ) ) options . html . push ( \"</\" + tag + \">\" ) // Pop ourselves if dom if ( options . dom ) options . dom = options . dom . parentNode } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_attributesProcessedForOJ : Process attributes to make them easier to use [CODESPLIT] function _attributesProcessedForOJ ( attr ) { var jqEvents = { bind : 1 , on : 1 , off : 1 , live : 1 , blur : 1 , change : 1 , click : 1 , dblclick : 1 , focus : 1 , focusin : 1 , focusout : 1 , hover : 1 , keydown : 1 , keypress : 1 , keyup : 1 , mousedown : 1 , mouseenter : 1 , mouseleave : 1 , mousemove : 1 , mouseout : 1 , mouseup : 1 , ready : 1 , resize : 1 , scroll : 1 , select : 1 , insert : 1 } , events , k , v // Allow attributes to alias c to class and use arrays instead of space seperated strings // Convert to c and class from arrays to strings if ( oj . isArray ( attr != null ? attr . c : void 0 ) ) attr . c = attr . c . join ( ' ' ) if ( oj . isArray ( attr != null ? attr [ \"class\" ] : void 0 ) ) attr [ \"class\" ] = attr [ \"class\" ] . join ( ' ' ) // Move c to class if ( ( attr != null ? attr . c : void 0 ) != null ) { if ( ( attr != null ? attr [ \"class\" ] : void 0 ) != null ) attr [ \"class\" ] += ' ' + attr . c else attr [ \"class\" ] = attr . c delete attr . c } // Allow attributes to take style as an object if ( oj . isPlainObject ( attr != null ? attr . style : void 0 ) ) { attr . style = _styleFromObject ( attr . style , { inline : true } ) } // Omit attributes with values of false, null, or undefined if ( oj . isPlainObject ( attr ) ) { for ( k in attr ) { v = attr [ k ] if ( v === null || v === void 0 || v === false ) delete attr [ k ] } } // Filter out jquery events events = { } if ( oj . isPlainObject ( attr ) ) { // Filter out attributes that are jquery events for ( k in attr ) { v = attr [ k ] // If this attribute (k) is an event if ( jqEvents [ k ] != null ) { events [ k ] = v delete attr [ k ] } } } // Returns bindable events return events }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind events to dom [CODESPLIT] function _attributesBindEventsToDOM ( events , el , inserts ) { var ek , ev , _results = [ ] for ( ek in events ) { ev = events [ ek ] _a ( oj . $ != null , \"jquery is missing when binding a '\" + ek + \"' event\" ) // accumulate insert events manually since DOMNodeInserted is slow and depreciated if ( ek == 'insert' && inserts ) inserts . push ( function ( ) { ev . call ( el , el ) } ) else if ( oj . isArray ( ev ) ) _results . push ( oj . $ ( el ) [ ek ] . apply ( this , ev ) ) else _results . push ( oj . $ ( el ) [ ek ] ( ev ) ) } return _results }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set : Set property by key or set all properties with object [CODESPLIT] function ( k , v ) { var key , obj = k , value // Optionally take key, value instead of object if ( ! oj . isPlainObject ( k ) ) { obj = { } obj [ k ] = v } // Set all keys that are valid properties for ( key in obj ) { value = obj [ key ] if ( this . has ( key ) ) { this [ key ] = value } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "toJSON : Use properties to generate json [CODESPLIT] function ( ) { var json = { } , prop , ix = 0 for ( ; ix < this . properties . length ; ix ++ ) { prop = this . properties [ ix ] json [ prop ] = this [ prop ] } return json }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Views are special objects map properties together . This is a union of arguments With the remaining arguments becoming a list [CODESPLIT] function ( ) { _a ( oj . isDOM ( this . el ) , this . typeName , 'constructor did not set this.el' ) // Set instance on @el _setInstanceOnElement ( this . el , this ) var u = oj . unionArguments ( arguments ) , options = u . options , args = u . args // Emit as a tag if it isn't quiet or used new keyword if ( this . __autonew__ && ! options . __quiet__ ) this . emit ( ) // Remove quiet flag as it has served its purpose if ( options . __quiet__ != null ) delete options . __quiet__ // Add class oj-typeName this . $el . addClass ( \"oj-\" + this . typeName ) // Views automatically set all options to their properties // arguments directly to properties this . set ( options ) // Remove options that were set options = _clone ( options ) this . properties . forEach ( function ( v ) { return delete options [ v ] } ) // Views pass through remaining options to be attributes on the root element // This can include jquery events and interpreted arguments this . addAttributes ( options ) // Record if view is fully constructed return this . _isConstructed = true }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "make : Remake view from model data using each [CODESPLIT] function ( ) { // Do nothing until fully constructed if ( ! this . isConstructed ) return // Some properties call make before construction completes var _t = this , ix , model , models , views , out // Convert models to views using each if ( ( this . models != null ) && ( this . each != null ) ) { // Get list of models from collection or array models = oj . isEvented ( this . models ) ? this . models . models : this . models // Add view item for every model views = models . map ( function ( model ) { return _t . _itemFromModel ( model ) } ) // Items are already views so just use them } else if ( this . items != null ) { views = this . items } // Render the views this . $el . oj ( function ( ) { return views . map ( function ( view ) { _t . _itemElFromItem ( view ) } ) } ) // Indicate to CollectionView the items changed this . itemsChanged ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_bound : Bound index to allow negatives throw when out of range [CODESPLIT] function ( ix , count , message ) { var ixNew = ix < 0 ? ix + count : ix if ( ! ( 0 <= ixNew && ixNew < count ) ) _e ( this . typeName , message + \" is out of bounds (\" + ix + \" in [0,\" + ( count - 1 ) + \"])\" ) return ixNew }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "make : Remake everything ( override ) [CODESPLIT] function ( ) { if ( ! this . isConstructed ) return // Some properties call make before construction completes var _t = this , models , rowViews = [ ] // Convert models to views if model/each exists if ( ( this . models != null ) && ( this . each != null ) ) { models = oj . isEvented ( this . models ) ? this . models . models : this . _models rowViews = models . map ( function ( model ) { return _t . _rowFromModel ( model ) } ) // Convert rows to views } else if ( this . rows != null ) { rowViews = this . rows . map ( function ( row ) { return oj ( function ( ) { row . forEach ( function ( cell ) { oj . td ( cell ) } ) } ) } ) } // Render rows into tbody if ( rowViews . length > 0 ) this . $tbodyMake . oj ( function ( ) { rowViews . forEach ( function ( r ) { oj . tr ( r ) } ) } ) this . bodyChanged ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "row : Get values at a given row [CODESPLIT] function ( rx , listOJML ) { rx = this . _bound ( rx , this . rowCount , \".row: rx\" ) if ( listOJML != null ) { _a ( listOJML . length === cellCount ( rx ) , this . typeName , \"array expected for second argument with length (\" + rx + \")\" ) // Set tds listOJML . forEach ( function ( ojml , cx ) { this . $td ( rx , cx ) . oj ( ojml ) } ) } else { return this . $tdsRow ( rx ) . ojValues ( ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "addRow : Add row to index rx [CODESPLIT] function ( rx , listOJML ) { if ( listOJML == null ) { listOJML = rx rx = - 1 } rx = this . _bound ( rx , this . rowCount + 1 , \".addRow: rx\" ) _a ( oj . isArray ( listOJML ) , 'addRow' , 'expected array for row content' ) this . _addRowTR ( rx , function ( ) { oj . tr ( function ( ) { listOJML . forEach ( function ( cell ) { oj . td ( cell ) } ) } ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_addRowTR : Helper to add row directly with <tr > [CODESPLIT] function ( rx , tr ) { // Empty if ( this . rowCount === 0 ) this . $el . oj ( tr ) // Last else if ( rx === this . rowCount ) this . $tr ( rx - 1 ) . ojAfter ( tr ) // Not last else this . $tr ( rx ) . ojBefore ( tr ) this . bodyChanged ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_bound : Bound index to allow negatives throw when out of range [CODESPLIT] function ( ix , count , message ) { var ixNew = ix < 0 ? ix + count : ix if ( ! ( 0 <= ixNew && ixNew < count ) ) { throw new Error ( \"oj.\" + this . typeName + message + \" is out of bounds (\" + ix + \" in [0,\" + ( count - 1 ) + \"])\" ) } return ixNew }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set compiles and inserts in innerHTML [CODESPLIT] function ( $el , args ) { // No arguments return the first instance if ( args . length === 0 ) return $el [ 0 ] . oj // Compile ojml var r = oj . compile . apply ( oj , [ { dom : 1 , html : 0 , cssMap : 1 } ] . concat ( slice . call ( args ) ) ) _insertStyles ( r . cssMap , { global : 0 } ) // Reset content and append to dom $el . html ( '' ) // Ensure r.dom is an array if ( ! oj . isArray ( r . dom ) ) r . dom = [ r . dom ] // Append resulting dom elements for ( var ix = 0 ; ix < r . dom . length ; ix ++ ) $el . append ( r . dom [ ix ] ) // Trigger inserted events _triggerInserted ( r . types , r . inserts ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "addAttributes : Add attributes and apply the oj magic with jquery binding [CODESPLIT] function ( attributes ) { var attr = _clone ( attributes ) , events = _attributesProcessedForOJ ( attr ) , k , v // Add attributes as object if ( oj . isPlainObject ( attr ) ) { for ( k in attr ) { v = attr [ k ] if ( k === 'class' ) this . addClass ( v ) else if ( v === true ) // Boolean attributes have no value this . el . setAttributeNode ( doc . createAttribute ( k ) ) else // Otherwise add it normally this . $el . attr ( k , v ) } } // Bind events if ( events != null ) _attributesBindEventsToDOM ( events , this . el ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "item : get or set item value at item ix [CODESPLIT] function ( ix , ojml ) { ix = this . _bound ( ix , this . count , \".item: index\" ) if ( ojml != null ) { if ( typeof ojml == 'object' && ojml . isListItem ) this . $item ( ix ) . ojReplaceWith ( ojml ) else this . $item ( ix ) . oj ( ojml ) this . itemsChanged ( ) } else return this . $item ( ix ) . ojValue ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper Methods _itemFromModel : Helper to map model to item [CODESPLIT] function ( model ) { var _t = this if ( oj . isOJType ( _t . each ) ) return new _t . each ( model ) return oj ( function ( ) { return _t . each ( model ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manipulation Methods [CODESPLIT] function ( ix , ojml ) { // ix defaults to -1 and is optional if ( ojml == null ) { ojml = ix ix = - 1 } ix = this . _bound ( ix , this . count + 1 , \".add: index\" ) var _t = this , tag = this . itemTagName // Empty if ( this . count === 0 ) this . $el . oj ( function ( ) { _t . _itemElFromItem ( ojml ) } ) // Last else if ( ix === this . count ) this . $item ( ix - 1 ) . ojAfter ( function ( ) { return _t . _itemElFromItem ( ojml ) } ) // Not last else this . $item ( ix ) . ojBefore ( function ( ) { return _t . _itemElFromItem ( ojml ) } ) this . itemsChanged ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method that abstracts getting oj values [CODESPLIT] function _jqGetValue ( $el , args ) { var el = $el [ 0 ] , child = el . firstChild // Return the instance if the element has an oj instance if ( oj . isOJInstance ( _getInstanceOnElement ( el ) ) ) return _getInstanceOnElement ( el ) // Parse the text to turn it into bool, number, or string else if ( oj . isDOMText ( child ) ) return oj . parse ( child . nodeValue ) // Return the first child otherwise as an oj instance or child element else if ( oj . isDOMElement ( child ) ) return _d ( _getInstanceOnElement ( child ) , child ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_styleFromObject : Convert object to style string [CODESPLIT] function _styleFromObject ( obj , options ) { options = _extend ( { inline : true , indent : '' } , options ) // Trailing semi should only exist on when we aren't indenting options . semi = ! options . inline ; var out = \"\" , // Sort keys to create consistent output keys = _keys ( obj ) . sort ( ) , // Support indention and inlining indent = options . indent != null ? options . indent : '' , newline = options . inline ? '' : '\\n' , ix , k , kFancy , semi for ( ix = 0 ; ix < keys . length ; ix ++ ) { kFancy = keys [ ix ] // Add semi if it is not inline or it is not the last key semi = options . semi || ix !== keys . length - 1 ? \";\" : '' // Allow keys to be camal case k = _dasherize ( kFancy ) // Collect css result for this key out += \"\" + indent + k + \":\" + obj [ kFancy ] + semi + newline } return out }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_attributesFromObject : Convert object to attribute string with no special conversions [CODESPLIT] function _attributesFromObject ( obj ) { if ( ! oj . isPlainObject ( obj ) ) return obj // Pass through non objects var k , v , ix , out = '' , space = '' , // Serialize attributes in order for consistent output attrs = _keys ( obj ) . sort ( ) for ( ix = 0 ; ix < attrs . length ; ix ++ ) { k = attrs [ ix ] v = obj [ k ] // Boolean attributes have no value if ( v === true ) out += \"\" + space + k // Other attributes have a value else out += \"\" + space + k + \"=\\\"\" + v + \"\\\"\" space = ' ' } return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_cssFromMediaObject : Convert css from a flattened mediaMap rule object . The rule object is of the form : mediaQuery = > selector = > rulesObject [CODESPLIT] function _cssFromMediaObject ( mediaMap , options ) { options = _d ( options , { } ) var indent , indentRule , media , rules , selector , selectorMap , space , styles , minify = options . minify != null ? options . minify : 0 , tags = options . tags != null ? options . tags : 0 , // Deterine what output characters are needed newline = minify ? '' : '\\n' , space = minify ? '' : ' ' , inline = minify , css = '' // Build css for media => selector =>  rules for ( media in mediaMap ) { selectorMap = mediaMap [ media ] ; // Serialize media query if ( media ) { media = media . replace ( / , / g , \",\" + space ) ; css += \"\" + media + space + \"{\" + newline ; } for ( selector in selectorMap ) { styles = selectorMap [ selector ] indent = ( ! minify ) && media ? '\\t' : '' // Serialize selector selector = selector . replace ( / , / g , \",\" + newline ) css += \"\" + indent + selector + space + \"{\" + newline // Serialize style rules indentRule = ! minify ? indent + '\\t' : indent rules = _styleFromObject ( styles , { inline : inline , indent : indentRule } ) ; css += rules + indent + '}' + newline } // End media query if ( media !== '' ) css += '}' + newline } try { css = oj . _minifyCSS ( css , options ) } catch ( e ) { throw new Error ( \"css minification error: \" + e . message + \"\\nCould not minify:\\n\" + css ) } return css }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_inherit : Inherit Child from Parent Based on but sadly incompatable with coffeescript inheritance [CODESPLIT] function _inherit ( Child , Parent ) { var Ctor , prop // Copy class properties and methods for ( prop in Parent ) oj . copyProperty ( Child , Parent , prop ) Ctor = function ( ) { } ; Ctor . prototype = Parent . prototype ; Child . prototype = new Ctor ( ) // Provide easy access for base class methods // Example: Parent.base.methodName(arguments...) Child . base = Child . __super__ = Parent . prototype }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get : Get property by key or get all properties [CODESPLIT] function ( k ) { // get specific property if ( oj . isString ( k ) ) { if ( this . has ( k ) ) return this [ k ] // get all properties } else { var out = { } , ix , p for ( ix = 0 ; ix < this . properties . length ; ix ++ ) { p = this . properties [ ix ] ; out [ p ] = this [ p ] ; } return out } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "removeRow : Remove row at index rx ( defaults to end ) [CODESPLIT] function ( rx ) { if ( rx == null ) rx = - 1 rx = this . _bound ( rx , this . rowCount , \".removeRow: index\" ) ; var out = this . row ( rx ) this . $tr ( rx ) . remove ( ) this . bodyChanged ( ) return out }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * expects a fileBuffer and the JSON describe payload for the m modules array [CODESPLIT] function ( describe , fileBuffer ) { if ( describe && ! util . isArray ( describe ) && describe . m ) { // those goofs, they sent the whole thing, instead of just the // modules section. describe = describe . m ; } if ( ! Buffer . isBuffer ( fileBuffer ) ) { return when . reject ( 'fileBuffer was invalid' ) ; } var parser = new HalModuleParser ( ) ; var fileInfo = { filename : 'user-file' , fileBuffer : fileBuffer } ; var that = this ; return pipeline ( [ function ( ) { return parser . parseBuffer ( fileInfo ) ; } , function ( ) { return that . resolveDependencies ( describe , fileInfo ) ; } ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function ( describe , fileInfo ) { if ( ! describe || ! util . isArray ( describe ) ) { return when . reject ( 'wrong describe payload given' ) ; } if ( ! fileInfo ) { return when . reject ( 'no fileInfo provided' ) ; } console . log ( 'resolving dependencies for ' , fileInfo . filename ) ; var that = this ; return pipeline ( [ function ( ) { // find out what we need for the binary described by fileInfo return that . solve ( describe , fileInfo . prefixInfo ) ; } , function ( modules ) { if ( ! modules || ( modules . length <= 0 ) ) { return when . resolve ( [ ] ) ; //no updates needed } // go get the module that we need if we have it. return that . retrieveModules ( modules ) ; } , function ( updates ) { if ( ! updates || ( updates . length <= 0 ) ) { return when . resolve ( [ ] ) ; //'no updates available' } // go figure out if the updates we found var promises = [ ] ; for ( var i = 0 ; i < updates . length ; i ++ ) { var promise = that . resolveDependencies ( describe , updates [ i ] ) ; promises . push ( promise ) ; } return when . all ( promises ) . then ( function ( arr ) { for ( var j = 0 ; j < arr . length ; j ++ ) { var resvArr = arr [ j ] ; if ( resvArr && ( resvArr . length > 0 ) ) { //NOTE: the photon isn't accepting updates in this order // part1, part2, user // insert these new dependencies at the start of the array updates = resvArr . concat ( updates ) ; // so lets flip that to // part2, part1, user //updates = updates.concat(resvArr); } } return when . resolve ( updates ) ; } , function ( err ) { return when . resolve ( updates ) ; } ) ; } ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * so lets take our typical path : [CODESPLIT] function ( filename ) { if ( ! fs . existsSync ( filename ) ) { return false ; } if ( ! this . _moduleStorage ) { this . _moduleStorage = [ ] ; } var that = this ; var parser = new HalModuleParser ( ) ; return parser . parseFile ( filename ) . then ( function ( fileInfo ) { fileInfo . describe = that . _binaryToDescribe ( fileInfo . prefixInfo ) ; that . _moduleStorage . push ( fileInfo ) ; } , function ( err ) { console . error ( 'assimilateModule err: ' , err ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * expects the array of module descriptions back from the solve routine and returns amodule description result complete with fileBuffer [CODESPLIT] function ( modules ) { // expects that we've been given storage of all our available // modules, and their binary info. if ( ! this . _moduleStorage ) { return null ; } if ( ! modules || ( modules . length <= 0 ) ) { return null ; } var results = [ ] ; // expecting something like... // { f: \"s\", n: \"2\", v: 2 } //iterate over our requirements for ( var i = 0 ; i < modules . length ; i ++ ) { var m = modules [ i ] ; //iterate over what's available for ( var a = 0 ; a < this . _moduleStorage . length ; a ++ ) { var module = this . _moduleStorage [ a ] ; var avail = module . describe ; //grab the converted bits var isMatch = ( ( avail . n === m . n ) && ( avail . f === m . f ) && ( avail . v >= m . v ) ) ; //console.log('comparing ', m, avail); if ( isMatch ) { results . push ( module ) ; break ; } } } return when . resolve ( results ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * given what modules are described as being on a photon and target binary info figure out which modules need to be updated on that photon . [CODESPLIT] function ( deviceModules , binaryInfo ) { var safeDeviceModules = this . _repairDescribeErrors ( deviceModules ) ; var safeBinaryRequires = this . _binaryDepsToDescribe ( binaryInfo ) ; var safeBinaryRequires2 = this . _binaryDepsToDescribe ( binaryInfo , 2 ) ; var result = this . _walkChain ( safeDeviceModules , safeBinaryRequires ) ; this . _walkChain ( safeDeviceModules , safeBinaryRequires2 , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * given what modules are described as being on a device and known firmware module info figure out which modules need to be updated on the device . [CODESPLIT] function ( deviceModules , firmwareModule ) { var safeDeviceModules = this . _repairDescribeErrors ( deviceModules ) ; var safeModuleRequires = firmwareModule . toDescribe ( ) ; return this . _walkChain ( safeDeviceModules , safeModuleRequires ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * given device s describe message figure out if it has missing modules . Rejected value contains missing dependencies [CODESPLIT] function ( describe ) { if ( ! Array . isArray ( describe . m ) ) { return when . reject ( 'no modules in describe message' ) ; } var modules = [ ] ; var userModule = null ; for ( var i = 0 ; i < describe . m . length ; i ++ ) { var module = new FirmwareModule ( describe . m [ i ] ) ; //modules.push(module); if ( module . isUserModule ( ) && module . isMainLocation ( ) ) { userModule = describe . m [ i ] ; } } if ( ! userModule ) { return when . resolve ( \"no user module\" ) ; } //return this._getModuleFirstDependecy(modules, userModule); for ( var i = 0 ; i < userModule . d . length ; i ++ ) { var dep = userModule . d [ i ] ; var deps = this . _walkChain ( describe . m , dep ) ; if ( deps && ( deps . length > 0 ) ) { // this function only originally returned one dependency. return when . reject ( [ new FirmwareModule ( deps [ 0 ] ) ] ) ; } } //\t\tif (deps && (deps.length > 0)) { //\t\t\treturn when.reject(new FirmwareModule(deps[0])); //\t\t} //\t\telse { return when . resolve ( \"nothing missing\" ) ; //\t\t} }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tell us if anything with dependencies is missing something [CODESPLIT] function ( describe ) { if ( ! Array . isArray ( describe . m ) ) { return when . reject ( 'no modules in describe message' ) ; } var allDeps = [ ] ; var modules = describe . m ; for ( var i = 0 ; i < modules . length ; i ++ ) { var checkModule = modules [ i ] ; // don't look for dependencies of things that don't have dependencies. // they'll never cause safe mode as a result of their requirements, // and they're probably referenced by other things for ( var d = 0 ; d < checkModule . d . length ; d ++ ) { var moduleNeeds = checkModule . d [ d ] ; // what things do we need that we don't have? var deps = this . _walkChain ( modules , moduleNeeds ) ; if ( deps && ( deps . length > 0 ) ) { allDeps = allDeps . concat ( deps ) ; } } } var keyFn = function ( dep ) { // todo - location should also be taken into account return [ dep . f , dep . n , dep . v ] . join ( '_' ) ; } ; return utilities . dedupArray ( allDeps , keyFn ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * walk over the described modules until we ve resolved our dependency chain for all the dependent things that need updating . [CODESPLIT] function ( modules , needs , arr ) { arr = arr || [ ] ; // todo - this assumes the entire set of dependencies exists on the device (i.e. a module with the same n/f values) // but this is not the case, e.g. when upgrading from a 2 module system to 3 module system. for ( var i = 0 ; i < modules . length ; i ++ ) { var m = modules [ i ] ; if ( m . n !== needs . n ) { continue ; } if ( m . f !== needs . f ) { continue ; } //found one! if ( m . v < needs . v ) { // // it's... //\t  .---.       .-''-.     .-'''-.    .-'''-.     ,---------. .---.  .---.    ____    ,---.   .--. //\t  | ,_|     .'_ _   \\   / _     \\  / _     \\    \\          \\|   |  |_ _|  .'  __ `. |    \\  |  | //\t,-./  )    / ( ` )   ' (`' )/`--' (`' )/`--'     `--.  ,---'|   |  ( ' ) /   '  \\  \\|  ,  \\ |  | //\t\\  '_ '`) . (_ o _)  |(_ o _).   (_ o _).           |   \\   |   '-(_{;}_)|___|  /  ||  |\\_ \\|  | //\t > (_)  ) |  (_,_)___| (_,_). '.  (_,_). '.         :_ _:   |      (_,_)    _.-`   ||  _( )_\\  | //\t(  .  .-' '  \\   .---..---.  \\  :.---.  \\  :        (_I_)   | _ _--.   | .'   _    || (_ o _)  | //\t `-'`-'|___\\  `-'    /\\    `-'  |\\    `-'  |       (_(=)_)  |( ' ) |   | |  _( )_  ||  (_,_)\\  | //\t  |        \\\\       /  \\       /  \\       /         (_I_)   (_{;}_)|   | \\ (_ o _) /|  |    |  | //\t  `--------` `'-..-'    `-...-'    `-...-'          '---'   '(_,_) '---'  '.(_,_).' '--'    '--' // //arr.push(m); // instead of returning the module we found, lets return the module with the version we need, // and any dependencies it requires, I think that's more clear. var missing = extend ( m , { v : needs . v } ) ; arr . push ( missing ) ; // todo mdm - this is wrong. we shouldn't be fabricating dependencies for a new version of a module // (need) from the installed version (m) - dependencies can and do change between versions. // The database of known modules should be the definitive source of module dependencies. // if we're updating this, we better check its dependencies too. if ( m . d && ( m . d . length > 0 ) ) { //oh no!  this module has dependencies! // do we have to update those too? // (this doesn't fully make sense to me right now, but lets go with it.) // todo mdm - this won't do anything, since `m` is always a satisfied dependency // (it came from the modules array.) // at the very least we should be iterating over m.d[] as the needed modules arr = this . _walkChain ( modules , m , arr ) ; } } } return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * for modules in location : main not for user modules function : user [CODESPLIT] function ( describeInfo ) { var arr = describeInfo ; // we're assuming the modules are in the reported order, // which should be dependency order. // essentially we're looking to add this to the correct module: //\tf: 's', n: '1', v: 1, for ( var i = 0 ; i < arr . length ; i ++ ) { var item = arr [ i ] ; if ( item . l !== 'm' ) { //not stored in main continue ; } else if ( item . f === 'u' ) { //I'm a user module, bail break ; } // are we the first thing and we don't have a name? if ( ( i === 0 ) && ( ! item . n ) ) { item . n = i + '' ; } //skip the first one. if ( i === 0 ) { continue ; } // i is at least 1 var lastItem = arr [ i - 1 ] ; //var nextOne = ((i+1) < arr.length) ? arr[i+1] : null; if ( lastItem . n && ! item . n ) { //last one had a name, and I don't have a name. item . n = ( parseInt ( lastItem . n ) + 1 ) + '' ; if ( ! item . f ) { // was missing a function designation item . f = 's' ; } if ( ! item . v ) { // was missing a version number item . v = 0 ; } } } return describeInfo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * the binary prefix contains a numeric value for its dependent module function convert that number into the same characters reported by the photon ( s u b etc ) [CODESPLIT] function ( moduleFunction ) { var result ; //var moduleFunctions = [ 'system' | 'user' | 'boot' | 'res' | 'mono' ]; switch ( moduleFunction ) { case 0 : result = null ; // undefined / none? break ; case 1 : result = '1_unknown' ; break ; case 2 : result = 'b' ; // bootloader? break ; case 3 : result = '3_unknown' ; //monolithic? break ; case 4 : result = 's' ; // system? break ; case 5 : result = 'u' ; // user? break ; default : result = 'undefined' ; break ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * convert the dependency keys from the binary prefix info into the common JSON format used by the describe messages . [CODESPLIT] function ( binaryInfo , dep ) { var result = { } ; dep = dep || 1 ; var depString = '' ; if ( dep > 1 ) { depString = '' + dep ; } if ( ! binaryInfo ) { return result ; } var keys = Object . keys ( binaryInfo ) ; // iterate over the prefix info, looking for the keys we need. for ( var i = 0 ; i < keys . length ; i ++ ) { var key = keys [ i ] ; var value = binaryInfo [ key ] ; switch ( key ) { case 'dep' + depString + 'ModuleFunction' : result . f = this . _modFuncToChar ( value ) ; break ; case 'dep' + depString + 'ModuleIndex' : result . n = value + '' ; break ; case 'dep' + depString + 'ModuleVersion' : result . v = value ; break ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * TODO : replace with buffer . compare once we move to node 0 . 12 [CODESPLIT] function ( left , right ) { if ( ( left === null ) && ( right === null ) ) { return true ; } else if ( ( left === null ) || ( right === null ) ) { return false ; } if ( ! Buffer . isBuffer ( left ) ) { left = new Buffer ( left ) ; } if ( ! Buffer . isBuffer ( right ) ) { right = new Buffer ( right ) ; } var same = ( left . length === right . length ) , i = 0 , max = left . length ; while ( i < max ) { same &= ( left [ i ] == right [ i ] ) ; //eslint-disable-line eqeqeq i ++ ; } return same ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * given a file / callback goes and reads out all the info! [CODESPLIT] function ( filename , callback ) { var fileInfo = { filename : filename } ; var that = this ; var allDone = pipeline ( [ function ( ) { return that . _loadFile ( filename ) ; } , function ( fileBuffer ) { fileInfo . fileBuffer = fileBuffer ; return that . parseBuffer ( fileInfo ) ; } ] ) ; if ( callback ) { when ( allDone ) . then ( function ( info ) { callback ( info , null ) ; } , function ( err ) { callback ( null , err ) ; } ) ; } return allDone ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * broken out if you re working with a buffer instead expects a fileInfo object with the fileBuffer property set to your buffer . [CODESPLIT] function ( fileInfo , callback ) { if ( ! Buffer . isBuffer ( fileInfo . fileBuffer ) ) { return when . reject ( 'fileBuffer was invalid' ) ; } var that = this ; var allDone = pipeline ( [ function ( ) { return that . _validateCRC ( fileInfo . fileBuffer ) ; } , function ( crcInfo ) { fileInfo . crc = crcInfo ; return that . _readPrefix ( fileInfo . fileBuffer ) ; } , function ( prefixInfo ) { fileInfo . prefixInfo = prefixInfo ; return that . _readSuffix ( fileInfo . fileBuffer ) ; } , function ( suffixInfo ) { fileInfo . suffixInfo = suffixInfo ; return when . resolve ( ) ; } , function ( ) { return fileInfo ; } ] ) ; if ( callback ) { when ( allDone ) . then ( function ( info ) { callback ( info , null ) ; } , function ( err ) { callback ( null , err ) ; } ) ; } return allDone ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * goes and reads out the file if it exists and returns a promise with the fileBuffer [CODESPLIT] function ( filename ) { if ( ! fs . existsSync ( filename ) ) { return when . reject ( filename + ' doesn\\'t exist' ) ; } var fileBuffer = fs . readFileSync ( filename ) ; if ( ! fileBuffer || ( fileBuffer . length === 0 ) ) { return when . reject ( filename + ' was empty!' ) ; } return when . resolve ( fileBuffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * calculates the CRC of the buffer and compares it to the stored CRC region of the file [CODESPLIT] function ( fileBuffer ) { if ( ! fileBuffer || ( fileBuffer . length === 0 ) ) { //console.log('validateCRC: buffer was empty!'); return false ; } var dataRegion = fileBuffer . slice ( 0 , fileBuffer . length - 4 ) ; var storedCrcValue = fileBuffer . slice ( fileBuffer . length - 4 , fileBuffer . length ) ; var crcResult = crc32 ( dataRegion ) ; var matching = utilities . bufferCompare ( storedCrcValue , crcResult ) ; //var matching = Buffer.compare(storedCrcValue, crcResult); var result = { //ok: (matching === 0), ok : matching , storedCrc : storedCrcValue . toString ( 'hex' ) , actualCrc : crcResult . toString ( 'hex' ) } ; //console.log('calculated crc was ' + result.actualCrc); return when . resolve ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * tries to determine where we should be looking in the file . [CODESPLIT] function ( fileBuffer ) { // try no offset var r = new buffers . BufferReader ( fileBuffer ) ; var userModuleStartAddy = r . shiftUInt32 ( true ) . toString ( 16 ) ; // start over r = new buffers . BufferReader ( fileBuffer ) ; // skip 0x184 for system modules to skip the vector table r . skip ( 388 ) ; var sysModuleStartAddy = r . shiftUInt32 ( true ) . toString ( 16 ) ; // start over, test for Mesh modular firmware which has a different offset than Photon/Electron modular firmware r = new buffers . BufferReader ( fileBuffer ) ; // skip 0x200 for Mesh firmware r . skip ( 0x200 ) ; var meshModule = this . _parsePrefix ( r ) ; // start over, test for Core monolithic firmware which has a different offset than modular firmware r = new buffers . BufferReader ( fileBuffer ) ; // skip 0x10C for Core firmware r . skip ( 0x10C ) ; var coreModuleStartAddy = r . shiftUInt32 ( true ) . toString ( 16 ) ; // start over, test for bluz system part which has a different offset than Photon r = new buffers . BufferReader ( fileBuffer ) ; // skip 0xc0 for bluz system modules to skip the vector table r . skip ( 192 ) ; var bluzModuleStartAddy = r . shiftUInt32 ( true ) ; // also check for the platform ID since the address is pretty nebulous to check for r = new buffers . BufferReader ( fileBuffer ) ; r . skip ( 192 + 12 ) ; var bluzModulesPlatformID = r . shiftUInt16 ( true ) ; //just system modules have the offset at the beginning. // system module addresses always tend to start at 0x2xxxxxxx // while user modules tend to start around 0x8xxxxxxx // but any valid address right now should start with 80... something, since they're small / in the realm // of the bootloader....  we'll need some extra sanity checks somehow later if hardware changes dramatically. var mightBeUser = ( userModuleStartAddy . indexOf ( \"80\" ) === 0 ) || ( userModuleStartAddy === 'd4000' ) ; var mightBeSystem = ( sysModuleStartAddy . indexOf ( \"80\" ) === 0 ) ; var isCore = ( ( userModuleStartAddy . indexOf ( \"20\" ) === 0 ) && ( coreModuleStartAddy === \"8005000\" ) ) ; var mightBeBluz = ( bluzModulesPlatformID == 103 && bluzModuleStartAddy < 262144 ) ; var isMesh = ( meshModule . platformID >= 12 && meshModule . platformID <= 30 ) && ( meshModule . moduleStartAddy === '30000' || meshModule . moduleStartAddy === 'f4000' ) && ( userModuleStartAddy . indexOf ( \"20\" ) == 0 ) ; // stack is located in ram at 0x2000000 if ( isCore ) { return 0x10C ; } else if ( ! mightBeUser && mightBeSystem ) { return 388 ; } else if ( mightBeUser && ! mightBeSystem ) { return 0 ; } else if ( mightBeBluz ) { return 192 ; } else if ( isMesh ) { return 0x200 ; } else { return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * parses out the prefix area of the binary after attempting to determine the correct offset . Returns : { moduleStartAddy : string moduleEndAddy : string moduleVersion : number platformID : number moduleFunction : number moduleIndex : number depModuleFunction : number depModuleIndex : number depModuleVersion : number } [CODESPLIT] function ( fileBuffer ) { var prefixOffset = this . _divineModulePrefixOffset ( fileBuffer ) ; var r = new buffers . BufferReader ( fileBuffer ) ; // skip to system module offset, or stay at user module no offset r . skip ( prefixOffset ) ; return this . _parsePrefix ( r ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * parses out the suffix area of the binary only reads back into the file as far as is provided by the suffixSize value . Returns : { productId : ( * |Number ) productVersion : ( * |Number ) fwUniqueId : ( * |String ) reserved : ( * |Number ) suffixSize : ( * |Number ) crcBlock : ( * |String ) } [CODESPLIT] function ( fileBuffer ) { // last 4 bytes of the file are the crc // 2 bytes before that is suffix payload size //lets read the suffix backwards. var idx = fileBuffer . length - 4 ; var crcBlock = fileBuffer . slice ( idx , idx + 4 ) . toString ( 'hex' ) ; idx -= 2 ; var suffixSize = fileBuffer . readUInt16LE ( idx ) ; idx -= 32 ; var fwUniqueId = fileBuffer . slice ( idx , idx + 32 ) . toString ( 'hex' ) ; idx -= 2 ; var reserved = fileBuffer . readUInt16LE ( idx ) ; idx -= 2 ; var productVersion = fileBuffer . readUInt16LE ( idx ) ; idx -= 2 ; var productId = fileBuffer . readUInt16LE ( idx ) ; if ( reserved === 0 ) { //cool! } if ( suffixSize < 40 ) { productId = - 1 ; productVersion = - 1 ; } return { productId : productId , productVersion : productVersion , fwUniqueId : fwUniqueId , reserved : reserved , suffixSize : suffixSize , crcBlock : crcBlock } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Application entry point . [CODESPLIT] async function main ( ) { // Initialize the application. process . title = 'Coveralls.js' ; // Parse the command line arguments. program . name ( 'coveralls' ) . description ( 'Send a coverage report to the Coveralls service.' ) . version ( packageVersion , '-v, --version' ) . arguments ( '<file>' ) . action ( file => program . file = file ) . parse ( process . argv ) ; if ( ! program . file ) { program . outputHelp ( ) ; process . exitCode = 64 ; return null ; } // Run the program. const client = new Client ( 'COVERALLS_ENDPOINT' in process . env ? new URL ( process . env . COVERALLS_ENDPOINT ) : Client . defaultEndPoint ) ; const coverage = await promises . readFile ( program . file , 'utf8' ) ; console . log ( ` ${ client . endPoint } ` ) ; return client . upload ( coverage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of Shortline which can be used to prompt users for input . [CODESPLIT] function Shortline ( options ) { const self = this ; self . _input = ( options && options . input ) || process . stdin ; self . _output = ( options && options . output ) || process . stderr ; /** Most recent error emitted by the input stream.\n   * @type {Error}\n   */ self . inputError = null ; self . _input . on ( 'end' , ( ) => { self . inputError = new EOFError ( EOF_MESSAGE ) ; } ) ; // Note:  Can't listen for 'error' since it changes behavior if there are no // other listeners.  Listen for it only when reading from input (since that // is our error and will be returned to the caller). }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines the shape of a node in an XML document . [CODESPLIT] function findElements ( node , name ) { return name in node && Array . isArray ( node [ name ] ) ? node [ name ] : [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uploads a coverage report . [CODESPLIT] async function main ( ) { // eslint-disable-line no-unused-vars try { const coverage = await promises . readFile ( '/path/to/coverage.report' , 'utf8' ) ; await new Client ( ) . upload ( coverage ) ; console . log ( 'The report was sent successfully.' ) ; } catch ( error ) { console . log ( ` ${ error . message } ` ) ; if ( error instanceof ClientError ) console . log ( ` ${ error . uri } ` ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of the travis - ci HTTP agent with a given endpoint and request options . [CODESPLIT] function TravisStatusHttp ( endpoint , options ) { if ( endpoint && typeof endpoint !== 'string' ) { throw new TypeError ( 'endpoint must be a string' ) ; } endpoint = endpoint && trimSlash ( endpoint ) ; if ( options && typeof options !== 'object' ) { throw new TypeError ( 'options must be an object' ) ; } options = Object . assign ( { gzip : true } , options ) ; options . headers = Object . assign ( { } , options . headers ) ; // Careful about providing default values for case-insensitive headers const caselessHeaders = caseless ( options . headers ) ; // The Travis CI API docs say // \"Always set the Accept header to application/vnd.travis-ci.2+json\" // but the API actually sends Content-Type application/json. // Declare that we accept either. if ( ! caselessHeaders . has ( 'Accept' ) ) { options . headers . Accept = 'application/vnd.travis-ci.2+json, application/json' ; } if ( ! caselessHeaders . has ( 'User-Agent' ) ) { options . headers [ 'User-Agent' ] = DEFAULT_USER_AGENT ; } TravisHttp . call ( this , endpoint === constants . PRO_URI , options . headers ) ; this . _endpoint = endpoint || constants . ORG_URI ; // Set this._headers as TravisHttp does this . _headers = options . headers ; delete options . headers ; this . _options = options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs git with given arguments . [CODESPLIT] function git ( ... args ) { return new Promise ( ( resolve , reject ) => { const child = execFile ( 'git' , args , ( err , stdout , stderr ) => { if ( err ) { reject ( err ) ; } else { // Creating an object with named properties would probably be clearer // but this is compatible with thenify/promisify if we switch later. resolve ( [ stdout , stderr ] ) ; } } ) ; child . stdin . end ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Options for command entry points . [CODESPLIT] function travisStatusCmd ( args , options , callback ) { if ( ! callback && typeof options === 'function' ) { callback = options ; options = null ; } if ( ! callback ) { return new Promise ( ( resolve , reject ) => { travisStatusCmd ( args , options , ( err , result ) => { if ( err ) { reject ( err ) ; } else { resolve ( result ) ; } } ) ; } ) ; } if ( typeof callback !== 'function' ) { throw new TypeError ( 'callback must be a function' ) ; } try { if ( args === undefined || args === null || args . length === 0 ) { // Fake args to keep Commander.js happy args = [ process . execPath , __filename ] ; } else if ( typeof args !== 'object' || Math . floor ( args . length ) !== args . length ) { throw new TypeError ( 'args must be Array-like' ) ; } else if ( args . length < 2 ) { throw new RangeError ( 'non-empty args must have at least 2 elements' ) ; } else { args = Array . prototype . map . call ( args , String ) ; } if ( options && typeof options !== 'object' ) { throw new TypeError ( 'options must be an object' ) ; } options = Object . assign ( { in : process . stdin , out : process . stdout , err : process . stderr } , options ) ; if ( ! options . in || typeof options . in . read !== 'function' ) { throw new TypeError ( 'options.in must be a stream.Readable' ) ; } if ( ! options . out || typeof options . out . write !== 'function' ) { throw new TypeError ( 'options.out must be a stream.Writable' ) ; } if ( ! options . err || typeof options . err . write !== 'function' ) { throw new TypeError ( 'options.err must be a stream.Writable' ) ; } } catch ( err ) { process . nextTick ( ( ) => { callback ( err ) ; } ) ; return undefined ; } const command = new Command ( ) . description ( 'Checks status of the latest build.' ) // Note:  Option order matches travis.rb with new ones at bottom . option ( '-i, --interactive' , 'be interactive and colorful' ) . option ( '-E, --explode' , 'ignored for compatibility with travis.rb' ) . option ( '--skip-version-check' , 'ignored for compatibility with travis.rb' ) . option ( '--skip-completion-check' , 'ignored for compatibility with travis.rb' ) . option ( '-I, --insecure' , 'do not verify SSL certificate of API endpoint' ) . option ( '-e, --api-endpoint <URL>' , 'Travis API server to talk to' ) . option ( '--pro' , ` ${ travisStatus . PRO_URI } ` ) . on ( 'option:pro' , function ( ) { this . apiEndpoint = travisStatus . PRO_URI ; } ) . option ( '--org' , ` ${ travisStatus . ORG_URI } ` ) . on ( 'option:org' , function ( ) { this . apiEndpoint = travisStatus . ORG_URI ; } ) . option ( '--staging' , 'talks to staging system' ) . on ( 'option:staging' , function ( ) { this . apiEndpoint = ( this . apiEndpoint || travisStatus . ORG_URI ) . replace ( / api / g , 'api-staging' ) ; } ) . option ( '-t, --token <ACCESS_TOKEN>' , 'access token to use' ) . option ( '--debug' , 'show API requests' ) . option ( '--debug-http' , 'show HTTP(S) exchange' ) . option ( '-r, --repo <SLUG>' , 'repository to use (will try to detect from current git clone)' ) . option ( '-R, --store-repo <SLUG>' , 'like --repo, but remembers value for current directory' ) . on ( 'option:store-repo' , function ( ) { this . repo = this . storeRepo ; } ) . option ( '-x, --exit-code' , 'sets the exit code to 1 if the build failed' ) . option ( '-q, --quiet' , 'does not print anything' ) . option ( '-p, --fail-pending' , 'sets the status code to 1 if the build is pending' ) . option ( '-b, --branch [BRANCH]' , 'query latest build for a branch (default: current)' ) . option ( '-c, --commit [COMMIT]' , 'require build to be for a specific commit (default: HEAD)' ) . option ( '-w, --wait [TIMEOUT]' , 'wait if build is pending (timeout in seconds)' ) . version ( packageJson . version ) ; // Patch stdout, stderr, and exit for Commander // See: https://github.com/tj/commander.js/pull/444 const exitDesc = Object . getOwnPropertyDescriptor ( process , 'exit' ) ; const stdoutDesc = Object . getOwnPropertyDescriptor ( process , 'stdout' ) ; const stderrDesc = Object . getOwnPropertyDescriptor ( process , 'stderr' ) ; const consoleDesc = Object . getOwnPropertyDescriptor ( global , 'console' ) ; const errExit = new Error ( 'process.exit() called' ) ; process . exit = function throwOnExit ( code ) { errExit . code = code ; throw errExit ; } ; if ( options . out ) { Object . defineProperty ( process , 'stdout' , { configurable : true , enumerable : true , value : options . out } ) ; } if ( options . err ) { Object . defineProperty ( process , 'stderr' , { configurable : true , enumerable : true , value : options . err } ) ; } if ( options . out || options . err ) { Object . defineProperty ( global , 'console' , { configurable : true , enumerable : true , // eslint-disable-next-line no-console value : new console . Console ( process . stdout , process . stderr ) } ) ; } try { command . parse ( args ) ; } catch ( errParse ) { const exitCode = errParse === errExit ? errExit . code || 0 : null ; process . nextTick ( ( ) => { if ( exitCode !== null ) { callback ( null , exitCode ) ; } else { callback ( errParse ) ; } } ) ; return undefined ; } finally { Object . defineProperty ( process , 'exit' , exitDesc ) ; Object . defineProperty ( process , 'stdout' , stdoutDesc ) ; Object . defineProperty ( process , 'stderr' , stderrDesc ) ; Object . defineProperty ( global , 'console' , consoleDesc ) ; } if ( command . commit === true ) { command . commit = 'HEAD' ; } if ( typeof command . interactive === 'undefined' ) { // Note:  Same default as travis.rb // Need cast to Boolean so undefined becomes false to disable Chalk command . interactive = Boolean ( options . out . isTTY ) ; } if ( command . wait === true ) { command . wait = Infinity ; } const chalk = new Chalk ( { enabled : command . interactive , // Note:  level: 0 overrides enabled: true, so must be specified here in // case supports-color returns false causing 0 default level. level : 1 } ) ; if ( command . args . length > 0 ) { options . err . write ( ` ${ chalk . red ( 'too many arguments' ) } \\n ${ command . helpInformation ( ) } ` ) ; process . nextTick ( ( ) => { callback ( null , 1 ) ; } ) ; return undefined ; } if ( hasOwnProperty . call ( command , 'wait' ) ) { const wait = Number ( command . wait ) ; if ( Number . isNaN ( wait ) ) { const waitErr = chalk . red ( ` ${ command . wait } ` ) ; options . err . write ( ` ${ waitErr } \\n ` ) ; process . nextTick ( ( ) => { callback ( null , 1 ) ; } ) ; return undefined ; } command . wait = wait * 1000 ; } // Pass through options command . in = options . in ; command . out = options . out ; command . err = options . err ; // Use HTTP keep-alive to avoid unnecessary reconnections command . requestOpts = { forever : true } ; if ( command . insecure ) { command . requestOpts . strictSSL = false ; } travisStatus ( command , ( err , build ) => { if ( err && err . name === 'SlugDetectionError' ) { debug ( 'Error detecting repo slug' , err ) ; options . err . write ( chalk . red ( 'Can\\'t figure out GitHub repo name. ' + 'Ensure you\\'re in the repo directory, or specify the repo name via ' + 'the -r option (e.g. travis-status -r <owner>/<repo>)\\n' ) ) ; callback ( null , 1 ) ; return ; } if ( err ) { options . err . write ( ` ${ chalk . red ( err . message ) } \\n ` ) ; callback ( null , 1 ) ; return ; } const state = build . repo ? build . repo . last_build_state : build . branch . state ; if ( ! command . quiet ) { const color = stateInfo . colors [ state ] || 'yellow' ; const number = build . repo ? build . repo . last_build_number : build . branch . number ; options . out . write ( ` ${ number } ${ chalk [ color ] ( state ) } \\n ` ) ; } let code = 0 ; if ( ( command . exitCode && stateInfo . isUnsuccessful [ state ] ) || ( command . failPending && stateInfo . isPending [ state ] ) ) { code = 1 ; } callback ( null , code ) ; } ) ; return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a SlugDetectionError . [CODESPLIT] function SlugDetectionError ( message ) { if ( ! ( this instanceof SlugDetectionError ) ) { return new SlugDetectionError ( message ) ; } Error . captureStackTrace ( this , SlugDetectionError ) ; // Like http://www.ecma-international.org/ecma-262/6.0/#sec-error-message if ( message !== undefined ) { Object . defineProperty ( this , 'message' , { value : String ( message ) , configurable : true , writable : true } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strips scoped style from html and return html and metadata . [CODESPLIT] function createScopedCss ( html , scope , filepath , cssVariables ) { scope = typeof scope === 'string' ? { ns : scope , vars : new Map ( ) } : scope ; const style = html . match ( styleMatcher ) ; if ( ! style ) { return [ { } , scope . vars , '' ] ; } const cssom = css . parse ( style [ 1 ] , { source : filepath } ) ; const vars = new Map ( scope . vars . entries ( ) ) ; getVariables ( cssom ) . forEach ( ( value , key ) => vars . set ( key , value ) ) ; if ( cssVariables ) { resolveScopeVariables ( cssom , vars ) ; } const [ classes , transformMap ] = rewriteSelectors ( ` ${ decamelize ( scope . ns , '-' ) } ` , cssom ) ; return [ classes , vars , css . stringify ( cssom ) , transformMap ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Based on http : // werxltd . com / wp / 2010 / 05 / 13 / javascript - implementation - of - javas - string - hashcode - method / [CODESPLIT] function createHash ( input ) { let hash = 0 ; if ( input . length === 0 ) { return hash ; } for ( let i = 0 ; i < input . length ; i ++ ) { const char = input . charCodeAt ( i ) ; hash = ( ( hash << 5 ) - hash ) + char ; // Convert to 32bit integer hash &= hash ; } return hash ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a combined CSS from all component CSS and scopedCss . [CODESPLIT] function combineCss ( templates , scopedCss ) { if ( ! Array . isArray ( scopedCss ) ) { scopedCss = [ scopedCss ] ; } return [ ... Object . keys ( templates ) . map ( name => templates [ name ] . css ) , ... scopedCss ] . join ( '\\n' ) . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs an InvalidSlugError . [CODESPLIT] function InvalidSlugError ( message ) { if ( ! ( this instanceof InvalidSlugError ) ) { return new InvalidSlugError ( message ) ; } Error . captureStackTrace ( this , InvalidSlugError ) ; // Like http://www.ecma-international.org/ecma-262/6.0/#sec-error-message if ( message !== undefined ) { Object . defineProperty ( this , 'message' , { value : String ( message ) , configurable : true , writable : true } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that a build has an expected commit hash . [CODESPLIT] function checkBuildCommit ( build , localCommit ) { const buildCommit = build . commit ; let message = ` ${ buildCommit . sha } ${ localCommit . sha } ` ; if ( localCommit . name ) { message += ` ${ localCommit . name } ` ; } // assert gives us useful exception properties for callers assert . strictEqual ( buildCommit . sha , localCommit . sha , message ) ; return build ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Options for { @link travisStatus } . [CODESPLIT] function travisStatus ( options , callback ) { if ( ! callback && typeof options === 'function' ) { callback = options ; options = null ; } if ( callback && typeof callback !== 'function' ) { throw new TypeError ( 'callback must be a function' ) ; } let agent , gitChecker , travisChecker ; try { if ( options && typeof options !== 'object' ) { throw new TypeError ( 'options must be an object' ) ; } options = options || { } ; if ( options . repo ) { GitStatusChecker . checkSlugFormat ( options . repo ) ; } if ( options . storeRepo ) { GitStatusChecker . checkSlugFormat ( options . storeRepo ) ; } // If the caller didn't request an agent behavior, control it ourselves. // Each function call will use HTTP keep-alive for the duration of the // function, but not after completion, which callers may not expect. let { requestOpts } = options ; if ( ! requestOpts || ( requestOpts . agent === undefined && requestOpts . agentClass === undefined && requestOpts . agentOptions === undefined && requestOpts . forever === undefined && requestOpts . pool === undefined ) ) { const apiUrl = url . parse ( options . apiEndpoint || TravisStatusChecker . ORG_URI ) ; const Agent = apiUrl . protocol === 'https:' ? https . Agent : apiUrl . protocol === 'http:' ? http . Agent : null ; if ( Agent ) { agent = new Agent ( { keepAlive : true } ) ; // .destroy() and keepAlive added to Agent in 0.11.4, nodejs@9fc9b874 // If Agent doesn't support keepAlive/destroy, we don't need/want it. if ( typeof agent . destroy === 'function' ) { requestOpts = Object . assign ( { } , requestOpts ) ; requestOpts . agent = agent ; options = Object . assign ( { } , options ) ; options . requestOpts = requestOpts ; } else { agent = undefined ; } } } gitChecker = new GitStatusChecker ( options ) ; travisChecker = new TravisStatusChecker ( options ) ; } catch ( errOptions ) { const errResult = Promise . reject ( errOptions ) ; return nodeify ( errResult , callback ) ; } let repoSlugP ; if ( options . storeRepo ) { const storedSlugP = gitChecker . tryStoreSlug ( options . storeRepo ) ; // If both .repo and .storeRepo are present, store .storeRepo and use .repo repoSlugP = options . repo ? storedSlugP . then ( ( ) => options . repo ) : storedSlugP ; } else if ( options . repo ) { repoSlugP = Promise . resolve ( options . repo ) ; } else { const foundSlugP = gitChecker . findSlug ( ) . then ( GitStatusChecker . checkSlugFormat ) ; if ( options . interactive ) { repoSlugP = foundSlugP . then ( ( slug ) => gitChecker . tryStoreSlug ( slug ) ) ; } else { repoSlugP = foundSlugP ; } } let localCommitP ; if ( options . commit ) { localCommitP = gitChecker . resolveHash ( options . commit ) . then ( ( resolved ) => { const localCommit = { sha : resolved } ; if ( resolved !== options . commit ) { localCommit . name = options . commit ; } return localCommit ; } ) ; } // Before doing remote queries, ensure that there are no errors locally const slugForQueryP = Promise . all ( [ repoSlugP , localCommitP ] ) . then ( ( slugAndHash ) => slugAndHash [ 0 ] ) ; let resultP ; if ( options . branch ) { const branchP = options . branch === true ? gitChecker . detectBranch ( ) : Promise . resolve ( options . branch ) ; resultP = Promise . all ( [ slugForQueryP , branchP ] ) . then ( ( results ) => { const slug = results [ 0 ] ; const branch = results [ 1 ] ; return travisChecker . getBranch ( slug , branch , options ) ; } ) ; } else { const repoP = slugForQueryP . then ( ( slug ) => travisChecker . getRepo ( slug , options ) ) ; if ( localCommitP ) { // Add build information to result resultP = repoP . then ( ( repo ) => travisChecker . getBuild ( repo . repo . slug , repo . repo . last_build_id ) . then ( ( build ) => Object . assign ( { } , repo , build ) ) ) ; } else { resultP = repoP ; } } let checkedResultP = resultP ; if ( localCommitP ) { checkedResultP = Promise . all ( [ resultP , localCommitP ] ) . then ( ( all ) => { const result = all [ 0 ] ; const localCommit = all [ 1 ] ; checkBuildCommit ( result , localCommit ) ; return result ; } ) ; } let cleanupP ; if ( agent ) { cleanupP = checkedResultP . then ( ( result ) => { agent . destroy ( ) ; return result ; } , ( err ) => { agent . destroy ( ) ; return Promise . reject ( err ) ; } ) ; } else { cleanupP = checkedResultP ; } return nodeify ( cleanupP , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trims a single slash from the end of a string if present . [CODESPLIT] function trimSlash ( string ) { if ( typeof string !== 'string' ) { return string ; } if ( string . length > 0 && string . charAt ( string . length - 1 ) === '/' ) { return string . slice ( 0 , string . length - 1 ) ; } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows any option to be passed as a function which gets webpack s context as its first argument in case some info from the loader context is necessary [CODESPLIT] function parseOptions ( opts ) { return removeEmpty ( { plugins : convertFn . call ( this , opts . plugins ) , locals : convertFn . call ( this , opts . locals ) , filename : convertFn . call ( this , opts . filename ) , parserOptions : convertFn . call ( this , opts . parserOptions ) , generatorOptions : convertFn . call ( this , opts . generatorOptions ) , runtime : convertFn . call ( this , opts . runtime ) , parser : convertFnSpecial . call ( this , opts . parser ) , multi : convertFn . call ( this , opts . multi ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The runtime contains functions which must be converted into strings without any escaping at all . Yes this method of doing so is insane . But it works! [CODESPLIT] function serializeVerbatim ( obj ) { let i = 0 const fns = [ ] let res = JSON . stringify ( obj , ( k , v ) => { if ( typeof v === 'function' ) { fns . push ( v . toString ( ) ) return ` ${ i ++ } ` } else { return v } } ) res = res . replace ( / \"__REPLACE(\\d{1})\" / g , ( m , v ) => { return fns [ v ] } ) return res }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders all given pages as static HTML into the destination folder . [CODESPLIT] function renderPages ( filepaths , dest , { templates , vars , statics , disableValidation , cssVariables , host } ) { console . log ( ` \\n ` ) ; return Promise . all ( filepaths . map ( filepath => { return sander . readFile ( filepath ) . then ( content => renderPage ( content , filepath , { templates , vars , dest , cssVariables } ) ) . then ( ( [ html , destinationPath , cssParts ] ) => sander . writeFile ( destinationPath , html ) . then ( ( ) => [ destinationPath , cssParts ] ) ) . then ( ( [ destinationPath , cssParts ] ) => { console . log ( ` ${ chalk . bold . green ( figures . tick ) } ${ filepath } ${ destinationPath } ` ) ; return [ destinationPath , cssParts ] ; } ) ; } ) ) . then ( pageResults => disableValidation || validatePages ( host , dest , pageResults . map ( result => result [ 0 ] ) , statics ) . then ( ( ) => pageResults . map ( result => result [ 1 ] ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Options for { @link TravisStatusChecker } . [CODESPLIT] function TravisStatusChecker ( options ) { if ( options && typeof options !== 'object' ) { throw new TypeError ( 'options must be an object' ) ; } options = options || { } ; const apiEndpoint = options . apiEndpoint && trimSlash ( options . apiEndpoint ) ; this . _travis = new Travis ( { pro : apiEndpoint === constants . PRO_URI , version : '2.0.0' } ) ; this . _travis . agent = new TravisStatusHttp ( apiEndpoint , options . requestOpts ) ; if ( options . token ) { this . _travis . agent . setAccessToken ( options . token ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Options for { @link TravisStatusQueryOptions } . [CODESPLIT] function queryWithWait ( query , valueIsPending , options ) { const maxWaitMs = options && options . wait ? Number ( options . wait ) : 0 ; if ( Number . isNaN ( maxWaitMs ) ) { return Promise . reject ( new TypeError ( 'wait must be a number' ) ) ; } if ( maxWaitMs < 0 ) { return Promise . reject ( new RangeError ( 'wait must be non-negative' ) ) ; } const startMs = Date . now ( ) ; // Note:  Divide by 2 so we can double unconditionally below let nextWaitMs = POLL_TIME_START_MS / 2 ; function doQuery ( cb ) { query . get ( cb ) ; } return new Promise ( ( resolve , reject ) => { function checkBuild ( err , result ) { if ( err ) { reject ( err ) ; return ; } if ( maxWaitMs ) { let isPending ; try { isPending = valueIsPending ( result ) ; } catch ( errPending ) { reject ( errPending ) ; return ; } if ( isPending ) { const nowMs = Date . now ( ) ; const totalWaitMs = nowMs - startMs ; if ( totalWaitMs < maxWaitMs ) { nextWaitMs = Math . min ( nextWaitMs * 2 , POLL_TIME_MAX_MS , maxWaitMs - totalWaitMs ) ; setTimeout ( doQuery , nextWaitMs , checkBuild ) ; return ; } } } resolve ( result ) ; } doQuery ( checkBuild ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "analyze [CODESPLIT] function ( input ) { var result = / @charset\\s+['|\"](\\w*)[\"|']; / . exec ( input ) , charset = 'UTF-8' ; if ( result && result [ 1 ] ) { charset = result [ 1 ] ; } //        else{ //            var detect = jschardet.detect(input); //            if(detect && detect.confidence > 0.9){ //                charset = detect.encoding; //            } //        } return charset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "中文转unicode [CODESPLIT] function ( text ) { text = escape ( text . toString ( ) ) . replace ( / \\+ / g , \"%2B\" ) ; var matches = text . match ( / (%([0-9A-F]{2})) / gi ) ; if ( matches ) { for ( var matchid = 0 ; matchid < matches . length ; matchid ++ ) { var code = matches [ matchid ] . substring ( 1 , 3 ) ; if ( parseInt ( code , 16 ) >= 128 ) { text = text . replace ( matches [ matchid ] , '%u00' + code ) ; } } } text = text . replace ( '%25' , '%u0025' ) ; return text ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从内容中提取import列表 [CODESPLIT] function ( content ) { var reg = / @import\\s*(url)?\\s*[\\('\"]+([^'\"]+)\\.css(\\?[^\\s]*)?\\s*['\"\\)]+\\s*[^;]*; / ig ; var result = reg . exec ( content ) ; if ( result && result [ 2 ] ) { return { match : result [ 0 ] , filePath : result [ 2 ] + '.css' } ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "修改子文件import的相对路径 子文件夹中所有的相对路径都要进行转换 先看一下什么形式的地址需要转换 [CODESPLIT] function ( content , filePath ) { 'use strict' ; var self = this ; var regImport = / @import\\s*(url)?\\(?['\"]([^'\"%]+)\\.css['\"]\\)?[^;]*; / ig , regImageOrFont = / (url)?\\(['\"]?([^:\\)]+\\.(png|jpg|gif|jpeg|ttf|eot|woff|svg))([^\\)]*)['\"]?\\) / ig , importResult , picAndFontResult ; var importFilePath = path . dirname ( path . resolve ( self . config . sourceDir , filePath ) ) ; // 替换import importResult = regImport . exec ( content ) ; if ( typeof importResult !== 'undefined' && importResult && importResult [ 2 ] ) { var importAbsoluteUrl = path . resolve ( importFilePath , importResult [ 2 ] ) ; // 用%号表示已经替换好的import路径，后续会再去掉百分号,这里替换的时 // 候要注意全局的替换 var regimportReplace = new RegExp ( importResult [ 2 ] , 'g' ) ; content = content . replace ( regimportReplace , \"%\" + path . relative ( self . config . sourceDir , importAbsoluteUrl ) ) ; return self . modifySubImportsPath ( content , filePath ) ; } // 替换图片和font的路径 picAndFontResult = regImageOrFont . exec ( content ) ; if ( typeof picAndFontResult !== 'undefined' && picAndFontResult && picAndFontResult [ 2 ] && ! / ^\\/\\/[^\\/]+ / . test ( picAndFontResult [ 2 ] ) ) { var regpicReplace = new RegExp ( picAndFontResult [ 2 ] , 'g' ) ; var picAbsolutePath = path . resolve ( importFilePath , picAndFontResult [ 2 ] ) ; //解决win平台下路径的斜杠问题 var isWin = ( process . platform === 'win32' ) ; var _path = path . relative ( self . config . sourceDir , picAbsolutePath ) ; if ( isWin ) { _path = path . relative ( self . config . sourceDir , picAbsolutePath ) . split ( path . sep ) . join ( \"\\/\" ) ; } // 用：号表示已经替换好的import路径，后续会再去掉冒号 content = content . replace ( regpicReplace , \":\" + _path ) ; return self . modifySubImportsPath ( content , filePath ) ; } return content ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Options for { @link GitStatusChecker } . [CODESPLIT] function GitStatusChecker ( options ) { if ( options && typeof options !== 'object' ) { throw new TypeError ( 'options must be an object' ) ; } options = Object . assign ( { in : process . stdin , out : process . stdout , err : process . stderr } , options ) ; if ( ! options . in || typeof options . in . read !== 'function' ) { throw new TypeError ( 'options.in must be a stream.Readable' ) ; } if ( ! options . out || typeof options . out . write !== 'function' ) { throw new TypeError ( 'options.out must be a stream.Writable' ) ; } if ( ! options . err || typeof options . err . write !== 'function' ) { throw new TypeError ( 'options.err must be a stream.Writable' ) ; } this . _options = options ; this . _chalk = new Chalk ( { enabled : Boolean ( options . interactive !== undefined ? options . interactive : options . out . isTTY ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the path portion of a git URL . [CODESPLIT] function gitUrlPath ( gitUrl ) { // Foreign URL for remote helper // See transport_get in transport.c // Note:  url.parse considers second : as part of path.  So check this first. const foreignParts = / ^([A-Za-z0-9][A-Za-z0-9+.-]*)::(.*)$ / . exec ( gitUrl ) ; if ( foreignParts ) { return foreignParts [ 2 ] ; } // Typical URL const gitUrlObj = url . parse ( gitUrl ) ; if ( gitUrlObj . protocol ) { return gitUrlObj . path ; } // SCP-like syntax.  Host can be wrapped in [] to disambiguate path. // See parse_connect_url and host_end in connect.c const scpParts = / ^([^@/]+)@(\\[[^]\\/]+\\]|[^:/]+):(.*)$ / . exec ( gitUrl ) ; if ( scpParts ) { return scpParts [ 3 ] ; } // Assume URL is a local path return gitUrl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pick env specific robots . txt [CODESPLIT] function ( ) { var appEnv = this . app . env ; if ( process . env . DEPLOY_TARGET ) { appEnv = process . env . DEPLOY_TARGET ; } var publicFiles = new Funnel ( this . app . trees . public ) ; this . _requireBuildPackages ( ) ; fs . stat ( path . join ( this . project . root , 'public' , 'robots.txt' ) , function ( err , stats ) { if ( stats && stats . isFile ( ) ) { console . log ( chalk . yellow ( 'There is a robots.txt in /public and ENV specific robots.txt are ignored!' ) ) ; } } ) ; publicFiles = stew . rename ( publicFiles , 'robots-' + appEnv + '.txt' , 'robots.txt' ) ; return new Funnel ( publicFiles , { srcDir : '/' , destDir : '/' } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "## BalanceSheet constructor [CODESPLIT] function BalanceSheet ( options ) { // ## Public properties this . sheets = { } ; this . sheet = null ; log = options . log || log ; /**\n * ### BalanceSheet.options\n *\n * Reference to current configuration\n *\n */ this . options = options || { } ; // ## BalanceSheet methods /**\n * ### BalanceSheet.init\n *\n * Configures the BalanceSheet instance\n *\n * Takes the configuration as an input parameter or\n * recycles the settings in `this.options`.\n *\n * The configuration object is of the type\n *\n * \tvar options = {\n * \t\treturnAt: 'first', // or 'last'\n * \t\ttriggers: [ myFunc,\n * \t\t\t\t\tmyFunc2\n * \t\t],\n * \t}\n *\n * @param {object} options Optional. Configuration object\n *\n */ BalanceSheet . prototype . init = function ( options ) { this . options = options || this . options ; if ( this . options . returnAt === BalanceSheet . first || this . options . returnAt === BalanceSheet . last ) { this . returnAt = this . options . returnAt ; } this . resetTriggers ( ) ; } ; /**\n * ### BalanceSheet.addSheet\n *\n * Adds a new sheet and sets it as default\n *\n * @param {string} sheet The sheet name\n * @param {object} options. Optional. Configuration options for the sheet\n * @param {array} items. Optional. An initial set of items for the sheet\n * @return {boolean} TRUE, if the sheet is added successfully\n */ //BalanceSheet.prototype.addSheet = function (sheet, pl, options) { //\tif (!isValidSheet(sheet)) return false; //\tpl = pl || new PlayerList(); // //\tthis.sheets[sheet] = pl; // //\tif (!this.initSheet(sheet, options)) { //\t\treturn false; //\t} // //\tthis.sheet = sheet; //\treturn true; //}; //BalanceSheet.prototype.initSheet = function (sheet, options) { //\tif  (!isValidSheet(sheet)) return false; //\tthis.sheets[sheet].each(function(p){ //\t\tif (!p.__balance) { //\t\t\tp.__balance = 0; //\t\t} //\t}); //}; BalanceSheet . prototype . updateBalance = function ( player , amount ) { if ( ! player || ! amount ) return ; if ( ! this . sheet ) { log ( 'No balance sheet selected' ) ; return ; } if ( ! this . sheet . player ) return } this . sheet . players [ player ] . __balance += amount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////// GROUP [CODESPLIT] function Group ( ) { this . elements = [ ] ; this . matched = [ ] ; this . leftOver = [ ] ; this . pointer = 0 ; this . matches = { } ; this . matches . total = 0 ; this . matches . requested = 0 ; this . matches . done = false ; this . rowLimit = 3 ; this . noSelf = true ; this . pool = [ ] ; this . shuffle = true ; this . stretch = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "## Group constructor [CODESPLIT] function Group ( options ) { /**\n         * ## Group.name\n         *\n         * The name of the group\n         *\n         * Must be unique amongst groups\n         */ this . name = null ; /**\n         * ## Group.elements\n         *\n         * The elements belonging to this group\n         *\n         * They can be matched with other elements contained in the _pool_.\n         *\n         * @see Group.pool\n         * @see Group.matched\n         */ this . elements = [ ] ; /**\n         * ## Group.pool\n         *\n         * Sets of elements that to match with the group members sequentially\n         *\n         * It is an array of arrays, and elements in ealier sets are more\n         * likely to be matched than subsequent ones.\n         *\n         * @see Group.elements\n         * @see Group.matched\n         */ this . pool = [ ] ; /**\n         * ## Group.matched\n         *\n         * Array of arrays of matched elements\n         *\n         * Each index in the parent array corresponds to a group member,\n         * and each array are the matched element for such a member.\n         *\n         * @see Group.elements\n         * @see Group.pool\n         */ this . matched = [ ] ; /**\n         * ## Group.leftOver\n         *\n         * Array of elements from the pool that could not be matched\n         */ this . leftOver = [ ] ; /**\n         * ## Group.pointer\n         *\n         * Index of the row we are trying to complete currently\n         */ this . pointer = 0 ; /**\n         * ## Group.matches\n         *\n         * Summary of matching results\n         *\n         */ this . matches = { total : 0 , requested : 0 , done : false } ; /**\n         * ## Group.rowLimit\n         *\n         * Number of elements necessary to a row\n         *\n         * Each group member will be matched with _rowLimit_ elements from\n         * the _pool_ elements.\n         */ this . rowLimit = 1 ; /**\n         * ## Group.noSelf\n         *\n         * If TRUE, a group member cannot be matched with himself.\n         */ this . noSelf = true ; /**\n         * ## Group.shuffle\n         *\n         * If TRUE, all elements of the pool will be randomly shuffled.\n         */ this . shuffle = true ; /**\n         * ## Group.stretch\n         *\n         * If TRUE,  each element in the pool will be replicated\n         * as many times as the _rowLimit_ variable.\n         */ this . stretch = true ; // Init user options. this . init ( options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "console . log ( getElements () ) console . log ( getPools () ) [CODESPLIT] function simulateMatch ( N ) { for ( var i = 0 ; i < N ; i ++ ) { var rm = new RMatcher ( ) , elements = getElements ( ) , pools = getPools ( ) ; //          console.log('NN ' , numbers); //          console.log(elements); //          console.log(pools) rm . init ( elements , pools ) ; var matched = rm . match ( ) ; if ( ! rm . allGroupsDone ( ) ) { console . log ( 'ERROR' ) ; console . log ( rm . options . elements ) ; console . log ( rm . options . pools ) ; console . log ( matched ) ; } for ( var j = 0 ; j < rm . groups . length ; j ++ ) { var g = rm . groups [ j ] ; for ( var h = 0 ; h < g . elements . length ; h ++ ) { if ( g . matched [ h ] . length !== g . rowLimit ) { console . log ( 'Wrong match: ' + h ) ; console . log ( rm . options . elements ) ; console . log ( rm . options . pools ) ; console . log ( matched ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "## SocketDirect constructor [CODESPLIT] function SocketDirect ( node , options ) { options = options || { } ; // ## Private properties /**\n         * ### SocketDirect.node\n         *\n         * Reference to the node object.\n         */ this . node = node ; /**\n         * ## SocketDirect.socket\n         *\n         * The SocketDirect object shared with the server\n         */ this . socket = options . socket ; /**\n         * ## SocketDirect.connected\n         *\n         * TRUE, if a connection is established\n         */ this . connected = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "## Example object All configuration options are listed below with their default value . [CODESPLIT] function myGame ( ) { this . solo_mode = false ; this . auto_wait = false ; this . auto_step = false ; this . observer = false ; this . minPlayers = 1 ; this . maxPlayers = 1000 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "## GameSession constructor [CODESPLIT] function GameSession ( node ) { SessionManager . call ( this ) ; /**\n         * ### GameSession.node\n         *\n         * The reference to the node object.\n         */ this . node = node ; // Register default variables in the session. this . register ( 'player' , { set : function ( p ) { node . createPlayer ( p ) ; } , get : function ( ) { return node . player ; } } ) ; this . register ( 'game.memory' , { set : function ( value ) { node . game . memory . clear ( true ) ; node . game . memory . importDB ( value ) ; } , get : function ( ) { return ( node . game . memory ) ? node . game . memory . fetch ( ) : null ; } } ) ; this . register ( 'events.history' , { set : function ( value ) { node . events . history . history . clear ( true ) ; node . events . history . history . importDB ( value ) ; } , get : function ( ) { return node . events . history ? node . events . history . history . fetch ( ) : null ; } } ) ; this . register ( 'stage' , { set : function ( ) { // GameSession.restoreStage } , get : function ( ) { return node . player . stage ; } } ) ; this . register ( 'node.env' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compile hogan template and open index . html [CODESPLIT] function compileIndex ( ) { fs . readFile ( path . join ( __dirname , 'templates' , 'index.hogan' ) , function ( err , data ) { if ( err ) throw err ; // write rendered result to index.html fs . writeFile ( path . join ( __dirname , 'index.html' ) , hogan . compile ( data . toString ( ) ) . render ( { 'schemes' : schemes , 'variations' : variations , 'colors' : colors , 'variants' : variants , } ) , function ( err ) { if ( err ) throw err } ) ; // open index.html in browser open ( path . join ( __dirname , 'index.html' ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort users by username length . Longest usernames first . [CODESPLIT] function sortMentions ( mentions ) { return mentions . slice ( ) . sort ( ( a , b ) => b . length - a . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Case - insensitively get the correct emoji name from the possible emoji for an input string . [CODESPLIT] function findEmoji ( names , match ) { const compare = match . toLowerCase ( ) ; for ( let i = 0 ; i < names . length ; i += 1 ) { const name = names [ i ] . toLowerCase ( ) ; if ( name === compare ) { return names [ i ] ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create set up and send an asynchronous request to the given path / URL with the given method and parameters . [CODESPLIT] function _request ( path , method , headers , body , withCredentials , callback ) { const xhr = new XMLHttpRequest ( { } ) ; // Set up the event handlers. const handler = evt => { if ( callback ) { callback ( evt ) ; } // The request has been completed: detach all the handlers. xhr . removeEventListener ( 'error' , handler ) ; xhr . removeEventListener ( 'load' , handler ) ; } ; xhr . addEventListener ( 'error' , handler , false ) ; xhr . addEventListener ( 'load' , handler , false ) ; // Set up the request. xhr . open ( method , path , true ) ; Object . keys ( headers || { } ) . forEach ( key => { xhr . setRequestHeader ( key , headers [ key ] ) ; } ) ; if ( withCredentials ) { xhr . withCredentials = withCredentials ; } xhr . send ( body || undefined ) ; return xhr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function RpcMessage ( opts ) { assert . object ( opts , 'options' ) ; assert . bool ( opts . incoming , 'options.incoming' ) ; assert . optionalNumber ( opts . type , 'options.type' ) ; assert . optionalNumber ( opts . xid , 'options.xid' ) ; stream . Transform . call ( this , opts ) ; this . type = opts . type ; this . xid = opts . xid ; this . incoming = opts . incoming ; this . _rpc_wrote_head = false ; this . _rpc_message = true ; // MDB }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function parseAuth ( xdr ) { assert . object ( xdr , 'xdr' ) ; var msg = { } ; var type = xdr . readInt ( ) ; var len = xdr . readInt ( ) ; switch ( type ) { case 0 : // null auth msg . type = 'null' ; // length is normally 0 for null auth, but that's not required xdr . xdr_offset += len ; break ; case 1 : // unix msg . type = 'unix' ; msg . stamp = xdr . readInt ( ) ; msg . machinename = xdr . readString ( ) ; msg . uid = xdr . readInt ( ) ; msg . gid = xdr . readInt ( ) ; msg . gids = xdr . readIntArray ( ) ; break ; case 2 : // TODO case 3 : // TODO default : throw new Error ( 'invalid auth type: ' + type ) ; } return ( msg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function PortmapGetPortCall ( opts ) { RpcCall . call ( this , opts ) ; this . mapping = { prog : 0 , vers : 0 , prot : 0 } ; this . _rpc_portmap_get_port_call = true ; // MDB }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function RpcClient ( opts ) { assert . object ( opts , 'options' ) ; assert . object ( opts . log , 'options.log' ) ; assert . number ( opts . program , 'options.program' ) ; assert . number ( opts . version , 'options.version' ) ; assert . string ( opts . url , 'options.url' ) ; EventEmitter . call ( this , opts ) ; var self = this ; this . conn = null ; this . log = opts . log . child ( { component : 'RpcClient' , serializers : require ( './bunyan' ) . serializers } ) ; this . messages = { } ; this . program = opts . program ; this . url = mod_url . parse ( opts . url ) ; this . version = opts . version ; var ID = 0 ; this . _next_xid = function ( ) { if ( ++ ID === ( Math . pow ( 2 , 32 ) - 1 ) ) ID = 0 ; return ( ID ) ; } ; this . _rpc_client = true ; // MDB ::findjsobjects flag this . conn = net . createConnection ( { port : this . url . port , host : this . url . hostname } ) ; this . conn . once ( 'error' , function onErr ( e ) { self . emit ( 'error' , e ) ; return ; } ) ; this . conn . once ( 'connect' , function onConnect ( ) { var parser = new RpcParser ( { log : self . log } ) ; parser . on ( 'message' , function onRpcMessage ( msg ) { var cfg = self . messages [ msg . xid ] ; var res ; if ( ! cfg ) { self . emit ( 'error' , new Error ( 'unsolicited RPC message' ) , msg ) ; return ; } if ( cfg . reply ) { res = new cfg . reply ( msg ) ; msg . pipe ( res ) ; } else { res = msg ; } msg . once ( 'end' , function cleanupMessageTable ( ) { if ( self . messages [ msg . xid ] ) delete self . messages [ msg . xid ] ; } ) ; var _cb = cfg . cb ; var _err = null ; if ( msg . reply_stat === 0 ) { switch ( msg . accept_stat ) { case 0 : break ; case 1 : _err = new errors . RpcProgramUnavailableError ( ) ; break ; case 2 : _err = new errors . RpcProgramMismatchError ( ) ; _err . mismatch_info = msg . mismatch_info ; break ; case 3 : _err = new errors . RpcProcedureUnavailableError ( ) ; break ; case 4 : _err = new errors . RpcGarbageArgumentsError ( ) ; break ; default : _err = new errors . RpcError ( 'invalid rpc.accept_stat: ' + msg . accept_stat ) ; break ; } } else if ( msg . reply_stat === 1 ) { if ( msg . reject_stat === 0 ) { _err = new errors . RpcMismatchError ( ) ; _err . mismatch_info = msg . mismatch_info ; } else { _err = new errors . RpcAuthError ( ) ; _err . auth_stat = msg . auth_stat ; } } process . nextTick ( function emitRpcReply ( ) { if ( _err ) { _cb ( _err , msg ) ; } else { _cb ( null , res , msg ) ; } } ) ; } ) ; self . conn . pipe ( parser ) ; self . emit ( 'connect' ) ; } ) ; this . _rpc_client = true ; // MDB }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function RpcCall ( opts ) { assert . object ( opts , 'options' ) ; RpcMessage . call ( this , opts ) ; this . rpcvers = opts . rpcvers || 2 ; this . prog = opts . prog ; this . vers = opts . vers ; this . proc = opts . proc ; this . auth = opts . auth || { } ; this . verifier = opts . verifier ; this . type = 0 ; this . _buffer = null ; this . _rpc_call = true ; // MDB }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function PortmapSetCall ( opts ) { RpcCall . call ( this , opts ) ; this . mapping = { prog : 0 , vers : 0 , prot : 0 , port : 0 } ; this . _rpc_portmap_set_call = true ; // MDB }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function RpcError ( cause , msg ) { var off = 0 ; if ( cause instanceof Error ) off = 1 ; var args = Array . prototype . slice . call ( arguments , off ) ; args . unshift ( { cause : off ? cause : undefined , ctor : RpcError } ) ; WError . apply ( this , args ) ; this . type = 1 ; // reply }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function PortmapClient ( opts ) { assert . object ( opts , 'options' ) ; if ( opts . log ) { var l = opts . log ; delete opts . log ; } var _opts = clone ( opts ) ; _opts . log = opts . log = l ; _opts . name = 'portmap' ; _opts . program = 100000 ; _opts . version = 2 ; RpcClient . call ( this , _opts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- Private Methods this is bound to an RpcServer [CODESPLIT] function ifError ( n ) { function _ifError ( err ) { if ( err ) { err . _rpc_next = n ; throw err ; } } return ( _ifError ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An RPC service is identified by its RPC program number version number and the transport address where it may be reached . The transport address in turn consists of a network address and a transport selector . In the case of a service available over TCP / IP or UDP / IP the network address will be an IP address and the transport selector will be a TCP or UDP port number . [CODESPLIT] function RpcServer ( opts ) { assert . object ( opts , 'options' ) ; assert . object ( opts . log , 'options.log' ) ; assert . number ( opts . program , 'options.program' ) ; var v = opts . version ; if ( typeof ( v ) === 'number' ) v = [ v ] ; assert . arrayOfNumber ( v , 'options.version' ) ; net . Server . call ( this , opts ) ; this . log = opts . log . child ( { component : 'RpcServer' } , true ) ; this . name = opts . name || 'RpcServer' ; this . program = opts . program ; this . rpc_table = { } ; this . saved_handlers = [ ] ; this . version = v . slice ( ) ; this . on ( 'connection' , onConnection . bind ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API RpcParser [CODESPLIT] function RpcParser ( opts ) { assert . optionalObject ( opts , 'options' ) ; stream . Writable . call ( this , opts ) ; this . _buffer = null ; this . rpc_table = { } ; // TODO - use this when fragments are supported this . _rpc_parser = true ; // MDB flag }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function RpcReply ( opts ) { RpcMessage . call ( this , opts ) ; this . _buffer = null ; this . rpc_reply_header_sent = false ; this . type = 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function PortmapUnsetCall ( opts ) { RpcCall . call ( this , opts ) ; this . mapping = { prog : 0 , vers : 0 , prot : 0 , port : 0 } ; this . _rpc_portmap_unset_call = true ; // MDB }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API [CODESPLIT] function PortmapServer ( opts ) { assert . object ( opts , 'options' ) ; if ( opts . log ) { var l = opts . log ; delete opts . log ; } var _opts = clone ( opts ) ; _opts . log = opts . log = l ; _opts . name = 'portmap' ; _opts . program = 100000 ; _opts . version = 2 ; RpcServer . call ( this , _opts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ --- API A set of helper functions for serdes on XDR datatypes . [CODESPLIT] function XDR ( buf ) { if ( buf ) assert . ok ( Buffer . isBuffer ( buf ) , 'buffer is required' ) ; this . xdr_buffer = buf || null ; this . xdr_offset = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * :: type BoxenOptions = { [ id : string ] : any } see : https : // github . com / sindresorhus / boxen#boxeninput - options [CODESPLIT] function notify ( opts /* : BoxenNotifyOptions */ ) { const isNpm = require ( 'is-npm' ) ; if ( ! process . stdout . isTTY || isNpm ) { return ; } const boxen = require ( 'boxen' ) ; opts = opts || { } ; opts . defer = typeof opts . defer === 'boolean' ? opts . defer : false ; opts . message = opts . message || '' ; opts . boxenOpts = opts . boxenOpts || { padding : 1 , margin : 1 , align : 'center' , borderColor : 'yellow' , borderStyle : 'round' , } ; const message = '\\n' + boxen ( opts . message , opts . boxenOpts ) ; if ( opts . defer === false ) { console . error ( message ) ; } else { process . on ( 'exit' , function ( ) { console . error ( message ) ; } ) ; process . on ( 'SIGINT' , function ( ) { console . error ( '\\n' + message ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------------ Validate and add in templates directory source . ------------------------------------------------------------------------ [CODESPLIT] function ( cb ) { var templatesDir = self . data . _templatesDir ; var templatesPath = path . join ( self . src , \"extracted\" , templatesDir ) ; fs . stat ( templatesPath , function ( err , stats ) { if ( err ) { if ( err . code === \"ENOENT\" ) { return void cb ( new Error ( \"Templates path '\" + templatesPath + \"' directory not found\" ) ) ; } return void cb ( err ) ; } if ( ! stats . isDirectory ( ) ) { return void cb ( new Error ( \"Templates path '\" + templatesPath + \"' exists, but is not a directory\" ) ) ; } cb ( null , templatesPath ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------------ Require empty target destination . ------------------------------------------------------------------------ [CODESPLIT] function ( cb ) { fs . stat ( self . dest , function ( err ) { if ( err ) { // Proxy all errors except not found. return void cb ( err . code === \"ENOENT\" ? null : err ) ; } // Otherwise exists. cb ( new Error ( \"Path: \" + self . dest + \" already exists\" ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Install an npm package ( [ str ] |str obj obj fn ) - > null [CODESPLIT] function npmInstallPackage ( deps , opts , cb ) { if ( ! cb ) { cb = opts opts = { } } deps = Array . isArray ( deps ) ? deps : [ deps ] opts = opts || opts cb = cb || noop var args = [ ] if ( opts . save ) args . push ( '-S' ) if ( opts . saveDev ) args . push ( '-D' ) if ( opts . global ) args . push ( '-g' ) if ( opts . cache ) args . push ( '--cache-min Infinity' ) if ( opts . silent === false ) { deps . forEach ( function ( dep ) { process . stdout . write ( 'pkg: ' + dep + '\\n' ) } ) } var cliArgs = [ 'npm i' ] . concat ( args , deps ) . join ( ' ' ) exec ( cliArgs , function ( err , name ) { if ( err ) return cb ( err ) cb ( ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap a function in a fiber . Correctly handles expected presence of done callback [CODESPLIT] function fiberize ( fn ) { return function ( done ) { var self = this ; Fiber ( function ( ) { try { if ( fn . length == 1 ) { fn . call ( self , done ) ; } else { fn . call ( self ) ; done ( ) ; } } catch ( e ) { process . nextTick ( function ( ) { throw ( e ) ; } ) ; } } ) . run ( ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find matches for a regular expression in a string and push their details to parts Type is a for IDs b for classes attributes and pseudo - classes and c for elements and pseudo - elements [CODESPLIT] function ( regex , type , types , selector ) { var matches = selector . match ( regex ) ; if ( matches ) { for ( var i = 0 ; i < matches . length ; i ++ ) { types [ type ] ++ ; // Replace this simple selector with whitespace so it won't be counted in further simple selectors selector = selector . replace ( matches [ i ] , ' ' ) ; } } return selector ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the specificity for a selector by dividing it into simple selectors and counting them [CODESPLIT] function ( selector ) { var commaIndex = selector . indexOf ( ',' ) ; if ( commaIndex !== - 1 ) { selector = selector . substring ( 0 , commaIndex ) ; } var types = { a : 0 , b : 0 , c : 0 } ; // Remove the negation psuedo-class (:not) but leave its argument because specificity is calculated on its argument selector = selector . replace ( notRegex , ' $1 ' ) ; // Remove anything after a left brace in case a user has pasted in a rule, not just a selector selector = selector . replace ( ruleRegex , ' ' ) ; // Add attribute selectors to parts collection (type b) selector = findMatch ( attributeRegex , 'b' , types , selector ) ; // Add ID selectors to parts collection (type a) selector = findMatch ( idRegex , 'a' , types , selector ) ; // Add class selectors to parts collection (type b) selector = findMatch ( classRegex , 'b' , types , selector ) ; // Add pseudo-element selectors to parts collection (type c) selector = findMatch ( pseudoElementRegex , 'c' , types , selector ) ; // Add pseudo-class selectors to parts collection (type b) selector = findMatch ( pseudoClassRegex , 'b' , types , selector ) ; // Remove universal selector and separator characters selector = selector . replace ( separatorRegex , ' ' ) ; // Remove any stray dots or hashes which aren't attached to words // These may be present if the user is live-editing this selector selector = selector . replace ( straysRegex , ' ' ) ; // The only things left should be element selectors (type c) findMatch ( elementRegex , 'c' , types , selector ) ; return ( types . a * 100 ) + ( types . b * 10 ) + ( types . c * 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@function can - log / dev . stringify stringify @parent can - log @description @hide [CODESPLIT] function ( value ) { var flagUndefined = function flagUndefined ( key , value ) { return value === undefined ? \"/* void(undefined) */\" : value ; } ; return JSON . stringify ( value , flagUndefined , \"  \" ) . replace ( / \"\\/\\* void\\(undefined\\) \\*\\/\" / g , \"undefined\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an index to a collection [CODESPLIT] function ( collectionName , indexName , columns , unique , callback ) { var options = { indexName : indexName , columns : columns , unique : unique } ; return this . _run ( 'createIndex' , collectionName , options ) . nodeify ( callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a migration record into the migration collection [CODESPLIT] function ( name , callback ) { return this . _run ( 'insert' , this . internals . migrationTable , { name : name , run_on : new Date ( ) } ) . nodeify ( callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a seeder record into the seeder collection [CODESPLIT] function ( name , callback ) { return this . _run ( 'insert' , this . internals . seedTable , { name : name , run_on : new Date ( ) } ) . nodeify ( callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a connection and runs a mongo command and returns the results [CODESPLIT] function ( command , collection , options , callback ) { var args = this . _makeParamArgs ( arguments ) , sort = null , callback = args [ 2 ] ; log . sql . apply ( null , arguments ) ; if ( options && typeof ( options ) === 'object' ) { if ( options . sort ) sort = options . sort ; } if ( this . internals . dryRun ) { return Promise . resolve ( ) . nodeify ( callback ) ; } return new Promise ( function ( resolve , reject ) { var prCB = function ( err , data ) { return ( err ? reject ( err ) : resolve ( data ) ) ; } ; // Get a connection to mongo this . connection . connect ( this . connectionString , function ( err , db ) { if ( err ) { prCB ( err ) ; } // Callback function to return mongo records var callbackFunction = function ( err , data ) { if ( err ) { prCB ( err ) ; } prCB ( null , data ) ; db . close ( ) ; } ; // Depending on the command, we need to use different mongo methods switch ( command ) { case 'find' : if ( sort ) { db . collection ( collection ) [ command ] ( options . query ) . sort ( sort ) . toArray ( callbackFunction ) ; } else { db . collection ( collection ) [ command ] ( options ) . toArray ( callbackFunction ) ; } break ; case 'renameCollection' : db [ command ] ( collection , options . newCollection , callbackFunction ) ; break ; case 'createIndex' : db [ command ] ( collection , options . columns , { name : options . indexName , unique : options . unique } , callbackFunction ) ; break ; case 'dropIndex' : db . collection ( collection ) [ command ] ( options . indexName , callbackFunction ) ; break ; case 'insert' : // options is the records to insert in this case if ( util . isArray ( options ) ) db . collection ( collection ) . insertMany ( options , { } , callbackFunction ) ; else db . collection ( collection ) . insertOne ( options , { } , callbackFunction ) ; break ; case 'remove' : // options is the records to insert in this case if ( util . isArray ( options ) ) db . collection ( collection ) . deleteMany ( options , callbackFunction ) ; else db . collection ( collection ) . deleteOne ( options , callbackFunction ) ; break ; case 'collections' : db . collections ( callbackFunction ) ; break ; case 'indexInformation' : db . indexInformation ( collection , callbackFunction ) ; break ; case 'dropDatabase' : db . dropDatabase ( callbackFunction ) ; break ; case 'update' : db . collection ( collection ) [ command ] ( options . query , options . update , options . options , callbackFunction ) ; break ; case 'updateMany' : db . collection ( collection ) [ command ] ( options . query , options . update , options . options , callbackFunction ) ; break ; case 'getDbInstance' : prCB ( null , db ) ; // When the user wants to get the DB instance we need to return the promise callback, so the DB connection is not automatically closed break ; default : db [ command ] ( collection , callbackFunction ) ; break ; } } ) ; } . bind ( this ) ) . nodeify ( callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback function to return mongo records [CODESPLIT] function ( err , data ) { if ( err ) { prCB ( err ) ; } prCB ( null , data ) ; db . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns default params overrides if provided with values [CODESPLIT] function parseParameters ( options ) { var opt = { maximumAge : 0 , enableHighAccuracy : true , timeout : Infinity , interval : 6000 , fastInterval : 1000 , priority : PRIORITY_HIGH_ACCURACY } ; if ( options ) { if ( options . maximumAge !== undefined && ! isNaN ( options . maximumAge ) && options . maximumAge > 0 ) { opt . maximumAge = options . maximumAge ; } if ( options . enableHighAccuracy !== undefined ) { opt . enableHighAccuracy = options . enableHighAccuracy ; } if ( options . timeout !== undefined && ! isNaN ( options . timeout ) ) { if ( options . timeout < 0 ) { opt . timeout = 0 ; } else { opt . timeout = options . timeout ; } } if ( options . interval !== undefined && ! isNaN ( options . interval ) && options . interval > 0 ) { opt . interval = options . interval ; } if ( options . fastInterval !== undefined && ! isNaN ( options . fastInterval ) && options . fastInterval > 0 ) { opt . fastInterval = options . fastInterval ; } if ( options . priority !== undefined && ! isNaN ( options . priority ) && options . priority >= PRIORITY_NO_POWER && options . priority <= PRIORITY_HIGH_ACCURACY ) { if ( options . priority === PRIORITY_NO_POWER ) { opt . priority = PRIORITY_NO_POWER ; } if ( options . priority === PRIORITY_LOW_POWER ) { opt . priority = PRIORITY_LOW_POWER ; } if ( options . priority === PRIORITY_BALANCED_POWER_ACCURACY ) { opt . priority = PRIORITY_BALANCED_POWER_ACCURACY ; } if ( options . priority === PRIORITY_HIGH_ACCURACY ) { opt . priority = PRIORITY_HIGH_ACCURACY ; } } } return opt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests whether the given props object contains a property with the name of propNameOrFunction . [CODESPLIT] function noProp ( props , propNameOrFunction ) { if ( ! props ) { throw new Error ( 'Headful: You must pass all declared props when you use headful.props.x() calls.' ) ; } const propName = typeof propNameOrFunction === 'function' ? propNameOrFunction . name : propNameOrFunction ; return ! props . hasOwnProperty ( propName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GifCli Converts the gif file into ASCII frames . [CODESPLIT] function GifCli ( path , callback ) { var frames = [ ] ; OneByOne ( [ Tmp . dir , function ( next , tmpDir ) { var str = Fs . createReadStream ( path ) , isFinished = false , complete = [ ] , i = 0 ; str . on ( \"end\" , function ( ) { isFinished = true ; } ) ; str . pipe ( GifExplode ( function ( frame ) { Tmp . file ( { postfix : \".gif\" , } , function ( err , cImg ) { ( function ( i , cImg ) { if ( err ) { return next ( err ) ; } var wStr = Fs . createWriteStream ( cImg ) ; frame . pipe ( wStr ) ; complete [ i ] = false ; wStr . on ( \"close\" , function ( ) { // TODO Allow passing options ImageToAscii ( cImg , function ( err , asciified ) { complete [ i ] = true ; frames [ i ] = asciified || \"\" ; // TODO https://github.com/hughsk/gif-explode/issues/4 //if (err) { return next(err); } if ( ! isFinished ) { return ; } if ( ! complete . filter ( function ( c ) { return c !== true } ) . length ) { next ( ) ; } } ) ; } ) ; } ) ( i ++ , cImg ) ; } ) ; } ) ) ; } , function ( next ) { frames = frames . filter ( Boolean ) ; next ( ) ; } ] , function ( err ) { if ( err ) { return callback ( err ) ; } callback ( null , frames ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assert ( test? : boolean message? : string optionalParams : any [] ) : void ; [CODESPLIT] function ( test , message , optionalParams ) { return invoke ( 'CONSOLE' , { type : 'assert' , test : test , message : message , optionalParams : optionalParams || [ ] } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test functional [CODESPLIT] function operationDataBase ( webview , db ) { console . log ( 'open then' ) ; db . executeSql ( 'SELECT 1 FROM Version LIMIT 1' ) . then ( function ( result ) { console . log ( 'executeSql then' ) ; console . log ( result ) ; function queryEmployees ( tx ) { console . log ( \"Executing employee query\" ) ; tx . executeSql ( 'SELECT a.name, b.name as deptName FROM Employees a, Departments b WHERE a.department = b.department_id' ) . then ( ( [ tx , results ] ) => { var payload = { } payload . result = [ ] payload . type = 'OPERATION_DATABASEE_DONE_QUERY_DB' ; var len = results . rows . length ; for ( let i = 0 ; i < len ; i ++ ) { let row = results . rows . item ( i ) ; payload . result . push ( row ) } webview . postMessage ( JSON . stringify ( payload ) ) ; } ) . catch ( ( error ) => { console . log ( error ) ; } ) ; } db . transaction ( queryEmployees ) . then ( ( ) => { console . log ( 'query done.' ) } ) ; } ) . catch ( function ( err ) { console . log ( 'executeSql catch' ) ; console . log ( err ) ; db . transaction ( function ( tx ) { tx . executeSql ( 'DROP TABLE IF EXISTS Employees;' ) ; tx . executeSql ( 'DROP TABLE IF EXISTS Offices;' ) ; tx . executeSql ( 'DROP TABLE IF EXISTS Departments;' ) ; tx . executeSql ( 'CREATE TABLE IF NOT EXISTS Version( ' + 'version_id INTEGER PRIMARY KEY NOT NULL); ' ) . catch ( ( error ) => { console . log ( error ) ; } ) ; tx . executeSql ( 'CREATE TABLE IF NOT EXISTS Departments( ' + 'department_id INTEGER PRIMARY KEY NOT NULL, ' + 'name VARCHAR(30) ); ' ) . catch ( ( error ) => { console . log ( error ) } ) ; tx . executeSql ( 'CREATE TABLE IF NOT EXISTS Offices( ' + 'office_id INTEGER PRIMARY KEY NOT NULL, ' + 'name VARCHAR(20), ' + 'longtitude FLOAT, ' + 'latitude FLOAT ) ; ' ) . catch ( ( error ) => { console . log ( error ) } ) ; tx . executeSql ( 'CREATE TABLE IF NOT EXISTS Employees( ' + 'employe_id INTEGER PRIMARY KEY NOT NULL, ' + 'name VARCHAR(55), ' + 'office INTEGER, ' + 'department INTEGER, ' + 'FOREIGN KEY ( office ) REFERENCES Offices ( office_id ) ' + 'FOREIGN KEY ( department ) REFERENCES Departments ( department_id ));' ) . catch ( ( error ) => { console . log ( error ) } ) ; tx . executeSql ( 'INSERT INTO Departments (name) VALUES (\"Client Services\");' ) ; tx . executeSql ( 'INSERT INTO Departments (name) VALUES (\"Investor Services\");' ) ; tx . executeSql ( 'INSERT INTO Departments (name) VALUES (\"Shipping\");' ) ; tx . executeSql ( 'INSERT INTO Departments (name) VALUES (\"Direct Sales\");' ) ; tx . executeSql ( 'INSERT INTO Offices (name, longtitude, latitude) VALUES (\"Denver\", 59.8,  34.1);' ) ; tx . executeSql ( 'INSERT INTO Offices (name, longtitude, latitude) VALUES (\"Warsaw\", 15.7, 54.1);' ) ; tx . executeSql ( 'INSERT INTO Offices (name, longtitude, latitude) VALUES (\"Berlin\", 35.3, 12.1);' ) ; tx . executeSql ( 'INSERT INTO Offices (name, longtitude, latitude) VALUES (\"Paris\", 10.7, 14.1);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES (\"Sylvester Stallone\", 2,  4);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES (\"Elvis Presley\", 2, 4);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES (\"Leslie Nelson\", 3,  4);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES (\"Fidel Castro\", 3, 3);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES (\"Bill Clinton\", 1, 3);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES (\"Margaret Thatcher\", 1, 3);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES (\"Donald Trump\", 1, 3);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES (\"Dr DRE\", 2, 2);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES (\"Samantha Fox\", 2, 1);' ) ; console . log ( \"all executed SQL done\" ) ; webview . postMessage ( JSON . stringify ( { type : \"OPERATION_DATABASEE_DONE_CREATE_TABLE_AND_INSERT_DATA\" , result : 'init table done.' } ) ) ; } ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delegate function for each log level [CODESPLIT] function delegate ( method , _args ) { var callPosition = metalogger . callposition ( ) , file , line ; if ( ! metalogger . shouldLog ( method , _level ) ) { return ; } var args = Array . prototype . slice . call ( _args ) ; var message = [ ] ; if ( args . length === 1 ) { message . push ( util . inspect ( args [ 0 ] , { showHidden : true , depth : null } ) ) ; } if ( args . length === 2 ) { message . push ( args . shift ( ) ) ; message . push ( util . inspect ( args [ 0 ] , { showHidden : true , depth : null } ) ) ; } if ( args . length > 2 ) { message . push ( args . shift ( ) ) ; message . push ( util . format . apply ( null , args ) ) ; } try { file = callPosition . split ( ':' ) [ 0 ] . replace ( ' [' , '' ) ; line = callPosition . split ( ':' ) [ 1 ] . replace ( '] ' , '' ) ; } catch ( e ) { // something went wrong with stack trace } var jsonFormat = { timestamp : ( new Date ( ) ) . toISOString ( ) , hostname : os . hostname ( ) , level : method , file : file , line : line , message : message . join ( ' ' ) } ; if ( options . token ) { client . log ( jsonFormat , function ( err ) { if ( err ) { console . error ( 'error occured while logging to loggly' , err ) ; } } ) ; } else { console . error ( 'Loggly auth token not provided' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delegate function for each log level [CODESPLIT] function delegate ( method , _args ) { var callPosition = metalogger . callposition ( ) , file , line ; if ( ! metalogger . shouldLog ( method , _level ) ) { return ; } var args = Array . prototype . slice . call ( _args ) ; var message = '' , inspect = null ; message = util . inspect ( args . shift ( ) , { showHidden : true , depth : null } ) . replace ( / \\n / g , ' ' ) ; inspect = args [ 0 ] ; if ( args . length > 2 ) { inspect = util . format . apply ( null , args ) ; } try { file = callPosition . split ( ':' ) [ 0 ] . replace ( ' [' , '' ) ; line = callPosition . split ( ':' ) [ 1 ] . replace ( '] ' , '' ) ; } catch ( e ) { // something went wrong with stack trace } var jsonFormat = { timestamp : ( new Date ( ) ) . toISOString ( ) , hostname : os . hostname ( ) , level : method , file : file , line : line , debug : inspect } ; if ( bucketDetails . bucket . length !== 0 && bucketDetails . access_key_id . length !== 0 && bucketDetails . secret_access_key . length !== 0 ) { client . write ( util . format ( \"%s %s [host=%s] [message=%s] [message.stream] %s\\n\" , jsonFormat . timestamp , method . toUpperCase ( ) , jsonFormat . hostname , message , JSON . stringify ( jsonFormat ) ) ) ; } else { console . error ( 'Configuration: Sumologic is not configured correctly, please provide `NODE_LOGGER_S3_BUCKET`, `NODE_LOGGER_S3_KEY_ID`, and `NODE_LOGGER_S3_KEY_SECRET` environment variables.' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Should I log? [CODESPLIT] function shouldLog ( testlevel , thresholdLevel ) { var allowed = logLevelAllowedGranular ( testlevel ) ; if ( allowed ) { return true ; } return logLevelAllowed ( testlevel , thresholdLevel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "As opposed to logLevelAllowed () this one doesn t take testlevel since that needs to be figured out in - function . [CODESPLIT] function logLevelAllowedGranular ( testlevel ) { if ( ! _granularlevels ) { return ; } var pos = callpositionObj ( ) ; if ( pos ) { var key = 'NODE_LOGGER_LEVEL_' + pos . filename . replace ( / [\\.\\/] / gi , '_' ) ; if ( key in process . env && process . env [ key ] ) { var thresholdLevel = process . env [ key ] . toLowerCase ( ) ; return logLevelsObj [ testlevel ] <= logLevelsObj [ thresholdLevel ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the true value for this specific checkbox . [CODESPLIT] function ( ) { if ( attrs . type === 'radio' ) { return attrs . value || $parse ( attrs . ngValue ) ( scope ) || true ; } var trueValue = ( $parse ( attrs . ngTrueValue ) ( scope ) ) ; if ( angular . isUndefined ( trueValue ) ) { trueValue = true ; } return trueValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value of the angular - bound attribute given its name . The returned value may or may not equal the attribute value as it may be transformed by a function . [CODESPLIT] function ( attrName ) { var map = { 'switchRadioOff' : getBooleanFromStringDefTrue , 'switchActive' : function ( value ) { return ! getBooleanFromStringDefTrue ( value ) ; } , 'switchAnimate' : getBooleanFromStringDefTrue , 'switchLabel' : function ( value ) { return value ? value : '&nbsp;' ; } , 'switchIcon' : function ( value ) { if ( value ) { return '<span class=\\'' + value + '\\'></span>' ; } } , 'switchWrapper' : function ( value ) { return value || 'wrapper' ; } , 'switchInverse' : getBooleanFromString , 'switchReadonly' : getBooleanFromString , 'switchChange' : getExprFromString } ; var transFn = map [ attrName ] || getValueOrUndefined ; return transFn ( attrs [ attrName ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a bootstrapSwitch parameter according to the angular - bound attribute . The parameter will be changed only if the switch has already been initialized ( to avoid creating it before the model is ready ) . [CODESPLIT] function ( element , attr , modelAttr ) { if ( ! isInit ) { return ; } var newValue = getSwitchAttrValue ( modelAttr ) ; element . bootstrapSwitch ( attr , newValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the directive has not been initialized yet do so . [CODESPLIT] function ( ) { // if it's the first initialization if ( ! isInit ) { var viewValue = ( controller . $modelValue === getTrueValue ( ) ) ; isInit = ! isInit ; // Bootstrap the switch plugin element . bootstrapSwitch ( { radioAllOff : getSwitchAttrValue ( 'switchRadioOff' ) , disabled : getSwitchAttrValue ( 'switchActive' ) , state : viewValue , onText : getSwitchAttrValue ( 'switchOnText' ) , offText : getSwitchAttrValue ( 'switchOffText' ) , onColor : getSwitchAttrValue ( 'switchOnColor' ) , offColor : getSwitchAttrValue ( 'switchOffColor' ) , animate : getSwitchAttrValue ( 'switchAnimate' ) , size : getSwitchAttrValue ( 'switchSize' ) , labelText : attrs . switchLabel ? getSwitchAttrValue ( 'switchLabel' ) : getSwitchAttrValue ( 'switchIcon' ) , wrapperClass : getSwitchAttrValue ( 'switchWrapper' ) , handleWidth : getSwitchAttrValue ( 'switchHandleWidth' ) , labelWidth : getSwitchAttrValue ( 'switchLabelWidth' ) , inverse : getSwitchAttrValue ( 'switchInverse' ) , readonly : getSwitchAttrValue ( 'switchReadonly' ) } ) ; if ( attrs . type === 'radio' ) { controller . $setViewValue ( controller . $modelValue ) ; } else { controller . $setViewValue ( viewValue ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Listen to model changes . [CODESPLIT] function ( ) { attrs . $observe ( 'switchActive' , function ( newValue ) { var active = getBooleanFromStringDefTrue ( newValue ) ; // if we are disabling the switch, delay the deactivation so that the toggle can be switched if ( ! active ) { $timeout ( setActive ) ; } else { // if we are enabling the switch, set active right away setActive ( ) ; } } ) ; // When the model changes controller . $render = function ( ) { initMaybe ( ) ; var newValue = controller . $modelValue ; if ( newValue !== undefined && newValue !== null ) { element . bootstrapSwitch ( 'state' , newValue === getTrueValue ( ) , true ) ; } else { element . bootstrapSwitch ( 'indeterminate' , true , true ) ; controller . $setViewValue ( undefined ) ; } switchChange ( ) ; } ; // angular attribute to switch property bindings var bindings = { 'switchRadioOff' : 'radioAllOff' , 'switchOnText' : 'onText' , 'switchOffText' : 'offText' , 'switchOnColor' : 'onColor' , 'switchOffColor' : 'offColor' , 'switchAnimate' : 'animate' , 'switchSize' : 'size' , 'switchLabel' : 'labelText' , 'switchIcon' : 'labelText' , 'switchWrapper' : 'wrapperClass' , 'switchHandleWidth' : 'handleWidth' , 'switchLabelWidth' : 'labelWidth' , 'switchInverse' : 'inverse' , 'switchReadonly' : 'readonly' } ; var observeProp = function ( prop , bindings ) { return function ( ) { attrs . $observe ( prop , function ( ) { setSwitchParamMaybe ( element , bindings [ prop ] , prop ) ; } ) ; } ; } ; // for every angular-bound attribute, observe it and trigger the appropriate switch function for ( var prop in bindings ) { attrs . $observe ( prop , observeProp ( prop , bindings ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Listen to view changes . [CODESPLIT] function ( ) { if ( attrs . type === 'radio' ) { // when the switch is clicked element . on ( 'change.bootstrapSwitch' , function ( e ) { // discard not real change events if ( ( controller . $modelValue === controller . $viewValue ) && ( e . target . checked !== $ ( e . target ) . bootstrapSwitch ( 'state' ) ) ) { // $setViewValue --> $viewValue --> $parsers --> $modelValue // if the switch is indeed selected if ( e . target . checked ) { // set its value into the view controller . $setViewValue ( getTrueValue ( ) ) ; } else if ( getTrueValue ( ) === controller . $viewValue ) { // otherwise if it's been deselected, delete the view value controller . $setViewValue ( undefined ) ; } switchChange ( ) ; } } ) ; } else { // When the checkbox switch is clicked, set its value into the ngModel element . on ( 'switchChange.bootstrapSwitch' , function ( e ) { // $setViewValue --> $viewValue --> $parsers --> $modelValue controller . $setViewValue ( e . target . checked ) ; switchChange ( ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * localize natives [CODESPLIT] function ( msg ) { if ( typeof scope . console === 'object' && scope . console !== null && typeof scope . console . warn === 'function' ) { warn = function ( msg ) { scope . console . warn ( msg ) ; } ; warn ( msg ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * localize natives [CODESPLIT] function ( o ) { var r , e ; if ( typeof o !== 'object' || o === null ) { r = default_options ; } else { r = { expires : default_options . expires , path : default_options . path , domain : default_options . domain , secure : default_options . secure } ; /*\n                     * I've been very finicky about the name and format of the expiration option over time,\n                     * so I'm accounting for older styles to maintain backwards compatibility. Preferably it\n                     * will be called \"expires\" and will be an instance of Date\n                     */ if ( typeof o . expires === 'object' && o . expires instanceof Date ) { r . expires = o . expires ; } else if ( typeof o . expires_at === 'object' && o . expires_at instanceof Date ) { r . expires = o . expires_at ; warn ( 'Cookie option \"expires_at\" has been deprecated. Rename to \"expires\". Support for \"expires_at\" will be removed in a version to come.' ) ; } else if ( typeof o . expiresAt === 'object' && o . expiresAt instanceof Date ) { r . expires = o . expiresAt ; warn ( 'Cookie option \"expiresAt\" has been deprecated. Rename to \"expires\". Support for \"expiresAt\" will be removed in a version to come.' ) ; } else if ( typeof o . hoursToLive === 'number' && o . hoursToLive !== 0 ) { e = new Date ( ) ; e . setTime ( e . getTime ( ) + ( o . hoursToLive * 60 * 60 * 1000 ) ) ; r . expires = e ; warn ( 'Cookie option \"hoursToLive\" has been deprecated. Rename to \"expires\" and prodvide a Date instance (see documentation). Support for \"hoursToLive\" will be removed in a version to come.' ) ; } if ( typeof o . path === 'string' && o . path !== '' ) { r . path = o . path ; } if ( typeof o . domain === 'string' && o . domain !== '' ) { r . domain = o . domain ; } if ( o . secure === true ) { r . secure = o . secure ; } } return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * localize natives [CODESPLIT] function ( o ) { o = resolveOptions ( o ) ; return ( [ ( typeof o . expires === 'object' && o . expires instanceof Date ? '; expires=' + o . expires . toGMTString ( ) : '' ) , ( '; path=' + o . path ) , ( typeof o . domain === 'string' ? '; domain=' + o . domain : '' ) , ( o . secure === true ? '; secure' : '' ) ] . join ( '' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get - get one several or all cookies [CODESPLIT] function ( n ) { var r , i , c = parseCookies ( ) ; if ( typeof n === 'string' ) { r = ( c [ n ] !== undef ) ? c [ n ] : null ; } else if ( typeof n === 'object' && n !== null ) { r = { } ; for ( i in n ) { if ( Object . prototype . hasOwnProperty . call ( n , i ) ) { if ( c [ n [ i ] ] !== undef ) { r [ n [ i ] ] = c [ n [ i ] ] ; } else { r [ n [ i ] ] = null ; } } } } else { r = c ; } return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "filter - get array of cookies whose names match the provided RegExp [CODESPLIT] function ( p ) { var n , r = { } , c = parseCookies ( ) ; if ( typeof p === 'string' ) { p = new RegExp ( p ) ; } for ( n in c ) { if ( Object . prototype . hasOwnProperty . call ( c , n ) && n . match ( p ) ) { r [ n ] = c [ n ] ; } } return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set - set or delete a cookie with desired options [CODESPLIT] function ( n , v , o ) { if ( typeof o !== 'object' || o === null ) { o = { } ; } if ( v === undef || v === null ) { v = '' ; o . expires = new Date ( ) ; o . expires . setFullYear ( 1978 ) ; } else { /* Logic borrowed from http://jquery.com/ dataAttr method and reversed */ v = ( v === true ) ? 'true' : ( v === false ) ? 'false' : ! isNaN ( v ) ? String ( v ) : v ; if ( typeof v !== 'string' ) { if ( typeof JSON === 'object' && JSON !== null && typeof JSON . stringify === 'function' ) { v = JSON . stringify ( v ) ; } else { throw new Error ( 'cookies.set() could not be serialize the value' ) ; } } } document . cookie = n + '=' + encodeURIComponent ( v ) + cookieOptions ( o ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "del - delete a cookie ( domain and path options must match those with which the cookie was set ; this is really an alias for set () with parameters simplified for this use ) [CODESPLIT] function ( n , o ) { var d = { } , i ; if ( typeof o !== 'object' || o === null ) { o = { } ; } if ( typeof n === 'boolean' && n === true ) { d = this . get ( ) ; } else if ( typeof n === 'string' ) { d [ n ] = true ; } for ( i in d ) { if ( Object . prototype . hasOwnProperty . call ( d , i ) && typeof i === 'string' && i !== '' ) { this . set ( i , null , o ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "test - test whether the browser is accepting cookies [CODESPLIT] function ( ) { var r = false , n = 'test_cookies_jaaulde_js' , v = 'data' ; this . set ( n , v ) ; if ( this . get ( n ) === v ) { this . del ( n ) ; r = true ; } return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shared functions Allow an error message to retain its color when split across multiple lines . [CODESPLIT] function formatMessage ( str ) { return String ( str ) . split ( '\\n' ) . map ( function ( s ) { return s . magenta ; } ) . join ( '\\n' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////// Apply earlier zoom [CODESPLIT] function applyZoom ( options , chart ) { if ( angular . isObject ( options . state ) && angular . isObject ( options . state ) && angular . isArray ( options . state . range ) ) { chart . zoom ( options . state . range ) ; } else { chart . unzoom ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create nested options objects . [CODESPLIT] function createZoomRangePath ( options ) { if ( ! angular . isObject ( options . state ) ) { options . state = { } ; } if ( ! angular . isObject ( options . state . range ) ) { options . state . range = [ ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup zoom event listeners which update the state [CODESPLIT] function synchronizeZoom ( options , configuration , watcher ) { if ( angular . isObject ( options . chart ) && angular . isObject ( options . chart . zoom ) && options . chart . zoom . enabled === true ) { // setup onzoomend listener configuration . zoom . onzoomend = function ( domain ) { // update state AngularChartWatcher . updateState ( watcher , function ( ) { createZoomRangePath ( options ) ; options . state . range = domain ; } ) ; // call user defined callback if ( angular . isFunction ( options . chart . zoom . onzoomend ) ) { AngularChartWatcher . applyFunction ( watcher , function ( ) { options . chart . zoom . onzoomend ( domain ) ; } ) ; } } ; } if ( angular . isObject ( options . chart ) && angular . isObject ( options . chart . subchart ) && options . chart . subchart . show === true ) { // setup onbrush listener configuration . subchart . onbrush = function ( domain ) { // update state AngularChartWatcher . updateState ( watcher , function ( ) { createZoomRangePath ( options ) ; options . state . range = domain ; } ) ; // call user defined callback if ( angular . isFunction ( options . chart . subchart . onbrush ) ) { AngularChartWatcher . applyFunction ( watcher , function ( ) { options . chart . subchart . onbrush ( domain ) ; } ) ; } } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add passed selection to the chart . [CODESPLIT] function addSelections ( chart , selections ) { service . disableSelectionListener = true ; selections . forEach ( function ( selection ) { chart . select ( [ selection . id ] , [ selection . index ] ) ; } ) ; service . disableSelectionListener = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove passed selections from the chart . function removeSelections ( chart selections ) { disableSelectionListener = true ; selections . forEach ( function ( selection ) { chart . unselect ( [ selection . id ] [ selection . index ] ) ; } ) ; disableSelectionListener = false ; } Remove all selections present in the chart . [CODESPLIT] function removeAllSelections ( chart ) { service . disableSelectionListener = true ; chart . unselect ( ) ; service . disableSelectionListener = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply earlier selections . [CODESPLIT] function applySelection ( options , chart ) { if ( angular . isObject ( options . state ) && angular . isArray ( options . state . selected ) ) { // TODO: get new selections // TODO: get removed selections // var chartSelections = chart.selected(); //    // addedSelections //    var addedSelections = newSelections.filter(function (elm) { //      var isNew = true; //      oldSelections.forEach(function (old) { //        if (old.id === elm.id && old.index === elm.index) { //          isNew = false; //          return isNew; //        } //      }); //      return isNew; //    }); // //    // removedSelections //    var removedSelections = oldSelections.filter(function (elm) { //      var isOld = true; //      newSelections.forEach(function (old) { //        if (old.id === elm.id && old.index === elm.index) { //          isOld = false; //          return isOld; //        } //      }); //      return isOld; //    }); // alternative: deselect all and select again //removeAllSelections(chart); addSelections ( chart , options . state . selected ) ; } else { removeAllSelections ( chart ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create nested options object . [CODESPLIT] function createSelectionsPath ( options ) { if ( ! angular . isObject ( options . state ) ) { options . state = { } ; } if ( ! angular . isArray ( options . state . selected ) ) { options . state . selected = [ ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Listen to chart events to save selections into to state object . [CODESPLIT] function synchronizeSelection ( options , configuration , watcher ) { if ( angular . isObject ( options . chart ) && angular . isObject ( options . chart . data ) && angular . isObject ( options . chart . data . selection ) && options . chart . data . selection . enabled === true ) { // add onselected listener configuration . data . onselected = function ( data , element ) { // check if listener is disabled currently if ( service . disableSelectionListener ) { return ; } // update state AngularChartWatcher . updateState ( watcher , function ( ) { createSelectionsPath ( options ) ; options . state . selected . push ( data ) ; } ) ; // call user defined callback if ( angular . isFunction ( options . chart . data . onselected ) ) { AngularChartWatcher . applyFunction ( watcher , function ( ) { options . chart . data . onselected ( data , element ) ; } ) ; } } ; // add onunselection listener configuration . data . onunselected = function ( data , element ) { // check if listener is disabled currently if ( service . disableSelectionListener ) { return ; } // update state AngularChartWatcher . updateState ( watcher , function ( ) { createSelectionsPath ( options ) ; options . state . selected = options . state . selected . filter ( function ( selected ) { return selected . id !== data . id || selected . index !== data . index ; } ) ; } ) ; // call user defined callback if ( angular . isFunction ( options . chart . data . onunselected ) ) { AngularChartWatcher . applyFunction ( watcher , function ( ) { options . chart . data . onunselected ( data , element ) ; } ) ; } } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////// [CODESPLIT] function init ( scope ) { var watcher = { scope : scope , dimensionsCallback : null , dimensionsTypeCallback : null , chartCallback : null , stateCallback : null , dataCallback : null , dataSmallWatcher : null , dataBigWatcher : null , disableStateWatcher : false } ; setupDimensionsWatcher ( watcher ) ; setupDimensionsTypeWatcher ( watcher ) ; setupChartWatcher ( watcher ) ; setupStateWatcher ( watcher ) ; setupWatchLimitWatcher ( watcher ) ; setupDataWatcher ( watcher ) ; return watcher ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "// SETUP // [CODESPLIT] function setupDimensionsWatcher ( watcher ) { watcher . scope . $watch ( function ( ) { var check = watcher . scope . options && watcher . scope . options . dimensions ; // remove types from copy to check only other changes if ( angular . isObject ( check ) ) { check = angular . copy ( check ) ; angular . forEach ( check , function ( dimension ) { if ( dimension . type ) { delete dimension . type ; } } ) ; } return check ; } , function ( ) { if ( angular . isFunction ( watcher . dimensionsCallback ) ) { watcher . dimensionsCallback ( ) ; } } , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start watcher changes in small datasets compares whole object [CODESPLIT] function setupDataSmallWatcher ( watcher ) { return watcher . scope . $watch ( 'options.data' , function ( ) { if ( angular . isFunction ( watcher . dataCallback ) ) { watcher . dataCallback ( ) ; } setupDataWatcher ( watcher ) ; } , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start watcher changes in big datasets compares length of records [CODESPLIT] function setupDataBigWatcher ( watcher ) { return watcher . scope . $watch ( function ( ) { if ( watcher . scope . options . data && angular . isArray ( watcher . scope . options . data ) ) { return watcher . scope . options . data . length ; } else { return 0 ; } } , function ( ) { if ( angular . isFunction ( watcher . dataCallback ) ) { watcher . dataCallback ( ) ; } setupDataWatcher ( watcher ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "// $apply // [CODESPLIT] function updateState ( watcher , func ) { watcher . disableStateWatcher = true ; watcher . scope . $apply ( func ) ; watcher . disableStateWatcher = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////// [CODESPLIT] function convertData ( options , configuration ) { // TODO support different data formats if ( angular . isArray ( options . data ) ) { configuration . data . json = options . data ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add unique identifier for each chart [CODESPLIT] function addIdentifier ( ) { $scope . dataAttributeChartID = 'chartid' + Math . floor ( Math . random ( ) * 1000000001 ) ; angular . element ( $element ) . attr ( 'id' , $scope . dataAttributeChartID ) ; configuration . bindto = '#' + $scope . dataAttributeChartID ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Redux thunk action creator for performing asynchronous actions . [CODESPLIT] function loadEntity ( name , promise , options ) { if ( ! name || typeof name !== 'string' ) throw new Error ( 'Missing required entity name' ) ; if ( ! promise || ! promise . then ) throw new Error ( 'Missing required entity promise' ) ; try { ! ( 0 , _validateOptions . default ) ( options ) ; } catch ( error ) { throw error ; } var entityLifecycle = new _entityLifecycle . default ( name , options ) ; return function ( dispatch , getState ) { entityLifecycle . setDispatch ( dispatch ) ; entityLifecycle . setGetState ( getState ) ; entityLifecycle . onLoad ( ) ; return new Promise ( function ( resolve , reject ) { promise . then ( function ( data ) { resolve ( entityLifecycle . onSuccess ( data ) ) ; } ) . catch ( function ( error ) { reject ( entityLifecycle . onFailure ( error ) ) ; } ) ; } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generation a Redux action object [CODESPLIT] function generateAction ( action , keys , values ) { var generatedAction = Object . assign ( { } , action ) ; keys . forEach ( function ( arg , index ) { generatedAction [ keys [ index ] ] = values [ index ] ; } ) ; return generatedAction ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate action creators based on input arguments . The first argument is always treated as the Redux action type ; all other passed arguments are treated as property on the action object itself . [CODESPLIT] function makeActionCreator ( type ) { for ( var _len = arguments . length , keys = new Array ( _len > 1 ? _len - 1 : 0 ) , _key = 1 ; _key < _len ; _key ++ ) { keys [ _key - 1 ] = arguments [ _key ] ; } if ( ! type ) throw new Error ( 'Type cannot be null/undefined' ) ; return function ( ) { for ( var _len2 = arguments . length , values = new Array ( _len2 ) , _key2 = 0 ; _key2 < _len2 ; _key2 ++ ) { values [ _key2 ] = arguments [ _key2 ] ; } return generateAction ( { type : type } , keys , values ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identical to makeActionCreator () however this function expects the second argument to be the name of an entity . [CODESPLIT] function makeEntityActionCreator ( type , entity ) { for ( var _len3 = arguments . length , keys = new Array ( _len3 > 2 ? _len3 - 2 : 0 ) , _key3 = 2 ; _key3 < _len3 ; _key3 ++ ) { keys [ _key3 - 2 ] = arguments [ _key3 ] ; } if ( ! type ) throw new Error ( 'Type cannot be null/undefined' ) ; if ( ! entity ) throw new Error ( 'Entity cannot be null/undefined' ) ; return function ( ) { for ( var _len4 = arguments . length , values = new Array ( _len4 ) , _key4 = 0 ; _key4 < _len4 ; _key4 ++ ) { values [ _key4 ] = arguments [ _key4 ] ; } return generateAction ( { type : type , entity : entity } , keys , values ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a random number in a given range and round to a given value [CODESPLIT] function _getRandomDelayBetween ( min , max , roundTo ) { return Number ( Math . random ( ) * ( max - min ) + min ) . toFixed ( roundTo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log Redux actions [CODESPLIT] function _logDetails ( action ) { if ( action ) { console . log ( ` ${ chalk . white . bgRed ( '  Prev State:' ) } ${ __toString ( state ) } ` ) ; console . log ( ` ${ chalk . white . bgBlue ( '      Action:' ) } ${ __toString ( action ) } ` ) ; } else { console . log ( ` ${ chalk . white . bgGreen ( '  Next State:' ) } ${ __toString ( state ) } ` ) ; console . log ( '\\n' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "to create a push parser pass in a callback function and omit the context parameter to create a pull parser pass in null for the callback function and initially provide an empty object as the context [CODESPLIT] function jgeParse ( s , callback , context ) { if ( context && context . newState ) { if ( ! context . keepToken ) context . token = '' ; context . state = context . newState ; } else { context = { } ; reset ( context ) ; } var c ; for ( var i = context . position ; i < s . length ; i ++ ) { c = s . charAt ( i ) ; if ( ( c . charCodeAt ( 0 ) < 32 ) && ( context . validControlChars . indexOf ( c ) < 0 ) ) { context . newState = context . state = sError ; } if ( context . state != sContent ) { if ( context . validControlChars . indexOf ( c ) >= 0 ) { //other unicode spaces are not treated as whitespace c = ' ' ; } } context . bIndex = - 1 ; for ( var b = 0 ; b < context . boundary . length ; b ++ ) { if ( s . substr ( i , context . boundary [ b ] . length ) == context . boundary [ b ] ) { context . bIndex = b ; if ( context . boundary [ context . bIndex ] . length > 1 ) { i = i + context . boundary [ context . bIndex ] . length - 1 ; } break ; } } if ( context . bIndex >= 0 ) { if ( ( context . state != sValue ) && ( context . state != sComment ) ) { // && (context.state != sContent) context . token = context . token . trim ( ) ; } context . keepToken = false ; if ( ( ( context . state & 1 ) == 1 ) && ( ( context . token . trim ( ) !== '' ) || context . state == sValue ) ) { // TODO test element names for validity (using regex?) if ( context . state != sCData ) { context . token = context . token . replaceAll ( '&amp;' , '&' ) ; context . token = context . token . replaceAll ( '&quot;' , '\"' ) ; context . token = context . token . replaceAll ( '&apos;' , \"'\" ) ; context . token = context . token . replaceAll ( '&gt;' , '>' ) ; context . token = context . token . replaceAll ( '&lt;' , '<' ) ; if ( context . token . indexOf ( '&#' ) >= 0 ) { context . token = context . token . replace ( / &(?:#([0-9]+)|#x([0-9a-fA-F]+)); / g , function ( match , group1 , group2 ) { var e ; if ( group2 ) { e = String . fromCharCode ( parseInt ( group2 , 16 ) ) ; if ( ( e . charCodeAt ( 0 ) < 32 ) && ( context . validControlChars . indexOf ( e ) < 0 ) ) { context . newState = context . state = sError ; } return e ; } else { e = String . fromCharCode ( group1 ) ; if ( ( e . charCodeAt ( 0 ) < 32 ) && ( context . validControlChars . indexOf ( e ) < 0 ) ) { context . newState = context . state = sError ; } return e ; } } ) ; } } if ( context . state == sElement ) context . depth ++ ; else if ( context . state == sEndElement ) { context . depth -- ; if ( context . depth < 0 ) { context . newState = context . state = sError ; } } if ( context . state == sError ) { context . error = true ; } if ( callback ) { callback ( context . state , context . token ) ; } if ( context . state == sError ) { context . boundary = [ ] ; } } if ( context . state == sInitial ) { if ( context . boundary [ context . bIndex ] == '<?' ) { context . newState = sDeclaration ; context . boundary = [ '?>' ] ; } else { context . newState = sElement ; context . boundary = [ '>' , ' ' , '/' , '!--' , '?' , '!DOCTYPE' , '![CDATA[' ] ; context . boundary = context . boundary . concat ( context . validControlChars ) ; } } else if ( context . state == sDeclaration ) { context . newState = sPreElement ; context . boundary = [ '<' ] ; if ( context . token . indexOf ( '1.1' ) > 0 ) { context . validControlChars . push ( '\\u2028' , '\\u0085' , '\\u0015' ) ; } } else if ( context . state == sPreElement ) { context . newState = sElement ; context . boundary = [ '>' , ' ' , '/' , '!--' , '?' , '!DOCTYPE' , '![CDATA[' ] ; context . boundary = context . boundary . concat ( context . validControlChars ) ; } else if ( context . state == sElement ) { context . lastElement = context . token ; if ( c == '>' ) { context . newState = sContent ; context . boundary = [ '<!DOCTYPE' , '<' ] ; } else if ( c == ' ' ) { context . newState = sAttribute ; context . boundary = [ '/' , '=' , '>' ] ; } else if ( c == '/' ) { context . newState = sEndElement ; context . boundary = [ '>' ] ; context . keepToken = true ; } else if ( c == '?' ) { context . newState = sProcessingInstruction ; context . boundary = [ '?>' ] ; } else if ( context . boundary [ context . bIndex ] == '!--' ) { context . newState = sComment ; context . boundary = [ '-->' ] ; } else if ( context . boundary [ context . bIndex ] == '![CDATA[' ) { context . newState = sCData ; context . boundary = [ ']]>' ] ; } else if ( context . boundary [ context . bIndex ] == '!DOCTYPE' ) { context . newState = sDocType ; context . boundary = [ '>' , '[' ] ; } } else if ( context . state == sAttribute ) { if ( c == '=' ) { context . newState = sAttrNML ; context . boundary = [ '\\'' , '\"' ] ; } else if ( c == '>' ) { context . newState = sContent ; context . boundary = [ '<!DOCTYPE' , '<' ] ; } else if ( c == '/' ) { context . newState = sEndElement ; context . keepToken = true ; context . state = sAttributeSpacer ; // to stop dummy attributes being emitted to pullparser context . token = context . lastElement ; } } else if ( context . state == sAttrNML ) { context . newState = sValue ; context . boundary = [ c ] ; } else if ( context . state == sValue ) { context . newState = sAttribute ; context . boundary = [ '=' , '/' , '>' ] ; } else if ( context . state == sEndElement ) { if ( context . depth !== 0 ) context . newState = sContent ; context . boundary = [ '<' ] ; // don't allow DOCTYPE's after the first sEndElement } else if ( context . state == sContent ) { if ( context . boundary [ context . bIndex ] == '<!DOCTYPE' ) { context . newState = sDocType ; context . boundary = [ '>' , '[' ] ; } else { context . newState = sElement ; context . boundary = [ '>' , ' ' , '/' , '!--' , '?' , '![CDATA[' ] ; context . boundary = context . boundary . concat ( context . validControlChars ) ; } } else if ( context . state == sComment ) { context . newState = sContent ; context . boundary = [ '<!DOCTYPE' , '<' ] ; } else if ( context . state == sProcessingInstruction ) { context . newState = sContent ; context . boundary = [ '<!DOCTYPE' , '<' ] ; } else if ( context . state == sCData ) { context . newState = sContent ; context . boundary = [ '<!DOCTYPE' , '<' ] ; } else if ( context . state == sDocType ) { if ( context . boundary [ context . bIndex ] == '[' ) { context . newState = sDTD ; context . boundary = [ ']>' ] ; } else { context . newState = sPreElement ; context . boundary = [ '<' ] ; } } else if ( context . state == sDTD ) { context . newState = sPreElement ; context . boundary = [ '<' ] ; } if ( ! callback ) { if ( ( ( context . state & 1 ) == 1 ) && ( ( context . token . trim ( ) !== '' ) || context . state == sValue ) ) { context . position = i + 1 ; return context ; } } context . state = context . newState ; if ( ! context . keepToken ) context . token = '' ; } else { context . token += c ; } } if ( ( context . state == sEndElement ) && ( context . depth === 0 ) && ( context . token . trim ( ) === '' ) ) { context . wellFormed = true ; } if ( ( ! context . wellFormed ) && ( ! context . error ) ) { if ( callback ) { // generate a final error, only for pushparsers though callback ( sError , context . token ) ; } } context . state = sEndDocument ; if ( callback ) { callback ( context . state , context . token ) ; return context . wellFormed ; } else { return context ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JSON Pointer specification : http : // tools . ietf . org / html / rfc6901 [CODESPLIT] function jptr ( obj , prop , newValue ) { //property not found if ( typeof obj === 'undefined' ) return false ; if ( ( ! prop ) || ( prop == '#' ) ) return obj ; if ( prop . startsWith ( '#' ) ) prop = prop . slice ( 1 ) ; if ( prop . startsWith ( '/' ) ) prop = prop . slice ( 1 ) ; var props = prop . split ( '/' ) ; var current = props [ 0 ] ; current = current . replaceAll ( '~1' , '/' ) ; current = current . replaceAll ( '~0' , '~' ) ; var index = - 1 ; if ( ( props . length > 1 ) && ( Array . isArray ( obj [ current ] ) ) ) { var next = props [ 1 ] ; var value = parseInt ( next , 10 ) ; if ( next == '-' ) { index = obj [ current ] . length ; } else { if ( ! isNaN ( value ) ) index = value ; } if ( index >= 0 ) { props . splice ( 1 , 1 ) ; prop = props . join ( '/' ) ; } } //property split found; recursive call if ( props . length > 1 ) { var pos = prop . indexOf ( '/' ) ; //get object at property (before split), pass on remainder if ( index >= 0 ) { return jptr ( obj [ current ] [ index ] , prop . substr ( pos + 1 ) , newValue ) ; //was props } else { return jptr ( obj [ current ] , prop . substr ( pos + 1 ) , newValue ) ; } } //no split; get property[index] or property var source = obj ; if ( current ) source = obj [ current ] ; if ( index >= 0 ) { if ( index >= source . length ) { if ( typeof newValue != 'undefined' ) { source . push ( newValue ) ; return newValue ; } else { return null ; } } else { if ( typeof newValue != 'undefined' ) { source [ index ] = newValue ; } return source [ index ] ; } } else { if ( typeof newValue != 'undefined' ) { obj [ prop ] = newValue ; source = obj [ prop ] ; } return source ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "simple object accessor using dotted notation and [] for array indices [CODESPLIT] function fetchFromObject ( obj , prop , newValue ) { //property not found if ( typeof obj === 'undefined' ) return false ; if ( ! prop ) { if ( typeof newValue != 'undefined' ) { obj = newValue ; } return obj ; } var props = prop . split ( '.' ) ; var arr = props [ 0 ] . split ( / [\\[\\]]+ / ) ; var index = - 1 ; if ( arr . length > 1 ) { index = parseInt ( arr [ 1 ] , 10 ) ; } //property split found; recursive call if ( props . length > 1 ) { var pos = prop . indexOf ( '.' ) ; //get object at property (before split), pass on remainder if ( index >= 0 ) { return fetchFromObject ( obj [ arr [ 0 ] ] [ index ] , prop . substr ( pos + 1 ) , newValue ) ; //was props } else { return fetchFromObject ( obj [ arr [ 0 ] ] , prop . substr ( pos + 1 ) , newValue ) ; } } //no split; get property[index] or property var source = obj ; if ( arr [ 0 ] ) source = obj [ prop ] ; if ( index >= 0 ) { if ( typeof newValue != 'undefined' ) source [ index ] = newValue ; return source [ index ] ; } else { if ( typeof newValue != 'undefined' ) obj [ prop ] = newValue ; return obj [ prop ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO convert this to an options object [CODESPLIT] function ( obj , attrPrefix , standalone , indent , indentStr , fragment ) { var attributePrefix = ( attrPrefix ? attrPrefix : '@' ) ; if ( fragment ) { xmlWrite . startFragment ( indent , indentStr ) ; } else { xmlWrite . startDocument ( 'UTF-8' , standalone , indent , indentStr ) ; } traverse ( obj , '' , attributePrefix ) ; return xmlWrite . endDocument ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_removeSubscribers remove the subscribers to one channel and return the number of subscribers that have been unsubscribed . [CODESPLIT] function _removeSubscribers ( aSubscribers , oSubscriber ) { let nUnsubscribed = 0 ; if ( ! isTypeOf ( aSubscribers , sNotDefined ) ) { let nIndex = aSubscribers . length - 1 ; for ( ; nIndex >= 0 ; nIndex -- ) { if ( aSubscribers [ nIndex ] . subscriber === oSubscriber ) { nUnsubscribed ++ ; aSubscribers . splice ( nIndex , 1 ) ; } } } return nUnsubscribed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loops per all the events to remove subscribers . [CODESPLIT] function _removeSubscribersPerEvent ( oEventsCallbacks , sChannelId , oSubscriber ) { let nUnsubscribed = 0 ; iterateObject ( oEventsCallbacks , function ( oItem , sEvent ) { const aEventsParts = sEvent . split ( ':' ) ; let sChannel = sChannelId ; let sEventType = sEvent ; if ( aEventsParts [ 0 ] === 'global' ) { sChannel = aEventsParts [ 0 ] ; sEventType = aEventsParts [ 1 ] ; } nUnsubscribed += _removeSubscribers ( oChannels [ sChannel ] [ sEventType ] , oSubscriber ) ; } ) ; return nUnsubscribed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_addSubscribers add all the events of one channel from the subscriber [CODESPLIT] function _addSubscribers ( oEventsCallbacks , sChannelId , oSubscriber ) { iterateObject ( oEventsCallbacks , function ( oItem , sEvent ) { subscribeTo ( sChannelId , sEvent , oItem , oSubscriber ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_getChannelEvents return the events array in channel . [CODESPLIT] function _getChannelEvents ( sChannelId , sEvent ) { if ( oChannels [ sChannelId ] === und ) { oChannels [ sChannelId ] = { } ; } if ( oChannels [ sChannelId ] [ sEvent ] === und ) { oChannels [ sChannelId ] [ sEvent ] = [ ] ; } return oChannels [ sChannelId ] [ sEvent ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "subscribersByEvent return all the subscribers of the event in the channel . [CODESPLIT] function subscribersByEvent ( oChannel , sEventName ) { let aSubscribers = [ ] ; if ( ! isTypeOf ( oChannel , sNotDefined ) ) { iterateObject ( oChannel , function ( oItem , sKey ) { if ( sKey === sEventName ) { aSubscribers = oItem ; } } ) ; } return aSubscribers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to add a single callback in one channel an in one event . [CODESPLIT] function subscribeTo ( sChannelId , sEventType , fpHandler , oSubscriber ) { const aChannelEvents = _getChannelEvents ( sChannelId , sEventType ) ; aChannelEvents . push ( { subscriber : oSubscriber , handler : fpHandler } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to unsubscribe a subscriber from a channel and event type . It iterates in reverse order to avoid messing with array length when removing items . [CODESPLIT] function unsubscribeFrom ( sChannelId , sEventType , oSubscriber ) { const aChannelEvents = _getChannelEvents ( sChannelId , sEventType ) ; for ( let nEvent = aChannelEvents . length - 1 ; nEvent >= 0 ; nEvent -- ) { const oItem = aChannelEvents [ nEvent ] ; if ( oItem . subscriber === oSubscriber ) { aChannelEvents . splice ( nEvent , 1 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "subscribe method gets the oEventsCallbacks object with all the handlers and add these handlers to the channel . [CODESPLIT] function subscribe ( oSubscriber ) { const oEventsCallbacks = oSubscriber . events ; if ( ! oSubscriber || oEventsCallbacks === und ) { return false ; } iterateObject ( oEventsCallbacks , function ( oItem , sChannelId ) { if ( oChannels [ sChannelId ] === und ) { oChannels [ sChannelId ] = { } ; } _addSubscribers ( oItem , sChannelId , oSubscriber ) ; } ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unsubscribe gets the oEventsCallbacks methods and removes the handlers of the channel . [CODESPLIT] function unsubscribe ( oSubscriber ) { let nUnsubscribed = 0 ; const oEventsCallbacks = oSubscriber . events ; if ( ! oSubscriber || oEventsCallbacks === und ) { return false ; } iterateObject ( oEventsCallbacks , function ( oItem , sChannelId ) { if ( oChannels [ sChannelId ] === und ) { oChannels [ sChannelId ] = { } ; } nUnsubscribed = _removeSubscribersPerEvent ( oItem , sChannelId , oSubscriber ) ; } ) ; return nUnsubscribed > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to execute handlers [CODESPLIT] function _executeHandler ( oHandlerObject , oData , sChannelId , sEvent ) { oHandlerObject . handler . call ( oHandlerObject . subscriber , oData ) ; if ( getDebug ( ) ) { const ErrorHandler = errorHandler ( ) ; ErrorHandler . log ( sChannelId , sEvent , oHandlerObject ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Publish the event in one channel . [CODESPLIT] function publish ( sChannelId , sEvent , oData ) { const aSubscribers = copyArray ( this . subscribers ( sChannelId , sEvent ) ) ; let oSubscriber ; const nLenSubscribers = aSubscribers . length ; if ( nLenSubscribers === 0 ) { return false ; } oData = preprocessorsPublishData ( oData ) ; while ( ! ! ( oSubscriber = aSubscribers . shift ( ) ) ) { _executeHandler ( oSubscriber , oData , sChannelId , sEvent ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create or get a namespace by a namespace defined as string [CODESPLIT] function resolveNamespace ( sNamespace ) { var oObj = root , aElements = sNamespace . split ( '.' ) , sElement ; while ( ! ! ( sElement = aElements . shift ( ) ) ) { oObj = oObj [ sElement ] !== und ? oObj [ sElement ] : oObj [ sElement ] = { } ; } return oObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve dependency injection by default . [CODESPLIT] function getResolveDICallback ( oMapping ) { return function ( sDependency ) { var oPromise = getPromise ( ) ; if ( ! oMapping . __map__ [ sDependency ] ) { return false ; } oPromise . resolve ( oMapping . __map__ [ sDependency ] ) ; return oPromise ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Traverse all the mapping systems to get a match . [CODESPLIT] function getDependencyThroughAllMaps ( sDependency ) { var oMap , oDependency , nIndexOrder , nLenOrder , aOrderDependency = oMappingMaps . ___order___ ; createMapping ( oMappingMaps , '__' , root , function ( sDependency ) { var oDependency , oPromise = getPromise ( ) ; oDependency = resolveNamespace ( sDependency ) ; oPromise . resolve ( oDependency ) ; return oPromise ; } ) ; for ( nIndexOrder = 0 , nLenOrder = aOrderDependency . length ; nIndexOrder < nLenOrder ; nIndexOrder ++ ) { oMap = oMappingMaps [ aOrderDependency [ nIndexOrder ] ] ; oDependency = oMap . __resolveDI__ ( sDependency ) ; if ( oDependency ) { delete oMappingMaps [ '__' ] ; return oDependency ; } } delete oMappingMaps [ '__' ] ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the promise callback by type [CODESPLIT] function getPromiseCallbacks ( oContext , sType ) { return function ( ) { var aCompleted , nLenPromises , oDeferred , aPromises , nPromise , oPromise , aResults = [ ] ; oContext . bCompleted = true ; oContext . sType = sType ; oContext . oResult = arguments ; while ( oContext . aPending [ 0 ] ) { oContext . aPending . shift ( ) [ sType ] . apply ( oContext , arguments ) ; } oDeferred = oContext . oDeferred ; if ( oDeferred ) { aCompleted = [ ] ; aPromises = oDeferred . aPromises ; nLenPromises = aPromises . length ; aResults = [ ] ; for ( nPromise = 0 ; nPromise < nLenPromises ; nPromise ++ ) { oPromise = aPromises [ nPromise ] ; aCompleted . push ( Number ( oPromise . bCompleted ) ) ; aResults . push ( oPromise . oResult ) ; } if ( aCompleted . join ( '' ) . indexOf ( '0' ) === - 1 ) { oDeferred [ sType ] . apply ( oDeferred , aResults ) ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds new callbacks to execute when the promise has been completed [CODESPLIT] function ( fpSuccess , fpFailure ) { var oResult = this . oResult ; if ( this . bCompleted ) { if ( this . sType === 'resolve' ) { fpSuccess . apply ( fpSuccess , oResult ) ; } else { fpFailure . apply ( fpFailure , oResult ) ; } } else { this . aPending . push ( { resolve : fpSuccess , reject : fpFailure } ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Module to be stored adds two methods to start and extend modules . [CODESPLIT] function FakeModule ( sModuleId , fpCreator ) { if ( isTypeOf ( fpCreator , sNotDefined ) ) { throw new Error ( 'Something goes wrong!' ) ; } this . creator = fpCreator ; this . instances = { } ; this . sModuleId = sModuleId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use jQuery detection [CODESPLIT] function isJqueryObject ( oObj ) { var isJquery = false , $ = getRoot ( ) . jQuery ; if ( $ ) { isJquery = isInstanceOf ( oObj , $ ) ; } return isJquery ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use Event detection and if it fails it degrades to use duck typing detection to test if the supplied object is an Event [CODESPLIT] function isEvent ( oObj ) { try { return isInstanceOf ( oObj , Event ) ; } catch ( erError ) { // Duck typing detection (If it sounds like a duck and it moves like a duck, it's a duck) if ( oObj . altKey !== und && ( oObj . srcElement || oObj . target ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add common properties and methods to avoid repeating code in modules [CODESPLIT] function addPropertiesAndMethodsToModule ( sModuleId , aDependencies , fpCallback ) { var oPromise ; function success ( mapping ) { const oModules = getModules ( ) ; var oModule , fpInitProxy ; oModule = oModules [ sModuleId ] . creator . apply ( oModules [ sModuleId ] , [ ] . slice . call ( arguments , 1 ) ) ; oModule . __children__ = [ ] ; oModule . dependencies = aDependencies || [ ] . slice . call ( arguments , 1 ) ; oModule . resolvedDependencies = mapping ; oModule . __module_id__ = sModuleId ; fpInitProxy = oModule . init || nullFunc ; // Provide compatibility with old versions of Hydra.js oModule . __action__ = oModule . __sandbox__ = Bus ; oModule . events = oModule . events || { } ; oModule . init = function ( ) { var aArgs = copyArray ( arguments ) . concat ( getVars ( ) ) ; if ( oModule . __children__ . length === 0 ) { // Only subscribe last element of inheritance. Bus . subscribe ( oModule ) ; } return fpInitProxy . apply ( this , aArgs ) ; } ; oModule . handleAction = function ( oNotifier ) { var fpCallback = this . events [ oNotifier . type ] ; if ( isTypeOf ( fpCallback , sNotDefined ) ) { return ; } fpCallback . call ( this , oNotifier ) ; } ; // Provide compatibility with old Hydra versions which used to use \"destroy\" as onDestroy hook. oModule . onDestroy = oModule . onDestroy || oModule . destroy || function ( ) { } ; oModule . destroy = function ( ) { this . onDestroy ( ) ; Bus . unsubscribe ( oModule ) ; delete oModules [ sModuleId ] . instances [ oModule . __instance_id__ ] ; } ; fpCallback ( oModule ) ; } oPromise = resolveDependencies ( sModuleId , aDependencies ) ; oPromise . then ( function ( ) { success . apply ( success , arguments ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wrapMethod is a method to wrap the original method to avoid failing code . This will be only called if bDebug flag is set to false . [CODESPLIT] function wrapMethod ( oInstance , sName , sModuleId , fpMethod ) { oInstance [ sName ] = ( function ( sName , fpMethod ) { return function ( ) { var aArgs = copyArray ( arguments ) ; try { return fpMethod . apply ( this , aArgs ) ; } catch ( erError ) { const ErrorHandler = errorHandler ( ) ; ErrorHandler . error ( sModuleId , sName , erError ) ; return false ; } } ; } ( sName , fpMethod ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "register is the method that will add the new module to the oModules object . sModuleId will be the key where it will be stored . [CODESPLIT] function register ( sModuleId , aDependencies , fpCreator ) { const oModules = getModules ( ) ; if ( isFunction ( aDependencies ) ) { fpCreator = aDependencies ; aDependencies = [ '$$_bus' , '$$_module' , '$$_log' , 'gl_Hydra' ] ; } oModules [ sModuleId ] = new FakeModule ( sModuleId , fpCreator ) ; oModules [ sModuleId ] . dependencies = aDependencies ; return oModules [ sModuleId ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to set an instance of a module [CODESPLIT] function setInstance ( sModuleId , sIdInstance , oInstance ) { const oModules = getModules ( ) ; var oModule = oModules [ sModuleId ] ; if ( ! oModule ) { fpThrowErrorModuleNotRegistered ( sModuleId , true ) ; } oModule . instances [ sIdInstance ] = oInstance ; return oModule ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start more than one module at the same time . [CODESPLIT] function _multiModuleStart ( oInstance , aModulesIds , sIdInstance , oData , bSingle ) { var aInstancesIds , aData , aSingle , nIndex , nLenModules , sModuleId ; if ( isArray ( sIdInstance ) ) { aInstancesIds = copyArray ( sIdInstance ) ; } if ( isArray ( oData ) ) { aData = copyArray ( oData ) ; } if ( isArray ( bSingle ) ) { aSingle = copyArray ( bSingle ) ; } for ( nIndex = 0 , nLenModules = aModulesIds . length ; nIndex < nLenModules ; nIndex ++ ) { sModuleId = aModulesIds [ nIndex ] ; sIdInstance = aInstancesIds && aInstancesIds [ nIndex ] || generateUniqueKey ( ) ; oData = aData && aData [ nIndex ] || oData ; bSingle = aSingle && aSingle [ nIndex ] || bSingle ; startSingleModule ( oInstance , sModuleId , sIdInstance , oData , bSingle ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to modify the init method to use it for extend . [CODESPLIT] function beforeInit ( oInstance , oData , bSingle ) { iterateObject ( oModifyInit , function ( oMember ) { if ( oMember && isTypeOf ( oMember , sFunctionType ) ) { oMember ( oInstance , oData , bSingle ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "startSingleModule is the method that will initialize the module . When start is called the module instance will be created and the init method is called . If bSingle is true and the module is started the module will be stopped before instance it again . This avoid execute the same listeners more than one time . [CODESPLIT] function startSingleModule ( oWrapper , sModuleId , sIdInstance , oData , bSingle ) { const oModules = getModules ( ) ; var oModule ; oModule = oModules [ sModuleId ] ; if ( ( bSingle && isModuleStarted ( sModuleId ) ) || isModuleStarted ( sModuleId , sIdInstance ) ) { oWrapper . stop ( sModuleId , sIdInstance ) ; } if ( ! isTypeOf ( oModule , sNotDefined ) ) { createInstance ( sModuleId , undefined , function ( oInstance ) { oModule . instances [ sIdInstance ] = oInstance ; oInstance . __instance_id__ = sIdInstance ; beforeInit ( oInstance , oData , bSingle ) ; if ( ! isTypeOf ( oData , sNotDefined ) ) { oInstance . init ( oData ) ; } else { oInstance . init ( ) ; } } ) ; } else { const ErrorHandler = errorHandler ( ) ; ErrorHandler . error ( new Error ( ) , fpThrowErrorModuleNotRegistered ( sModuleId ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start only one module . [CODESPLIT] function _singleModuleStart ( oInstance , sModuleId , sIdInstance , oData , bSingle ) { if ( ! isTypeOf ( sIdInstance , 'string' ) ) { bSingle = oData ; oData = sIdInstance ; sIdInstance = generateUniqueKey ( ) ; } startSingleModule ( oInstance , sModuleId , sIdInstance , oData , bSingle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start is the method that initialize the module / s If you use array instead of arrays you can start more than one module even adding the instance the data and if it must be executed as single module start . [CODESPLIT] function start ( oModuleId , oIdInstance , oData , oSingle ) { var bStartMultipleModules = isArray ( oModuleId ) ; if ( bStartMultipleModules ) { _multiModuleStart ( this , copyArray ( oModuleId ) , oIdInstance , oData , oSingle ) ; } else { _singleModuleStart ( this , oModuleId , oIdInstance , oData , oSingle ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "createInstance is the method that will create the module instance and wrap the method if needed . [CODESPLIT] function createInstance ( sModuleId , aDependencies , fpCallback ) { const oModules = getModules ( ) ; if ( isTypeOf ( oModules [ sModuleId ] , sNotDefined ) ) { fpThrowErrorModuleNotRegistered ( sModuleId , true ) ; } addPropertiesAndMethodsToModule ( sModuleId , aDependencies , function ( oInstance ) { if ( ! getDebug ( ) ) { iterateObject ( oInstance , function ( oItem , sName ) { if ( isFunction ( oItem ) ) { wrapMethod ( oInstance , sName , sModuleId , oInstance [ sName ] ) ; } } ) ; } fpCallback ( oInstance ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets properties and methods from a template object . [CODESPLIT] function getCallbackToSetObjectFromTemplate ( oMethodsObject , oPropertiesObject ) { return function ( oValue , sKey ) { if ( typeof oValue === 'function' ) { oMethodsObject [ sKey ] = getSimpleFunction ( oValue ) ; } else if ( isArray ( oValue ) ) { oPropertiesObject [ sKey ] = copyArray ( oValue ) ; } else if ( typeof oValue === 'object' && oValue !== null ) { oPropertiesObject [ sKey ] = simpleMerge ( { } , oValue ) ; } else if ( isInstanceOf ( oValue , Date ) ) { oPropertiesObject [ sKey ] = new Date ( ) ; oPropertiesObject [ sKey ] . setTime ( oValue . getTime ( ) ) ; } else { oPropertiesObject [ sKey ] = oValue ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "startAll is the method that will initialize all the registered modules . [CODESPLIT] function startAll ( ) { const oModules = getModules ( ) ; iterateObject ( oModules , function ( _oModule , sModuleId ) { if ( ! isTypeOf ( _oModule , sNotDefined ) ) { start ( sModuleId , generateUniqueKey ( ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stop is the method that will finish the module if it was registered and started . When stop is called the module will call the destroy method and will nullify the instance . [CODESPLIT] function stop ( sModuleId , sInstanceId ) { const oModules = getModules ( ) ; var oModule ; oModule = oModules [ sModuleId ] ; if ( isTypeOf ( oModule , sNotDefined ) ) { return false ; } if ( ! isTypeOf ( sInstanceId , sNotDefined ) ) { _singleModuleStop ( oModule , sInstanceId ) ; } else { _multiModuleStop ( oModule ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stop more than one module at the same time . [CODESPLIT] function _multiModuleStop ( oModule ) { iterateObject ( oModule . instances , function ( oInstance ) { if ( ! isTypeOf ( oModule , sNotDefined ) && ! isTypeOf ( oInstance , sNotDefined ) ) { oInstance . destroy ( ) ; } } ) ; oModule . instances = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop only one module . [CODESPLIT] function _singleModuleStop ( oModule , sInstanceId ) { var oInstance = oModule . instances [ sInstanceId ] ; if ( ! isTypeOf ( oModule , sNotDefined ) && ! isTypeOf ( oInstance , sNotDefined ) ) { oInstance . destroy ( ) ; delete oModule . instances [ sInstanceId ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stopAll is the method that will finish all the registered and started modules . [CODESPLIT] function stopAll ( ) { const oModules = getModules ( ) ; iterateObject ( oModules , function ( _oModule , sModuleId ) { if ( ! isTypeOf ( _oModule , sNotDefined ) ) { _stopOneByOne ( _oModule , sModuleId ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loops over instances of modules to stop them . [CODESPLIT] function _stopOneByOne ( oModule , sModuleId ) { iterateObject ( oModule . instances , function ( oItem , sInstanceId ) { stop ( sModuleId , sInstanceId ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove is the method that will remove the full module from the oModules object [CODESPLIT] function remove ( sModuleId ) { const oModules = getModules ( ) ; var oModule = oModules [ sModuleId ] ; if ( isTypeOf ( oModule , sNotDefined ) ) { return null ; } if ( ! isTypeOf ( oModule , sNotDefined ) ) { try { return Module ; } finally { _delete ( sModuleId ) ; createMapping ( getMappingMaps ( ) , 'hm_' , oModules ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_delete is a wrapper method that will call the native delete javascript function It s important to test the full code . [CODESPLIT] function _delete ( sModuleId ) { const oModules = getModules ( ) ; if ( ! isTypeOf ( oModules [ sModuleId ] , sNotDefined ) ) { delete oModules [ sModuleId ] ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Entry point . [CODESPLIT] function main ( ) { return __awaiter ( this , void 0 , void 0 , function ( ) { var outputDataSize , interval , dataFrame , dateFormat , api ; return __generator ( this , function ( _a ) { switch ( _a . label ) { case 0 : outputDataSize = \"compact\" ; if ( argv . outputDataSize ) { outputDataSize = argv . outputDataSize ; } interval = '60min' ; if ( argv . interval ) { interval = argv . interval ; } api = new index_1 . AlphaVantageAPI ( argv . apiKey , outputDataSize , argv . verbose ) ; if ( ! ( argv . type === 'daily' ) ) return [ 3 /*break*/ , 2 ] ; return [ 4 /*yield*/ , api . getDailyDataFrame ( argv . symbol ) ] ; case 1 : dataFrame = _a . sent ( ) ; dateFormat = 'YYYY-MM-DD' ; return [ 3 /*break*/ , 5 ] ; case 2 : if ( ! ( argv . type === 'intraday' ) ) return [ 3 /*break*/ , 4 ] ; return [ 4 /*yield*/ , api . getIntradayDataFrame ( argv . symbol , interval ) ] ; case 3 : dataFrame = _a . sent ( ) ; dateFormat = \"YYYY-MM-DD HH:mm:ss\" ; return [ 3 /*break*/ , 5 ] ; case 4 : throw new Error ( \"Unexpected data type: \" + argv . type + \", expected it to be either 'daily' or 'intrday'\" ) ; case 5 : if ( ! argv . verbose ) { console . log ( '>> ' + argv . out ) ; } dataFrame . transformSeries ( { Timestamp : function ( t ) { return moment ( t ) . format ( dateFormat ) ; } , } ) . asCSV ( ) . writeFileSync ( argv . out ) ; return [ 2 /*return*/ ] ; } } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "instance identifier for bind / unbind events [CODESPLIT] function ( name , opts ) { //triggers an event bound to the element opts = opts || { } ; this . element . trigger ( $ . extend ( { type : name , pickerInstance : this } , opts ) ) ; //console.log(name + ' triggered for instance #' + this._id); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the internal item value and updates everything excepting the input or element . For doing so call setSourceValue () or update () instead [CODESPLIT] function ( val ) { // sanitize first var _val = this . getValid ( val ) ; if ( _val !== false ) { this . pickerValue = _val ; this . _trigger ( 'pickerSetValue' , { pickerValue : _val } ) ; return this . pickerValue ; } else { this . _trigger ( 'pickerInvalid' , { pickerValue : val } ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the formatted item value [CODESPLIT] function ( val ) { // here you may parse your format when you build your plugin var valueInPicker = this . options . itemProperty ? this . pickerValue [ this . options . itemProperty ] : this . pickerValue ; return ( val ? val : valueInPicker ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls setValue and if it s a valid item value sets the input or element value [CODESPLIT] function ( val ) { val = this . setValue ( val ) ; if ( ( val !== false ) && ( val !== '' ) ) { if ( this . hasInput ( ) ) { this . input . val ( this . getValue ( ) ) ; } else { this . element . data ( 'pickerValue' , this . getValue ( ) ) ; } this . _trigger ( 'pickerSetSourceValue' , { pickerValue : val } ) ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the input or element item value without formatting or defaultValue if it s empty string undefined false or null [CODESPLIT] function ( defaultValue ) { // returns the input or element value, as string defaultValue = defaultValue || this . options . defaultValue ; var val = defaultValue ; if ( this . hasInput ( ) ) { val = this . input . val ( ) ; } else { val = this . element . data ( 'pickerValue' ) ; val = this . options . itemProperty ? val [ this . options . itemProperty ] : val ; } if ( ( val === undefined ) || ( val === '' ) || ( val === null ) || ( val === false ) ) { // if not defined or empty, return default val = defaultValue ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "based on from https : // github . com / inuyaksa / jquery . nicescroll / blob / master / jquery . nicescroll . js [CODESPLIT] function ( e , p ) { if ( ! e ) return false ; var el = e . target || e . srcElement || e || false ; while ( el && el != p ) { el = el . parentNode || false ; } return ( el !== false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SelectFx function [CODESPLIT] function ( el , options ) { events . EventEmitter . call ( this ) ; this . el = el ; this . options = extend ( { } , this . options ) ; this . options = extend ( this . options , options ) ; this . _init ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helpers [CODESPLIT] function findUuidIndex ( array , uuid ) { for ( let i = 0 , len = array . length ; i < len ; i ++ ) { if ( array [ i ] . uuid == uuid ) { // eslint-disable-line\r return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "createMarkdownSerializer create a snapshot serializer . [CODESPLIT] function createMarkdownSerializer ( indentCodeBlocks ) { return { serialize : ( name , suite ) => snapshotToMarkdown ( name , suite , indentCodeBlocks ) , deserialize : markdownToSnapshot , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "markdownToSnapshot converts snapshot from markdown format into native . [CODESPLIT] function markdownToSnapshot ( content ) { const tree = mdParser . parse ( content ) ; const state = { name : null , suite : null , suiteStack : [ ] , currentSuite : null , currentSnapshotList : null , depth : 0 } ; const children = tree . children ; for ( let i = 0 ; i < children . length ; i ++ ) { const c = children [ i ] ; switch ( c . type ) { case 'heading' : if ( c . depth === 1 ) { enterRootSuite ( state , c ) ; } else if ( c . depth === 2 ) { tryExit ( state , suiteDepth ( c ) ) ; enterSuite ( state , c ) ; } else if ( c . depth === 4 ) { enterSnapshot ( state , c ) ; } break ; case 'code' : pushSnapshotCode ( state , c ) ; break ; } } return { name : state . name , suite : state . suite } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tryExit tries to pop state until it has correct depth . [CODESPLIT] function tryExit ( state , depth ) { while ( state . depth >= depth ) { state . suiteStack . pop ( ) ; state . currentSuite = state . suiteStack [ state . suiteStack . length - 1 ] ; state . currentSnapshotList = null ; state . depth -- ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "enterRootSuite pushes root suite into the current state . [CODESPLIT] function enterRootSuite ( state , node ) { const inlineCode = node . children [ 0 ] ; const name = inlineCode . value ; const suite = { children : { } , snapshots : { } } state . name = name ; state . suite = suite ; state . suiteStack . push ( suite ) ; state . currentSuite = suite ; state . currentSnapshotList = null ; state . depth = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "enterSnapshot pushes snapshot into the current state . [CODESPLIT] function enterSnapshot ( state , node ) { const inlineCode = node . children [ 0 ] ; const name = inlineCode . value ; const snapshotList = [ ] ; state . currentSuite . snapshots [ name ] = snapshotList ; state . currentSnapshotList = snapshotList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pushSnapshotCode adds snapshot to the current snapshot . [CODESPLIT] function pushSnapshotCode ( state , node ) { state . currentSnapshotList . push ( { lang : node . lang , code : normalizeNewlines ( node . value ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "transformSuite converts suite from native into markdown format . [CODESPLIT] function transformSuite ( name , suite , depth , indentCodeBlocks ) { const children = suite . children ; const snapshots = suite . snapshots ; const nextDepth = depth + 1 ; let result = suiteHeader ( name , depth ) ; let keys , i ; keys = Object . keys ( snapshots ) ; for ( i = 0 ; i < keys . length ; i ++ ) { const key = keys [ i ] ; const snapshotList = snapshots [ key ] ; result += transformSnapshotList ( key , snapshotList , nextDepth , indentCodeBlocks ) ; } keys = Object . keys ( children ) ; for ( i = 0 ; i < keys . length ; i ++ ) { const key = keys [ i ] ; result += transformSuite ( key , children [ key ] , nextDepth , indentCodeBlocks ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "transformSnapshotList converts snapshot list from native into markdown format . [CODESPLIT] function transformSnapshotList ( name , snapshotList , depth , indentCodeBlocks ) { let result = snapshotHeader ( name , depth ) ; for ( let i = 0 ; i < snapshotList . length ; i ++ ) { if ( i > 0 && indentCodeBlocks ) { result += '---\\n\\n' ; } const snapshot = snapshotList [ i ] ; const lang = snapshot . lang ; const code = snapshot . code ; const delimiter = safeDelimiter ( code ) ; if ( indentCodeBlocks ) { const lines = code . split ( '\\n' ) ; for ( let i = 0 ; i < lines . length ; i ++ ) { result += '    ' + lines [ i ] + '\\n' ; } } else { result += delimiter ; if ( lang ) { result += lang ; } result += '\\n' + code + '\\n' + delimiter + '\\n' ; } result += '\\n' ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "suiteHeader serializes suite header . [CODESPLIT] function suiteHeader ( name , depth ) { if ( depth === - 1 ) { return \"# \" + serializeName ( name ) + \"\\n\\n\" ; } return \"## \" + indent ( depth ) + serializeName ( name ) + \"\\n\\n\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "safeDelimiter tries to find a safe delimiter by appending backticks until it finally finds it . [CODESPLIT] function safeDelimiter ( s , delimiter ) { if ( delimiter === undefined ) { delimiter = '```' ; } while ( s . indexOf ( delimiter ) !== - 1 ) { delimiter += '`' ; } return delimiter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "defaultPathResolver is a default path resolver for snapshot files . [CODESPLIT] function defaultPathResolver ( basePath , suiteName ) { const suiteSourcePath = path . join ( basePath , suiteName ) ; const suiteSourceDir = path . dirname ( suiteSourcePath ) ; const sourceFileName = path . basename ( suiteName ) ; return path . join ( suiteSourceDir , \"__snapshots__\" , sourceFileName + \".md\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders a list of snapshots up to specified limit of lines [CODESPLIT] function formatSnapshotList ( list , limit ) { limit = ( typeof limit != 'undefined' ) ? limit : - 1 ; const limitedList = limit > 0 ? list . slice ( 0 , limit ) : list ; const hasMore = list . length > limitedList . length ; const buildList = ( snapshots ) => snapshots . map ( ( s ) => s . join ( ' > ' ) ) . join ( '\\n' ) ; if ( hasMore ) { return buildList ( limitedList . slice ( 0 , - 1 ) ) + ` \\n ${ list . length - limitedList . length + 1 } ` ; } return buildList ( limitedList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders the message for unused snapshots warning [CODESPLIT] function formatUnusedSnapshotsWarning ( list , limit ) { if ( limit == 0 ) { return ` ${ list . length } ` ; } const prunedList = formatSnapshotList ( list , limit ) ; return ` ${ list . length } \\n ${ prunedList } ` ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "snapshotFramework [CODESPLIT] function snapshotFramework ( files , config , emitter , loggerFactory ) { const logger = loggerFactory . create ( 'framework.snapshot' ) ; const snapshotConfig = Object . assign ( { update : false , prune : false , format : \"md\" , checkSourceFile : false , pathResolver : defaultPathResolver , limitUnusedSnapshotsInWarning : - 1 } , config . snapshot ) ; if ( typeof snapshotConfig . format === \"string\" ) { switch ( snapshotConfig . format ) { case \"indented-md\" : snapshotSerializer = createMarkdownSerializer ( true ) ; break ; case \"md\" : default : snapshotSerializer = createMarkdownSerializer ( false ) ; } } else { snapshotSerializer = snapshotConfig . format ; } // it should be in a files list after `adapter.js` if ( snapshotConfig . update ) { files . unshift ( filePattern ( path . join ( __dirname , 'snapshot-state-update.js' ) ) ) ; } // inject snapshot adapter files . unshift ( filePattern ( path . join ( __dirname , 'adapter.js' ) ) ) ; emitter . on ( 'browser_complete' , ( clientInfo , data ) => { const lastResult = clientInfo . lastResult ; if ( ! lastResult . disconnected ) { if ( data && data . snapshot ) { let rootSuite = data . snapshot ; let dirty = rootSuite . dirty ; // prune dead snapshots if ( ! lastResult . error && lastResult . failed === 0 && lastResult . skipped === 0 ) { const prunedSnapshots = prune . pruneSnapshots ( rootSuite ) ; if ( prunedSnapshots . pruned . length > 0 ) { if ( snapshotConfig . prune ) { const prunedList = formatSnapshotList ( prunedSnapshots . pruned ) logger . warn ( ` ${ prunedSnapshots . pruned . length } \\n ${ prunedList } ` ) ; rootSuite = prunedSnapshots . suite ; prune . pruneFiles ( snapshotConfig . pathResolver , config . basePath , prunedSnapshots . prunedFiles ) ; dirty = true ; } else { logger . warn ( formatUnusedSnapshotsWarning ( prunedSnapshots . pruned , snapshotConfig . limitUnusedSnapshotsInWarning ) ) ; } } } if ( dirty ) { Object . keys ( rootSuite . children ) . forEach ( ( suiteName ) => { const suite = rootSuite . children [ suiteName ] ; if ( suite . dirty ) { if ( snapshotConfig . checkSourceFile ) { const suiteSourceFilePath = path . join ( config . basePath , suiteName ) ; if ( ! fs . existsSync ( suiteSourceFilePath ) ) { logger . error ( 'Failed to save snapshot file. ' + 'Source file \"' + suiteSourceFilePath + '\" does not exist.' ) ; return ; } } const snapshotPath = snapshotConfig . pathResolver ( config . basePath , suiteName ) ; const snapshotDir = path . dirname ( snapshotPath ) ; if ( ! fs . existsSync ( snapshotDir ) ) { mkdirp . sync ( snapshotDir ) ; } fs . writeFileSync ( snapshotPath , snapshotSerializer . serialize ( suiteName , suite ) ) ; } } ) ; } } } else { logger . warn ( 'Snapshot data is unavailable' ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Snapshot preprocessor . [CODESPLIT] function snapshotPreprocessor ( basePath , loggerFactory ) { const logger = loggerFactory . create ( 'preprocessor.snapshot' ) ; return function ( content , file , done ) { const root = snapshotSerializer . deserialize ( content ) ; done ( iifeWrapper ( 'window.__snapshot__.addSuite(\"' + root . name + '\",' + JSON . stringify ( root . suite ) + ');' ) ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Single Line Plugin [CODESPLIT] function singleLinePlugin ( options = { } ) { options = Object . assign ( { } , defaultOptions , options ) return { /**\n     * Return a compatible blockRenderMap\n     *\n     * NOTE: Needs to be explicitly applied, the plugin system doesn’t do\n     * anything with this at the moment.\n     *\n     * @type {ImmutableMap}\n     */ blockRenderMap : Map ( { 'unstyled' : { element : 'div' , } , } ) , /**\n     * onChange\n     *\n     * Condense multiple blocks into a single block and (optionally) strip all\n     * entities from the content of that block.\n     *\n     * @param  {EditorState} editorState The current state of the editor\n     * @return {EditorState} A new editor state\n     */ onChange ( editorState ) { const blocks = editorState . getCurrentContent ( ) . getBlocksAsArray ( ) // If we have more than one block, compress them if ( blocks . length > 1 ) { editorState = condenseBlocks ( editorState , blocks , options ) } else { // We only have one content block let contentBlock = blocks [ 0 ] let text = contentBlock . getText ( ) let characterList = contentBlock . getCharacterList ( ) let hasEntitiesToStrip = options . stripEntities && characterListhasEntities ( characterList ) if ( NEWLINE_REGEX . test ( text ) || hasEntitiesToStrip ) { // Replace the text stripped of its newlines. Note that we replace // one '\\n' with one ' ' so we don't need to modify the characterList text = replaceNewlines ( text ) // Strip entities? if ( options . stripEntities ) { characterList = characterList . map ( stripEntityFromCharacterMetadata ) } // Create a new content block based on the old one contentBlock = new ContentBlock ( { key : genKey ( ) , text : text , type : 'unstyled' , characterList : characterList , depth : 0 , } ) // Update the editor state with the compressed version // const selection = editorState.getSelection() const newContentState = ContentState . createFromBlockArray ( [ contentBlock ] ) // Create the new state as an undoable action editorState = EditorState . push ( editorState , newContentState , 'insert-characters' ) } } return editorState } , /**\n     * Stop new lines being inserted by always handling the return\n     *\n     * @param  {KeyboardEvent} e Synthetic keyboard event from draftjs\n     * @return {String} Did we handle the return or not? (pro-trip: yes, we did)\n     */ handleReturn ( e ) { return 'handled' } , } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace newline characters with the passed string [CODESPLIT] function replaceNewlines ( str ) { var replacement = arguments . length <= 1 || arguments [ 1 ] === undefined ? ' ' : arguments [ 1 ] ; return str . replace ( NEWLINE_REGEX , replacement ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Condense an array of content blocks into a single block [CODESPLIT] function condenseBlocks ( editorState , blocks , options ) { blocks = blocks || editorState . getCurrentContent ( ) . getBlocksAsArray ( ) ; var text = ( 0 , _immutable . List ) ( ) ; var characterList = ( 0 , _immutable . List ) ( ) ; // Gather all the text/characterList and concat them blocks . forEach ( function ( block ) { // Atomic blocks should be ignored (stripped) if ( block . getType ( ) !== 'atomic' ) { text = text . push ( replaceNewlines ( block . getText ( ) ) ) ; characterList = characterList . concat ( block . getCharacterList ( ) ) ; } } ) ; // Strip entities? if ( options . stripEntities ) { characterList = characterList . map ( stripEntityFromCharacterMetadata ) ; } // Create a new content block var contentBlock = new _draftJs . ContentBlock ( { key : ( 0 , _draftJs . genKey ) ( ) , text : text . join ( '' ) , type : 'unstyled' , characterList : characterList , depth : 0 } ) ; // Update the editor state with the compressed version var newContentState = _draftJs . ContentState . createFromBlockArray ( [ contentBlock ] ) ; // Create the new state as an undoable action editorState = _draftJs . EditorState . push ( editorState , newContentState , 'remove-range' ) ; // Move the selection to the end return _draftJs . EditorState . moveFocusToEnd ( editorState ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a CharacterList contains entities [CODESPLIT] function characterListhasEntities ( characterList ) { var hasEntities = false ; characterList . forEach ( function ( characterMeta ) { if ( characterMeta . get ( 'entity' ) !== null ) { hasEntities = true ; } } ) ; return hasEntities ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eslint - disable - line node / prefer - global / process [CODESPLIT] function getClosestVersion ( ) { if ( ! process . versions . v8 ) { // Assume compatibility with Node.js 8.9.4 return 'v8-6.1' ; } const v8 = parseFloat ( process . versions . v8 ) ; if ( v8 >= 6.6 ) { return 'v8-6.6' ; } if ( v8 >= 6.2 ) { return 'v8-6.2' ; } return 'v8-6.1' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! [CODESPLIT] function GstLaunch ( ) { const gst_launch_executable = 'gst-launch-1.0' ; const gst_launch_versionarg = '--version' ; const SpawnSync = require ( 'child_process' ) . spawnSync ; const Spawn = require ( 'child_process' ) . spawn ; const Assert = require ( 'assert' ) ; const Path = require ( 'path' ) ; const OS = require ( 'os' ) ; const FS = require ( 'fs' ) ; /**\n   * @fn getPath\n   * @brief Returns path to gst-launch or undefined on error\n   */ var getPath = function ( ) { var detected_path = undefined ; if ( OS . platform ( ) == 'win32' ) { // On Windows, GStreamer MSI installer defines the following // environment variables. const detected_path_x64 = process . env . GSTREAMER_1_0_ROOT_X86_64 ; const detected_path_x32 = process . env . GSTREAMER_1_0_ROOT_X86 ; if ( detected_path_x64 || detected_path_x32 ) { // If both variables are present, favor the architecture // of GStreamer which is the same as Node.js runtime. if ( detected_path_x64 && detected_path_x32 ) { if ( process . arch == 'x64' ) detected_path = detected_path_x64 ; else if ( process . arch == 'x32' ) detected_path = detected_path_x32 ; } else { detected_path = detected_path_x64 || detected_path_x32 ; } } if ( detected_path ) { detected_path = Path . join ( detected_path , 'bin' , ( gst_launch_executable + '.exe' ) ) ; try { FS . accessSync ( detected_path , FS . F_OK ) ; } catch ( e ) { detected_path = undefined ; } } else { // Look for GStreamer on PATH var path_dirs = process . env . PATH . split ( ';' ) ; for ( var index = 0 ; index < path_dirs . length ; ++ index ) { try { var base = Path . normalize ( path_dirs [ index ] ) ; var bin = Path . join ( base , ( gst_launch_executable + '.exe' ) ) ; FS . accessSync ( bin , FS . F_OK ) ; detected_path = bin ; } catch ( e ) { /* no-op */ } } } } else if ( OS . platform ( ) == 'linux' ) { // Look for GStreamer on PATH var path_dirs = process . env . PATH . split ( ':' ) ; for ( var index = 0 ; index < path_dirs . length ; ++ index ) { try { var base = Path . normalize ( path_dirs [ index ] ) ; var bin = Path . join ( base , gst_launch_executable ) ; FS . accessSync ( bin , FS . F_OK ) ; detected_path = bin ; } catch ( e ) { /* no-op */ } } } else if ( OS . platform ( ) == 'darwin' ) { try { var bin = '/usr/local/bin/gst-launch-1.0' FS . accessSync ( bin , FS . F_OK ) ; detected_path = bin ; } catch ( e ) { /* no-op */ } } return detected_path ; } /**\n   * @fn getVersion\n   * @brief Returns version string of GStreamer on this machine by\n   * invoking the gst-launch executable or 'undefined' on failure.\n   */ var getVersion = function ( ) { var version_str = undefined ; try { var gst_launch_path = getPath ( ) ; Assert . ok ( typeof ( gst_launch_path ) , 'string' ) ; var output = SpawnSync ( gst_launch_path , [ gst_launch_versionarg ] , { 'timeout' : 1000 } ) . stdout ; if ( output && output . toString ( ) . includes ( 'GStreamer' ) ) { version_str = output . toString ( ) . match ( / GStreamer\\s+.+ / g ) [ 0 ] . replace ( / GStreamer\\s+ / , '' ) ; } } catch ( ex ) { version_str = undefined ; } return version_str ; } /*!\n   * @fn isAvailable\n   * @brief Answers true if gst-launch executable is available\n   */ var isAvailable = function ( ) { return getVersion ( ) != undefined ; } /*!\n   * @fn spawnPipeline\n   * @brief Spawns a GStreamer pipeline using gst-launch\n   * @return A Node <child-process> of the launched pipeline\n   * @see To construct a correct pipeline arg, consult the link below:\n   * https://gstreamer.freedesktop.org/data/doc/gstreamer/head/manual/html/chapter-programs.html\n   * @usage spawnPipeline('videotestsrc ! autovideosink')\n   */ var spawnPipeline = function ( pipeline ) { Assert . ok ( typeof ( pipeline ) , 'string' ) ; Assert . ok ( isAvailable ( ) , \"gst-launch is not available.\" ) ; var gst_launch_path = getPath ( ) ; Assert . ok ( typeof ( gst_launch_path ) , 'string' ) ; return Spawn ( gst_launch_path , pipeline . split ( ' ' ) ) ; } return { 'getPath' : getPath , 'getVersion' : getVersion , 'isAvailable' : isAvailable , 'spawnPipeline' : spawnPipeline } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! [CODESPLIT] function ( pipeline ) { Assert . ok ( typeof ( pipeline ) , 'string' ) ; Assert . ok ( isAvailable ( ) , \"gst-launch is not available.\" ) ; var gst_launch_path = getPath ( ) ; Assert . ok ( typeof ( gst_launch_path ) , 'string' ) ; return Spawn ( gst_launch_path , pipeline . split ( ' ' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! [CODESPLIT] function GstLiveCamServer ( config ) { const Assert = require ( 'assert' ) ; const OS = require ( 'os' ) ; Assert . ok ( [ 'win32' , 'linux' , 'darwin' ] . indexOf ( OS . platform ( ) ) > - 1 , \"livecam module supports Windows, Linux, and Mac OSX for broadcasting.\" ) ; config = config || { } ; Assert . ok ( typeof ( config ) , 'object' ) ; const fake = config . fake || false ; const width = config . width || 800 ; const height = config . height || 600 ; const framerate = config . framerate || 30 ; const grayscale = config . grayscale || false ; const deviceIndex = config . deviceIndex || - 1 ; Assert . ok ( typeof ( fake ) , 'boolean' ) ; Assert . ok ( typeof ( width ) , 'number' ) ; Assert . ok ( typeof ( height ) , 'number' ) ; Assert . ok ( typeof ( framerate ) , 'number' ) ; Assert . ok ( typeof ( grayscale ) , 'boolean' ) ; var gst_multipart_boundary = '--videoboundary' ; var gst_video_src = '' ; if ( ! fake ) { if ( OS . platform ( ) == 'win32' ) gst_video_src = 'ksvideosrc device-index=' + deviceIndex + ' ! decodebin' ; else if ( OS . platform ( ) == 'linux' ) gst_video_src = 'v4l2src ! decodebin' ; else if ( OS . platform ( ) == 'darwin' ) gst_video_src = 'avfvideosrc device-index=' + deviceIndex ; else Assert . ok ( false , 'unsupported platform' ) } else { gst_video_src = 'videotestsrc' ; } if ( width > 0 || height > 0 ) { gst_video_src += ' ! videoscale ! video/x-raw,width=' + parseInt ( width ) + ',height=' + parseInt ( height ) ; } if ( framerate > 0 ) { gst_video_src += ' ! videorate ! video/x-raw,framerate=' + parseInt ( framerate ) + '/1' ; } if ( grayscale ) { gst_video_src += ' ! videobalance saturation=0.0 ! videoconvert' ; } /*!\n   * @fn start\n   * @brief Starts a GStreamer pipeline that broadcasts the default\n   * webcam over the given TCP address and port.\n   * @return A Node <child-process> of the launched pipeline\n   */ var start = function ( tcp_addr , tcp_port ) { Assert . ok ( typeof ( tcp_addr ) , 'string' ) ; Assert . ok ( typeof ( tcp_port ) , 'number' ) ; const cam_pipeline = gst_video_src + ' ! jpegenc ! multipartmux  boundary=\"' + gst_multipart_boundary + '\" ! tcpserversink host=' + tcp_addr + ' port=' + tcp_port ; var gst_launch = new GstLaunch ( ) ; if ( gst_launch . isAvailable ( ) ) { console . log ( 'GstLaunch found: ' + gst_launch . getPath ( ) ) ; console . log ( 'GStreamer version: ' + gst_launch . getVersion ( ) ) ; console . log ( 'GStreamer pipeline: ' + cam_pipeline ) ; return gst_launch . spawnPipeline ( cam_pipeline ) ; } else { throw new Error ( 'GstLaunch not found.' ) ; } } return { 'start' : start } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! [CODESPLIT] function ( tcp_addr , tcp_port ) { Assert . ok ( typeof ( tcp_addr ) , 'string' ) ; Assert . ok ( typeof ( tcp_port ) , 'number' ) ; const cam_pipeline = gst_video_src + ' ! jpegenc ! multipartmux  boundary=\"' + gst_multipart_boundary + '\" ! tcpserversink host=' + tcp_addr + ' port=' + tcp_port ; var gst_launch = new GstLaunch ( ) ; if ( gst_launch . isAvailable ( ) ) { console . log ( 'GstLaunch found: ' + gst_launch . getPath ( ) ) ; console . log ( 'GStreamer version: ' + gst_launch . getVersion ( ) ) ; console . log ( 'GStreamer pipeline: ' + cam_pipeline ) ; return gst_launch . spawnPipeline ( cam_pipeline ) ; } else { throw new Error ( 'GstLaunch not found.' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! [CODESPLIT] function SocketCamWrapper ( gst_tcp_addr , gst_tcp_port , broadcast_tcp_addr , broadcast_tcp_port ) { const Net = require ( 'net' ) ; const Http = require ( 'http' ) ; const Dicer = require ( 'dicer' ) ; const Assert = require ( 'assert' ) ; const SocketIO = require ( 'socket.io' ) ; const gst_multipart_boundary = '--videoboundary' ; /*!\n   * @fn wrap\n   * @brief wraps a TCP server previously started by GstLiveCamServer.\n   */ var wrap = function ( gst_tcp_addr , gst_tcp_port , broadcast_tcp_addr , broadcast_tcp_port ) { Assert . ok ( typeof ( gst_tcp_addr ) , 'string' ) ; Assert . ok ( typeof ( gst_tcp_port ) , 'number' ) ; Assert . ok ( typeof ( broadcast_tcp_addr ) , 'string' ) ; Assert . ok ( typeof ( broadcast_tcp_port ) , 'number' ) ; var socket = Net . Socket ( ) ; socket . connect ( gst_tcp_port , gst_tcp_addr , function ( ) { var io = SocketIO . listen ( Http . createServer ( ) . listen ( broadcast_tcp_port , broadcast_tcp_addr ) ) ; var dicer = new Dicer ( { boundary : gst_multipart_boundary } ) ; dicer . on ( 'part' , function ( part ) { var frameEncoded = '' ; part . setEncoding ( 'base64' ) ; part . on ( 'data' , function ( data ) { frameEncoded += data ; } ) ; part . on ( 'end' , function ( ) { io . sockets . emit ( 'image' , frameEncoded ) ; } ) ; } ) ; dicer . on ( 'finish' , function ( ) { console . log ( 'Dicer finished: ' + broadcast_tcp_addr + ':' + broadcast_tcp_port ) ; } ) ; socket . on ( 'close' , function ( ) { console . log ( 'Socket closed: ' + broadcast_tcp_addr + ':' + broadcast_tcp_port ) ; } ) ; socket . pipe ( dicer ) ; } ) ; } return { 'wrap' : wrap } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! [CODESPLIT] function LiveCamUI ( ) { const Http = require ( 'http' ) ; const Assert = require ( 'assert' ) ; const template = ( function ( ) { /*\n    \t<!doctype html>\n    \t<html lang=\"en\">\n    \t\t<head>\n    \t\t\t<meta charset=\"utf-8\">\n    \t\t\t<title>livecam UI</title>\n    \t\t\t<script type=\"text/javascript\" src=\"https://cdn.socket.io/socket.io-1.4.5.js\"></script>\n    \t\t\t<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-1.12.4.min.js\"></script>\n    \t\t\t<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css\">\n    \t\t\t<style type=\"text/css\">html,body,.feed,.feed img{width:100%;height:100%;overflow:hidden;}</style>\n    \t\t</head>\n    \t\t<body>\n    \t\t\t<div class=\"feed\"><img id=\"video\" src=\"\" /></div>\n    \t\t\t<script>\n    \t\t\t\tvar webcam_addr = \"@WEBCAM_ADDR@\";\n    \t\t\t\tvar webcam_port = \"@WEBCAM_PORT@\";\n    \t\t\t\tvar webcam_host = $(\".feed img\");\n    \t\t\t\tvar socket = io.connect('http://' + webcam_addr + ':' + webcam_port);\n\n    \t\t\t\tsocket.on('image', function (data) {\n    \t\t\t\t\twebcam_host.attr(\"src\", \"data:image/jpeg;base64,\" + data );\n    \t\t\t\t});\n    \t\t\t</script>\n    \t\t</body>\n    \t</html>\n    \t*/ } ) . toString ( ) . match ( / \\/\\*\\s*([\\s\\S]*?)\\s*\\*\\/ / m ) [ 1 ] ; var server = undefined ; var serve = function ( ui_addr , ui_port , webcam_addr , webcam_port ) { Assert . ok ( typeof ( ui_addr ) , 'object' ) ; Assert . ok ( typeof ( ui_port ) , 'number' ) ; Assert . ok ( typeof ( webcam_addr ) , 'object' ) ; Assert . ok ( typeof ( webcam_port ) , 'number' ) ; close ( ) ; server = Http . createServer ( function ( request , response ) { response . writeHead ( 200 , { \"Content-Type\" : \"text/html\" } ) ; response . write ( template . replace ( '@WEBCAM_ADDR@' , webcam_addr ) . replace ( '@WEBCAM_PORT@' , webcam_port ) ) ; response . end ( ) ; } ) ; server . listen ( ui_port , ui_addr ) ; console . log ( 'Open http://' + ui_addr + ':' + ui_port + '/ in your browser!' ) ; } var close = function ( ) { if ( server ) { server . close ( ) ; server = undefined ; } } return { 'serve' : serve , 'close' : close } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! [CODESPLIT] function LiveCam ( config ) { const Assert = require ( 'assert' ) ; config = config || { } ; Assert . ok ( typeof ( config ) , 'object' ) ; const gst_tcp_addr = config . gst_addr || \"127.0.0.1\" ; const gst_tcp_port = config . gst_port || 10000 ; const ui_addr = config . ui_addr || \"127.0.0.1\" ; const ui_port = config . ui_port || 11000 ; const broadcast_addr = config . broadcast_addr || \"127.0.0.1\" ; const broadcast_port = config . broadcast_port || 12000 ; const start = config . start ; const webcam = config . webcam || { } ; if ( start ) Assert . ok ( typeof ( start ) , 'function' ) ; if ( broadcast_port ) Assert . ok ( typeof ( broadcast_port ) , 'number' ) ; if ( broadcast_addr ) Assert . ok ( typeof ( broadcast_addr ) , 'string' ) ; if ( ui_port ) Assert . ok ( typeof ( ui_port ) , 'number' ) ; if ( ui_addr ) Assert . ok ( typeof ( ui_addr ) , 'string' ) ; if ( gst_tcp_port ) Assert . ok ( typeof ( gst_tcp_port ) , 'number' ) ; if ( gst_tcp_addr ) Assert . ok ( typeof ( gst_tcp_addr ) , 'string' ) ; if ( webcam ) Assert . ok ( typeof ( webcam ) , 'object' ) ; if ( ! ( new GstLaunch ( ) ) . isAvailable ( ) ) { console . log ( \"==================================================\" ) ; console . log ( \"Unable to locate gst-launch executable.\" ) ; console . log ( \"Look at https://github.com/sepehr-laal/livecam\" ) ; console . log ( \"You are most likely missing the GStreamer runtime.\" ) ; console . log ( \"==================================================\" ) ; throw new Error ( 'Unable to broadcast.' ) ; } console . log ( \"LiveCam parameters:\" , { 'broadcast_addr' : broadcast_addr , 'broadcast_port' : broadcast_port , 'ui_addr' : ui_addr , 'ui_port' : ui_port , 'gst_tcp_addr' : gst_tcp_addr , 'gst_tcp_port' : gst_tcp_port } ) ; var broadcast = function ( ) { var gst_cam_ui = new LiveCamUI ( ) ; var gst_cam_wrap = new SocketCamWrapper ( ) ; var gst_cam_server = new GstLiveCamServer ( webcam ) ; var gst_cam_process = gst_cam_server . start ( gst_tcp_addr , gst_tcp_port ) ; gst_cam_process . stdout . on ( 'data' , function ( data ) { console . log ( data . toString ( ) ) ; // This catches GStreamer when pipeline goes into PLAYING state if ( data . toString ( ) . includes ( 'Setting pipeline to PLAYING' ) > 0 ) { gst_cam_wrap . wrap ( gst_tcp_addr , gst_tcp_port , broadcast_addr , broadcast_port ) ; gst_cam_ui . serve ( ui_addr , ui_port , broadcast_addr , broadcast_port ) ; gst_cam_ui . close ( ) ; if ( start ) start ( ) ; } } ) ; gst_cam_process . stderr . on ( 'data' , function ( data ) { console . log ( data . toString ( ) ) ; gst_cam_ui . close ( ) ; } ) ; gst_cam_process . on ( 'error' , function ( err ) { console . log ( \"Webcam server error: \" + err ) ; gst_cam_ui . close ( ) ; } ) ; gst_cam_process . on ( 'exit' , function ( code ) { console . log ( \"Webcam server exited: \" + code ) ; gst_cam_ui . close ( ) ; } ) ; } return { 'broadcast' : broadcast } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hex to RGB converter [CODESPLIT] function hexRgb ( hex ) { let shorthandCheck = / ^([a-f\\d])([a-f\\d])([a-f\\d])$ / i , rgbRegex = / ^([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$ / i , rgb ; hex = hex . replace ( shorthandCheck , function ( m , r , g , b ) { return r + r + g + g + b + b ; } ) ; rgb = hex . replace ( / ^\\s+|\\s+$ / g , '' ) . match ( rgbRegex ) ; // Convert it return rgb ? [ parseInt ( rgb [ 1 ] , 16 ) , parseInt ( rgb [ 2 ] , 16 ) , parseInt ( rgb [ 3 ] , 16 ) ] : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CSS rule handler [CODESPLIT] function ruleHandler ( decl , result ) { let input = decl . value ; // Get the raw hex values and replace them let output = input . replace ( / rgba\\(#(.*?), / g , ( match , hex ) => { let rgb = hexRgb ( hex ) , matchHex = new RegExp ( '#' + hex ) ; // If conversion fails, emit a warning if ( ! rgb ) { result . warn ( 'not a valid hex' , { node : decl } ) ; return match ; } rgb = rgb . toString ( ) ; return match . replace ( matchHex , rgb ) ; } ) ; decl . replaceWith ( { prop : decl . prop , value : output , important : decl . important } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Segment service [CODESPLIT] function Segment ( config ) { this . config = config ; // Checks condition before calling Segment method this . factory = function ( method ) { var _this = this ; return function ( ) { // If a condition has been set, only call the Segment method if it returns true if ( _this . config . condition && ! _this . config . condition ( method , arguments ) ) { _this . debug ( 'Not calling method, condition returned false.' , { method : method , arguments : arguments , } ) ; return ; } //  No condition set, call the Segment method _this . debug ( 'Calling method ' + method + ' with arguments:' , arguments ) ; return window . analytics [ method ] . apply ( analytics , arguments ) ; } ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates analytics . js method stubs [CODESPLIT] function ( ) { for ( var i = 0 ; i < this . config . methods . length ; i ++ ) { var key = this . config . methods [ i ] ; // Only create analytics stub if it doesn't already exist if ( ! analytics [ key ] ) { analytics [ key ] = analytics . factory ( key ) ; } this [ key ] = this . factory ( key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Segment provider available during . config () Angular app phase . Inherits from Segment prototype . [CODESPLIT] function SegmentProvider ( segmentDefaultConfig ) { this . config = angular . copy ( segmentDefaultConfig ) ; // Stores any analytics.js method calls this . queue = [ ] ; // Overwrite Segment factory to queue up calls if condition has been set this . factory = function ( method ) { var queue = this . queue ; return function ( ) { // Defer calling analytics.js methods until the service is instantiated queue . push ( { method : method , arguments : arguments } ) ; } ; } ; // Create method stubs using overridden factory this . init ( ) ; this . setKey = function ( apiKey ) { this . config . apiKey = apiKey ; this . validate ( 'apiKey' ) ; return this ; } ; this . setLoadDelay = function ( milliseconds ) { this . config . loadDelay = milliseconds ; this . validate ( 'loadDelay' ) ; return this ; } ; this . setCondition = function ( callback ) { this . config . condition = callback ; this . validate ( 'condition' ) ; return this ; } ; this . setEvents = function ( events ) { this . events = events ; return this ; } ; this . setConfig = function ( config ) { if ( ! angular . isObject ( config ) ) { throw new Error ( this . config . tag + 'Config must be an object.' ) ; } angular . extend ( this . config , config ) ; // Validate new settings var _this = this ; Object . keys ( config ) . forEach ( function ( key ) { _this . validate ( key ) ; } ) ; return this ; } ; this . setAutoload = function ( bool ) { this . config . autoload = ! ! bool ; return this ; } ; this . setDebug = function ( bool ) { this . config . debug = ! ! bool ; return this ; } ; var validations = { apiKey : function ( config ) { if ( ! angular . isString ( config . apiKey ) || ! config . apiKey ) { throw new Error ( config . tag + 'API key must be a valid string.' ) ; } } , loadDelay : function ( config ) { if ( ! angular . isNumber ( config . loadDelay ) ) { throw new Error ( config . tag + 'Load delay must be a number.' ) ; } } , condition : function ( config ) { if ( ! angular . isFunction ( config . condition ) && ! ( angular . isArray ( config . condition ) && angular . isFunction ( config . condition [ config . condition . length - 1 ] ) ) ) { throw new Error ( config . tag + 'Condition callback must be a function or array.' ) ; } } , } ; // Allows validating a specific property after set[Prop] // or all config after provider/constant config this . validate = function ( property ) { if ( typeof validations [ property ] === 'function' ) { validations [ property ] ( this . config ) ; } } ; this . createService = function ( $injector , segmentLoader ) { // Apply user-provided config constant if it exists if ( $injector . has ( 'segmentConfig' ) ) { var constant = $injector . get ( 'segmentConfig' ) ; if ( ! angular . isObject ( constant ) ) { throw new Error ( this . config . tag + 'Config constant must be an object.' ) ; } angular . extend ( this . config , constant ) ; this . debug ( 'Found segment config constant' ) ; // Validate settings passed in by constant var _this = this ; Object . keys ( constant ) . forEach ( function ( key ) { _this . validate ( key ) ; } ) ; } // Autoload Segment on service instantiation if an API key has been set via the provider if ( this . config . autoload ) { this . debug ( 'Autoloading Analytics.js' ) ; if ( this . config . apiKey ) { segmentLoader . load ( this . config . apiKey , this . config . loadDelay ) ; } else { this . debug ( this . config . tag + ' Warning: API key is not set and autoload is not disabled.' ) ; } } // Create dependency-injected condition if ( typeof this . config . condition === 'function' || ( typeof this . config . condition === 'array' && typeof this . config . condition [ this . config . condition - 1 ] === 'function' ) ) { var condition = this . config . condition ; this . config . condition = function ( method , params ) { return $injector . invoke ( condition , condition , { method : method , params : params } ) ; } ; } // Pass any provider-set configuration down to the service var segment = new Segment ( angular . copy ( this . config ) ) ; // Transfer events if set if ( this . events ) { segment . events = angular . copy ( this . events ) ; } // Set up service method stubs segment . init ( ) ; // Play back any segment calls that were made against the provider now that the // condition callback has been injected with dependencies this . queue . forEach ( function ( item ) { segment [ item . method ] . apply ( segment , item . arguments ) ; } ) ; return segment ; } ; // Returns segment service and creates dependency-injected condition callback, if provided this . $get = [ '$injector' , 'segmentLoader' , this . createService ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In hindsight we can do without most of ES6 ( str obj ) - > transformStream [CODESPLIT] function es2020 ( filename , options ) { if ( / \\.json$ / i . test ( filename ) ) return through ( ) const bufs = [ ] const transformStream = through ( write , end ) return transformStream function write ( buf , enc , next ) { bufs . push ( buf ) next ( ) } function end ( ) { const src = Buffer . concat ( bufs ) . toString ( 'utf8' ) try { var res = babel . transform ( src , { plugins : preset . plugins , sourceMaps : options . _flags . debug ? 'inline' : false , filename : filename , compact : false } ) } catch ( err ) { this . emit ( 'error' , err ) return } this . push ( res . code ) this . push ( null ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For each small multiple… [CODESPLIT] function bulvar ( g ) { g . each ( function ( d , i ) { var rangez = ranges . call ( this , d , i ) . slice ( ) . sort ( d3Descending ) , markerz = markers . call ( this , d , i ) . slice ( ) . sort ( d3Descending ) , measurez = measures . call ( this , d , i ) . slice ( ) . sort ( d3Descending ) , g2 = d3Select ( this ) , extentX , extentY ; var wrap = g2 . select ( \"g.wrap\" ) ; if ( wrap . empty ( ) ) wrap = g2 . append ( \"g\" ) . attr ( \"class\" , \"wrap\" ) ; if ( vertical ) { extentX = height , extentY = width ; wrap . attr ( \"transform\" , \"rotate(90)translate(0,\" + - width + \")\" ) ; } else { extentX = width , extentY = height ; wrap . attr ( \"transform\" , null ) ; } // Compute the new x-scale. var x1 = d3ScaleLinear ( ) . domain ( [ 0 , Math . max ( rangez [ 0 ] , markerz [ 0 ] , measurez [ 0 ] ) ] ) . range ( reverse ? [ extentX , 0 ] : [ 0 , extentX ] ) ; // Retrieve the old x-scale, if this is an update. var x0 = this . __chart__ || d3ScaleLinear ( ) . domain ( [ 0 , Infinity ] ) . range ( x1 . range ( ) ) ; // Stash the new scale. this . __chart__ = x1 ; // Derive width-scales from the x-scales. var w0 = bulvarWidth ( x0 ) , w1 = bulvarWidth ( x1 ) ; // Update the range rects. var range = wrap . selectAll ( \"rect.range\" ) . data ( rangez ) ; range . enter ( ) . append ( \"rect\" ) . attr ( \"class\" , function ( _d , i2 ) { return \"range s\" + i2 ; } ) . attr ( \"width\" , w0 ) . attr ( \"height\" , extentY ) . attr ( \"x\" , reverse ? x0 : 0 ) . merge ( range ) . transition ( range ) . attr ( \"x\" , reverse ? x1 : 0 ) . attr ( \"width\" , w1 ) . attr ( \"height\" , extentY ) ; // Update the measure rects. var measure = wrap . selectAll ( \"rect.measure\" ) . data ( measurez ) ; measure . enter ( ) . append ( \"rect\" ) . attr ( \"class\" , function ( _d , i2 ) { return \"measure s\" + i2 ; } ) . attr ( \"width\" , w0 ) . attr ( \"height\" , extentY / 3 ) . attr ( \"x\" , reverse ? x0 : 0 ) . attr ( \"y\" , extentY / 3 ) . merge ( measure ) . transition ( measure ) . attr ( \"width\" , w1 ) . attr ( \"height\" , extentY / 3 ) . attr ( \"x\" , reverse ? x1 : 0 ) . attr ( \"y\" , extentY / 3 ) ; // Update the marker lines. var marker = wrap . selectAll ( \"line.marker\" ) . data ( markerz ) ; marker . enter ( ) . append ( \"line\" ) . attr ( \"class\" , \"marker\" ) . attr ( \"x1\" , x0 ) . attr ( \"x2\" , x0 ) . attr ( \"y1\" , extentY / 6 ) . attr ( \"y2\" , extentY * 5 / 6 ) . merge ( marker ) . transition ( marker ) . attr ( \"x1\" , x1 ) . attr ( \"x2\" , x1 ) . attr ( \"y1\" , extentY / 6 ) . attr ( \"y2\" , extentY * 5 / 6 ) ; var axis = g2 . selectAll ( \"g.axis\" ) . data ( [ 0 ] ) ; axis . enter ( ) . append ( \"g\" ) . attr ( \"class\" , \"axis\" ) ; axis . attr ( \"transform\" , vertical ? null : \"translate(0,\" + extentY + \")\" ) . call ( xAxis . scale ( x1 ) ) ; } ) ; d3TimerFlush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the Name - Based UUID hashes v3 and v5 according to RFC - 4122 https : // tools . ietf . org / html / rfc4122#section - 4 . 3 [CODESPLIT] function generateUuid ( target , namespace , version ) { if ( typeof target !== 'string' ) { throw TypeError ( 'Value must be string' ) ; } if ( typeof namespace === 'number' ) { return generateUuid ( target , undefined , namespace ) ; } if ( version == null ) { return generateUuid ( target , namespace , 5 ) ; } if ( version !== 3 && version !== 5 ) { throw TypeError ( 'Version of UUID can be only 3 or 5' ) ; } // Parsing target chars var charBuffer = lib . stringToCharBuffer ( target ) ; // TODO: Test namespace for uuid and parse to buffer var namespaceCharBuffer = typeof namespace === 'string' ? lib . stringToCharBuffer ( namespace ) : EMPTY_UINT8_ARRAY ; // Concatenation two buffers of strings to one var buffer = lib . concatBuffers ( namespaceCharBuffer , charBuffer ) ; // Getting hash var hash = version === 3 ? lib . md5Hash ( buffer ) : lib . sha1Hash ( buffer ) ; return lib . hashToUuid ( hash , version ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get color for value [CODESPLIT] function getColorGrad ( pct , col , maxBri ) { var no , inc , colors , percentage , rval , gval , bval , lower , upper , range , rangePct , pctLower , pctUpper , color , pow ; no = col . length ; if ( no === 1 ) return col [ 0 ] ; inc = 1 / ( no - 1 ) ; colors = [ ] ; for ( var i = 0 ; i < col . length ; i ++ ) { if ( typeof col [ i ] === 'object' ) { percentage = col [ i ] . pct ? col [ i ] . pct : inc * i ; pow = col [ i ] . pow || 1 ; rval = parseInt ( ( cutHex ( col [ i ] . color ) ) . substring ( 0 , 2 ) , 16 ) ; gval = parseInt ( ( cutHex ( col [ i ] . color ) ) . substring ( 2 , 4 ) , 16 ) ; bval = parseInt ( ( cutHex ( col [ i ] . color ) ) . substring ( 4 , 6 ) , 16 ) ; } else { percentage = inc * i ; pow = 1 ; rval = parseInt ( ( cutHex ( col [ i ] ) ) . substring ( 0 , 2 ) , 16 ) ; gval = parseInt ( ( cutHex ( col [ i ] ) ) . substring ( 2 , 4 ) , 16 ) ; bval = parseInt ( ( cutHex ( col [ i ] ) ) . substring ( 4 , 6 ) , 16 ) ; } colors [ i ] = { pct : percentage , pow : pow , color : { r : rval , g : gval , b : bval } } ; } if ( pct === 0 ) { return 'rgb(' + [ colors [ 0 ] . color . r , colors [ 0 ] . color . g , colors [ 0 ] . color . b ] . join ( ',' ) + ')' ; } for ( var j = 0 ; j < colors . length ; j ++ ) { if ( pct <= colors [ j ] . pct ) { var colorMax = Math . max ( colors [ j ] . color . r , colors [ j ] . color . g , colors [ j ] . color . b ) ; lower = colors [ j - 1 ] ; upper = colors [ j ] ; range = upper . pct - lower . pct ; rangePct = Math . pow ( ( pct - lower . pct ) / range , colors [ j ] . pow / colors [ j - 1 ] . pow ) ; pctLower = 1 - rangePct ; pctUpper = rangePct ; color = { r : Math . floor ( lower . color . r * pctLower + upper . color . r * pctUpper ) , g : Math . floor ( lower . color . g * pctLower + upper . color . g * pctUpper ) , b : Math . floor ( lower . color . b * pctLower + upper . color . b * pctUpper ) } ; if ( maxBri ) { var colorMax2 = Math . max ( color . r , color . g , color . b ) ; return 'rgb(' + [ Math . floor ( color . r / colorMax2 * colorMax ) , Math . floor ( color . g / colorMax2 * colorMax ) , Math . floor ( color . b / colorMax2 * colorMax ) ] . join ( ',' ) + ')' ; } else { return 'rgb(' + [ color . r , color . g , color . b ] . join ( ',' ) + ')' ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tiny helper function to lookup value of a key from two hash tables if none found return defaultvalue key : string tablea : object tableb : DOMStringMap|object defval : string|integer|float|null datatype : return datatype delimiter : delimiter to be used in conjunction with datatype formatting [CODESPLIT] function kvLookup ( key , tablea , tableb , defval , datatype , delimiter ) { var val = defval ; var canConvert = false ; if ( ! ( key === null || key === undefined ) ) { if ( tableb !== null && tableb !== undefined && typeof tableb === \"object\" && key in tableb ) { val = tableb [ key ] ; canConvert = true ; } else if ( tablea !== null && tablea !== undefined && typeof tablea === \"object\" && key in tablea ) { val = tablea [ key ] ; canConvert = true ; } else { val = defval ; } if ( canConvert === true ) { if ( datatype !== null && datatype !== undefined ) { switch ( datatype ) { case 'int' : val = parseInt ( val , 10 ) ; break ; case 'float' : val = parseFloat ( val ) ; break ; default : break ; } } } } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get color for value [CODESPLIT] function getColor ( val , pct , col , noGradient , custSec , fullBri ) { var no , inc , colors , percentage , rval , gval , bval , lower , upper , range , rangePct , pctLower , pctUpper , color , pow ; var noGradient = noGradient || custSec . length > 0 ; if ( custSec . length > 0 ) { for ( var i = 0 ; i < custSec . length ; i ++ ) { if ( val >= custSec [ i ] . lo && val <= custSec [ i ] . hi ) { return custSec [ i ] . color ; } } } no = col . length ; if ( no === 1 ) return col [ 0 ] ; inc = ( noGradient ) ? ( 1 / no ) : ( 1 / ( no - 1 ) ) ; colors = [ ] ; for ( i = 0 ; i < col . length ; i ++ ) { if ( typeof col [ i ] === 'object' ) { percentage = col [ i ] . pct ? col [ i ] . pct : ( ( noGradient ) ? ( inc * ( i + 1 ) ) : ( inc * i ) ) ; pow = col [ i ] . pow || 1 ; rval = parseInt ( ( cutHex ( col [ i ] . color ) ) . substring ( 0 , 2 ) , 16 ) ; gval = parseInt ( ( cutHex ( col [ i ] . color ) ) . substring ( 2 , 4 ) , 16 ) ; bval = parseInt ( ( cutHex ( col [ i ] . color ) ) . substring ( 4 , 6 ) , 16 ) ; } else { percentage = ( noGradient ) ? ( inc * ( i + 1 ) ) : ( inc * i ) ; pow = 1 ; rval = parseInt ( ( cutHex ( col [ i ] ) ) . substring ( 0 , 2 ) , 16 ) ; gval = parseInt ( ( cutHex ( col [ i ] ) ) . substring ( 2 , 4 ) , 16 ) ; bval = parseInt ( ( cutHex ( col [ i ] ) ) . substring ( 4 , 6 ) , 16 ) ; } colors [ i ] = { pct : percentage , pow : pow , color : { r : rval , g : gval , b : bval } } ; } if ( pct === 0 ) { return 'rgb(' + [ colors [ 0 ] . color . r , colors [ 0 ] . color . g , colors [ 0 ] . color . b ] . join ( ',' ) + ')' ; } for ( var j = 0 ; j < colors . length ; j ++ ) { if ( pct <= colors [ j ] . pct ) { var colorMax = Math . max ( colors [ j ] . color . r , colors [ j ] . color . g , colors [ j ] . color . b ) ; if ( noGradient ) { return 'rgb(' + [ colors [ j ] . color . r , colors [ j ] . color . g , colors [ j ] . color . b ] . join ( ',' ) + ')' ; } else { lower = colors [ j - 1 ] ; upper = colors [ j ] ; range = upper . pct - lower . pct ; rangePct = Math . pow ( ( pct - lower . pct ) / range , colors [ j ] . pow / colors [ j - 1 ] . pow ) ; pctLower = 1 - rangePct ; pctUpper = rangePct ; color = { r : Math . floor ( lower . color . r * pctLower + upper . color . r * pctUpper ) , g : Math . floor ( lower . color . g * pctLower + upper . color . g * pctUpper ) , b : Math . floor ( lower . color . b * pctLower + upper . color . b * pctUpper ) } ; if ( fullBri ) { colorMax2 = Math . max ( color . r , color . g , color . b ) ; return 'rgb(' + [ Math . floor ( color . r / colorMax2 * colorMax ) , Math . floor ( color . g / colorMax2 * colorMax ) , Math . floor ( color . b / colorMax2 * colorMax ) ] . join ( ',' ) + ')' ; } else { return 'rgb(' + [ color . r , color . g , color . b ] . join ( ',' ) + ')' ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fix Raphael display : none tspan dy attribute bug [CODESPLIT] function setDy ( elem , fontSize , txtYpos ) { if ( ( ! ie || ie > 9 ) && elem . node . firstChild . attributes . dy ) { elem . node . firstChild . attributes . dy . value = 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Human friendly number suffix - From : http : // stackoverflow . com / questions / 2692323 / code - golf - friendly - number - abbreviator [CODESPLIT] function humanFriendlyNumber ( n , d ) { var p , d2 , i , s ; p = Math . pow ; d2 = p ( 10 , d ) ; i = 7 ; while ( i ) { s = p ( 10 , i -- * 3 ) ; if ( s <= n ) { n = Math . round ( n * d2 / s ) / d2 + \"KMGTPE\" [ i ] ; } } return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format numbers with commas - From : http : // stackoverflow . com / questions / 2901102 / how - to - print - a - number - with - commas - as - thousands - separators - in - javascript [CODESPLIT] function formatNumber ( x ) { var parts = x . toString ( ) . split ( \".\" ) ; parts [ 0 ] = parts [ 0 ] . replace ( / \\B(?=(\\d{3})+(?!\\d)) / g , \",\" ) ; return parts . join ( \".\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Short format for ms . [CODESPLIT] function fmtShort ( ms ) { if ( ms >= d$1 ) { return Math . round ( ms / d$1 ) + 'd' } if ( ms >= h ) { return Math . round ( ms / h ) + 'h' } if ( ms >= m ) { return Math . round ( ms / m ) + 'm' } if ( ms >= s ) { return Math . round ( ms / s ) + 's' } return ms + 'ms' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Long format for ms . [CODESPLIT] function fmtLong ( ms ) { return plural ( ms , d$1 , 'day' ) || plural ( ms , h , 'hour' ) || plural ( ms , m , 'minute' ) || plural ( ms , s , 'second' ) || ms + ' ms' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a debugger with the given namespace . [CODESPLIT] function debug ( namespace ) { // define the `disabled` version function disabled ( ) { } disabled . enabled = false ; // define the `enabled` version function enabled ( ) { var self = enabled ; // set `diff` timestamp var curr = + new Date ( ) ; var ms = curr - ( prevTime || curr ) ; self . diff = ms ; self . prev = prevTime ; self . curr = curr ; prevTime = curr ; // add the `color` if not set if ( null == self . useColors ) self . useColors = exports . useColors ( ) ; if ( null == self . color && self . useColors ) self . color = selectColor ( ) ; var args = new Array ( arguments . length ) ; for ( var i = 0 ; i < args . length ; i ++ ) { args [ i ] = arguments [ i ] ; } args [ 0 ] = exports . coerce ( args [ 0 ] ) ; if ( 'string' !== typeof args [ 0 ] ) { // anything else let's inspect with %o args = [ '%o' ] . concat ( args ) ; } // apply any `formatters` transformations var index = 0 ; args [ 0 ] = args [ 0 ] . replace ( / %([a-z%]) / g , function ( match , format ) { // if we encounter an escaped % then don't increase the array index if ( match === '%%' ) return match ; index ++ ; var formatter = exports . formatters [ format ] ; if ( 'function' === typeof formatter ) { var val = args [ index ] ; match = formatter . call ( self , val ) ; // now we need to remove `args[index]` since it's inlined in the `format` args . splice ( index , 1 ) ; index -- ; } return match ; } ) ; // apply env-specific formatting args = exports . formatArgs . apply ( self , args ) ; var logFn = enabled . log || exports . log || console . log . bind ( console ) ; logFn . apply ( self , args ) ; } enabled . enabled = true ; var fn = exports . enabled ( namespace ) ? enabled : disabled ; fn . namespace = namespace ; return fn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables a debug mode by namespaces . This can include modes separated by a colon and wildcards . [CODESPLIT] function enable ( namespaces ) { exports . save ( namespaces ) ; var split = ( namespaces || '' ) . split ( / [\\s,]+ / ) ; var len = split . length ; for ( var i = 0 ; i < len ; i ++ ) { if ( ! split [ i ] ) continue ; // ignore empty strings namespaces = split [ i ] . replace ( / [\\\\^$+?.()|[\\]{}] / g , '\\\\$&' ) . replace ( / \\* / g , '.*?' ) ; if ( namespaces [ 0 ] === '-' ) { exports . skips . push ( new RegExp ( '^' + namespaces . substr ( 1 ) + '$' ) ) ; } else { exports . names . push ( new RegExp ( '^' + namespaces + '$' ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse or format the given val . [CODESPLIT] function ( val , options ) { options = options || { } ; if ( 'string' == typeof val ) return parse$1 ( val ) ; return options . long ? long ( val ) : short ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given str and return milliseconds . [CODESPLIT] function parse$1 ( str ) { str = '' + str ; if ( str . length > 10000 ) return ; var match = / ^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$ / i . exec ( str ) ; if ( ! match ) return ; var n = parseFloat ( match [ 1 ] ) ; var type = ( match [ 2 ] || 'ms' ) . toLowerCase ( ) ; switch ( type ) { case 'years' : case 'year' : case 'yrs' : case 'yr' : case 'y' : return n * y$1 ; case 'days' : case 'day' : case 'd' : return n * d$2 ; case 'hours' : case 'hour' : case 'hrs' : case 'hr' : case 'h' : return n * h$1 ; case 'minutes' : case 'minute' : case 'mins' : case 'min' : case 'm' : return n * m$1 ; case 'seconds' : case 'second' : case 'secs' : case 'sec' : case 's' : return n * s$1 ; case 'milliseconds' : case 'millisecond' : case 'msecs' : case 'msec' : case 'ms' : return n ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Short format for ms . [CODESPLIT] function short ( ms ) { if ( ms >= d$2 ) return Math . round ( ms / d$2 ) + 'd' ; if ( ms >= h$1 ) return Math . round ( ms / h$1 ) + 'h' ; if ( ms >= m$1 ) return Math . round ( ms / m$1 ) + 'm' ; if ( ms >= s$1 ) return Math . round ( ms / s$1 ) + 's' ; return ms + 'ms' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Long format for ms . [CODESPLIT] function long ( ms ) { return plural$1 ( ms , d$2 , 'day' ) || plural$1 ( ms , h$1 , 'hour' ) || plural$1 ( ms , m$1 , 'minute' ) || plural$1 ( ms , s$1 , 'second' ) || ms + ' ms' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pluralization helper . [CODESPLIT] function plural$1 ( ms , n , name ) { if ( ms < n ) return ; if ( ms < n * 1.5 ) return Math . floor ( ms / n ) + ' ' + name ; return Math . ceil ( ms / n ) + ' ' + name + 's' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if obj is a buffer or an arraybuffer . [CODESPLIT] function isBuf$1 ( obj ) { return ( commonjsGlobal . Buffer && commonjsGlobal . Buffer . isBuffer ( obj ) ) || ( commonjsGlobal . ArrayBuffer && obj instanceof ArrayBuffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a string representing the specified number . [CODESPLIT] function encode$1 ( num ) { var encoded = '' ; do { encoded = alphabet [ num % length ] + encoded ; num = Math . floor ( num / length ) ; } while ( num > 0 ) ; return encoded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the integer value specified by the given string . [CODESPLIT] function decode$1 ( str ) { var decoded = 0 ; for ( i = 0 ; i < str . length ; i ++ ) { decoded = decoded * length + map [ str . charAt ( i ) ] ; } return decoded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Yeast : A tiny growing id generator . [CODESPLIT] function yeast$1 ( ) { var now = encode$1 ( + new Date ( ) ) ; if ( now !== prev ) return seed = 0 , prev = now ; return now + '.' + encode$1 ( seed ++ ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse or format the given val . [CODESPLIT] function ( val , options ) { options = options || { } ; var type = typeof val ; if ( type === 'string' && val . length > 0 ) { return parse$2 ( val ) } else if ( type === 'number' && isNaN ( val ) === false ) { return options . long ? fmtLong$1 ( val ) : fmtShort$1 ( val ) } throw new Error ( 'val is not a non-empty string or a valid number. val=' + JSON . stringify ( val ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given str and return milliseconds . [CODESPLIT] function parse$2 ( str ) { str = String ( str ) ; if ( str . length > 10000 ) { return } var match = / ^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$ / i . exec ( str ) ; if ( ! match ) { return } var n = parseFloat ( match [ 1 ] ) ; var type = ( match [ 2 ] || 'ms' ) . toLowerCase ( ) ; switch ( type ) { case 'years' : case 'year' : case 'yrs' : case 'yr' : case 'y' : return n * y$2 case 'days' : case 'day' : case 'd' : return n * d$3 case 'hours' : case 'hour' : case 'hrs' : case 'hr' : case 'h' : return n * h$2 case 'minutes' : case 'minute' : case 'mins' : case 'min' : case 'm' : return n * m$2 case 'seconds' : case 'second' : case 'secs' : case 'sec' : case 's' : return n * s$2 case 'milliseconds' : case 'millisecond' : case 'msecs' : case 'msec' : case 'ms' : return n default : return undefined } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Short format for ms . [CODESPLIT] function fmtShort$1 ( ms ) { if ( ms >= d$3 ) { return Math . round ( ms / d$3 ) + 'd' } if ( ms >= h$2 ) { return Math . round ( ms / h$2 ) + 'h' } if ( ms >= m$2 ) { return Math . round ( ms / m$2 ) + 'm' } if ( ms >= s$2 ) { return Math . round ( ms / s$2 ) + 's' } return ms + 'ms' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Long format for ms . [CODESPLIT] function fmtLong$1 ( ms ) { return plural$2 ( ms , d$3 , 'day' ) || plural$2 ( ms , h$2 , 'hour' ) || plural$2 ( ms , m$2 , 'minute' ) || plural$2 ( ms , s$2 , 'second' ) || ms + ' ms' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pluralization helper . [CODESPLIT] function plural$2 ( ms , n , name ) { if ( ms < n ) { return } if ( ms < n * 1.5 ) { return Math . floor ( ms / n ) + ' ' + name } return Math . ceil ( ms / n ) + ' ' + name + 's' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Polling interface . [CODESPLIT] function Polling$1 ( opts ) { var forceBase64 = ( opts && opts . forceBase64 ) ; if ( ! hasXHR2 || forceBase64 ) { this . supportsBinary = false ; } Transport . call ( this , opts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JSONP Polling constructor . [CODESPLIT] function JSONPPolling ( opts ) { Polling$2 . call ( this , opts ) ; this . query = this . query || { } ; // define global callbacks array if not present // we do this here (lazily) to avoid unneeded global pollution if ( ! callbacks ) { // we need to consider multiple engines in the same page if ( ! commonjsGlobal . ___eio ) commonjsGlobal . ___eio = [ ] ; callbacks = commonjsGlobal . ___eio ; } // callback identifier this . index = callbacks . length ; // add callback to jsonp global var self = this ; callbacks . push ( function ( msg ) { self . onData ( msg ) ; } ) ; // append to query string this . query . j = this . index ; // prevent spurious errors from being emitted when the window is unloaded if ( commonjsGlobal . document && commonjsGlobal . addEventListener ) { commonjsGlobal . addEventListener ( 'beforeunload' , function ( ) { if ( self . script ) self . script . onerror = empty$1 ; } , false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When the socket is upgraded while we re probing [CODESPLIT] function onupgrade ( to ) { if ( transport$$1 && to . name !== transport$$1 . name ) { debug$2 ( '\"%s\" works - aborting \"%s\"' , to . name , transport$$1 . name ) ; freezeTransport ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all listeners on the transport and on self [CODESPLIT] function cleanup ( ) { transport$$1 . removeListener ( 'open' , onTransportOpen ) ; transport$$1 . removeListener ( 'error' , onerror ) ; transport$$1 . removeListener ( 'close' , onTransportClose ) ; self . removeListener ( 'close' , onclose ) ; self . removeListener ( 'upgrading' , onupgrade ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize backoff timer with opts . [CODESPLIT] function Backoff$1 ( opts ) { opts = opts || { } ; this . ms = opts . min || 100 ; this . max = opts . max || 10000 ; this . factor = opts . factor || 2 ; this . jitter = opts . jitter > 0 && opts . jitter <= 1 ? opts . jitter : 0 ; this . attempts = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse or format the given val . [CODESPLIT] function ( val , options ) { options = options || { } ; var type = typeof val ; if ( type === 'string' && val . length > 0 ) { return parse$3 ( val ) ; } else if ( type === 'number' && isNaN ( val ) === false ) { return options . long ? fmtLong$2 ( val ) : fmtShort$2 ( val ) ; } throw new Error ( 'val is not a non-empty string or a valid number. val=' + JSON . stringify ( val ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given str and return milliseconds . [CODESPLIT] function parse$3 ( str ) { str = String ( str ) ; if ( str . length > 100 ) { return ; } var match = / ^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$ / i . exec ( str ) ; if ( ! match ) { return ; } var n = parseFloat ( match [ 1 ] ) ; var type = ( match [ 2 ] || 'ms' ) . toLowerCase ( ) ; switch ( type ) { case 'years' : case 'year' : case 'yrs' : case 'yr' : case 'y' : return n * y$3 ; case 'days' : case 'day' : case 'd' : return n * d$4 ; case 'hours' : case 'hour' : case 'hrs' : case 'hr' : case 'h' : return n * h$3 ; case 'minutes' : case 'minute' : case 'mins' : case 'min' : case 'm' : return n * m$3 ; case 'seconds' : case 'second' : case 'secs' : case 'sec' : case 's' : return n * s$3 ; case 'milliseconds' : case 'millisecond' : case 'msecs' : case 'msec' : case 'ms' : return n ; default : return undefined ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Short format for ms . [CODESPLIT] function fmtShort$2 ( ms ) { if ( ms >= d$4 ) { return Math . round ( ms / d$4 ) + 'd' ; } if ( ms >= h$3 ) { return Math . round ( ms / h$3 ) + 'h' ; } if ( ms >= m$3 ) { return Math . round ( ms / m$3 ) + 'm' ; } if ( ms >= s$3 ) { return Math . round ( ms / s$3 ) + 's' ; } return ms + 'ms' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Long format for ms . [CODESPLIT] function fmtLong$2 ( ms ) { return plural$3 ( ms , d$4 , 'day' ) || plural$3 ( ms , h$3 , 'hour' ) || plural$3 ( ms , m$3 , 'minute' ) || plural$3 ( ms , s$3 , 'second' ) || ms + ' ms' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pluralization helper . [CODESPLIT] function plural$3 ( ms , n , name ) { if ( ms < n ) { return ; } if ( ms < n * 1.5 ) { return Math . floor ( ms / n ) + ' ' + name ; } return Math . ceil ( ms / n ) + ' ' + name + 's' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract code comments from the given string . [CODESPLIT] function extract ( str , options ) { const res = babylon . parse ( str , options ) ; return res . comments ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extends the API returned by noUiSlider with the $on function which wraps the on function to use Angular . [CODESPLIT] function extendApi ( api ) { api . $on = ( eventName , callback ) => { const wrappedCallback = ( ) => { $timeout ( ( ) => { callback ( api . get ( ) ) ; } ) ; } ; api . on ( eventName , wrappedCallback ) ; return ( ) => { api . off ( eventName , wrappedCallback ) ; } ; } ; return api ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a watcher that looks for changes in the slider - options directive attribute . When a change is detected the options for the noUiSlider instance are updated . Note that only the margin limit step range animate and snap options can be updated this way ( as documented in https : // refreshless . com / nouislider / more / #section - update ) . All other option updates require you to destroy the current instance and create a new one . [CODESPLIT] function setOptionsWatcher ( api ) { scope . $watch ( 'options' , ( newOptions , oldOptions ) => { if ( angular . equals ( newOptions , oldOptions ) ) { return ; } options = angular . copy ( scope . options ) ; api . updateOptions ( options ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add ngModel controls to the directive . This allows the use of ngModel to set and get the value in the slider . It uses the noUiSlider API s get and set functions so no custom formatters need to be defined for ngModel . The ngModelOptions can be used . [CODESPLIT] function bindNgModelControls ( api ) { ngModel . $render = ( ) => { api . set ( ngModel . $modelValue ) ; } ; api . on ( 'update' , ( ) => { const positions = api . get ( ) ; ngModel . $setViewValue ( positions ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A utility function that returns a promise which resolves when ngModel is correctly loaded using $timeout . [CODESPLIT] function initializeNgModel ( ) { if ( ngModel === null ) { return $q . resolve ( null ) ; } return $q ( ( resolve ) => { $timeout ( ( ) => { if ( ! ( angular . isArray ( ngModel . $modelValue ) || angular . isNumber ( ngModel . $modelValue ) ) ) { throw new Error ( ` ${ ngModel . $modelValue } ` ) ; } resolve ( ngModel . $modelValue ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a noUiSlider instance . [CODESPLIT] function createInstance ( ) { const api = extendApi ( noUiSlider . create ( htmlElement , options ) ) ; setCreatedWatcher ( api ) ; setOptionsWatcher ( api ) ; if ( ngModel !== null ) { bindNgModelControls ( api ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "suffix fixes [CODESPLIT] function postprocess ( arr ) { //trim whitespace arr = arr . map ( function ( w ) { return w . trim ( ) ; } ) ; arr = arr . filter ( function ( w ) { return w !== '' ; } ) ; // if (arr.length > 2) { //   return arr; // } let l = arr . length ; if ( l > 1 ) { let suffix = arr [ l - 2 ] + arr [ l - 1 ] ; for ( let i = 0 ; i < ones . length ; i ++ ) { if ( suffix . match ( ones [ i ] ) ) { arr [ l - 2 ] = arr [ l - 2 ] + arr [ l - 1 ] ; arr . pop ( ) ; } } } // since the open syllable detection is overzealous, // sometimes need to rejoin incorrect splits if ( arr . length > 1 ) { let first_is_open = ( arr [ 0 ] . length === 1 || arr [ 0 ] . match ( starts_with_consonant_vowel ) ) && arr [ 0 ] . match ( ends_with_vowel ) ; let second_is_joining = arr [ 1 ] . match ( joining_consonant_vowel ) ; if ( first_is_open && second_is_joining ) { let possible_combination = arr [ 0 ] + arr [ 1 ] ; let probably_separate_syllables = possible_combination . match ( cvcv_same_consonant ) || possible_combination . match ( cvcv_same_vowel ) || possible_combination . match ( cvcv_known_consonants ) ; if ( ! probably_separate_syllables ) { arr [ 0 ] = arr [ 0 ] + arr [ 1 ] ; arr . splice ( 1 , 1 ) ; } } } if ( arr . length > 1 ) { let second_to_last_is_open = arr [ arr . length - 2 ] . match ( starts_with_consonant_vowel ) && arr [ arr . length - 2 ] . match ( ends_with_vowel ) ; let last_is_joining = arr [ arr . length - 1 ] . match ( joining_consonant_vowel ) && ones . every ( re => ! arr [ arr . length - 1 ] . match ( re ) ) ; if ( second_to_last_is_open && last_is_joining ) { let possible_combination = arr [ arr . length - 2 ] + arr [ arr . length - 1 ] ; let probably_separate_syllables = possible_combination . match ( cvcv_same_consonant ) || possible_combination . match ( cvcv_same_vowel ) || possible_combination . match ( cvcv_known_consonants ) ; if ( ! probably_separate_syllables ) { arr [ arr . length - 2 ] = arr [ arr . length - 2 ] + arr [ arr . length - 1 ] ; arr . splice ( arr . length - 1 , 1 ) ; } } } if ( arr . length > 1 ) { let single = arr [ 0 ] + arr [ 1 ] ; if ( single . match ( starts_with_single_vowel_combos ) ) { arr [ 0 ] = single ; arr . splice ( 1 , 1 ) ; } } if ( arr . length > 1 ) { if ( arr [ arr . length - 1 ] . match ( only_one_or_more_c ) ) { arr [ arr . length - 2 ] = arr [ arr . length - 2 ] + arr [ arr . length - 1 ] ; arr . splice ( arr . length - 1 , 1 ) ; } } return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method is nested because it s called recursively [CODESPLIT] function ( w ) { let vow = / [aeiouy]$ / ; let chars = w . split ( '' ) ; let before = '' ; let after = '' ; let current = '' ; for ( let i = 0 ; i < chars . length ; i ++ ) { before = chars . slice ( 0 , i ) . join ( '' ) ; current = chars [ i ] ; after = chars . slice ( i + 1 , chars . length ) . join ( '' ) ; let candidate = before + chars [ i ] ; //it's a consonant that comes after a vowel if ( before . match ( ends_with_vowel ) && ! current . match ( ends_with_vowel ) ) { if ( after . match ( starts_with_e_then_specials ) ) { candidate += 'e' ; after = after . replace ( starts_with_e , '' ) ; } all . push ( candidate ) ; return doer ( after ) ; } //unblended vowels ('noisy' vowel combinations) if ( candidate . match ( ends_with_noisy_vowel_combos ) ) { //'io' is noisy, not in 'ion' all . push ( before ) ; all . push ( current ) ; return doer ( after ) ; //recursion } // if candidate is followed by a CV, assume consecutive open syllables if ( candidate . match ( ends_with_vowel ) && after . match ( starts_with_consonant_vowel ) ) { all . push ( candidate ) ; return doer ( after ) ; } } //if still running, end last syllable if ( str . match ( aiouy ) || str . match ( ends_with_ee ) ) { //allow silent trailing e all . push ( w ) ; } else { all [ all . length - 1 ] = ( all [ all . length - 1 ] || '' ) + w ; //append it to the last one } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used by ProxyDomain - derived classes to create an API method called apiName ; the API can have methods send and reply which are bound to self ; a promise is created in api . replied which is satisfied after the reply method has been called [CODESPLIT] function addApi ( self , apiName , api ) { for ( var name in api ) { var fn = api [ name ] ; if ( typeof fn === \"function\" ) api [ name ] = api [ name ] . bind ( self ) ; } var tmp = null ; api . replied = new Promise ( ( resolve , reject ) => { tmp = { resolve , reject } ; } ) ; api . replied . resolve = tmp . resolve ; api . replied . reject = tmp . reject ; self [ apiName ] = api ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets JSON from the remote server [CODESPLIT] function getJson ( path ) { return httpGet ( { hostname : t . options . remoteClientHostname , port : t . options . remoteClientPort , path : path , method : 'GET' } ) . then ( ( obj ) => { var contentType = getContentType ( obj . response ) ; if ( contentType !== \"application/json\" ) LOG . warn ( \"Expecting JSON from \" + path + \" but found wrong content type: \" + contentType ) ; try { return JSON . parse ( obj . data ) ; } catch ( ex ) { LOG . warn ( \"Cannot parse JSON returned from \" + path ) ; return null ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits a string into domain and method [CODESPLIT] function splitName ( method ) { var pos = method . indexOf ( '.' ) ; if ( pos < 0 ) return [ null , method ] ; var domainName = method . substring ( 0 , pos ) ; var methodName = method . substring ( pos + 1 ) ; return [ domainName , methodName ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets data from the remote server and copies it to the client [CODESPLIT] function copyToClient ( req , res ) { return httpGet ( { hostname : t . options . remoteClientHostname , port : t . options . remoteClientPort , path : req . originalUrl , method : 'GET' } ) . then ( function ( obj ) { var contentType = getContentType ( obj . response ) ; if ( contentType ) res . set ( \"Content-Type\" , contentType ) ; res . send ( obj . data ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simple promisify [CODESPLIT] function promisify ( fn ) { return new Promise ( function ( resolve , reject ) { fn ( function ( err , value ) { if ( err ) reject ( err ) ; else resolve ( value ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helpers ------- [CODESPLIT] function toFixed ( value , precision ) { var power = Math . pow ( 10 , precision ) ; return ( Math . round ( value * power ) / power ) . toFixed ( precision ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a result object and pass it ( among other things ) into the done function . [CODESPLIT] function ( code , stdout , stderr ) { // Remove trailing whitespace (newline) stdout = _ . rtrim ( stdout ) ; stderr = _ . rtrim ( stderr ) ; // Create the result object. var result = { stdout : stdout , stderr : stderr , code : code , toString : function ( ) { if ( code === 0 ) { return stdout ; } else if ( 'fallback' in opts ) { return opts . fallback ; } else if ( opts . grunt ) { // grunt.log.error uses standard out, to be fixed in 0.5. return stderr || stdout ; } return stderr ; } } ; // On error (and no fallback) pass an error object, otherwise pass null. done ( code === 0 || 'fallback' in opts ? null : new Error ( stderr ) , result , code ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get native stack [CODESPLIT] function ( ) { // Save original Error.prepareStackTrace const origPrepareStackTrace = Error . prepareStackTrace // Override with function that just returns `stack` Error . prepareStackTrace = ( _ , stack ) => stack // Create a new `Error`, which automatically gets `stack` const err = new Error ( ) // Evaluate `err.stack`, which calls our new `Error.prepareStackTrace` const stack = err . stack // Restore original `Error.prepareStackTrace` Error . prepareStackTrace = origPrepareStackTrace // Remove superfluous function call on stack stack . shift ( ) // getStack --> Error return stack }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Public Executes the provided function with the output on the provided streams . Accepts options to silence the output going to the console . [CODESPLIT] function capture ( streams , opts , exec ) { var args = _shift ( opts , exec ) ; opts = args [ 0 ] ; exec = args [ 1 ] ; if ( ! Array . isArray ( streams ) ) { streams = [ streams ] ; } var outputs = [ ] ; streams . forEach ( function ( stream , index ) { outputs [ index ] = '' ; startCapture ( stream , opts , function ( output ) { outputs [ index ] += output ; } ) ; } ) ; exec ( ) ; streams . forEach ( stopCapture ) ; return outputs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Captures stdout and stderr into an object for the provided execution scope . [CODESPLIT] function captureStdio ( opts , exec ) { var streams = [ process . stdout , process . stderr ] ; var outputs = capture ( streams , opts , exec ) ; return { stdout : outputs . shift ( ) , stderr : outputs . shift ( ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Listens to a provided stream and executes the provided function for every write call . Accepts options to silence the output going to the console . [CODESPLIT] function hook ( stream , opts , exec ) { var args = _shift ( opts , exec ) ; opts = args [ 0 ] ; exec = args [ 1 ] ; var old_write = stream . write ; stream . write = ( function override ( stream , writer ) { return function write ( string , encoding , fd ) { exec ( string , encoding , fd ) ; if ( ! opts [ 'quiet' ] ) { writer . apply ( stream , [ string , encoding , fd ] ) ; } } } ) ( stream , stream . write ) ; return function unhook ( ) { stream . write = old_write ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts a capture on the provided stream using the provided options and stream execution . [CODESPLIT] function startCapture ( stream , opts , exec ) { var unhook = hook ( stream , opts , exec ) ; var str_id = random . generate ( ) ; unhooks [ str_id ] = unhook ; stream . _id = str_id ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps capturing functions with quiet flags to allow for interception . [CODESPLIT] function _wrapIntercept ( func , stream , opts , exec ) { var idex = Number ( arguments . length > 3 ) ; var args = _shift ( arguments [ idex + 1 ] , arguments [ idex + 2 ] ) ; opts = args [ 0 ] ; exec = args [ 1 ] ; opts . quiet = true ; return idex ? func ( stream , opts , exec ) : func ( opts , exec ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "function to find nearest value in select options [CODESPLIT] function getNearest ( $select , value ) { var delta = { } ; $select . children ( 'option' ) . each ( function ( i , opt ) { var optValue = $ ( opt ) . attr ( 'value' ) , distance ; if ( optValue === '' ) return ; distance = Math . abs ( optValue - value ) ; if ( typeof delta . distance === 'undefined' || distance < delta . distance ) { delta = { value : optValue , distance : distance } ; } } ) ; return delta . value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Round x to the nearest integer choosing the even integer if it lies halfway between two . [CODESPLIT] function evenRound ( x ) { // There are four cases for numbers with fractional part being .5: // // case |     x     | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 |   example //   1  |  2n + 0.5 |  2n      |  2n + 1  |  2n      |   >    |  0.5  |   0   |  0.5 ->  0 //   2  |  2n + 1.5 |  2n + 1  |  2n + 2  |  2n + 2  |   >    |  0.5  |   1   |  1.5 ->  2 //   3  | -2n - 0.5 | -2n - 1  | -2n      | -2n      |   <    | -0.5  |   0   | -0.5 ->  0 //   4  | -2n - 1.5 | -2n - 2  | -2n - 1  | -2n - 2  |   <    | -0.5  |   1   | -1.5 -> -2 // (where n is a non-negative integer) // // Branch here for cases 1 and 4 if ( ( x > 0 && ( x % 1 ) === + 0.5 && ( x & 1 ) === 0 ) || ( x < 0 && ( x % 1 ) === - 0.5 && ( x & 1 ) === 1 ) ) { return censorNegativeZero ( Math . floor ( x ) ) ; } return censorNegativeZero ( Math . round ( x ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "delay only used for debugging [CODESPLIT] function addFrameAt ( time , value , delay , array ) { array . push ( { time : time , value : value , delay : delay } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Insert extra keyframe to preserve frame - by - frame ( keyframing ) effect because CSS is spec ed to attempt tweening on all properties even those that cannot be undesirably resulting in changes occuring immediately instead of on the following keyframe [CODESPLIT] function addPreservationFrameAt ( time , value , delay , array ) { addFrameAt ( time , value , delay , array ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * FROM OLD CODE -- here in case it s ever needed [CODESPLIT] function relateTime ( time , extendedDur , resolution ) { // Relative to sibling animations time = new Decimal ( time ) . dividedBy ( extendedDur ) ; // Clean up any repeating decimals time = applyResolution ( time , resolution ) ; return time ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * See test / special / css - delay / looping - multiple . svg See test / special / css - delay / repeatCount - loop - with - syncbases . svg [CODESPLIT] function delay ( data , definedLoop ) { var preDelay = data . sequence [ 0 ] [ definedLoop ? \"begin\" : \"beginStatic\" ] ; data . sequence . forEach ( function ( value , i ) { data . sequence [ i ] . begin = value . begin - preDelay ; } ) ; return preDelay ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Check if supported animation elements exist [CODESPLIT] function isCompatible ( instance ) { var supported = instance . $root . find ( definitions . selectors . supported ) ; var unsupported = instance . $root . find ( definitions . selectors . unsupported ) ; if ( unsupported . length ) { // See test/erroneous/unsupported-elements.svg error . incompatible ( \"Unsupported animation elements detected\" , \"https://github.com/stevenvachon/smil2css/wiki/Current-Status#animation-elements\" , instance ) ; } else if ( ! supported . length ) { // See test/erroneous/non-animating.svg error . unnecessary ( \"No animation elements detected\" , null , instance ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Usage : instance = new smil2css () ; instance . convert () ; [CODESPLIT] function smil2css ( options ) { var defaults = { compress : true , force : false , targetBrowsers : null // use autoprefixer defaults } ; this . options = Object . assign ( defaults , options || { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Patch polarity and valence properties on nodes with a value and word - nodes . Then patch the same properties on their parents . [CODESPLIT] function sentiment ( options ) { return transformer function transformer ( node ) { var concatenate = concatenateFactory ( ) visit ( node , any ( options ) ) visit ( node , concatenate ) concatenate . done ( ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory to gather parents and patch them based on their childrens directionality . [CODESPLIT] function concatenateFactory ( ) { var queue = [ ] concatenate . done = done return concatenate // Gather a parent if not already gathered. function concatenate ( node , index , parent ) { if ( parent && parent . type !== 'WordNode' && queue . indexOf ( parent ) === - 1 ) { queue . push ( parent ) } } // Patch all words in `parent`. function one ( node ) { var children = node . children var length = children . length var polarity = 0 var index = - 1 var child var hasNegation while ( ++ index < length ) { child = children [ index ] if ( child . data && child . data . polarity ) { polarity += ( hasNegation ? - 1 : 1 ) * child . data . polarity } // If the value is a word, remove any present negation.  Otherwise, add // negation if the node contains it. if ( child . type === 'WordNode' ) { if ( hasNegation ) { hasNegation = false } else if ( isNegation ( child ) ) { hasNegation = true } } } patch ( node , polarity ) } // Patch all parents. function done ( ) { var length = queue . length var index = - 1 queue . reverse ( ) while ( ++ index < length ) { one ( queue [ index ] ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Patch all words in parent . [CODESPLIT] function one ( node ) { var children = node . children var length = children . length var polarity = 0 var index = - 1 var child var hasNegation while ( ++ index < length ) { child = children [ index ] if ( child . data && child . data . polarity ) { polarity += ( hasNegation ? - 1 : 1 ) * child . data . polarity } // If the value is a word, remove any present negation.  Otherwise, add // negation if the node contains it. if ( child . type === 'WordNode' ) { if ( hasNegation ) { hasNegation = false } else if ( isNegation ( child ) ) { hasNegation = true } } } patch ( node , polarity ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Patch all parents . [CODESPLIT] function done ( ) { var length = queue . length var index = - 1 queue . reverse ( ) while ( ++ index < length ) { one ( queue [ index ] ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory to patch based on the bound config . [CODESPLIT] function any ( config ) { return setter // Patch data-properties on `node`s with a value and words. function setter ( node ) { var value var polarity if ( 'value' in node || node . type === 'WordNode' ) { value = nlcstToString ( node ) if ( config && own . call ( config , value ) ) { polarity = config [ value ] } else if ( own . call ( polarities , value ) ) { polarity = polarities [ value ] } if ( polarity ) { patch ( node , polarity ) } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Patch a polarity and valence property on node s . [CODESPLIT] function patch ( node , polarity ) { var data = node . data || { } data . polarity = polarity || 0 data . valence = classify ( polarity ) node . data = data }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detect if a value is used to negate something . [CODESPLIT] function isNegation ( node ) { var value value = nlcstToString ( node ) . toLowerCase ( ) if ( value === 'not' || value === 'neither' || value === 'nor' || / n['’]t/. t e st(v a lue)  ) { return true } return false }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fire a listener on a target [CODESPLIT] function fire ( event , target , listener ) { var returned , oldData ; if ( listener . d !== null ) { oldData = event . data ; event . data = listener . d ; returned = listener . h . call ( target , event , target ) ; event . data = oldData ; } else { returned = listener . h . call ( target , event , target ) ; } return returned ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function proxied by Delegate#on [CODESPLIT] function handle ( listenerList , root , event ) { var listener , returned , specificList , target ; if ( event [ EVENT_IGNORE ] === true ) { return ; } target = event . target ; if ( target . nodeType === Node . TEXT_NODE ) { target = target . parentNode ; } specificList = listenerList [ event . type ] ; // If the fire function actually causes the specific list to be destroyed, // Need check that the specific list is still populated while ( target && specificList . length > 0 ) { listener = specificList . first ; do { // Check for match and fire the event if there's one // TODO:MCG:20120117: Need a way to check if event#stopImmediateProgagation was called. If so, break both loops. if ( listener . m . call ( target , listener . p , target ) ) { returned = fire ( event , target , listener ) ; } // Stop propagation to subsequent callbacks if the callback returned false if ( returned === false ) { event [ EVENT_IGNORE ] = true ; return ; } listener = listener . next ; // If the fire function actually causes the specific list object to be destroyed, // need a way of getting out of here so check listener is set } while ( listener !== specificList . first && listener ) ; // TODO:MCG:20120117: Need a way to check if event#stopProgagation was called. If so, break looping through the DOM. // Stop if the delegation root has been reached if ( target === root ) { break ; } target = target . parentElement ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function proxied by Delegate#on [CODESPLIT] function on ( that , listenerList , root , eventType , selector , eventData , handler ) { var matcher , matcherParam ; if ( ! eventType ) { throw new TypeError ( 'Invalid event type: ' + eventType ) ; } if ( ! selector ) { throw new TypeError ( 'Invalid selector: ' + selector ) ; } // Support a separated list of event types if ( eventType . indexOf ( SEPARATOR ) !== - 1 ) { eventType . split ( SEPARATOR ) . forEach ( function ( eventType ) { on . call ( that , that , listenerList , root , eventType , selector , eventData , handler ) ; } ) ; return ; } if ( handler === undefined ) { handler = eventData ; eventData = null ; // Normalise undefined eventData to null } else if ( eventData === undefined ) { eventData = null ; } if ( typeof handler !== 'function' ) { throw new TypeError ( \"Handler must be a type of Function\" ) ; } // Add master handler for type if not created yet if ( ! listenerList [ eventType ] ) { root . addEventListener ( eventType , that . handle , ( eventType === 'error' ) ) ; listenerList [ eventType ] = new CircularList ( ) ; } // Compile a matcher for the given selector if ( / ^[a-z]+$ / i . test ( selector ) ) { if ( ! tagsCaseSensitive ) { matcherParam = selector . toUpperCase ( ) ; } else { matcherParam = selector ; } matcher = matchesTag ; } else if ( / ^#[a-z0-9\\-_]+$ / i . test ( selector ) ) { matcherParam = selector . slice ( 1 ) ; matcher = matchesId ; } else { matcherParam = selector ; matcher = matches ; } // Add to the list of listeners listenerList [ eventType ] . append ( { s : selector , d : eventData , h : handler , m : matcher , p : matcherParam } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function proxied by Delegate#off [CODESPLIT] function off ( that , listenerList , root , eventType , selector , handler ) { var listener , nextListener , firstListener , specificList , singleEventType ; if ( ! eventType ) { for ( singleEventType in listenerList ) { if ( listenerList . hasOwnProperty ( singleEventType ) ) { off . call ( that , that , listenerList , root , singleEventType , selector , handler ) ; } } return ; } specificList = listenerList [ eventType ] ; if ( ! specificList ) { return ; } // Support a separated list of event types if ( eventType . indexOf ( SEPARATOR ) !== - 1 ) { eventType . split ( SEPARATOR ) . forEach ( function ( eventType ) { off . call ( that , that , listenerList , root , eventType , selector , handler ) ; } ) ; return ; } // Remove only parameter matches if specified listener = firstListener = specificList . first ; do { if ( ( ! selector || selector === listener . s ) && ( ! handler || handler === listener . h ) ) { // listener.next will be undefined after listener is removed, so save a reference here nextListener = listener . next ; specificList . remove ( listener ) ; listener = nextListener ; } else { listener = listener . next ; } } while ( listener && listener !== firstListener ) ; // All listeners removed if ( ! specificList . length ) { delete listenerList [ eventType ] ; // Remove the main handler root . removeEventListener ( eventType , that . handle , false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DOM event delegator [CODESPLIT] function Delegate ( root ) { var /**\n\t\t\t * Keep a reference to the current instance\n\t\t\t *\n\t\t\t * @internal\n\t\t\t * @type Delegate\n\t\t\t */ that = this , /**\n\t\t\t * Maintain a list of listeners, indexed by event name\n\t\t\t *\n\t\t\t * @internal\n\t\t\t * @type Object\n\t\t\t */ listenerList = { } ; if ( typeof root === 'string' ) { root = document . querySelector ( root ) ; } if ( ! root || ! root . addEventListener ) { throw new TypeError ( 'Root node not specified' ) ; } /**\n\t\t * Attach a handler to one event for all elements that match the selector, now or in the future\n\t\t *\n\t\t * The handler function receives three arguments: the DOM event object, the node that matched the selector while the event was bubbling\n\t\t * and a reference to itself. Within the handler, 'this' is equal to the second argument.\n\t\t * The node that actually received the event can be accessed via 'event.target'.\n\t\t *\n\t\t * @param {string} eventType Listen for these events (in a space-separated list)\n\t\t * @param {string} selector Only handle events on elements matching this selector\n\t\t * @param {Object} [eventData] If this parameter is not specified, the third parameter must be the handler\n\t\t * @param {function()} handler Handler function - event data passed here will be in event.data\n\t\t * @returns {Delegate} This method is chainable\n\t\t */ this . on = function ( ) { Array . prototype . unshift . call ( arguments , that , listenerList , root ) ; on . apply ( that , arguments ) ; return this ; } ; /**\n\t\t * Remove an event handler for elements that match the selector, forever\n\t\t *\n\t\t * @param {string} eventType Remove handlers for events matching this type, considering the other parameters\n\t\t * @param {string} [selector] If this parameter is omitted, only handlers which match the other two will be removed\n\t\t * @param {function()} [handler] If this parameter is omitted, only handlers which match the previous two will be removed\n\t\t * @returns {Delegate} This method is chainable\n\t\t */ this . off = function ( ) { Array . prototype . unshift . call ( arguments , that , listenerList , root ) ; off . apply ( that , arguments ) ; return this ; } ; /**\n\t\t * Handle an arbitrary event\n\t\t *\n\t\t * @private\n\t\t * @param {Event} event\n\t\t */ this . handle = function ( event ) { handle . call ( that , listenerList , root , event ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Methods [CODESPLIT] function setArticle ( id ) { database . getAsync ( id , function ( article ) { orange . model . set ( article ) ; orange . render ( ) . setup ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Module constructor [CODESPLIT] function Module ( options ) { // Shallow clone the options options = mixin ( { } , options ) ; // Various config steps this . _configure ( options ) ; this . _add ( options . children ) ; // Fire before initialize event hook this . fireStatic ( 'before initialize' , options ) ; // Run initialize hooks if ( this . initialize ) this . initialize ( options ) ; // Fire initialize event hook this . fireStatic ( 'initialize' , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shortcut method for creating lazy views . [CODESPLIT] function fm ( options ) { var Module = fm . modules [ options . module ] ; if ( Module ) { return new Module ( options ) ; } throw new Error ( \"Unable to find module '\" + options . module + \"'\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "！！！非常关键的配置信息 当前模块配置 表配置：变量放到顶部，代码重用只需要更改头部的配置代码 [CODESPLIT] function Service ( oodbc , _config ) { this . instanceConfig = _config ; this . databaseConfig = _config . database || \"MySQL\" ; //数据源\r this . oodbc = oodbc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "常规SQL的方式 [CODESPLIT] function service ( oodbc , _config ) { if ( _config === undefined ) { throw new TypeError ( 'Expected object for argument _config' ) } if ( ! ( this instanceof Service ) ) { return new Service ( oodbc , _config ) } throw new TypeError ( 'Expected object for argument _config' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "数据库实例对象 [CODESPLIT] function Service ( oodbc , _database , _instance ) { //数据库标签识别，如果没有标识默认使用MYSQL\r var database = _database || \"MYSQL\" ; database = database . toUpperCase ( ) ; this . database = database ; var source = oodbc [ database ] ; //判断数据库识别\r if ( source ) { //实例识别\r var dbsource = source [ _instance . toUpperCase ( ) ] ; if ( dbsource ) { //识别正确，返回数据源实例对象，读写分离的实例一起返回\r this . db = dbsource ; } else { console . log ( '数据源实例配置节点识别错误，请检查' + _instance.toUpperCase() + '节点是否 在 );\r         throw new TypeError ( '数据源实例配置节点识别错误，请检查' + _instance.toUpperCase() + '节点是否 在 );\r         } } else { console . log ( '数据库类型节点配置识别错误，请检查' + this.database.toUpperCase() + ' 点 否存在' ) ;\r         throw new TypeError ( '数据库类型节点配置识别错误，请检查' + this.database.toUpperCase() + ' 点 否存在' ) ;\r         } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "数据库实例命令执行（高频执行） 读写实例走这一个对象 [CODESPLIT] function ( instance , sql , parameters ) { return new Promise ( function ( resolve , reject ) { //执行对数据库的访问\r console . time ( '【onela】执行SQL时间');\r   //console.log('执行sql', sql, '参数', parameters);\r if ( instance ) { instance . query ( sql , parameters , function ( err , doc ) { console . timeEnd ( '【onela】执行SQL时间');\r   if ( err ) { reject ( err ) ; } else { resolve ( doc ) ; } } ) ; } else { reject ( \"数据库instance实例未正确指向，请检查oodbc数据实例配置和表结构配置（onelaInstanceConfig.json）的实例对照是否正确\");\r   } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an object into a persistent or temporary directory structure . [CODESPLIT] function ( structure = [ ] ) { return new Promise ( ( resolve , reject ) => { if ( Array . isArray ( structure ) === false ) { throw new Error ( ` ` ) } parseStructure ( structure , opts . cwd ) . then ( ( parsedStructure ) => writeStructure ( parsedStructure ) ) . then ( ( parsedStructure ) => binStructure ( parsedStructure , bin , opts . persistent ) ) . then ( resolve , reject ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends WHERE conditions to query builder based on given date parameters [CODESPLIT] function addAndWhereDate ( queryBuilder , column , from , to ) { if ( from && to ) { queryBuilder . whereBetween ( column , [ from , to ] ) ; } else if ( from ) { queryBuilder . andWhere ( column , '>=' , from ) ; } else if ( to ) { queryBuilder . andWhere ( column , '<=' , to ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use this to add an equation clause for the value which is either an object or an array [CODESPLIT] function _handleMultiValuedParameters ( knexBuilder , attrName , parameter ) { if ( parameter instanceof Set ) { knexBuilder = knexBuilder . whereIn ( attrName , Array . from ( parameter ) ) ; } else if ( Array . isArray ( parameter ) ) { knexBuilder = knexBuilder . whereIn ( attrName , parameter ) ; } else { knexBuilder = knexBuilder . where ( attrName , parameter ) ; } return knexBuilder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clean db [CODESPLIT] function cleanDb ( knex , tableNames , logger , verboseLog = false ) { validate . notNil ( tableNames ) ; return tableCleaner . cleanTables ( knex , tableNames , verboseLog ) . then ( ( ) => { if ( logger ) { logger . info ( 'Tables cleaned successfully: ' , tableNames . join ( ', ' ) ) ; } } ) . catch ( err => { if ( logger ) { logger . error ( 'Error cleaning tables' , err ) ; } throw err ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Knex instance without validating the connection [CODESPLIT] function getKnexInstance ( config , registry = _registry , logger = console ) { validate . notNil ( config , 'Config is null or undefined' ) ; validate . notNil ( config . client , 'DB client is null or undefined' ) ; const { host , database , user } = config . connection ; const connectionTimeout = config . acquireConnectionTimeout ; logger . info ( ` ${ user } ${ host } ${ database } ` ) ; logger . info ( ` ${ connectionTimeout } ` ) ; const knex = module . exports . _initKnexInstance ( config ) ; module . exports . registerKnexInstance ( knex , registry ) ; // unfortunately, we can't check heartbeat here and fail-fast, as this initialization is synchronous\r return knex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to close all registered knex instances [CODESPLIT] function closeAllInstances ( registry = _registry ) { const promises = [ ] ; const errors = [ ] ; while ( registry . length > 0 ) { const knex = registry . pop ( ) ; const destructionPromise = knex . destroy ( ) . catch ( e => { errors . push ( { knex , cause : e } ) ; } ) ; promises . push ( destructionPromise ) ; } return Promise . all ( promises ) . then ( ( ) => { return errors ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remark plugin for custom tags : <x - foo data - value = 42 / > [CODESPLIT] function remarkCustomTags ( customTags ) { return ast => visit ( ast , 'html' , node => { if ( node . value . startsWith ( '<x-' ) ) { // Parse tag’s HTML const dom = parse5 . parseFragment ( unescapeMarkdown ( node . value ) ) ; const tagNode = dom . childNodes [ 0 ] ; if ( ! tagNode ) { throw new Error ( 'Cannot parse custom tag:' , node . value ) ; } let { tagName , attrs } = tagNode ; const childNode = tagNode . childNodes [ 0 ] ; attrs . push ( { name : 'children' , value : childNode ? childNode . value . trim ( ) : null , } ) ; tagName = tagName . replace ( / ^x- / , '' ) ; // Check tag function const tagFunction = customTags [ tagName ] ; if ( ! tagFunction || ! _ . isFunction ( tagFunction ) ) { throw new Error ( ` ${ tagName } ` ) ; } // Unzip attributes attrs = attrs . reduce ( ( attrsObj , attr ) => { attrsObj [ attr . name ] = attr . value ; return attrsObj ; } , { } ) ; // Render let result ; try { result = tagFunction ( attrs ) || '' ; } catch ( exception ) { result = errorInlineHtml ( ` ${ tagName } ${ exception . message } ` , { block : true } ) ; } node . value = result . toString ( ) . trim ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remark plugin for Highlight . js . [CODESPLIT] function remarkHljs ( { aliases } ) { return ast => visit ( ast , 'code' , node => { if ( ! node . data ) { node . data = { } ; } const lang = node . lang ; const highlighted = lang ? low . highlight ( aliases [ lang ] || lang , node . value ) . value : low . highlightAuto ( node . value ) . value ; node . data . hChildren = highlighted ; node . data . hProperties = { className : [ 'hljs' , lang && ` ${ lang } ` ] , } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render Markdow using given processor . [CODESPLIT] function render ( processor , source ) { try { return processor . processSync ( source ) . contents ; } catch ( exception ) { const error = ` ${ exception . message } ` ; console . error ( error ) ; return errorInlineHtml ( error ) . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * function parseWithDox ( content ) { const dox = require ( dox ) [CODESPLIT] function readTemplate ( doc ) { return fs . readFileAsync ( flags . template , \"utf8\" ) . then ( template => ( { doc , template } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends an arrow head marker to the defs element to be used later . [CODESPLIT] function createColorArrow ( defElement , color ) { defElement . append ( \"marker\" ) . attr ( \"id\" , \"arrow-\" + color ) . attr ( \"viewBox\" , \"0 -5 10 10\" ) . attr ( \"refX\" , 8 ) . attr ( \"markerWidth\" , 6 ) . attr ( \"markerHeight\" , 6 ) . attr ( \"fill\" , color ) . attr ( \"orient\" , \"auto\" ) . append ( \"path\" ) . attr ( \"d\" , \"M0,-5L10,0L0,5\" ) . attr ( \"class\" , \"arrowHead\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The main entry point of this module takes a CSS property / value pair and validates it . It will return either true if valid or a message object if either invalid or unknown . [CODESPLIT] function cssValues ( property , value ) { if ( typeof value === 'string' ) { value = valueParser ( value ) ; } var first = value . nodes [ 0 ] ; if ( value . nodes . length === 1 && ( isKeyword ( first , cssGlobals ) || isVariable ( first ) ) ) { return true ; } if ( validators [ property ] ) { var result = validators [ property ] ( value ) ; if ( result . type ) { return result ; } if ( ! ! result === false ) { return invalidMessage ( '\"' + value + '\" is not a valid value for \"' + property + '\".' ) ; } return true ; } // Pass through unknown properties return unknownMessage ( '\"' + property + '\" is not a recognised property.' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test that the nodes from postcss - value - parser are a certain length . This uses strict equality by default but you can supply an alternate operator . [CODESPLIT] function valueParserNodesLength ( length , operator = '===' ) { return t . binaryExpression ( operator , valueParserASTNodesLength , t . numericLiteral ( length ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add colors to selenium log messages . ** Note ** : Naive but fun . [CODESPLIT] function ( data ) { data = ( data || \"\" ) . toString ( ) . trim ( ) ; _ . any ( SEL_LOG_COLORS , function ( val , key ) { if ( data . indexOf ( key ) > NOT_FOUND ) { data = data . split ( key ) . join ( key [ val ] ) ; return true ; } } ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This is a temporary function to be removed once generation of all functions has been achieved . [CODESPLIT] function known ( parsed ) { return parsed . every ( node => { return node . type === 'keyword' || node . type === 'string' || node . type === 'group' && ! node . order && ! node . min && node . values . every ( n => n . type === 'keyword' ) || ( node . type === 'data' && validators [ dataValidator ( node . value ) ] ) ; // eslint-disable-line } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Decrypt encrypted data block of keyword index ( attrs . Encrypted = 2 ) . [CODESPLIT] function decrypt ( buf , key ) { key = ripemd128 . ripemd128 ( key ) ; var byte , keylen = key . length , prev = 0x36 , i = 0 , len = buf . length ; for ( ; i < len ; i ++ ) { byte = buf [ i ] ; byte = ( ( byte >> 4 ) | ( byte << 4 ) ) ; // & 0xFF;  <-- it's already a byte byte = byte ^ prev ^ ( i & 0xFF ) ^ key [ i % keylen ] ; prev = buf [ i ] ; buf [ i ] = byte ; } return buf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For sliceThen ( .. ) . exec ( proc .. ) mark what proc function returns is multiple values to be passed to further Promise#spread ( .. ) call . [CODESPLIT] function spreadus ( ) { var args = Array . prototype . slice . apply ( arguments ) ; args . _spreadus_ = true ; return args ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "var fd = null ; var fdFileName = null ; [CODESPLIT] function sliceThen ( file , offset , len ) { var p = new Promise ( function ( _resolve ) { fs . open ( file , 'r' , function ( err , fd ) { if ( err ) { throw err ; } var res = new Buffer ( len ) ; fs . read ( fd , res , 0 , len , offset , function ( err , bytesRead , buffer ) { if ( err ) { throw err ; } _resolve ( buffer ) ; } ) ; } ) ; } ) ; /**\n     * Call proc with specified arguments prepending with sliced file/blob data (ArrayBuffer) been read.\n     * @param the first argument is a function to be executed\n     * @param other optional arguments are passed to the function following auto supplied input ArrayBuffer\n     * @return a promise object which can be chained with further process through spread() method\n     */ p . exec = function ( proc /*, args... */ ) { var args = Array . prototype . slice . call ( arguments , 1 ) ; return p . then ( function ( data ) { args . unshift ( data ) ; var ret = proc . apply ( null , args ) ; return resolve ( ret !== UNDEFINED && ret . _spreadus_ ? ret : [ ret ] ) ; } ) ; } ; return p ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Harvest any resolved promises if all failed then return reasons . [CODESPLIT] function harvest ( outcomes ) { return Promise . settle ( outcomes ) . then ( function ( results ) { if ( results . length === 0 ) { return reject ( \"** NOT FOUND **\" ) ; } var solved = [ ] , failed = [ ] ; for ( var i = 0 ; i < results . length ; i ++ ) { if ( results [ i ] . isResolved ( ) ) { solved . push ( results [ i ] . value ( ) ) ; } else { failed . push ( results [ i ] . reason ( ) ) ; } } return solved . length ? solved : failed ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Create a Record Block Table object to load record block info from record section in mdx / mdd file . Retrived data is stored in an Uint32Array which contains N pairs of ( offset_comp offset_decomp ) value where N is number of record blocks . [CODESPLIT] function createRecordBlockTable ( ) { var pos = 0 , // current position arr ; // backed Uint32Array return { // Allocate required ArrayBuffer for storing record block table, where len is number of record blocks. alloc : function ( len ) { arr = new Uint32Array ( len * 2 ) ; } , // Store offset pair value (compressed & decompressed) for a record block // NOTE: offset_comp is absolute offset counted from start of mdx/mdd file. put : function ( offset_comp , offset_decomp ) { arr [ pos ++ ] = offset_comp ; arr [ pos ++ ] = offset_decomp ; } , // Given offset of a keyword after decompression, return a record block info containing it, else undefined if not found. find : function ( keyAt ) { var hi = ( arr . length >> 1 ) - 1 , lo = 0 , i = ( lo + hi ) >> 1 , val = arr [ ( i << 1 ) + 1 ] ; if ( keyAt > arr [ ( hi << 1 ) + 1 ] || keyAt < 0 ) { return ; } while ( true ) { if ( hi - lo <= 1 ) { if ( i < hi ) { return { block_no : i , comp_offset : arr [ i <<= 1 ] , comp_size : arr [ i + 2 ] - arr [ i ] , decomp_offset : arr [ i + 1 ] , decomp_size : arr [ i + 3 ] - arr [ i + 1 ] } ; } else { return ; } } ( keyAt < val ) ? hi = i : lo = i ; i = ( lo + hi ) >> 1 ; val = arr [ ( i << 1 ) + 1 ] ; } } , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given offset of a keyword after decompression return a record block info containing it else undefined if not found . [CODESPLIT] function ( keyAt ) { var hi = ( arr . length >> 1 ) - 1 , lo = 0 , i = ( lo + hi ) >> 1 , val = arr [ ( i << 1 ) + 1 ] ; if ( keyAt > arr [ ( hi << 1 ) + 1 ] || keyAt < 0 ) { return ; } while ( true ) { if ( hi - lo <= 1 ) { if ( i < hi ) { return { block_no : i , comp_offset : arr [ i <<= 1 ] , comp_size : arr [ i + 2 ] - arr [ i ] , decomp_offset : arr [ i + 1 ] , decomp_size : arr [ i + 3 ] - arr [ i + 1 ] } ; } else { return ; } } ( keyAt < val ) ? hi = i : lo = i ; i = ( lo + hi ) >> 1 ; val = arr [ ( i << 1 ) + 1 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a MDict dictionary / resource file ( mdx / mdd ) . [CODESPLIT] function parse_mdict ( file , ext ) { var KEY_INDEX , // keyword index array RECORD_BLOCK_TABLE = createRecordBlockTable ( ) ; // record block table var attrs = { } , // storing dictionary attributes _v2 , // true if enginge version > 2 _bpu , // bytes per unit when converting text size to byte length for text data _tail , // need to skip extra tail bytes after decoding text _decoder , // text decorder _decryptors = [ false , false ] , // [keyword_header_decryptor, keyword_index_decryptor], only keyword_index_decryptor is supported _searchTextLen , // search NUL to get text length _readShort = function ( scanner ) { return scanner . readUint8 ( ) ; } , // read a \"short\" number representing kewword text size, 8-bit for version < 2, 16-bit for version >= 2 _readNum = function ( scanner ) { return scanner . readInt ( ) ; } , // Read a number representing offset or data block size, 16-bit for version < 2, 32-bit for version >= 2 _checksum_v2 = function ( ) { } , // Version >= 2.0 only checksum _adaptKey = function ( key ) { return key ; } , // adapt key by converting to lower case or stripping punctuations according to dictionary attributes (KeyCaseSensitive, StripKey) _slice = sliceThen . bind ( null , file ) ; // bind sliceThen() with file argument           /**\n     * Config scanner according to dictionary attributes.\n     */ function config ( ) { attrs . Encoding = attrs . Encoding || 'UTF-16' ; _searchTextLen = ( attrs . Encoding === 'UTF-16' ) ? function ( dv , offset ) { offset = offset ; var mark = offset ; while ( dv . getUint16 ( offset ++ ) ) { /* scan for NUL */ } ; return offset - mark ; } : function ( dv , offset ) { offset = offset ; var mark = offset ; while ( dv . getUint8 ( offset ++ ) ) { /* scan for NUL */ } return offset - mark - 1 ; } ; _decoder = new TextDecoder ( attrs . Encoding || 'UTF-16LE' ) ; _bpu = ( attrs . Encoding === 'UTF-16' ) ? 2 : 1 ; if ( parseInt ( attrs . GeneratedByEngineVersion , 10 ) >= 2.0 ) { _v2 = true ; _tail = _bpu ; // HUGE dictionary file (>4G) is not supported, take only lower 32-bit _readNum = function ( scanner ) { return scanner . forward ( 4 ) , scanner . readInt ( ) ; } ; _readShort = function ( scanner ) { return scanner . readUint16 ( ) ; } ; _checksum_v2 = function ( scanner ) { return scanner . checksum ( ) ; } ; } else { _tail = 0 ; } // keyword index decrypted? if ( attrs . Encrypted & 0x02 ) { _decryptors [ 1 ] = decrypt ; } var regexp = common . REGEXP_STRIPKEY [ ext ] ; if ( isTrue ( attrs . KeyCaseSensitive ) ) { _adaptKey = isTrue ( attrs . StripKey ) ? function ( key ) { return key . replace ( regexp , '$1' ) ; } : function ( key ) { return key ; } ; } else { _adaptKey = isTrue ( attrs . StripKey || ( _v2 ? '' : 'yes' ) ) ? function ( key ) { return key . toLowerCase ( ) . replace ( regexp , '$1' ) ; } : function ( key ) { return key . toLowerCase ( ) ; } ; } } // Read data in current offset from target data ArrayBuffer function Scanner ( buf , len ) { var offset = 0 , dv = new DataView ( buf ) ; var methods = { // target data size in bytes size : function ( ) { return len || buf . byteLength ; } , // update offset to new position forward : function ( len ) { return offset += len ; } , // return current offset offset : function ( ) { return offset ; } , // MDict file format uses big endian to store number // 32-bit unsigned int readInt : function ( ) { return conseq ( dv . getUint32 ( offset , false ) , this . forward ( 4 ) ) ; } , readUint16 : function ( ) { return conseq ( dv . getUint16 ( offset , false ) , this . forward ( 2 ) ) ; } , readUint8 : function ( ) { return conseq ( dv . getUint8 ( offset , false ) , this . forward ( 1 ) ) ; } , // Read a \"short\" number representing keyword text size, 8-bit for version < 2, 16-bit for version >= 2 readShort : function ( ) { return _readShort ( this ) ; } , // Read a number representing offset or data block size, 16-bit for version < 2, 32-bit for version >= 2 readNum : function ( ) { return _readNum ( this ) ; } , readUTF16 : function ( len ) { return conseq ( UTF_16LE . decode ( newUint8Array ( buf , offset , len ) ) , this . forward ( len ) ) ; } , // Read data to an Uint8Array and decode it to text with specified encoding. // Text length in bytes is determined by searching terminated NUL. // NOTE: After decoding the text, it is need to forward extra \"tail\" bytes according to specified encoding.  readText : function ( ) { var len = _searchTextLen ( dv , offset ) ; return conseq ( _decoder . decode ( newUint8Array ( buf , offset , len ) ) , this . forward ( len + _bpu ) ) ; } , // Read data to an Uint8Array and decode it to text with specified encoding. // @param len length in basic unit, need to multiply byte per unit to get length in bytes // NOTE: After decoding the text, it is need to forward extra \"tail\" bytes according to specified encoding.  readTextSized : function ( len ) { len *= _bpu ; var read = conseq ( _decoder . decode ( newUint8Array ( buf , offset , len ) ) , this . forward ( len + _tail ) ) ; return read ; } , // Skip checksum, just ignore it anyway. checksum : function ( ) { this . forward ( 4 ) ; } , // Version >= 2.0 only checksum_v2 : function ( ) { return _checksum_v2 ( this ) ; } , // Read data block of keyword index, key block or record content. // These data block are maybe in compressed (gzip or lzo) format, while keyword index maybe be encrypted. // @see https://github.com/zhansliu/writemdict/blob/master/fileformat.md#compression (with typo mistake) readBlock : function ( len , expectedBufSize , decryptor ) { var comp_type = dv . getUint8 ( offset , false ) ; // compression type, 0 = non, 1 = lzo, 2 = gzip if ( comp_type === 0 ) { if ( _v2 ) { this . forward ( 8 ) ; // for version >= 2, skip comp_type (4 bytes with tailing \\x00) and checksum (4 bytes) } return this ; } else { // skip comp_type (4 bytes with tailing \\x00) and checksum (4 bytes) offset += 8 ; len -= 8 ; var tmp = new Uint8Array ( len ) ; buf . copy ( tmp , 0 , offset , offset + len ) ; if ( decryptor ) { var passkey = new Uint8Array ( 8 ) ; var q = new Buffer ( 4 ) ; buf . copy ( passkey , 0 , offset - 4 , offset ) ; // var q = new Buffer(4); passkey . set ( [ 0x95 , 0x36 , 0x00 , 0x00 ] , 4 ) ; // key part 2: fixed data tmp = decryptor ( tmp , passkey ) ; } tmp = comp_type === 2 ? pako . inflate ( tmp ) : lzo . decompress ( tmp , expectedBufSize , 1308672 ) ; this . forward ( len ) ; var d = new Buffer ( tmp ) ; return Scanner ( d , tmp . length ) ; } } , // Read raw data as Uint8Array from current offset with specified length in bytes readRaw : function ( len ) { return conseq ( newUint8Array ( buf , offset , len ) , this . forward ( len === UNDEFINED ? buf . length - offset : len ) ) ; } , } ; return Object . create ( methods ) ; } /**\n     * Read the first 4 bytes of mdx/mdd file to get length of header_str.\n     * @see https://github.com/zhansliu/writemdict/blob/master/fileformat.md#file-structure\n     * @param input sliced file (start = 0, length = 4)\n     * @return length of header_str\n     */ function read_file_head ( input ) { return Scanner ( input ) . readInt ( ) ; } /**\n     * Read header section, parse dictionary attributes and config scanner according to engine version attribute.\n     * @see https://github.com/zhansliu/writemdict/blob/master/fileformat.md#header-section\n     * @param input sliced file (start = 4, length = len + 48), header string + header section (max length 48)\n     * @param len lenghth of header_str\n     * @return [remained length of header section (header_str and checksum, = len + 4), original input]\n     */ function read_header_sect ( input , len ) { var scanner = Scanner ( input ) , header_str = scanner . readUTF16 ( len ) . replace ( / \\0$ / , '' ) ; // need to remove tailing NUL // parse dictionary attributes var doc = new DOMParser ( ) . parseFromString ( header_str , 'text/xml' ) ; var elem = doc . getElementsByTagName ( 'Dictionary' ) [ 0 ] ; if ( ! elem ) { elem = doc . getElementsByTagName ( 'Library_Data' ) [ 0 ] ; } // console.log(doc.getElementsByTagName('Dictionary')[0].attributes); // var xml = parseXml(header_str).querySelector('Dictionary, Library_Data').attributes; for ( var i = 0 , item ; i < elem . attributes . length ; i ++ ) { item = elem . attributes [ i ] ; attrs [ item . nodeName ] = item . nodeValue ; } attrs . Encrypted = parseInt ( attrs . Encrypted , 10 ) || 0 ; config ( ) ; return spreadus ( len + 4 , input ) ; } /**\n     * Read keyword summary at the begining of keyword section.\n     * @see https://github.com/zhansliu/writemdict/blob/master/fileformat.md#keyword-section\n     * @param input sliced file, same as input passed to read_header_sect()\n     * @param offset start position of keyword section in sliced file, equals to length of header string plus checksum.\\\n     * @return keyword_sect object\n     */ function read_keyword_summary ( input , offset ) { var scanner = Scanner ( input ) ; scanner . forward ( offset ) ; return { num_blocks : scanner . readNum ( ) , num_entries : scanner . readNum ( ) , key_index_decomp_len : _v2 && scanner . readNum ( ) , // Ver >= 2.0 only key_index_comp_len : scanner . readNum ( ) , key_blocks_len : scanner . readNum ( ) , chksum : scanner . checksum_v2 ( ) , // extra field len : scanner . offset ( ) - offset , // actual length of keyword section, varying with engine version attribute } ; } /**\n     * Read keyword index part of keyword section. \n     * @see https://github.com/zhansliu/writemdict/blob/master/fileformat.md#keyword-header-encryption\n     * @see https://github.com/zhansliu/writemdict/blob/master/fileformat.md#keyword-index\n     * @param input sliced file, remained part of keyword section after keyword summary which can also be used to read following key blocks.\n     * @param keyword_summary \n     * @return [keyword_summary, array of keyword index]\n     */ function read_keyword_index ( input , keyword_summary ) { var scanner = Scanner ( input ) . readBlock ( keyword_summary . key_index_comp_len , keyword_summary . key_index_decomp_len , _decryptors [ 1 ] ) , keyword_index = Array ( keyword_summary . num_blocks ) , offset = 0 ; for ( var i = 0 , size ; i < keyword_summary . num_blocks ; i ++ ) { keyword_index [ i ] = { num_entries : conseq ( scanner . readNum ( ) , size = scanner . readShort ( ) ) , // UNUSED, can be ignored         //          first_size:  size = scanner.readShort(), first_word : conseq ( scanner . readTextSized ( size ) , size = scanner . readShort ( ) ) , // UNUSED, can be ignored //          last_size:   size = scanner.readShort(), last_word : scanner . readTextSized ( size ) , comp_size : size = scanner . readNum ( ) , decomp_size : scanner . readNum ( ) , // extra fields offset : offset , // offset of the first byte for the target key block in mdx/mdd file index : i // index of this key index, used to search previous/next block } ; offset += size ; } return spreadus ( keyword_summary , keyword_index ) ; } /**\n     * Read keyword entries inside a keyword block and fill KEY_TABLE.\n     * @param scanner scanner object to read key entries, which starts at begining of target key block\n     * @param kdx corresponding keyword index object\n     * NOTE: no need to read keyword block anymore, for debug only.\n     */ function read_key_block ( scanner , kdx ) { var scanner = scanner . readBlock ( kdx . comp_size , kdx . decomp_size ) ; for ( var i = 0 ; i < kdx . num_entries ; i ++ ) { //        scanner.readNum(); scanner.readText(); var kk = [ scanner . readNum ( ) , scanner . readText ( ) ] ; } } /**\n     * Delay to scan key table, for debug onyl.\n     * @param slicedKeyBlock a promise object which will resolve to an ArrayBuffer containing keyword blocks \n     *                       sliced from mdx/mdd file.\n     * @param num_entries number of keyword entries\n     * @param keyword_index array of keyword index\n     * @param delay time to delay for scanning key table\n     */ function willScanKeyTable ( slicedKeyBlock , num_entries , keyword_index , delay ) { slicedKeyBlock . delay ( delay ) . then ( function ( input ) { var scanner = Scanner ( input ) ; for ( var i = 0 , size = keyword_index . length ; i < size ; i ++ ) { // common.log('z',keyword_index[i]); read_key_block ( scanner , keyword_index [ i ] ) ; } } ) ; } /**\n     * Read record summary at the begining of record section.\n     * @see https://github.com/zhansliu/writemdict/blob/master/fileformat.md#record-section\n     * @param input sliced file, start = begining of record section, length = 32 (max length of record summary)\n     * @param pos begining of record section\n     * @returj record summary object\n     */ function read_record_summary ( input , pos ) { var scanner = Scanner ( input ) , record_summary = { num_blocks : scanner . readNum ( ) , num_entries : scanner . readNum ( ) , index_len : scanner . readNum ( ) , blocks_len : scanner . readNum ( ) , // extra field len : scanner . offset ( ) , // actual length of record section (excluding record block index), varying with engine version attribute } ; // start position of record block from head of mdx/mdd file record_summary . block_pos = pos + record_summary . index_len + record_summary . len ; return record_summary ; } /**\n     * Read record block index part in record section, and fill RECORD_BLOCK_TABLE\n     * @see https://github.com/zhansliu/writemdict/blob/master/fileformat.md#record-section\n     * @param input sliced file, start = begining of record block index, length = record_summary.index_len\n     * @param record_summary record summary object\n     */ function read_record_block ( input , record_summary ) { var scanner = Scanner ( input ) , size = record_summary . num_blocks , record_index = Array ( size ) , p0 = record_summary . block_pos , p1 = 0 ; RECORD_BLOCK_TABLE . alloc ( size + 1 ) ; for ( var i = 0 , rdx ; i < size ; i ++ ) { record_index [ i ] = rdx = { comp_size : scanner . readNum ( ) , decomp_size : scanner . readNum ( ) } ; RECORD_BLOCK_TABLE . put ( p0 , p1 ) ; p0 += rdx . comp_size ; p1 += rdx . decomp_size ; } RECORD_BLOCK_TABLE . put ( p0 , p1 ) ; } /**\n     * Read definition in text for given keyinfo object.\n     * @param input record block sliced from the file\n     * @param block record block index \n     * @param keyinfo a object with property of record's offset and optional size for the given keyword\n     * @return definition in text\n     */ function read_definition ( input , block , keyinfo ) { var scanner = Scanner ( input ) . readBlock ( block . comp_size , block . decomp_size ) ; scanner . forward ( keyinfo . offset - block . decomp_offset ) ; return scanner . readText ( ) ; } /**\n     * Following link to find actual definition of keyword.\n     * @param definition maybe starts with \"@@@LINK=\" which links to another keyword \n     * @param lookup search function\n     * @return resolved actual definition\n     */ function followLink ( definition , lookup ) { return ( definition . substring ( 0 , 8 ) !== '@@@LINK=' ) ? definition : lookup ( definition . substring ( 8 ) ) ; } /**\n     * Read content in ArrayBuffer for give keyinfo object\n     * @param input record block sliced from the file\n     * @param block record block index \n     * @param keyinfo a object with property of record's offset and optional size for the given keyword\n     * @return an ArrayBuffer containing resource of image/audio/css/font etc.\n     */ function read_object ( input , block , keyinfo ) { if ( input . byteLength > 0 ) { var scanner = Scanner ( input ) . readBlock ( block . comp_size , block . decomp_size ) ; scanner . forward ( keyinfo . offset - block . decomp_offset ) ; return scanner . readRaw ( keyinfo . size ) ; } else { throw '* OUT OF FILE RANGE * ' + keyinfo + ' @offset=' + block . comp_offset ; } } /**\n     * Find word definition for given keyinfo object.\n     * @param keyinfo a object with property of record's offset and optional size for the given keyword\n     * @return a promise object which will resolve to definition in text. Link to other keyword is followed to get actual definition.\n     */ function findWord ( keyinfo ) { var block = RECORD_BLOCK_TABLE . find ( keyinfo . offset ) ; return _slice ( block . comp_offset , block . comp_size ) . exec ( read_definition , block , keyinfo ) . spread ( function ( definition ) { return resolve ( followLink ( definition , LOOKUP . mdx ) ) ; } ) ; } /**\n     * Find resource (image, sound etc.) for given keyinfo object.\n     * @param keyinfo a object with property of record's offset and optional size for the given keyword\n     * @return a promise object which will resolve to an ArrayBuffer containing resource of image/audio/css/font etc.\n     * TODO: Follow link, maybe it's too expensive and a rarely used feature?\n     */ function findResource ( keyinfo ) { var block = RECORD_BLOCK_TABLE . find ( keyinfo . offset ) ; return _slice ( block . comp_offset , block . comp_size ) . exec ( read_object , block , keyinfo ) . spread ( function ( blob ) { return resolve ( blob ) ; } ) ; } //------------------------------------------------------------------------------------------------ // Implementation for look-up //------------------------------------------------------------------------------------------------ var slicedKeyBlock , _cached_keys , // cache latest keys  _trail , // store latest visited record block & position when search for candidate keys mutual_ticket = 0 ; // a oneway increased ticket used to cancel unfinished pattern match /**\n      * Reduce the key index array to an element which contains or is the nearest one matching a given phrase.\n      */ function reduce ( arr , phrase ) { var len = arr . length ; if ( len > 1 ) { len = len >> 1 ; return phrase > _adaptKey ( arr [ len - 1 ] . last_word ) ? reduce ( arr . slice ( len ) , phrase ) : reduce ( arr . slice ( 0 , len ) , phrase ) ; } else { return arr [ 0 ] ; } } /**\n      * Reduce the array to index of an element which contains or is the nearest one matching a given phrase.\n      */ function shrink ( arr , phrase ) { var len = arr . length , sub ; if ( len > 1 ) { len = len >> 1 ; var key = _adaptKey ( arr [ len ] ) ; if ( phrase < key ) { sub = arr . slice ( 0 , len ) ; sub . pos = arr . pos ; } else { sub = arr . slice ( len ) ; sub . pos = ( arr . pos || 0 ) + len ; } return shrink ( sub , phrase ) ; } else { return ( arr . pos || 0 ) + ( phrase <= _adaptKey ( arr [ 0 ] ) ? 0 : 1 ) ; } } /**\n     * Load keys for a keyword index object from mdx/mdd file.\n     * @param kdx keyword index object\n     */ function loadKeys ( kdx ) { if ( _cached_keys && _cached_keys . pilot === kdx . first_word ) { return resolve ( _cached_keys . list ) ; } else { return slicedKeyBlock . then ( function ( input ) { var scanner = Scanner ( input ) , list = Array ( kdx . num_entries ) ; scanner . forward ( kdx . offset ) ; scanner = scanner . readBlock ( kdx . comp_size , kdx . decomp_size ) ; for ( var i = 0 ; i < kdx . num_entries ; i ++ ) { var offset = scanner . readNum ( ) ; list [ i ] = new Object ( scanner . readText ( ) ) ; list [ i ] . offset = offset ; if ( i > 0 ) { list [ i - 1 ] . size = offset - list [ i - 1 ] . offset ; } } _cached_keys = { list : list , pilot : kdx . first_word } ; return list ; } ) ; } } /**\n     * Search for the first keyword match given phrase.\n     */ function seekVanguard ( phrase ) { phrase = _adaptKey ( phrase ) ; var kdx = reduce ( KEY_INDEX , phrase ) ; // look back for the first record block containing keyword for the specified phrase if ( phrase <= _adaptKey ( kdx . last_word ) ) { var index = kdx . index - 1 , prev ; while ( prev = KEY_INDEX [ index ] ) { if ( _adaptKey ( prev . last_word ) !== _adaptKey ( kdx . last_word ) ) { break ; } kdx = prev ; index -- ; } } return loadKeys ( kdx ) . then ( function ( list ) { var idx = shrink ( list , phrase ) ; // look back for the first matched keyword position while ( idx > 0 ) { if ( _adaptKey ( list [ -- idx ] ) !== _adaptKey ( phrase ) ) { idx ++ ; break ; } } return [ kdx , Math . min ( idx , list . length - 1 ) , list ] ; } ) ; } // TODO: have to restrict max count to improve response /**\n     * Append more to word list according to a filter or expected size.\n     */ function appendMore ( word , list , nextKdx , expectedSize , filter , ticket ) { if ( ticket !== mutual_ticket ) { throw 'force terminated' ; } if ( filter ) { if ( _trail . count < expectedSize && nextKdx && nextKdx . first_word . substr ( 0 , word . length ) === word ) { return loadKeys ( nextKdx ) . delay ( 30 ) . then ( function ( more ) { _trail . offset = 0 ; _trail . block = nextKdx . index ; Array . prototype . push . apply ( list , more . filter ( filter , _trail ) ) ; return appendMore ( word , list , KEY_INDEX [ nextKdx . index + 1 ] , expectedSize , filter , ticket ) ; } ) ; } else { if ( list . length === 0 ) { _trail . exhausted = true ; } return resolve ( list ) ; } } else { var shortage = expectedSize - list . length ; if ( shortage > 0 && nextKdx ) { _trail . block = nextKdx . index ; return loadKeys ( nextKdx ) . then ( function ( more ) { _trail . offset = 0 ; _trail . pos = Math . min ( shortage , more . length ) ; Array . prototype . push . apply ( list , more . slice ( 0 , shortage ) ) ; return appendMore ( word , list , KEY_INDEX [ nextKdx . index + 1 ] , expectedSize , filter , ticket ) ; } ) ; } else { if ( _trail . pos > expectedSize ) { _trail . pos = expectedSize ; } list = list . slice ( 0 , expectedSize ) ; _trail . count = list . length ; _trail . total += _trail . count ; return resolve ( list ) ; } } } function followUp ( ) { var kdx = KEY_INDEX [ _trail . block ] ; return loadKeys ( kdx ) . then ( function ( list ) { return [ kdx , Math . min ( _trail . offset + _trail . pos , list . length - 1 ) , list ] ; } ) ; } function matchKeys ( phrase , expectedSize , follow ) { expectedSize = Math . max ( expectedSize || 0 , 10 ) ; var str = phrase . trim ( ) . toLowerCase ( ) , m = / ([^?*]+)[?*]+ / . exec ( str ) , word ; if ( m ) { word = m [ 1 ] ; var wildcard = new RegExp ( '^' + str . replace ( / ([\\.\\\\\\+\\[\\^\\]\\$\\(\\)]) / g , '\\\\$1' ) . replace ( / \\*+ / g , '.*' ) . replace ( / \\? / g , '.' ) + '$' ) , tester = phrase [ phrase . length - 1 ] === ' ' ? function ( s ) { return wildcard . test ( s ) ; } : function ( s ) { return wildcard . test ( s ) && ! /   / . test ( s ) ; } , filter = function ( s , i ) { if ( _trail . count < expectedSize && tester ( s ) ) { _trail . count ++ ; _trail . total ++ ; _trail . pos = i + 1 ; return true ; } return false ; } ; } else { word = phrase . trim ( ) ; } if ( _trail && _trail . phrase !== phrase ) { follow = false ; } if ( follow && _trail && _trail . exhausted ) { return resolve ( [ ] ) ; } var startFrom = follow && _trail ? followUp ( ) : seekVanguard ( word ) ; return startFrom . spread ( function ( kdx , idx , list ) { list = list . slice ( idx ) ; _trail = { phrase : phrase , block : kdx . index , offset : idx , pos : list . length , count : 0 , total : follow ? _trail && _trail . total || 0 : 0 } ; if ( filter ) { list = list . filter ( filter , _trail ) ; } return appendMore ( word , list , KEY_INDEX [ kdx . index + 1 ] , expectedSize , filter , ++ mutual_ticket ) . then ( function ( result ) { if ( _trail . block === KEY_INDEX . length - 1 ) { if ( _trail . offset + _trail . pos >= KEY_INDEX [ _trail . block ] . num_entries ) { _trail . exhausted = true ; // console.log('EXHAUSTED!!!!'); } } // console.log('trail: ', _trail);           return result ; } ) ; } ) ; } ; /**\n     * Match the first element in list with given offset.\n     */ function matchOffset ( list , offset ) { return list . some ( function ( el ) { return el . offset === offset ? list = [ el ] : false ; } ) ? list : [ ] ; } // Lookup functions var LOOKUP = { /**\n       * @param query \n       *          String\n       *          {phrase: .., max: .., follow: true} object\n       */ mdx : function ( query ) { if ( typeof query === 'string' || query instanceof String ) { _trail = null ; var word = query . trim ( ) . toLowerCase ( ) , offset = query . offset ; return seekVanguard ( word ) . spread ( function ( kdx , idx , list ) { list = list . slice ( idx ) ; if ( offset !== UNDEFINED ) { list = matchOffset ( list , offset ) ; } else { list = list . filter ( function ( el ) { return el . toLowerCase ( ) === word ; } ) ; } return harvest ( list . map ( findWord ) ) ; } ) ; } else { return matchKeys ( query . phrase , query . max , query . follow ) ; } } , // TODO: chain multiple mdd file mdd : function ( phrase ) { var word = phrase . trim ( ) . toLowerCase ( ) ; word = '\\\\' + word . replace ( / (^[/\\\\])|([/]$) / , '' ) ; word = word . replace ( / \\/ / g , '\\\\' ) ; return seekVanguard ( word ) . spread ( function ( kdx , idx , list ) { return list . slice ( idx ) . filter ( function ( one ) { return one . toLowerCase ( ) === word ; } ) ; } ) . then ( function ( candidates ) { if ( candidates . length === 0 ) { throw '*RESOURCE NOT FOUND* ' + phrase ; } else { return findResource ( candidates [ 0 ] ) ; } } ) ; } } ; // ------------------------------------------ // start to load mdx/mdd file // ------------------------------------------ var pos = 0 ; // read first 4 bytes to get header length return _slice ( pos , 4 ) . exec ( read_file_head ) . then ( function ( len ) { len = parseInt ( len , 10 ) ; pos += 4 ; // start of header string in header section return _slice ( pos , len + 48 ) . exec ( read_header_sect , len ) ; } ) . then ( function ( ret ) { var header_remain_len = ret [ 0 ] ; var input = ret [ 1 ] ; pos += header_remain_len ; // start of keyword section return read_keyword_summary ( input , header_remain_len ) ; } ) . then ( function ( keyword_summary ) { pos += keyword_summary . len ; // start of key index in keyword section return _slice ( pos , keyword_summary . key_index_comp_len ) . exec ( read_keyword_index , keyword_summary ) ; } ) . then ( function ( data ) { var keyword_summary = data [ 0 ] ; var keyword_index = data [ 1 ] ; // console.log(data[1]); // console.log(data); pos += keyword_summary . key_index_comp_len ; // start of keyword block in keyword section slicedKeyBlock = _slice ( pos , keyword_summary . key_blocks_len ) ; // Now it's fast enough to look up word without key table, which scans keyword from the specified key blocks in an effcient way. // No need to scan the whole key table in ahead. // willScanKeyTable(slicedKeyBlock, keyword_summary.num_entries, keyword_index, 00); dasd; //  pos += keyword_summary . key_blocks_len ; // start of record section KEY_INDEX = keyword_index ; } ) . then ( function ( ) { return _slice ( pos , 32 ) . exec ( read_record_summary , pos ) ; } ) . spread ( function ( record_summary ) { pos += record_summary . len ; // start of record blocks in record section return _slice ( pos , record_summary . index_len ) . exec ( read_record_block , record_summary ) ; } ) . spread ( function ( ) { // resolve and return lookup() function according to file extension (mdx/mdd) LOOKUP [ ext ] . description = attrs . Description ; return resolve ( LOOKUP [ ext ] ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "bind sliceThen () with file argument Config scanner according to dictionary attributes . [CODESPLIT] function config ( ) { attrs . Encoding = attrs . Encoding || 'UTF-16' ; _searchTextLen = ( attrs . Encoding === 'UTF-16' ) ? function ( dv , offset ) { offset = offset ; var mark = offset ; while ( dv . getUint16 ( offset ++ ) ) { /* scan for NUL */ } ; return offset - mark ; } : function ( dv , offset ) { offset = offset ; var mark = offset ; while ( dv . getUint8 ( offset ++ ) ) { /* scan for NUL */ } return offset - mark - 1 ; } ; _decoder = new TextDecoder ( attrs . Encoding || 'UTF-16LE' ) ; _bpu = ( attrs . Encoding === 'UTF-16' ) ? 2 : 1 ; if ( parseInt ( attrs . GeneratedByEngineVersion , 10 ) >= 2.0 ) { _v2 = true ; _tail = _bpu ; // HUGE dictionary file (>4G) is not supported, take only lower 32-bit _readNum = function ( scanner ) { return scanner . forward ( 4 ) , scanner . readInt ( ) ; } ; _readShort = function ( scanner ) { return scanner . readUint16 ( ) ; } ; _checksum_v2 = function ( scanner ) { return scanner . checksum ( ) ; } ; } else { _tail = 0 ; } // keyword index decrypted? if ( attrs . Encrypted & 0x02 ) { _decryptors [ 1 ] = decrypt ; } var regexp = common . REGEXP_STRIPKEY [ ext ] ; if ( isTrue ( attrs . KeyCaseSensitive ) ) { _adaptKey = isTrue ( attrs . StripKey ) ? function ( key ) { return key . replace ( regexp , '$1' ) ; } : function ( key ) { return key ; } ; } else { _adaptKey = isTrue ( attrs . StripKey || ( _v2 ? '' : 'yes' ) ) ? function ( key ) { return key . toLowerCase ( ) . replace ( regexp , '$1' ) ; } : function ( key ) { return key . toLowerCase ( ) ; } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data in current offset from target data ArrayBuffer [CODESPLIT] function Scanner ( buf , len ) { var offset = 0 , dv = new DataView ( buf ) ; var methods = { // target data size in bytes size : function ( ) { return len || buf . byteLength ; } , // update offset to new position forward : function ( len ) { return offset += len ; } , // return current offset offset : function ( ) { return offset ; } , // MDict file format uses big endian to store number // 32-bit unsigned int readInt : function ( ) { return conseq ( dv . getUint32 ( offset , false ) , this . forward ( 4 ) ) ; } , readUint16 : function ( ) { return conseq ( dv . getUint16 ( offset , false ) , this . forward ( 2 ) ) ; } , readUint8 : function ( ) { return conseq ( dv . getUint8 ( offset , false ) , this . forward ( 1 ) ) ; } , // Read a \"short\" number representing keyword text size, 8-bit for version < 2, 16-bit for version >= 2 readShort : function ( ) { return _readShort ( this ) ; } , // Read a number representing offset or data block size, 16-bit for version < 2, 32-bit for version >= 2 readNum : function ( ) { return _readNum ( this ) ; } , readUTF16 : function ( len ) { return conseq ( UTF_16LE . decode ( newUint8Array ( buf , offset , len ) ) , this . forward ( len ) ) ; } , // Read data to an Uint8Array and decode it to text with specified encoding. // Text length in bytes is determined by searching terminated NUL. // NOTE: After decoding the text, it is need to forward extra \"tail\" bytes according to specified encoding.  readText : function ( ) { var len = _searchTextLen ( dv , offset ) ; return conseq ( _decoder . decode ( newUint8Array ( buf , offset , len ) ) , this . forward ( len + _bpu ) ) ; } , // Read data to an Uint8Array and decode it to text with specified encoding. // @param len length in basic unit, need to multiply byte per unit to get length in bytes // NOTE: After decoding the text, it is need to forward extra \"tail\" bytes according to specified encoding.  readTextSized : function ( len ) { len *= _bpu ; var read = conseq ( _decoder . decode ( newUint8Array ( buf , offset , len ) ) , this . forward ( len + _tail ) ) ; return read ; } , // Skip checksum, just ignore it anyway. checksum : function ( ) { this . forward ( 4 ) ; } , // Version >= 2.0 only checksum_v2 : function ( ) { return _checksum_v2 ( this ) ; } , // Read data block of keyword index, key block or record content. // These data block are maybe in compressed (gzip or lzo) format, while keyword index maybe be encrypted. // @see https://github.com/zhansliu/writemdict/blob/master/fileformat.md#compression (with typo mistake) readBlock : function ( len , expectedBufSize , decryptor ) { var comp_type = dv . getUint8 ( offset , false ) ; // compression type, 0 = non, 1 = lzo, 2 = gzip if ( comp_type === 0 ) { if ( _v2 ) { this . forward ( 8 ) ; // for version >= 2, skip comp_type (4 bytes with tailing \\x00) and checksum (4 bytes) } return this ; } else { // skip comp_type (4 bytes with tailing \\x00) and checksum (4 bytes) offset += 8 ; len -= 8 ; var tmp = new Uint8Array ( len ) ; buf . copy ( tmp , 0 , offset , offset + len ) ; if ( decryptor ) { var passkey = new Uint8Array ( 8 ) ; var q = new Buffer ( 4 ) ; buf . copy ( passkey , 0 , offset - 4 , offset ) ; // var q = new Buffer(4); passkey . set ( [ 0x95 , 0x36 , 0x00 , 0x00 ] , 4 ) ; // key part 2: fixed data tmp = decryptor ( tmp , passkey ) ; } tmp = comp_type === 2 ? pako . inflate ( tmp ) : lzo . decompress ( tmp , expectedBufSize , 1308672 ) ; this . forward ( len ) ; var d = new Buffer ( tmp ) ; return Scanner ( d , tmp . length ) ; } } , // Read raw data as Uint8Array from current offset with specified length in bytes readRaw : function ( len ) { return conseq ( newUint8Array ( buf , offset , len ) , this . forward ( len === UNDEFINED ? buf . length - offset : len ) ) ; } , } ; return Object . create ( methods ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data to an Uint8Array and decode it to text with specified encoding . Text length in bytes is determined by searching terminated NUL . NOTE : After decoding the text it is need to forward extra tail bytes according to specified encoding . [CODESPLIT] function ( ) { var len = _searchTextLen ( dv , offset ) ; return conseq ( _decoder . decode ( newUint8Array ( buf , offset , len ) ) , this . forward ( len + _bpu ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data to an Uint8Array and decode it to text with specified encoding . [CODESPLIT] function ( len ) { len *= _bpu ; var read = conseq ( _decoder . decode ( newUint8Array ( buf , offset , len ) ) , this . forward ( len + _tail ) ) ; return read ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data block of keyword index key block or record content . These data block are maybe in compressed ( gzip or lzo ) format while keyword index maybe be encrypted . [CODESPLIT] function ( len , expectedBufSize , decryptor ) { var comp_type = dv . getUint8 ( offset , false ) ; // compression type, 0 = non, 1 = lzo, 2 = gzip if ( comp_type === 0 ) { if ( _v2 ) { this . forward ( 8 ) ; // for version >= 2, skip comp_type (4 bytes with tailing \\x00) and checksum (4 bytes) } return this ; } else { // skip comp_type (4 bytes with tailing \\x00) and checksum (4 bytes) offset += 8 ; len -= 8 ; var tmp = new Uint8Array ( len ) ; buf . copy ( tmp , 0 , offset , offset + len ) ; if ( decryptor ) { var passkey = new Uint8Array ( 8 ) ; var q = new Buffer ( 4 ) ; buf . copy ( passkey , 0 , offset - 4 , offset ) ; // var q = new Buffer(4); passkey . set ( [ 0x95 , 0x36 , 0x00 , 0x00 ] , 4 ) ; // key part 2: fixed data tmp = decryptor ( tmp , passkey ) ; } tmp = comp_type === 2 ? pako . inflate ( tmp ) : lzo . decompress ( tmp , expectedBufSize , 1308672 ) ; this . forward ( len ) ; var d = new Buffer ( tmp ) ; return Scanner ( d , tmp . length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read raw data as Uint8Array from current offset with specified length in bytes [CODESPLIT] function ( len ) { return conseq ( newUint8Array ( buf , offset , len ) , this . forward ( len === UNDEFINED ? buf . length - offset : len ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read header section parse dictionary attributes and config scanner according to engine version attribute . [CODESPLIT] function read_header_sect ( input , len ) { var scanner = Scanner ( input ) , header_str = scanner . readUTF16 ( len ) . replace ( / \\0$ / , '' ) ; // need to remove tailing NUL // parse dictionary attributes var doc = new DOMParser ( ) . parseFromString ( header_str , 'text/xml' ) ; var elem = doc . getElementsByTagName ( 'Dictionary' ) [ 0 ] ; if ( ! elem ) { elem = doc . getElementsByTagName ( 'Library_Data' ) [ 0 ] ; } // console.log(doc.getElementsByTagName('Dictionary')[0].attributes); // var xml = parseXml(header_str).querySelector('Dictionary, Library_Data').attributes; for ( var i = 0 , item ; i < elem . attributes . length ; i ++ ) { item = elem . attributes [ i ] ; attrs [ item . nodeName ] = item . nodeValue ; } attrs . Encrypted = parseInt ( attrs . Encrypted , 10 ) || 0 ; config ( ) ; return spreadus ( len + 4 , input ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read keyword summary at the begining of keyword section . [CODESPLIT] function read_keyword_summary ( input , offset ) { var scanner = Scanner ( input ) ; scanner . forward ( offset ) ; return { num_blocks : scanner . readNum ( ) , num_entries : scanner . readNum ( ) , key_index_decomp_len : _v2 && scanner . readNum ( ) , // Ver >= 2.0 only key_index_comp_len : scanner . readNum ( ) , key_blocks_len : scanner . readNum ( ) , chksum : scanner . checksum_v2 ( ) , // extra field len : scanner . offset ( ) - offset , // actual length of keyword section, varying with engine version attribute } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read keyword index part of keyword section . [CODESPLIT] function read_keyword_index ( input , keyword_summary ) { var scanner = Scanner ( input ) . readBlock ( keyword_summary . key_index_comp_len , keyword_summary . key_index_decomp_len , _decryptors [ 1 ] ) , keyword_index = Array ( keyword_summary . num_blocks ) , offset = 0 ; for ( var i = 0 , size ; i < keyword_summary . num_blocks ; i ++ ) { keyword_index [ i ] = { num_entries : conseq ( scanner . readNum ( ) , size = scanner . readShort ( ) ) , // UNUSED, can be ignored         //          first_size:  size = scanner.readShort(), first_word : conseq ( scanner . readTextSized ( size ) , size = scanner . readShort ( ) ) , // UNUSED, can be ignored //          last_size:   size = scanner.readShort(), last_word : scanner . readTextSized ( size ) , comp_size : size = scanner . readNum ( ) , decomp_size : scanner . readNum ( ) , // extra fields offset : offset , // offset of the first byte for the target key block in mdx/mdd file index : i // index of this key index, used to search previous/next block } ; offset += size ; } return spreadus ( keyword_summary , keyword_index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read keyword entries inside a keyword block and fill KEY_TABLE . [CODESPLIT] function read_key_block ( scanner , kdx ) { var scanner = scanner . readBlock ( kdx . comp_size , kdx . decomp_size ) ; for ( var i = 0 ; i < kdx . num_entries ; i ++ ) { //        scanner.readNum(); scanner.readText(); var kk = [ scanner . readNum ( ) , scanner . readText ( ) ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delay to scan key table for debug onyl . [CODESPLIT] function willScanKeyTable ( slicedKeyBlock , num_entries , keyword_index , delay ) { slicedKeyBlock . delay ( delay ) . then ( function ( input ) { var scanner = Scanner ( input ) ; for ( var i = 0 , size = keyword_index . length ; i < size ; i ++ ) { // common.log('z',keyword_index[i]); read_key_block ( scanner , keyword_index [ i ] ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read record summary at the begining of record section . [CODESPLIT] function read_record_summary ( input , pos ) { var scanner = Scanner ( input ) , record_summary = { num_blocks : scanner . readNum ( ) , num_entries : scanner . readNum ( ) , index_len : scanner . readNum ( ) , blocks_len : scanner . readNum ( ) , // extra field len : scanner . offset ( ) , // actual length of record section (excluding record block index), varying with engine version attribute } ; // start position of record block from head of mdx/mdd file record_summary . block_pos = pos + record_summary . index_len + record_summary . len ; return record_summary ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read record block index part in record section and fill RECORD_BLOCK_TABLE [CODESPLIT] function read_record_block ( input , record_summary ) { var scanner = Scanner ( input ) , size = record_summary . num_blocks , record_index = Array ( size ) , p0 = record_summary . block_pos , p1 = 0 ; RECORD_BLOCK_TABLE . alloc ( size + 1 ) ; for ( var i = 0 , rdx ; i < size ; i ++ ) { record_index [ i ] = rdx = { comp_size : scanner . readNum ( ) , decomp_size : scanner . readNum ( ) } ; RECORD_BLOCK_TABLE . put ( p0 , p1 ) ; p0 += rdx . comp_size ; p1 += rdx . decomp_size ; } RECORD_BLOCK_TABLE . put ( p0 , p1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read definition in text for given keyinfo object . [CODESPLIT] function read_definition ( input , block , keyinfo ) { var scanner = Scanner ( input ) . readBlock ( block . comp_size , block . decomp_size ) ; scanner . forward ( keyinfo . offset - block . decomp_offset ) ; return scanner . readText ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read content in ArrayBuffer for give keyinfo object [CODESPLIT] function read_object ( input , block , keyinfo ) { if ( input . byteLength > 0 ) { var scanner = Scanner ( input ) . readBlock ( block . comp_size , block . decomp_size ) ; scanner . forward ( keyinfo . offset - block . decomp_offset ) ; return scanner . readRaw ( keyinfo . size ) ; } else { throw '* OUT OF FILE RANGE * ' + keyinfo + ' @offset=' + block . comp_offset ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find word definition for given keyinfo object . [CODESPLIT] function findWord ( keyinfo ) { var block = RECORD_BLOCK_TABLE . find ( keyinfo . offset ) ; return _slice ( block . comp_offset , block . comp_size ) . exec ( read_definition , block , keyinfo ) . spread ( function ( definition ) { return resolve ( followLink ( definition , LOOKUP . mdx ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find resource ( image sound etc . ) for given keyinfo object . [CODESPLIT] function findResource ( keyinfo ) { var block = RECORD_BLOCK_TABLE . find ( keyinfo . offset ) ; return _slice ( block . comp_offset , block . comp_size ) . exec ( read_object , block , keyinfo ) . spread ( function ( blob ) { return resolve ( blob ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a oneway increased ticket used to cancel unfinished pattern match Reduce the key index array to an element which contains or is the nearest one matching a given phrase . [CODESPLIT] function reduce ( arr , phrase ) { var len = arr . length ; if ( len > 1 ) { len = len >> 1 ; return phrase > _adaptKey ( arr [ len - 1 ] . last_word ) ? reduce ( arr . slice ( len ) , phrase ) : reduce ( arr . slice ( 0 , len ) , phrase ) ; } else { return arr [ 0 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reduce the array to index of an element which contains or is the nearest one matching a given phrase . [CODESPLIT] function shrink ( arr , phrase ) { var len = arr . length , sub ; if ( len > 1 ) { len = len >> 1 ; var key = _adaptKey ( arr [ len ] ) ; if ( phrase < key ) { sub = arr . slice ( 0 , len ) ; sub . pos = arr . pos ; } else { sub = arr . slice ( len ) ; sub . pos = ( arr . pos || 0 ) + len ; } return shrink ( sub , phrase ) ; } else { return ( arr . pos || 0 ) + ( phrase <= _adaptKey ( arr [ 0 ] ) ? 0 : 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load keys for a keyword index object from mdx / mdd file . [CODESPLIT] function loadKeys ( kdx ) { if ( _cached_keys && _cached_keys . pilot === kdx . first_word ) { return resolve ( _cached_keys . list ) ; } else { return slicedKeyBlock . then ( function ( input ) { var scanner = Scanner ( input ) , list = Array ( kdx . num_entries ) ; scanner . forward ( kdx . offset ) ; scanner = scanner . readBlock ( kdx . comp_size , kdx . decomp_size ) ; for ( var i = 0 ; i < kdx . num_entries ; i ++ ) { var offset = scanner . readNum ( ) ; list [ i ] = new Object ( scanner . readText ( ) ) ; list [ i ] . offset = offset ; if ( i > 0 ) { list [ i - 1 ] . size = offset - list [ i - 1 ] . offset ; } } _cached_keys = { list : list , pilot : kdx . first_word } ; return list ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for the first keyword match given phrase . [CODESPLIT] function seekVanguard ( phrase ) { phrase = _adaptKey ( phrase ) ; var kdx = reduce ( KEY_INDEX , phrase ) ; // look back for the first record block containing keyword for the specified phrase if ( phrase <= _adaptKey ( kdx . last_word ) ) { var index = kdx . index - 1 , prev ; while ( prev = KEY_INDEX [ index ] ) { if ( _adaptKey ( prev . last_word ) !== _adaptKey ( kdx . last_word ) ) { break ; } kdx = prev ; index -- ; } } return loadKeys ( kdx ) . then ( function ( list ) { var idx = shrink ( list , phrase ) ; // look back for the first matched keyword position while ( idx > 0 ) { if ( _adaptKey ( list [ -- idx ] ) !== _adaptKey ( phrase ) ) { idx ++ ; break ; } } return [ kdx , Math . min ( idx , list . length - 1 ) , list ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : have to restrict max count to improve response Append more to word list according to a filter or expected size . [CODESPLIT] function appendMore ( word , list , nextKdx , expectedSize , filter , ticket ) { if ( ticket !== mutual_ticket ) { throw 'force terminated' ; } if ( filter ) { if ( _trail . count < expectedSize && nextKdx && nextKdx . first_word . substr ( 0 , word . length ) === word ) { return loadKeys ( nextKdx ) . delay ( 30 ) . then ( function ( more ) { _trail . offset = 0 ; _trail . block = nextKdx . index ; Array . prototype . push . apply ( list , more . filter ( filter , _trail ) ) ; return appendMore ( word , list , KEY_INDEX [ nextKdx . index + 1 ] , expectedSize , filter , ticket ) ; } ) ; } else { if ( list . length === 0 ) { _trail . exhausted = true ; } return resolve ( list ) ; } } else { var shortage = expectedSize - list . length ; if ( shortage > 0 && nextKdx ) { _trail . block = nextKdx . index ; return loadKeys ( nextKdx ) . then ( function ( more ) { _trail . offset = 0 ; _trail . pos = Math . min ( shortage , more . length ) ; Array . prototype . push . apply ( list , more . slice ( 0 , shortage ) ) ; return appendMore ( word , list , KEY_INDEX [ nextKdx . index + 1 ] , expectedSize , filter , ticket ) ; } ) ; } else { if ( _trail . pos > expectedSize ) { _trail . pos = expectedSize ; } list = list . slice ( 0 , expectedSize ) ; _trail . count = list . length ; _trail . total += _trail . count ; return resolve ( list ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match the first element in list with given offset . [CODESPLIT] function matchOffset ( list , offset ) { return list . some ( function ( el ) { return el . offset === offset ? list = [ el ] : false ; } ) ? list : [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : chain multiple mdd file [CODESPLIT] function ( phrase ) { var word = phrase . trim ( ) . toLowerCase ( ) ; word = '\\\\' + word . replace ( / (^[/\\\\])|([/]$) / , '' ) ; word = word . replace ( / \\/ / g , '\\\\' ) ; return seekVanguard ( word ) . spread ( function ( kdx , idx , list ) { return list . slice ( idx ) . filter ( function ( one ) { return one . toLowerCase ( ) === word ; } ) ; } ) . then ( function ( candidates ) { if ( candidates . length === 0 ) { throw '*RESOURCE NOT FOUND* ' + phrase ; } else { return findResource ( candidates [ 0 ] ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether the specified modifier keys match the modifier keys that were pressed . [CODESPLIT] function isValidModifierKeyCombo ( modifierKeys , e ) { var modifierKeyNames = [ 'alt' , 'ctrl' , 'meta' , 'shift' ] , numModKeys = modifierKeys . length , i , j , currModifierKey , isValid = true ; // check that all required modifier keys were pressed for ( i = 0 ; i < numModKeys ; i += 1 ) { if ( ! e [ modifierKeys [ i ] ] ) { isValid = false ; break ; } } // if the requirements were met, check for additional modifier keys if ( isValid ) { for ( i = 0 ; i < modifierKeyNames . length ; i += 1 ) { currModifierKey = modifierKeyNames [ i ] + 'Key' ; // if this key was pressed if ( e [ currModifierKey ] ) { // if there are required keys, check whether the current key // is required if ( numModKeys ) { isValid = false ; // if this is a required key, continue for ( j = 0 ; j < numModKeys ; j += 1 ) { if ( currModifierKey === modifierKeys [ j ] ) { isValid = true ; break ; } } } else { // no required keys, but one was pressed isValid = false ; } } // an extra key was pressed, don't check anymore if ( ! isValid ) { break ; } } } return isValid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a function to get and set the specified key combination . [CODESPLIT] function createKeyComboFunction ( keyFunc , modifierKeys ) { return function ( keyCode , modifierKeyNames ) { var i , keyCombo = '' ; if ( arguments . length ) { if ( typeof keyCode === 'number' ) { keyFunc ( keyCode ) ; modifierKeys . length = 0 ; // clear the array if ( modifierKeyNames && modifierKeyNames . length ) { for ( i = 0 ; i < modifierKeyNames . length ; i += 1 ) { modifierKeys . push ( modifierKeyNames [ i ] + 'Key' ) ; } } } return this ; } for ( i = 0 ; i < modifierKeys . length ; i += 1 ) { keyCombo += modifierKeys [ i ] . slice ( 0 , - 3 ) + '+' ; } return keyCombo + keyFunc ( ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler to insert or remove tabs and newlines on the keydown event for the tab or enter key . [CODESPLIT] function overrideKeyDown ( e ) { e = e || event ; // textarea elements can only contain text nodes which don't receive // keydown events, so the event target/srcElement will always be the // textarea element, however, prefer currentTarget in order to support // delegated events in compliant browsers var target = e . currentTarget || e . srcElement , // don't use the \"this\" keyword (doesn't work in old IE) key = e . keyCode , // the key code for the key that was pressed tab , // the string representing a tab tabLen , // the length of a tab text , // initial text in the textarea range , // the IE TextRange object tempRange , // used to calculate selection start and end positions in IE preNewlines , // the number of newline character sequences before the selection start (for IE) selNewlines , // the number of newline character sequences within the selection (for IE) initScrollTop , // initial scrollTop value used to fix scrolling in Firefox selStart , // the selection start position selEnd , // the selection end position sel , // the selected text startLine , // for multi-line selections, the first character position of the first line endLine , // for multi-line selections, the last character position of the last line numTabs , // the number of tabs inserted / removed in the selection startTab , // if a tab was removed from the start of the first line preTab , // if a tab was removed before the start of the selection whitespace , // the whitespace at the beginning of the first selected line whitespaceLen , // the length of the whitespace at the beginning of the first selected line CHARACTER = 'character' ; // string constant used for the Range.move methods // don't do any unnecessary work if ( ( target . nodeName && target . nodeName . toLowerCase ( ) !== 'textarea' ) || ( key !== tabKey && key !== untabKey && ( key !== 13 || ! autoIndent ) ) ) { return ; } // initialize variables used for tab and enter keys inWhitespace = false ; // this will be set to true if enter is pressed in the leading whitespace text = target . value ; // this is really just for Firefox, but will be used by all browsers that support // selectionStart and selectionEnd - whenever the textarea value property is reset, // Firefox scrolls back to the top - this is used to set it back to the original value // scrollTop is nonstandard, but supported by all modern browsers initScrollTop = target . scrollTop ; // get the text selection if ( typeof target . selectionStart === 'number' ) { selStart = target . selectionStart ; selEnd = target . selectionEnd ; sel = text . slice ( selStart , selEnd ) ; } else if ( document . selection ) { // IE range = document . selection . createRange ( ) ; sel = range . text ; tempRange = range . duplicate ( ) ; tempRange . moveToElementText ( target ) ; tempRange . setEndPoint ( 'EndToEnd' , range ) ; selEnd = tempRange . text . length ; selStart = selEnd - sel . length ; // whenever the value of the textarea is changed, the range needs to be reset // IE <9 (and Opera) use both \\r and \\n for newlines - this adds an extra character // that needs to be accounted for when doing position calculations with ranges // these values are used to offset the selection start and end positions if ( newlineLen > 1 ) { preNewlines = text . slice ( 0 , selStart ) . split ( newline ) . length - 1 ; selNewlines = sel . split ( newline ) . length - 1 ; } else { preNewlines = selNewlines = 0 ; } } else { return ; // cannot access textarea selection - do nothing } // tab / untab key - insert / remove tab if ( key === tabKey || key === untabKey ) { // initialize tab variables tab = aTab ; tabLen = tab . length ; numTabs = 0 ; startTab = 0 ; preTab = 0 ; // multi-line selection if ( selStart !== selEnd && sel . indexOf ( '\\n' ) !== - 1 ) { // for multiple lines, only insert / remove tabs from the beginning of each line // find the start of the first selected line if ( selStart === 0 || text . charAt ( selStart - 1 ) === '\\n' ) { // the selection starts at the beginning of a line startLine = selStart ; } else { // the selection starts after the beginning of a line // set startLine to the beginning of the first partially selected line // subtract 1 from selStart in case the cursor is at the newline character, // for instance, if the very end of the previous line was selected // add 1 to get the next character after the newline // if there is none before the selection, lastIndexOf returns -1 // when 1 is added to that it becomes 0 and the first character is used startLine = text . lastIndexOf ( '\\n' , selStart - 1 ) + 1 ; } // find the end of the last selected line if ( selEnd === text . length || text . charAt ( selEnd ) === '\\n' ) { // the selection ends at the end of a line endLine = selEnd ; } else if ( text . charAt ( selEnd - 1 ) === '\\n' ) { // the selection ends at the start of a line, but no // characters are selected - don't indent this line endLine = selEnd - 1 ; } else { // the selection ends before the end of a line // set endLine to the end of the last partially selected line endLine = text . indexOf ( '\\n' , selEnd ) ; if ( endLine === - 1 ) { endLine = text . length ; } } // tab key combo - insert tabs if ( tabKeyComboPressed ( key , e ) ) { numTabs = 1 ; // for the first tab // insert tabs at the beginning of each line of the selection target . value = text . slice ( 0 , startLine ) + tab + text . slice ( startLine , endLine ) . replace ( / \\n / g , function ( ) { numTabs += 1 ; return '\\n' + tab ; } ) + text . slice ( endLine ) ; // set start and end points if ( range ) { // IE range . collapse ( ) ; range . moveEnd ( CHARACTER , selEnd + ( numTabs * tabLen ) - selNewlines - preNewlines ) ; range . moveStart ( CHARACTER , selStart + tabLen - preNewlines ) ; range . select ( ) ; } else { // the selection start is always moved by 1 character target . selectionStart = selStart + tabLen ; // move the selection end over by the total number of tabs inserted target . selectionEnd = selEnd + ( numTabs * tabLen ) ; target . scrollTop = initScrollTop ; } } else if ( untabKeyComboPressed ( key , e ) ) { // if the untab key combo was pressed, remove tabs instead of inserting them if ( text . slice ( startLine ) . indexOf ( tab ) === 0 ) { // is this tab part of the selection? if ( startLine === selStart ) { // it is, remove it sel = sel . slice ( tabLen ) ; } else { // the tab comes before the selection preTab = tabLen ; } startTab = tabLen ; } target . value = text . slice ( 0 , startLine ) + text . slice ( startLine + preTab , selStart ) + sel . replace ( new RegExp ( '\\n' + tab , 'g' ) , function ( ) { numTabs += 1 ; return '\\n' ; } ) + text . slice ( selEnd ) ; // set start and end points if ( range ) { // IE // setting end first makes calculations easier range . collapse ( ) ; range . moveEnd ( CHARACTER , selEnd - startTab - ( numTabs * tabLen ) - selNewlines - preNewlines ) ; range . moveStart ( CHARACTER , selStart - preTab - preNewlines ) ; range . select ( ) ; } else { // set start first for Opera target . selectionStart = selStart - preTab ; // preTab is 0 or tabLen // move the selection end over by the total number of tabs removed target . selectionEnd = selEnd - startTab - ( numTabs * tabLen ) ; } } else { return ; // do nothing for invalid key combinations } } else { // single line selection // tab key combo - insert a tab if ( tabKeyComboPressed ( key , e ) ) { if ( range ) { // IE range . text = tab ; range . select ( ) ; } else { target . value = text . slice ( 0 , selStart ) + tab + text . slice ( selEnd ) ; target . selectionEnd = target . selectionStart = selStart + tabLen ; target . scrollTop = initScrollTop ; } } else if ( untabKeyComboPressed ( key , e ) ) { // if the untab key combo was pressed, remove a tab instead of inserting one // if the character before the selection is a tab, remove it if ( text . slice ( selStart - tabLen ) . indexOf ( tab ) === 0 ) { target . value = text . slice ( 0 , selStart - tabLen ) + text . slice ( selStart ) ; // set start and end points if ( range ) { // IE // collapses range and moves it by -1 tab range . move ( CHARACTER , selStart - tabLen - preNewlines ) ; range . select ( ) ; } else { target . selectionEnd = target . selectionStart = selStart - tabLen ; target . scrollTop = initScrollTop ; } } } else { return ; // do nothing for invalid key combinations } } } else if ( autoIndent ) { // Enter key // insert a newline and copy the whitespace from the beginning of the line // find the start of the first selected line if ( selStart === 0 || text . charAt ( selStart - 1 ) === '\\n' ) { // the selection starts at the beginning of a line // do nothing special inWhitespace = true ; return ; } // see explanation under \"multi-line selection\" above startLine = text . lastIndexOf ( '\\n' , selStart - 1 ) + 1 ; // find the end of the first selected line endLine = text . indexOf ( '\\n' , selStart ) ; // if no newline is found, set endLine to the end of the text if ( endLine === - 1 ) { endLine = text . length ; } // get the whitespace at the beginning of the first selected line (spaces and tabs only) whitespace = text . slice ( startLine , endLine ) . match ( / ^[ \\t]* / ) [ 0 ] ; whitespaceLen = whitespace . length ; // the cursor (selStart) is in the whitespace at beginning of the line // do nothing special if ( selStart < startLine + whitespaceLen ) { inWhitespace = true ; return ; } if ( range ) { // IE // insert the newline and whitespace range . text = '\\n' + whitespace ; range . select ( ) ; } else { // insert the newline and whitespace target . value = text . slice ( 0 , selStart ) + '\\n' + whitespace + text . slice ( selEnd ) ; // Opera uses \\r\\n for a newline, instead of \\n, // so use newlineLen instead of a hard-coded value target . selectionEnd = target . selectionStart = selStart + newlineLen + whitespaceLen ; target . scrollTop = initScrollTop ; } } if ( e . preventDefault ) { e . preventDefault ( ) ; } else { e . returnValue = false ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler to prevent the default action for the keypress event when tab or enter is pressed . Opera and Firefox also fire a keypress event when the tab or enter key is pressed . Opera requires that the default action be prevented on this event or the textarea will lose focus . [CODESPLIT] function overrideKeyPress ( e ) { e = e || event ; var key = e . keyCode ; if ( tabKeyComboPressed ( key , e ) || untabKeyComboPressed ( key , e ) || ( key === 13 && autoIndent && ! inWhitespace ) ) { if ( e . preventDefault ) { e . preventDefault ( ) ; } else { e . returnValue = false ; return false ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes all registered extension functions for the specified hook . [CODESPLIT] function executeExtensions ( hook , args ) { var i , extensions = hooks [ hook ] || [ ] , len = extensions . length ; for ( i = 0 ; i < len ; i += 1 ) { extensions [ i ] . apply ( null , args ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@typedef { Object } tabOverride . utils~listenersObj [CODESPLIT] function createListeners ( handlerList ) { var i , len = handlerList . length , remove , add ; function loop ( func ) { for ( i = 0 ; i < len ; i += 1 ) { func ( handlerList [ i ] . type , handlerList [ i ] . handler ) ; } } // use the standard event handler registration method when available if ( document . addEventListener ) { remove = function ( elem ) { loop ( function ( type , handler ) { elem . removeEventListener ( type , handler , false ) ; } ) ; } ; add = function ( elem ) { // remove listeners before adding them to make sure they are not // added more than once remove ( elem ) ; loop ( function ( type , handler ) { elem . addEventListener ( type , handler , false ) ; } ) ; } ; } else if ( document . attachEvent ) { // support IE 6-8 remove = function ( elem ) { loop ( function ( type , handler ) { elem . detachEvent ( 'on' + type , handler ) ; } ) ; } ; add = function ( elem ) { remove ( elem ) ; loop ( function ( type , handler ) { elem . attachEvent ( 'on' + type , handler ) ; } ) ; } ; } return { add : add , remove : remove } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * global threesixty : true [CODESPLIT] function generateImagesToPreload ( totalImages ) { for ( var i = 0 , images = [ ] , index ; i < totalImages ; i ++ ) { index = ( i < 10 ) ? '0' + i : i images . push ( 'https://github.com/rbartoli/threesixty/raw/master/example/images/sequence-' + index + '.png' ) } return images }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper function that asynchronously converts ImapMessage instance to instance of Message class . [CODESPLIT] function ( imapMessage ) { var deferred = Q . defer ( ) ; var message = new Message ( ) ; imapMessage . on ( 'body' , function ( stream , info ) { var buffer = '' ; stream . on ( 'data' , function ( chunk ) { buffer += chunk . toString ( 'utf8' ) ; } ) ; stream . on ( 'end' , function ( ) { if ( info . which === 'TEXT' ) { message . body = buffer ; } else { message . headers = Imap . parseHeader ( buffer ) ; } } ) ; } ) ; imapMessage . on ( 'attributes' , function ( attrs ) { message . attributes = attrs ; } ) ; imapMessage . on ( 'end' , function ( ) { deferred . resolve ( message ) ; } ) ; return deferred . promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GUID Partition Table [CODESPLIT] function GPT ( options ) { if ( ! ( this instanceof GPT ) ) { return new GPT ( options ) } options = options != null ? options : { } /** @type {Number} Storage device's block size in bytes */ this . blockSize = options . blockSize || 512 /** @type {String} GUID of the GUID Partition Table */ this . guid = options . guid || GPT . GUID . ZERO /** @type {Number} GPT format revision (?) */ this . revision = options . revision || 0 /** @type {Number} Size of the GPT header in bytes */ this . headerSize = options . headerSize || GPT . HEADER_SIZE /** @type {Number} GPT header's CRC32 checksum */ this . headerChecksum = 0 /** @type {Number} Logical block address of *this* GPT */ this . currentLBA = options . currentLBA || 1 /** @type {Number} Logical block address of the secondary GPT */ this . backupLBA = options . backupLBA || 0 /** @type {Number} Address of the first user-space usable logical block */ this . firstLBA = options . firstLBA || 34 /** @type {Number} Address of the last user-space usable logical block */ this . lastLBA = options . lastLBA || 0 /** @type {Number} LBA of partition table */ this . tableOffset = options . tableOffset || GPT . TABLE_OFFSET /** @type {Number} Number of partition table entries */ this . entries = options . entries || GPT . TABLE_ENTRIES /** @type {Number} Partition entry's size in bytes */ this . entrySize = options . entrySize || GPT . TABLE_ENTRY_SIZE /** @type {Number} Partition table's CRC32 checksum */ this . tableChecksum = 0 // Array of partition entries this . partitions = [ ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves . and .. elements in a path with directory names [CODESPLIT] function normalizeString ( path , allowAboveRoot ) { var res = '' var lastSegmentLength = 0 var lastSlash = - 1 var dots = 0 var code for ( var i = 0 ; i <= path . length ; i += 1 ) { if ( i < path . length ) code = path . charCodeAt ( i ) else if ( code === CHAR_FORWARD_SLASH ) break else code = CHAR_FORWARD_SLASH if ( code === CHAR_FORWARD_SLASH ) { if ( lastSlash === i - 1 || dots === 1 ) { // NOOP } else if ( lastSlash !== i - 1 && dots === 2 ) { if ( res . length < 2 || lastSegmentLength !== 2 || res . charCodeAt ( res . length - 1 ) !== CHAR_DOT || res . charCodeAt ( res . length - 2 ) !== CHAR_DOT ) { if ( res . length > 2 ) { var lastSlashIndex = res . lastIndexOf ( '/' ) if ( lastSlashIndex !== res . length - 1 ) { if ( lastSlashIndex === - 1 ) { res = '' lastSegmentLength = 0 } else { res = res . slice ( 0 , lastSlashIndex ) lastSegmentLength = res . length - 1 - res . lastIndexOf ( '/' ) } lastSlash = i dots = 0 continue } } else if ( res . length === 2 || res . length === 1 ) { res = '' lastSegmentLength = 0 lastSlash = i dots = 0 continue } } if ( allowAboveRoot ) { if ( res . length > 0 ) res += '/..' else res = '..' lastSegmentLength = 2 } } else { if ( res . length > 0 ) res += '/' + path . slice ( lastSlash + 1 , i ) else res = path . slice ( lastSlash + 1 , i ) lastSegmentLength = i - lastSlash - 1 } lastSlash = i dots = 0 } else if ( code === CHAR_DOT && dots !== - 1 ) { ++ dots } else { dots = - 1 } } return res }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "path . resolve ( [ from ... ] to ) [CODESPLIT] function resolve ( ) { var resolvedPath = '' var resolvedAbsolute = false var cwd for ( var i = arguments . length - 1 ; i >= - 1 && ! resolvedAbsolute ; i -= 1 ) { var path if ( i >= 0 ) { path = arguments [ i ] } else { if ( cwd === undefined ) { cwd = posix . dirname ( sketchSpecifics . cwd ( ) ) } path = cwd } path = sketchSpecifics . getString ( path , 'path' ) // Skip empty entries if ( path . length === 0 ) { continue } resolvedPath = path + '/' + resolvedPath resolvedAbsolute = path . charCodeAt ( 0 ) === CHAR_FORWARD_SLASH } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeString ( resolvedPath , ! resolvedAbsolute ) if ( resolvedAbsolute ) { if ( resolvedPath . length > 0 ) return '/' + resolvedPath else return '/' } else if ( resolvedPath . length > 0 ) { return resolvedPath } else { return '.' } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return gpt } [CODESPLIT] function readBackupGPT ( primaryGPT ) { var backupGPT = new GPT ( { blockSize : primaryGPT . blockSize } ) var buffer = Buffer . alloc ( 33 * primaryGPT . blockSize ) var offset = ( ( primaryGPT . backupLBA - 32 ) * blockSize ) fs . readSync ( fd , buffer , 0 , buffer . length , offset ) backupGPT . parseBackup ( buffer ) return backupGPT }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PartitionEntry [CODESPLIT] function PartitionEntry ( options ) { if ( ! ( this instanceof PartitionEntry ) ) { return new PartitionEntry ( options ) } options = options != null ? options : { } /** @type {String} Type GUID */ this . type = options . type || GUID . ZERO /** @type {String} GUID */ this . guid = options . guid || GUID . ZERO /** @type {String} Partition label */ this . name = options . name || '' /** @type {Number} First addressable block address */ this . firstLBA = options . firstLBA || 0 /** @type {Number} Last addressable block address */ this . lastLBA = options . lastLBA || 0 // NOTE: Can't use this as uint64 as logical ops will cast to uint32; // Maybe revert to buffer, or use bitfield module? /** @type {Number} Attribute flags */ this . attr = options . attr || 0 }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Limit the execution rate of a function using a leaky bucket algorithm . [CODESPLIT] function stopcock ( fn , options ) { options = Object . assign ( { queueSize : Math . pow ( 2 , 32 ) - 1 , bucketSize : 40 , interval : 1000 , limit : 2 } , options ) ; const bucket = new TokenBucket ( options ) ; const queue = [ ] ; let timer = null ; function shift ( ) { clearTimeout ( timer ) ; while ( queue . length ) { const delay = bucket . consume ( ) ; if ( delay > 0 ) { timer = setTimeout ( shift , delay ) ; break ; } const data = queue . shift ( ) ; data [ 2 ] ( fn . apply ( data [ 0 ] , data [ 1 ] ) ) ; } } function limiter ( ) { const args = arguments ; return new Promise ( ( resolve , reject ) => { if ( queue . length === options . queueSize ) { return reject ( new Error ( 'Queue is full' ) ) ; } queue . push ( [ this , args , resolve ] ) ; shift ( ) ; } ) ; } Object . defineProperty ( limiter , 'size' , { get : ( ) => queue . length } ) ; return limiter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format quantity values either encode to hex or decode to BigNumber should intake null stringNumber number BN [CODESPLIT] function formatQuantity ( value , encode , pad ) { if ( [ 'string' , 'number' , 'object' ] . indexOf ( typeof value ) === - 1 || value === null ) { return value ; } const numberValue = numberToBN ( value ) ; const numPadding = numberValue . lt ( ten ) && pad === true && ! numberValue . isZero ( ) ? '0' : '' ; if ( numberToBN ( value ) . isNeg ( ) ) { throw new Error ( ` ${ numberValue . toString ( 10 ) } ` ) ; } return encode ? ` ${ numPadding } ${ numberValue . toString ( 16 ) } ` : numberValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format quantity or tag if tag bypass return else format quantity should intake null stringNumber number BN string tag [CODESPLIT] function formatQuantityOrTag ( value , encode ) { var output = value ; // eslint-disable-line // if the value is a tag, bypass if ( schema . tags . indexOf ( value ) === - 1 ) { output = formatQuantity ( value , encode ) ; } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FormatData under strict conditions hex prefix [CODESPLIT] function formatData ( value , byteLength ) { var output = value ; // eslint-disable-line var outputByteLength = 0 ; // eslint-disable-line // prefix only under strict conditions, else bypass if ( typeof value === 'string' ) { output = ` ${ padToEven ( stripHexPrefix ( value ) ) } ` ; outputByteLength = getBinarySize ( output ) ; } // format double padded zeros. if ( output === '0x00' ) { output = '0x0' ; } // throw if bytelength is not correct if ( typeof byteLength === 'number' && value !== null && output !== '0x' && output !== '0x0' // support empty values && ( ! / ^[0-9A-Fa-f]+$ / . test ( stripHexPrefix ( output ) ) || outputByteLength !== 2 + byteLength * 2 ) ) { throw new Error ( ` ${ output } ${ 2 + byteLength * 2 } ${ outputByteLength } ` ) ; } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format object even with random RPC caviets [CODESPLIT] function formatObject ( formatter , value , encode ) { var output = Object . assign ( { } , value ) ; // eslint-disable-line var formatObject = null ; // eslint-disable-line // if the object is a string flag, then retreive the object if ( typeof formatter === 'string' ) { if ( formatter === 'Boolean|EthSyncing' ) { formatObject = Object . assign ( { } , schema . objects . EthSyncing ) ; } else if ( formatter === 'DATA|Transaction' ) { formatObject = Object . assign ( { } , schema . objects . Transaction ) ; } else { formatObject = Object . assign ( { } , schema . objects [ formatter ] ) ; } } // check if all required data keys are fulfilled if ( ! arrayContainsArray ( Object . keys ( value ) , formatObject . __required ) ) { // eslint-disable-line throw new Error ( ` ${ JSON . stringify ( value ) } ${ formatObject . __required . join ( ', ' ) } ` ) ; // eslint-disable-line } // assume formatObject is an object, go through keys and format each Object . keys ( formatObject ) . forEach ( ( valueKey ) => { if ( valueKey !== '__required' && typeof value [ valueKey ] !== 'undefined' ) { output [ valueKey ] = format ( formatObject [ valueKey ] , value [ valueKey ] , encode ) ; } } ) ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format array [CODESPLIT] function formatArray ( formatter , value , encode , lengthRequirement ) { var output = value . slice ( ) ; // eslint-disable-line var formatObject = formatter ; // eslint-disable-line // if the formatter is an array or data, then make format object an array data if ( formatter === 'Array|DATA' ) { formatObject = [ 'D' ] ; } // if formatter is a FilterChange and acts like a BlockFilter // or PendingTx change format object to tx hash array if ( formatter === 'FilterChange' && typeof value [ 0 ] === 'string' ) { formatObject = [ 'D32' ] ; } // enforce minimum value length requirements if ( encode === true && typeof lengthRequirement === 'number' && value . length < lengthRequirement ) { throw new Error ( ` ${ JSON . stringify ( value ) } ${ lengthRequirement } ${ value . length } ` ) ; // eslint-disable-line } // make new array, avoid mutation formatObject = formatObject . slice ( ) ; // assume formatObject is an object, go through keys and format each value . forEach ( ( valueKey , valueIndex ) => { // use key zero as formatter for all values, unless otherwise specified var formatObjectKey = 0 ; // eslint-disable-line // if format array is exact, check each argument against formatter argument if ( formatObject . length > 1 ) { formatObjectKey = valueIndex ; } output [ valueIndex ] = format ( formatObject [ formatObjectKey ] , valueKey , encode ) ; } ) ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format various kinds of data to RPC spec or into digestable JS objects [CODESPLIT] function format ( formatter , value , encode , lengthRequirement ) { var output = value ; // eslint-disable-line // if formatter is quantity or quantity or tag if ( formatter === 'Q' ) { output = formatQuantity ( value , encode ) ; } else if ( formatter === 'QP' ) { output = formatQuantity ( value , encode , true ) ; } else if ( formatter === 'Q|T' ) { output = formatQuantityOrTag ( value , encode ) ; } else if ( formatter === 'D' ) { output = formatData ( value ) ; // dont format data flagged objects like compiler output } else if ( formatter === 'D20' ) { output = formatData ( value , 20 ) ; // dont format data flagged objects like compiler output } else if ( formatter === 'D32' ) { output = formatData ( value , 32 ) ; // dont format data flagged objects like compiler output } else { // if value is an object or array if ( typeof value === 'object' && value !== null && Array . isArray ( value ) === false ) { output = formatObject ( formatter , value , encode ) ; } else if ( Array . isArray ( value ) ) { output = formatArray ( formatter , value , encode , lengthRequirement ) ; } } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format RPC inputs generally to the node or TestRPC [CODESPLIT] function formatInputs ( method , inputs ) { return format ( schema . methods [ method ] [ 0 ] , inputs , true , schema . methods [ method ] [ 2 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Register methods for this model [CODESPLIT] function ( model , schema ) { function apply ( method , schema ) { Object . defineProperty ( model . prototype , method , { get : function ( ) { var h = { } ; for ( var k in schema . methods [ method ] ) { h [ k ] = schema . methods [ method ] [ k ] . bind ( this ) ; } return h ; } , configurable : true , } ) ; } for ( var method in schema . methods ) { if ( typeof schema . methods [ method ] === 'function' ) { model . prototype [ method ] = schema . methods [ method ] ; } else { apply ( method , schema ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Register statics for this model [CODESPLIT] function ( model , schema ) { for ( var i in schema . statics ) { model [ i ] = schema . statics [ i ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a merged set of yaml files [CODESPLIT] function ( files ) { if ( ! _ . isArray ( files ) ) { throw new Error ( 'Arguments to config-helper.mergeConfig should be an array' ) ; } var appConfig = { } ; files . forEach ( function ( filePath ) { if ( gruntFile . exists ( filePath ) ) { var fileConfig = gruntFile . readYAML ( filePath ) ; // Use lodash to do a 'deep merge' which only overwrites the properties // specified in previous config files, without wiping out their child properties. _ . merge ( appConfig , fileConfig ) ; } } ) ; return appConfig ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses [CODESPLIT] function parseBinding ( node ) { consume ( ) ; // '@' var binding = [ ] , first = once ( true ) ; while ( hasNext ( ) ) { if ( validChar ( peek ( ) , first ( ) ) ) { binding [ binding . length ] = next ( ) ; } else { break ; } } if ( binding . length > 0 ) { node . binding = binding . join ( '' ) ; } else { throw \"No binding name given at \" + index + \" for \" + node . type ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the ( ... ) component of an array pattern . [CODESPLIT] function parseArrayList ( node ) { consume ( ) ; // '(' // a() matches the empty list. if ( peek ( ) === ')' ) { node . type = '()' ; return ; } while ( true ) { // The whole array may be matched with 'a(|)' or (preferably) 'a'. if ( peek ( ) === '|' ) { break ; } /**\n       * Use clear() to allow whitespace on certain locations:\n       * (n,n@x), (n, n@x), ( n , n@x ) are all accepted.\n       * (n, n @x) is not accepted: bindings do not allow\n       * any whitespace.\n       */ clear ( ) ; stage1 ( node . nodes ) ; clear ( ) ; if ( peek ( ) !== ',' ) { break ; } consume ( ) ; // ',' } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a single property . Valid property names can contain upper - and lowercase letters _ $ and numbers . [CODESPLIT] function parseProperty ( node , proto ) { consume ( ) ; // '.' var name = [ ] , property , first = once ( true ) ; while ( hasNext ( ) && validChar ( peek ( ) , first ( ) ) ) { name [ name . length ] = next ( ) ; } if ( name . length > 0 ) { property = newNode ( proto ? ':' : '.' , node . nodes ) ; property . name = name . join ( '' ) ; /**\n       * Properties may have type specifiers. This is the way to go\n       * to match nested objects.\n       *\n       * e.g. 'o(.coord:o(.x, .y))' matches objects like\n       *  '{coord: {x: 5, y: 7} }'\n       */ if ( hasNext ( ) && peek ( ) === ':' ) { consume ( ) ; // '(' stage1 ( property . nodes ) ; } // The property value might be bound to a name if ( hasNext ( ) && peek ( ) === '@' ) { parseBinding ( property ) ; } } else { throw \"No property name given at \" + index + \" for \" + node . type ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the property list of an object pattern . [CODESPLIT] function parseProperties ( node ) { consume ( ) ; // '(' while ( true ) { clear ( ) ; /**\n       * Properties always have to start with '.' or ':'\n       * o(.x, :y) matches an object with at least an owned property\n       * 'x' and a owned or inherited property 'y'. \n       */ if ( peek ( ) === '.' ) { parseProperty ( node , false ) ; // own property } else if ( peek ( ) === ':' ) { parseProperty ( node , true ) ; // prototype property } else { unexpectedTokenException ( '. or :' ) ; } clear ( ) ; if ( peek ( ) !== ',' ) { break ; } consume ( ) ; // ',' } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a list of literals . The type of literal is determined by the second parameter : a function to parse a certain type ( string numeric boolean date ) of literals [CODESPLIT] function parseLiteralList ( AST , parseFunction ) { consume ( ) ; // '(' while ( true ) { clear ( ) ; parseFunction ( AST ) ; clear ( ) ; if ( peek ( ) !== ',' ) { break ; } consume ( ) ; // ',' } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "String literals might start with or [CODESPLIT] function extractStringLiteral ( ) { var literal = [ ] , enclosing = next ( ) ; if ( ! ( enclosing === '\"' || enclosing === \"'\" ) ) { throw \"Unexpected token at index \" + index + \" expected 'string' but found \" + enclosing ; } while ( hasNext ( ) && peek ( ) !== enclosing ) { literal [ literal . length ] = next ( ) ; } consume ( ) ; // ' or \" return literal . join ( '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A string literal list may contain strings or regular expressions . [CODESPLIT] function parseStringLiteral ( AST ) { if ( peek ( ) === '/' ) { newNode ( extractRegex ( ) , newNode ( 'r=' , AST ) . nodes ) ; } else { newNode ( extractStringLiteral ( ) , newNode ( '=' , AST ) . nodes ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse numeric literals like 1 1 . 05 . 05 8e5 ... [CODESPLIT] function parseNumericLiteral ( AST ) { var literal = [ ] , value ; while ( hasNext ( ) && validNum ( peek ( ) ) ) { literal [ literal . length ] = next ( ) ; } value = parseFloat ( literal . join ( '' ) ) ; /**\n     * Thanks to CMS's answer on StackOverflow:\n     * http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric\n     */ if ( ! isNaN ( value ) && isFinite ( value ) ) { newNode ( value , newNode ( '=' , AST ) . nodes ) ; } else { unexpectedTokenException ( 'numeric' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches any of ( a o n s b f d r _ ) [CODESPLIT] function parseGeneric ( AST , type ) { var node = newNode ( next ( ) , AST ) ; // Parse literal lists, e.g. s(\"a\", \"b\", ...) if ( peek ( ) === '(' ) { switch ( type ) { case \"s\" : parseLiteralList ( node . nodes , parseStringLiteral ) ; break ; case \"n\" : parseLiteralList ( node . nodes , parseNumericLiteral ) ; break ; case \"b\" : parseLiteralList ( node . nodes , parseBooleanLiteral ) ; break ; case \"d\" : parseLiteralList ( node . nodes , parseDateLiteral ) ; break ; } node . type = '||' ; consume ( ) ; // ')' } if ( peek ( ) === '@' ) { parseBinding ( node ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parser entry point [CODESPLIT] function stage1 ( AST ) { if ( hasNext ( ) ) { switch ( peek ( ) ) { case 'a' : parseArray ( AST ) ; break ; case 'o' : parseObject ( AST ) ; break ; default : if ( / [nsSbfdr_] / . test ( peek ( ) ) ) { parseGeneric ( AST , peek ( ) ) ; } else { unexpectedTokenException ( 'one of (a,o,n,s,S,b,f,d,r,_)' ) ; } } } return AST ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "curry takes a function and a partial list of arguments and returns a function that can be executed with the rest of the arguments . [CODESPLIT] function curry ( fun , args ) { return function ( x ) { return fun . apply ( bindingContext , args . concat ( [ x ] ) ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "bind acts like a predicate but it also binds a variable to a name and puts it in the binding context . The parameters are : n : the binding name p : the actual predicate associated with this binding v : the value that this function is executed on . [CODESPLIT] function bind ( n , p , v ) { var m = p ( v ) ; if ( m . result ) { // Throw an exception if the same name is bound multiple times.  if ( bindingContext . hasOwnProperty ( n ) ) { throw \"Name '\" + n + \"' is already used in another binding.\" ; } bindingContext [ n ] = m . obj ? m . obj [ m . param ] : m . param ; } /**\n     * When the rest of an array is matched, the binding value has to\n     * be changed after executing bind. Thats because at bind time the\n     * rest of the array is not known. Therefore the name of the last\n     * binding is stored and can be retrieved in the continuing function.\n     */ m . this_binding = n ; return m ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * matches exactly the same date object [CODESPLIT] function equalsDate ( x , o ) { return { result : x . getTime ( ) === o . getTime ( ) , param : x } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Match a property that is owned by the object [CODESPLIT] function hasProperty ( m , x , o ) { return testProperty ( m , x , o , o . hasOwnProperty ( x ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Match a property somewhere in the prototype chain [CODESPLIT] function hasPrototypeProperty ( m , x , o ) { return testProperty ( m , x , o , x in o ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "or takes a list of predicate functions ( m ) and executes them on it s second parameter ( o ) . If one of the predicates return true then or returns true . Otherwise false . [CODESPLIT] function or ( m , o ) { var index , result = { result : false , param : o } ; for ( index = 0 ; index < m . length ; index ++ ) { if ( m [ index ] ( o ) . result ) { result . result = true ; break ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "m is an array of predicates a is the array to match [CODESPLIT] function matchArray ( m , a ) { var from = 0 , rest = false , restBindingResult , index , matcher , item , matchResult , restOfArray = [ ] , i , result = { result : false , param : a } ; // If this isn't an array then it can't match if ( ! is ( a , '[object Array]' ) ) { return result ; } // If there are more matchers than array elements it also can't match unless the // last matcher is a rest matcher if ( m . length > a . length && ! m [ m . length - 1 ] . name ) { return result ; } /**\n     * If there are no predicates at all, this matches because it is \n     * already ensured that argument a is an array.\n     */ if ( m . length === 0 ) { result . result = true ; return result ; } for ( index = 0 ; index < a . length ; index ++ ) { matcher = m [ index ] ; item = a [ index ] ; if ( ! matcher ) { return result ; } matchResult = matcher ( item ) ; if ( ! matchResult . result ) { return result ; } /**\n       * If the rest of an array is matched, the predicate will\n       * return an object that has a'rest' parameter. We can't\n       * recognize the rest predicate by it's function name, because\n       * it might be hidden behind a 'bind' call.\n       */ if ( matchResult . rest ) { restBindingResult = matchResult ; from = index ; rest = true ; break ; } } if ( rest && restBindingResult . this_binding ) { for ( i = from ; i < a . length ; i ++ ) { restOfArray [ restOfArray . length ] = a [ i ] ; } bindingContext [ restBindingResult . this_binding ] = restOfArray ; } result . result = true ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile a single level of the AST [CODESPLIT] function compileNode ( ast ) { var result = [ ] , index , node , matcher ; for ( index = 0 ; index < ast . length ; index ++ ) { node = ast [ index ] ; switch ( node . type ) { case 'a' : matcher = curry ( matchArray , [ compileNode ( node . nodes ) ] ) ; break ; case 'o' : matcher = curry ( matchObject , [ compileNode ( node . nodes ) ] ) ; break ; case '.' : matcher = curry ( hasProperty , [ compileNode ( node . nodes ) , node . name ] ) ; break ; case ':' : matcher = curry ( hasPrototypeProperty , [ compileNode ( node . nodes ) , node . name ] ) ; break ; case '=' : matcher = curry ( equals , [ node . nodes [ 0 ] . type ] ) ; break ; case 'd=' : matcher = curry ( equalsDate , [ node . nodes [ 0 ] . type ] ) ; break ; case 'r=' : matcher = curry ( matchesRegex , [ node . nodes [ 0 ] . type ] ) ; break ; case '||' : matcher = curry ( or , [ compileNode ( node . nodes ) ] ) ; break ; case 'n' : matcher = curry ( matchType , [ 'number' ] ) ; break ; case 's' : matcher = curry ( matchType , [ 'string' ] ) ; break ; case 'S' : matcher = matchNonBlankString ; break ; case 'b' : matcher = curry ( matchType , [ 'boolean' ] ) ; break ; case 'f' : matcher = curry ( matchType , [ 'function' ] ) ; break ; case '_' : matcher = any ; break ; case '|' : matcher = rest ; break ; case '()' : matcher = matchEmptyArray ; break ; case 'd' : matcher = curry ( matchInstanceOf , [ '[object Date]' ] ) ; break ; case 'r' : matcher = curry ( matchInstanceOf , [ '[object RegExp]' ] ) ; break ; default : throw \"Unknown AST entity: \" + node . type ; } // Bind requested. Wrap the matcher function with a call to bind. if ( node . binding ) { matcher = curry ( bind , [ node . binding , matcher ] ) ; } result [ result . length ] = matcher ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ o 42 ] = > { o : 42 } [CODESPLIT] function arrayToObject ( array ) { var obj = { } , i ; if ( array . length % 2 !== 0 ) { throw \"Missing handler for pattern\" ; } for ( i = 0 ; i < array . length ; i += 2 ) { obj [ array [ i ] ] = array [ i + 1 ] ; } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns name of given matched token [CODESPLIT] function getName ( tag ) { return tag . name ? tag . name . value . toLowerCase ( ) : ` ${ tag . type } ` ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consumes attribute value from given location [CODESPLIT] function eatAttributeValue ( stream ) { const start = stream . pos ; if ( eatQuoted ( stream ) ) { // Should return token that points to unquoted value. // Use stream readers’ public API to traverse instead of direct // manipulation const current = stream . pos ; let valueStart , valueEnd ; stream . pos = start ; stream . next ( ) ; valueStart = stream . start = stream . pos ; stream . pos = current ; stream . backUp ( 1 ) ; valueEnd = stream . pos ; const result = token ( stream , valueStart , valueEnd ) ; stream . pos = current ; return result ; } return eatPaired ( stream ) || eatUnquoted ( stream ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if given character code is valid unquoted value [CODESPLIT] function isUnquoted ( code ) { return ! isNaN ( code ) && ! isQuote ( code ) && ! isSpace ( code ) && ! isTerminator ( code ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sarcasm mark ( ! ) / * Sentiment Constructor To be instantiated for a certain language [CODESPLIT] function Sentiment ( args ) { this . path = args . path || \"\" ; this . language = args . language ; this . confidence = args . confidence || null ; this . synset = args . synset ; this . synsets = { } ; this . labeler = { } ; this . negations = def ( args . negations , [ \"no\" , \"not\" , \"n't\" , \"never\" ] ) ; this . modifiers = def ( args . modifiers , [ \"RB\" ] ) ; this . modifier = def ( args . modifier , function ( w ) { return _str . endsWith ( w , \"ly\" ) ; } ) ; this . tokenizer = def ( args . tokenizer , find_tokens ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "var syn = self . synsets [ id ] ; if ( _ . isUndefined ( syn )) { syn = def ( self . synsets [ id . replace ( / - 0 + / - ) ] [ 0 . 0 0 . 0 ] ) ; } return syn . slice ( 0 2 ) ; } } ; [CODESPLIT] function avgAssessment ( assessments , weighted ) { var w ; var s = 0 ; var n = 0 ; assessments . forEach ( function ( ws ) { w = weighted ( ws [ 0 ] ) ; s += w * ws [ 1 ] ; n += w ; } ) ; if ( n === 0 ) { return 0 ; } else { return s / n ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Auxiliary Functions Average of number vector ( 0 if empty ) [CODESPLIT] function avg ( vct ) { if ( vct . length === 0 ) { return 0 ; } return ( vct . reduce ( function ( a , c ) { return a + c ; } , 0 ) / vct . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If given key is set in the object it returns the associated value otherwise it sets the value to val and returns it . [CODESPLIT] function setDefault ( obj , key , val ) { if ( _ . isUndefined ( obj [ key ] ) ) { obj [ key ] = val ; return val ; } return obj [ key ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read and Parse XML file from given path pass result to finish Any error that occurs is simpy thrown . [CODESPLIT] function getXml ( path , finish ) { fs . readFile ( path , function ( err , data ) { if ( err ) throw err ; xmlParser . parseString ( data , function ( err , result ) { if ( err ) throw err ; finish ( result ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a pair of key / value to an array if the value is true only the key is kept Example : toParameter ( lineBreak 2 ) // = > [ -- line - break 2 ] toParameter ( preserveComments true ) // = > [ -- preserve - comments ] [CODESPLIT] function toParameter ( val , key ) { var str = '--' + key . replace ( / ([A-Z]) / g , function ( a ) { return '-' + a . toLowerCase ( ) ; } ) ; return ( val === true ) ? [ str ] : [ str , val ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "hookIt ( authorize proto . authorize ) ; [CODESPLIT] function injectDependencies ( func , args , callback ) { var declaredArguments = toolbox . parseDeclaredArguments ( func ) ; declaredArguments = declaredArguments . replace ( / \\s+ / g , \"\" ) . split ( \",\" ) ; logger . trace ( \"injectDependencies() declaredArguments: \" , declaredArguments , \"provided args:\" , args ) ; var useCallback = false ; var len = args . length > declaredArguments . length ? args . length : declaredArguments . length ; for ( var i = 0 ; i < len ; i ++ ) { // this is problematic: functions may be wrapped and lost the arguments data /** if client did not provide enough number of arguments, we fill it with null*/ if ( typeof ( args [ i ] ) == 'undefined' ) args [ i ] = undefined ; else if ( args [ i ] === \"$callback\" ) { useCallback = true ; args [ i ] = callback ; } switch ( declaredArguments [ i ] ) { case '$callback' : logger . debug ( \"Injecting callback handler\" ) ; args [ i ] = callback ; useCallback = true ; break ; case '$context' : logger . debug ( \"Injecting angoose context\" ) ; args [ i ] = angoose ( ) . getContext ( ) ; break ; default : break ; } } return useCallback ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "append angoose - ui sources [CODESPLIT] function appendUISource ( client ) { angoose . getLogger ( 'angoose' ) . debug ( \"Appending angoose-ui sources\" ) ; //    client.source += \" \\n;console.log('####################----------- angoose-ui -----------##############');\\n\"; var output = \"\" ; output += readFile ( path . resolve ( __dirname , 'angular-modules.js' ) ) ; output += concatFilesInDirectory ( [ 'services' , 'controllers' , 'directives' , 'filters' ] ) ; //'directives', output += concatTemplates ( ) ; client . source += \"\\n\\n\" + output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show an error [CODESPLIT] function error ( msg , addHint ) { console . log ( '\\x1b[31m' ) ; console . log ( 'The compiler has stopped on an error' ) console . log ( ` \\x1b ${ msg } \\x1b ` ) ; if ( addHint ) console . log ( ` \\n ` ) ; process . exit ( 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compile the model based on the server side schema [CODESPLIT] function compile ( modelName , schema , dependencies ) { logger . trace ( \"Compiling schema \" , modelName ) var model = function AngooseModule ( data ) { //@todo proper clone for ( var i in data ) { this [ i ] = data [ i ] ; } } ; model . toString = function ( ) { return \"PROXY: function \" + modelName + \"()\" ; } // static methods for ( var name in schema . statics ) { model [ name ] = createProxy ( model , name , schema . statics [ name ] , 'static' ) ; } for ( var name in schema . methods ) { model . prototype [ name ] = createProxy ( model , name , schema . methods [ name ] , 'instance' ) ; } //model.angoose$ = staticInvoker; model . dependencies$ = dependencies ; model . schema = schema ; //model.prototype.angoose$ = instanceInvoker; //model.prototype.classname$ = modelName; //model.prototype.schema$ = schema; model . prototype . get = getter ; model . prototype . set = setter ; model . modelName = modelName ; // this is to be compatible with backend mongoose\r model . name = modelName ; // merge data into this instance model . prototype . mergeData = function ( source ) { if ( typeof source != \"object\" ) throw \"Invalid source object, must be an model instance\" ; //@todo: proper implementation for ( var i in source ) { this [ i ] = source [ i ] ; } } AngooseClient . models = AngooseClient . models || { } ; AngooseClient . models [ modelName ] = model ; return model ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loop through all the top level props [CODESPLIT] function addProps ( props , options ) { if ( ! props ) return '## No props' const keys = Object . keys ( props ) . filter ( key => filterProps ( key , props [ key ] , options ) , ) const filteredProps = keys . reduce ( ( last , key ) => ( { ... last , [ key ] : props [ key ] } ) , { } , ) let output = '\\n## Props\\n' let isFlow = false const items = [ TABLE_HEADERS , ... keys . map ( key => { const prop = filteredProps [ key ] if ( isFlowType ( prop ) ) isFlow = true const row = [ isFlowType ( prop ) ? key : getKey ( key , getType ( prop ) ) , getTypeName ( getType ( prop ) ) , getDefaultValue ( prop ) , prop . required , prop . description , ] return row . map ( rowValue => { if ( typeof rowValue === 'string' ) { return rowValue . split ( '\\n' ) . join ( '<br>' ) } return rowValue } ) } ) , ] output += ` ${ table ( items ) } \\n ` // Add subtypes if ( ! isFlow ) { const subTypes = describeSubTypes ( filteredProps ) if ( subTypes . length ) { output += '\\n## Complex Props\\n' output += subTypes } } return output }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Debounces a function . Returns a function that calls the original fn function only if no invocations have been made within the last quietMillis milliseconds . [CODESPLIT] function debounce ( quietMillis , fn , ctx ) { ctx = ctx || undefined ; var timeout ; return function ( ) { var args = arguments ; clearTimeout ( timeout ) ; timeout = setTimeout ( function ( ) { fn . apply ( ctx , args ) ; } , quietMillis ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Workaround for Q module with CLS [CODESPLIT] function matroshka ( fn ) { var babushka = fn ; Object . keys ( process . namespaces ) . forEach ( function ( name ) { babushka = process . namespaces [ name ] . bind ( babushka ) ; } ) ; return babushka ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "end directiveFunc get a list of fields with a specific tag [CODESPLIT] function findTagged ( modelClass , tag ) { if ( ! modelClass || ! modelClass . schema ) return [ ] ; var cols = [ ] ; Object . keys ( modelClass . schema . paths ) . forEach ( function ( path ) { var data = modelClass . schema . paths [ path ] ; if ( data . options . tags && data . options . tags . indexOf ( tag ) >= 0 ) cols . push ( data ) ; } ) ; return cols ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "scope wrapper [CODESPLIT] function enterscope ( scope , name , arg1 ) { angoose . logger . trace ( \"Entering scope \" , name , scope . $id , arg1 ) window [ 'scope' + scope . $id ] = scope ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "end invoke [CODESPLIT] function postPack ( next , invocation ) { //console.log(\"In mongoose post pack\", invocation) if ( ! invocation . redacted ) return next ( ) ; var type = getValueType ( invocation . redacted ) ; if ( type ) invocation . packed . datatype = type ; next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Emit an error [CODESPLIT] function error ( msg ) { if ( exports . error ) exports . error ( msg ) ; else console . log ( 'Error: ' + msg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call a command [CODESPLIT] function call ( name , isLong ) { var obj = isLong ? long [ name ] : short [ name ] ; if ( ! obj ) return error ( ` ${ name } ` ) ; if ( n + obj . length > count ) return error ( ` ${ name } ` ) ; var arr = process . argv . slice ( n , n + obj . length ) ; n += obj . length ; obj . callback ( arr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "** extend ** This static method is used to create Angoose model or service classes . All classes created using this method is a subclass of Remotable [CODESPLIT] function extend ( target , options ) { options = options || { } ; var parentClass = this ; logger . trace ( \"Extending from \" , parentClass . _angoosemeta . name , options ) ; var rv = null ; if ( typeof ( target ) == 'function' ) { rv = target ; mixinInstance ( parentClass , rv , options ) ; /**@todo: temp hack */ bindMongooseMethods ( rv ) ; } else { /** schema object */ rv = parentClass . $extend ( target ) ; } /** mixin Angoose class level functions */ rv = mixinStatic ( parentClass , rv , options ) ; if ( rv . _angoosemeta . name ) { /**  register it with Angoose */ //require(\"./angoose\").registerClass(rv._angoosemeta.name, rv); } return rv ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "synchronous hooks [CODESPLIT] function addHook ( loc , method , func ) { var tmp = hooks [ loc ] [ method ] ; logger . debug ( \"ADdding bundle hook to\" , loc , method , tmp ) ; if ( ! tmp ) return false ; tmp . push ( func ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the input element in the template . It will be one of input select or textarea . We need to ensure it is wrapped in jqLite \\ jQuery [CODESPLIT] function findInputElement ( templateElement ) { return angular . element ( templateElement . find ( 'input' ) [ 0 ] || templateElement . find ( 'select' ) [ 0 ] || templateElement . find ( 'textarea' ) [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search through the originalDirective s element for elements that contain information about how to map validation keys to messages [CODESPLIT] function getValidationMessageMap ( originalElement ) { // Find all the <validator> child elements and extract their (key, message) info var validationMessages = { } ; angular . forEach ( originalElement . find ( 'validator' ) , function ( element ) { // Wrap the element in jqLite/jQuery element = angular . element ( element ) ; // Store the message info to be provided to the scope later // The content of the validation element may include interpolation {{}} // so we will actually store a function created by the $interpolate service // To get the interpolated message we will call this function with the scope. e.g. //   var messageString = getMessage(scope); validationMessages [ element . attr ( 'key' ) ] = $interpolate ( element . text ( ) ) ; } ) ; return validationMessages ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- list of sub schemas : deform - sublist - single subschema object : deform - subschema [CODESPLIT] function mapDirective ( path , pathSchema , modelSchema , itemIndex ) { if ( itemIndex !== undefined ) return null ; // we're in a array if ( pathSchema && pathSchema . options && Array . isArray ( pathSchema . options . type ) ) { if ( pathSchema . schema ) return \"deform-sublist\" if ( pathSchema . caster && ( ! pathSchema . caster . options || ! pathSchema . caster . options . ref ) ) { // !pathSchema.options.ref filters out CustomRef, ugly! /** array of simple types */ //console.log(\"Simple array type!!!\",pathSchema, pathSchema.options.ref, pathSchema.options.type); return \"ang-array\" } } else if ( pathSchema . schema ) return \"deform-subschema\" return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "** mapTemplate ** Default mapping for Mongoose schema type - > form field - ObjectID : selector - Boolean : Checkbox - String : input - Number : input - Date : ? - Array of simple types : selector multi - Array of ref objects : selector multi - String / Number with enum values : Select - Mixed : ?? [CODESPLIT] function mapTemplate ( path , pathSchema , modelSchema ) { if ( pathSchema . options . template ) return pathSchema . options . template ; if ( pathSchema . options . multiline ) return \"textarea\" var template = 'input' ; var opts = pathSchema . options || { } ; //@todo: refactor them into subclasses switch ( pathSchema . instance || ( pathSchema . options && pathSchema . options . type ) ) { case 'ObjetcID' : if ( opts . ref ) template = 'selector' ; break ; case 'Boolean' : template = 'checkbox' ; break ; case 'Date' : case 'String' : case 'Number' : default : break ; } if ( getRef ( pathSchema ) ) template = \"selector\" ; if ( Array . isArray ( opts [ 'enum' ] ) && opts [ 'enum' ] . length > 0 ) { template = \"select\" ; } if ( Array . isArray ( opts . type ) ) { if ( pathSchema . caster ) { /** array of simple types */ // console.log(\"Simple types\", pathSchema) } } angoose . logger . trace ( \"Path \" , path , \" Type \" , pathSchema , \" template: \" , template ) return template ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "** init ( app options ) ** Initialize Angoose . This function should be called in the express app * [CODESPLIT] function init ( app , conf , force ) { if ( this . initialized && ! force ) return ; //beans = {}; /** configurations*/ initialConfig ( conf ) ; logger . info ( \"Angoose Initialization Start\" ) ; logger . trace ( \"Init options:\" , conf ) ; /** connect to Mongo if necessary */ connectMongo ( options ) ; /** register initial hooks */ //registerHooks();         /** pre-load models/services from directories */ harvestModules ( options ) ; /** plugin extensions */ hookupExtensions ( ) ; /** build client side schemas */ generateClient ( ) ; /** configure the routes for handling RMI and client loading*/ /**@todo: middleware*/ configureRoutes ( app , options ) ; logger . info ( \"Angoose Initialization Complete\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "** module ( name function_or_object ) ** Retrieve an Angoose module or register one If only one argument name is provided returns the registered module with that name . This form is same as angoose . getClass () If two arguments are provided register the function / object as Angular module under that name . [CODESPLIT] function lookupOrRegister ( name , target ) { if ( arguments . length == 0 ) return null ; if ( arguments . length == 1 ) return getClass ( name ) ; if ( arguments . length == 2 ) return registerClass ( name , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "register module with angoose so it knows to publish it [CODESPLIT] function registerClass ( nameOrOpts , claz ) { var opts = typeof ( nameOrOpts ) == 'object' ? nameOrOpts : { name : nameOrOpts } ; var className = opts . name ; if ( ! className ) throw \"Missing module name: \" + className if ( beans [ className ] ) logger . warn ( \"Overriding existing bean: \" , className ) ; if ( claz . _angoosemeta && ( claz . _angoosemeta . baseClass == 'Service' || claz . _angoosemeta . baseClass == 'Model' ) ) { // already mixed } else { if ( typeof ( claz ) === 'function' && claz . schema && claz . modelName ) opts . baseClass = 'Model' ; else if ( claz instanceof getMongoose ( ) . Schema ) { opts . baseClass = 'Model' ; claz = getMongoose ( ) . model ( className , claz ) ; } else opts . baseClass = 'Service' ; angoose . Remotable . mixin ( opts , claz ) ; } _ . extend ( claz . _angoosemeta , nameOrOpts ) ; beans [ className ] = claz ; //if(!nameOrOpts.isExtension) logger . debug ( \"Registered module\" , claz . _angoosemeta . baseClass , className ) ; return claz ; // if(claz._angoosemeta && (claz._angoosemeta.baseClass == 'Service' || claz._angoosemeta.baseClass == 'Model') ){ //          // } // else{ // throw \"Invalid class: must be a Model or Service class: \" + claz; // } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "** getContext () ** Returns the current execution context . This methods returns a Context object which allows you to get a reference to the current request object and / or login user s Principal object . If the callee isn t inside Angoose execution context an error will be thrown . See [ Context ] ( Context . html ) for more . [CODESPLIT] function getContext ( ) { if ( ! domain . active || ! domain . active . context ) { if ( this . mockContext ) return this . mockContext logger . error ( \"getContext called but no active domain\" , domain . active ) ; logger . error ( \"Caller is \" , arguments . callee && arguments . callee . caller && arguments . callee . caller . name , arguments . callee && arguments . callee . caller ) ; throw \"Context not available. This may happen if the code was not originated by Angoose\" ; } return domain . active . context ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sample model [CODESPLIT] function scanDir ( dirname ) { if ( ! dirname || dirname . indexOf ( \"node_modules\" ) >= 0 ) return ; logger . debug ( \"Scanning directory for modules: \" , dirname ) ; if ( fs . existsSync ( path . resolve ( dirname , 'index.js' ) ) ) { files . push ( path . resolve ( dirname , 'index.js' ) ) ; return ; } fs . readdirSync ( dirname ) . forEach ( function ( file ) { var fullpath = path . resolve ( dirname , file ) ; if ( ! fs . statSync ( fullpath ) . isFile ( ) ) scanDir ( fullpath ) ; else if ( file . match ( / .+\\.js / g ) !== null ) { files . push ( fullpath ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "** geneateClient () ** Generates the client file to be served as the contents of resource / angoose / angoose - client . js [CODESPLIT] function generateClient ( ) { logger . debug ( \"Generating angoose client file: \" ) ; var bundle = new Bundle ( ) ; var client = { } ; bundle . generateClient ( client ) ; var filename = angoose . config ( ) [ 'client-file' ] ; writeToFile ( filename , client . source ) //compressFile(filename, client.source); logger . info ( \"Generated  angoose client file: \" , filename ) ; return client . source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set or get configurations . [CODESPLIT] function config ( path , val ) { if ( ! path ) return options ; /**@todo: probably a deep copy */ if ( ! angoose . initialized && typeof ( path ) == 'string' ) throw \"Cannot call config(\" + path + \") before angoose is intialized\" ; //if(angoose.initialized && typeof(conf) == 'object') throw \"Cannot config Angoose after startup\"; if ( typeof ( path ) === 'string' ) { if ( val === undefined ) return toolbox . getter ( options , path ) ; toolbox . setter ( options , path , val ) ; } if ( typeof ( path ) === 'object' ) { // deep merge options = toolbox . merge ( options , path ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a connection to the given url . [CODESPLIT] function connect ( url , next ) { log ( 'connecting to %s' , url ) ; mongo . Db . connect ( url , { db : { w : 1 } } , next ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts up a shell with the given context . [CODESPLIT] function startShell ( db , program , files ) { var repl = global . repl = term ( db ) ; createContext ( db , repl , function ( ) { var code = program . eval ; if ( code ) { executeJS ( code ) ; if ( ! program . shell ) { repl . emit ( 'exit' ) ; return ; } } if ( files . length ) { executeFiles ( files ) ; printCloseMsg ( ) ; } repl . prompt = prompt ; repl . displayPrompt ( ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the given files in the context shared with the shell when started . [CODESPLIT] function executeFiles ( files ) { var dir = process . cwd ( ) ; files . forEach ( function ( file ) { require ( dir + '/' + file ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes javascript passed by -- eval [CODESPLIT] function executeJS ( script ) { if ( ! script ) return ; try { var ret = vm . runInThisContext ( script , '[eval]' ) ; if ( 'undefined' != typeof ret ) { console . log ( ret ) ; } } catch ( err ) { if ( ! ( err instanceof Error ) ) { err = new Error ( err ) ; } console . log ( err . stack . split ( '\\n' ) [ 0 ] ) ; process . exit ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * :: const callAssign = { call ( thisFn : any arg : string ) { [CODESPLIT] function ErrorFunction ( message : string ) { const Err = /*::Object.assign({}, callAssign, */ Error /*::)*/ Err . call ( this , message ) if ( noFallback ) { Error . captureStackTrace ( this , ErrorFunction ) } else { this . stack = ( new Error ( ) ) . stack } this . name = this . constructor . name this . message = message }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We create DB constructors dynamically to avoid assigning the db or collections directly to the database instance thereby avoiding them displaying in autocomplete mixed together with the collection names . [CODESPLIT] function createConstructor ( db ) { var collections = [ ] ; function DB ( ) { this . cols ( false , noop ) ; } /**\n   * Logs help text for all db methods\n   */ ; ( DB . prototype . help = function ( ) { var proto = this . constructor . prototype ; var len = 0 ; var msgs = [ ] ; Object . keys ( proto ) . forEach ( function ( method ) { if ( proto [ method ] . help ) { var msg = proto [ method ] . help ( true ) ; len = Math . max ( len , method . length ) ; msgs . push ( { method : method , text : msg } ) } } ) msgs . sort ( function ( a , b ) { return a . method > b . method ? 1 : a . method < b . method ? - 1 : 0 } ) msgs . forEach ( function ( msg ) { var space = Array ( len - msg . method . length + 1 ) . join ( ' ' ) ; log ( \"db.\" + msg . method + \"() \" + space + msg . text ) ; } ) } ) . help = help ( \"Logs help text for all db methods\" ) ; /**\n   * Drop this database\n   *\n   * @param {Function} [cb]\n   */ ; ( DB . prototype . drop = function ( cb ) { var name = db . databaseName ; db . dropDatabase ( cb || function ( err ) { if ( err ) { return console . error ( err ) ; } db . collections ( function ( ) { log ( 'database \"%s\" was dropped' , name ) ; } ) ; } ) ; } ) . help = help ( \"Drops the database\" ) ; wrap ( DB . prototype , 'drop' ) ; /**\n   * Close this database connection\n   *\n   * @param {Function} [cb]\n   */ ; ( DB . prototype . close = function ( cb ) { if ( 'function' != typeof cb ) { cb = handleError ; } db . close ( true , cb ) ; } ) . help = help ( \"Closes the database connection\" ) ; wrap ( DB . prototype , 'close' ) ; /**\n   * Open the database connection\n   *\n   * @param {Function} [cb]\n   */ ; ( DB . prototype . open = function ( cb ) { db . open ( function ( err ) { if ( err ) { return handleError ( err , cb ) ; } if ( 'function' == typeof cb ) { cb ( ) ; } } ) ; } ) . help = help ( \"Opens the database connection\" ) wrap ( DB . prototype , 'open' ) ; /**\n   * Use a different database\n   */ ; ( DB . prototype . use = function ( name ) { return create ( db . db ( name ) ) ; } ) . help = help ( \"Changes to a different database\" ) /**\n   * Access a collection\n   */ ; ( DB . prototype . col = function ( name , opts ) { if ( this [ name ] ) { return this [ name ] ; } // accessor management collections . push ( name ) ; return this [ name ] = db . collection ( name , opts ) ; } ) . help = help ( \"Accesses a collection\" ) /**\n   * Creates a collection\n   *\n   * @param {String} name\n   * @param {Object} [options]\n   * @param {Function} [cb]\n   */ ; ( DB . prototype . createCol = function ( name , opts , cb ) { if ( 'function' == typeof opts ) { cb = opts ; opts = { } ; } if ( 'string' != typeof name ) { error ( new TypeError ( 'collection name must be a string' ) ) ; return ; } if ( ! opts ) opts = { } ; // force error if collection exists if ( ! ( 'strict' in opts ) ) opts . strict = true ; var self = this ; db . createCollection ( name , opts , function ( err , col ) { if ( err ) { if ( / already exists / . test ( err ) ) { // remove the \"safe mode\" message err . message = 'collection \"' + name + '\" already exists' ; } return handleError ( err ) ; } // register name for accessor management collections . push ( name ) ; return self [ name ] = col ; } ) ; } ) . help = help ( \"Creates a collection\" ) wrap ( DB . prototype , 'createCol' ) ; /**\n   * Refresh and return the list of collections on this database\n   *\n   * @param {Boolean} [print] if the collection names should be printed\n   * @param {Function} [cb] passed any error and the result array\n   */ ; ( DB . prototype . cols = function ( print , cb ) { var self = this ; if ( 'function' == typeof print ) { cb = print ; print = false ; } if ( undefined == print ) print = true db . collectionNames ( { namesOnly : true } , function ( err , names ) { if ( err ) { if ( cb ) return cb ( err ) ; console . error ( err . stack ) ; return ; } if ( ! Array . isArray ( names ) ) { names = [ ] ; } // remove cached collections collections . forEach ( function ( name ) { delete self [ name ] ; } ) ; // strip db from name var ns = db . databaseName ; var len = ns . length + 1 ; names = names . map ( function ( name ) { return name . substring ( len ) ; } ) ; collections = names ; // expose collection access from `db` // TODO abstract collection names . forEach ( function ( name ) { self [ name ] = db . collection ( name ) ; // handle system.indexes etc if ( / \\. / . test ( name ) ) { var parts = name . split ( '.' ) ; parts . reduce ( function ( out , part , i ) { if ( i == parts . length - 1 ) { out [ part ] = self [ name ] ; } else { if ( ! out [ part ] ) { out [ part ] = { } ; } } return out [ part ] ; } , self ) ; } } ) ; if ( cb ) return cb ( err , names ) ; if ( print ) { console . log ( ) ; names . forEach ( function ( name ) { log ( name ) ; } ) global . repl . displayPrompt ( ) ; } } ) ; } ) . help = help ( \"Retreives an array of collection names in the db\" ) wrap ( DB . prototype , 'cols' ) ; /**\n   * Execute a command on the database\n   *\n   * @param {Object} cmd\n   * @param {Object} [opts]\n   * @param {Function} [cb]\n   */ ; ( DB . prototype . runCommand = function ( cmd , opts , cb ) { if ( 'function' == typeof opts ) { cb = opts ; opts = { } ; } if ( ! cmd ) { var err = new Error ( 'missing command' ) ; if ( cb ) return cb ( err ) ; console . error ( err ) ; return ; } if ( ! cb ) cb = p ; if ( ! opts ) opts = { } ; var admin = ! ! opts . admin ; delete opts . admin ; var method = admin ? 'executeDbAdminCommand' : 'executeDbCommand' db [ method ] ( cmd , opts , cb ) ; } ) . help = help ( \"Runs a command on the database\" ) wrap ( DB . prototype , 'runCommand' ) ; /**\n   * Retreive database stats\n   */ ; ( DB . prototype . stats = function ( scale , cb ) { if ( 'function' == typeof scale ) cb = scale ; scale |= 0 ; db . stats ( function ( err , stats ) { cb ( err , stats ) ; } ) } ) . help = help ( 'Retreive database stats' ) ; wrap ( DB . prototype , 'stats' ) ; /**\n   * console.log helper\n   */ ; ( DB . prototype . inspect = function ( ) { return db . databaseName ; } ) . help = help ( \"Returns the name of the database\" ) ; return DB ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap async functions with animation etc [CODESPLIT] function wrap ( proto , name ) { var old = proto [ name ] ; proto [ name ] = function ( ) { if ( global . repl ) global . repl . bufferStart ( ) ; var args = slice ( arguments ) ; var last = args [ args . length - 1 ] ; if ( 'function' == typeof last ) { args [ args . length - 1 ] = function ( ) { if ( global . repl ) global . repl . bufferEnd ( ) if ( p != last ) console . log ( ) ; last . apply ( null , arguments ) if ( global . repl ) { global . repl . displayPrompt ( ) ; global . repl . moveCursorToEnd ( ) ; } } } else { args . push ( function ( ) { if ( global . repl ) global . repl . bufferEnd ( ) p . apply ( null , arguments ) ; if ( global . repl ) global . repl . moveCursorToEnd ( ) ; } ) ; } old . apply ( this , args ) ; } if ( old . help ) { proto [ name ] . help = old . help ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Error reporting helper [CODESPLIT] function handleError ( err , cb ) { if ( err ) { if ( cb ) { return process . nextTick ( function ( ) { cb ( err ) ; } ) ; } console . error ( err ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Display values in a table . [CODESPLIT] function tablature ( conf ) { const { keys = [ ] , data = [ ] , headings = { } , replacements = { } , centerValues = [ ] , centerHeadings = [ ] , } = conf const [ i ] = data if ( ! i ) return '' const cv = makeBinaryHash ( centerValues ) const hv = makeBinaryHash ( centerHeadings ) const k = Object . keys ( i ) . reduce ( ( acc , key ) => { const h = headings [ key ] return { ... acc , [ key ] : h ? h . length : key . length , // initialise with titles lengths } } , { } ) const widths = data . reduce ( ( dac , d ) => { const res = Object . keys ( d ) . reduce ( ( acc , key ) => { const maxLength = dac [ key ] const val = d [ key ] const r = getReplacement ( replacements , key ) const { length } = r ( val ) return { ... acc , [ key ] : Math . max ( length , maxLength ) , } } , { } ) return res } , k ) const kk = keys . reduce ( ( acc , key ) => { const h = headings [ key ] return { ... acc , [ key ] : h || key , } } , { } ) const hr = keys . reduce ( ( acc , key ) => { return { ... acc , [ key ] : heading , } } , { } ) const hl = getLine ( keys , kk , widths , hr , hv ) const rl = data . map ( ( row ) => { const line = getLine ( keys , row , widths , replacements , cv ) return line } ) return [ hl , ... rl , ] . join ( '\\n' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add Test : Add proper test to ensure the format of the metric mocking logger was giving troubles [CODESPLIT] function metric ( name , val , message ) { // val is not a NaN should log the metric if ( isNaN ( val ) ) { return message ; } var metadata = _ . pick ( message , [ 'type' , 'rid' , 'address' , 'status' , 'client' , 'clientId' , 'transaction' ] ) ; metadata [ 'micrometric' ] = { name : name , value : val } log . info ( metadata , 'Publishing metric \"%s\":%sms' , name , val ) ; return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "============================================================================== -- constructor [CODESPLIT] function StdError ( message ) { if ( ! ( this instanceof StdError ) ) { return new StdError ( message ) ; } Error . captureStackTrace ( this , this . constructor ) ; this . code = this . _defaults . code ; this . name = this . _defaults . name ; this . message = this . _defaults . message ; switch ( typeof ( message ) ) { case \"string\" : this . message = message ; break ; case \"object\" : ( message . code ) && ( this . code = message . code ) ; ( message . name ) && ( this . name = message . name ) ; ( message . message ) && ( this . message = message . message ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- constructor [CODESPLIT] function ( ) { var args = Array . prototype . slice . call ( arguments ) ; if ( ! ( this instanceof child ) ) { var obj = Object . create ( child . prototype ) ; child . apply ( obj , args ) ; return obj ; } self . apply ( this , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "console . log ( pathPart pathPart ) ; [CODESPLIT] function sanatize ( str ) { return str . replace ( / \\.\\w+$ / , '' ) // remove .html . replace ( / %[\\dA-Z]+ / g , '' ) // remove %20 . replace ( / \\ban?\\b / g , '' ) // ignore a/an . replace ( / \\bthe\\b / g , '' ) // ignore the . replace ( / \\bof\\b / g , '' ) // ignore of . replace ( / [^a-z0-9] / g , '' ) // remove non-alphanumerics ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "console . log ( fixRedir request . url ) ; [CODESPLIT] function fixRedirectPost ( ) { // Permament Redirect response . statusCode = 301 ; response . setHeader ( 'Location' , path . normalize ( servepath + '/' + permalinkify ( request . query . blogger ) ) ) ; response . end ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a lodash chain that calls . value () automatically after the first . method () It also returns a promise or value For example : lowChain ( _ array save ) . method () is the same as : _ . chain ( array ) . method () . value () [CODESPLIT] function lowChain ( _ , array , save ) { var chain = _ . chain ( array ) ; _ . functionsIn ( chain ) . forEach ( function ( method ) { chain [ method ] = _ . flow ( chain [ method ] , function ( arg ) { var v = void 0 ; if ( arg ) { v = _ . isFunction ( arg . value ) ? arg . value ( ) : arg ; } var s = save ( ) ; if ( s ) return s . then ( function ( ) { return Promise . resolve ( v ) ; } ) ; return v ; } ) ; } ) ; return chain ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a promise or nothing in sync mode or if the database hasn t changed [CODESPLIT] function _save ( ) { if ( db . source && db . write && writeOnChange ) { var str = JSON . stringify ( db . object ) ; if ( str !== db . _checksum ) { db . _checksum = str ; return db . write ( db . source , db . object ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Picklr object . [CODESPLIT] function Picklr ( startDir , options ) { options = options || { } ; let defaultExcludeDirsRe ; if ( / ^\\. / . test ( startDir ) ) { defaultExcludeDirsRe = / \\/\\.|node_modules / i ; } else { defaultExcludeDirsRe = / ^\\.|\\/\\.|node_modules / i ; } this . totalFileCount = 0 ; this . matchedFileCount = 0 ; this . startDir = startDir || '.' ; this . targetText = options . targetText || '' ; this . replacementText = options . replacementText || '' ; this . action = options . action || 'echo' ; this . includeExts = options . includeExts || [ '.js' ] ; this . excludeDirs = options . excludeDirsRe || defaultExcludeDirsRe ; this . logger = options . logger || console . log ; this . picklrActions = picklrActions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively process files . [CODESPLIT] function ( p ) { fs . readdirSync ( p ) . forEach ( function ( file ) { const curPath = path . join ( p , path . sep , file ) ; const stats = fs . statSync ( curPath ) ; if ( this . isDirectory ( stats , curPath ) ) { this . recurseFiles ( curPath ) ; } else if ( this . isFile ( stats , curPath ) ) { this . picklrActions [ this . action ] . call ( this , curPath ) ; } } , this ) ; if ( p === this . startDir ) { this . logger ( 'Total file count = ' + this . totalFileCount ) ; if ( this . action !== 'echo' ) { this . logger ( 'Matched file count = ' + this . matchedFileCount ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "File type determination . [CODESPLIT] function ( stats , p ) { let result = stats . isFile ( ) ; if ( result ) { const ext = path . extname ( p ) ; result = this . includeExts . indexOf ( ext ) !== - 1 ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Directory type determination . [CODESPLIT] function ( stats , p ) { let result = stats . isDirectory ( ) ; if ( result ) { result = ! this . excludeDirs . test ( p ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process all files under startDir using options . [CODESPLIT] function processAllFiles ( startDir , options ) { const picklr = new Picklr ( startDir , options ) ; picklr . recurseFiles ( startDir ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does the actual audit or update of a single file . [CODESPLIT] function processFile ( filePath , update ) { let change , found = false ; const lines = fs . readFileSync ( filePath , { encoding : 'utf8' } ) . split ( '\\n' ) ; for ( let i = 0 ; i < lines . length ; i ++ ) { if ( lines [ i ] . indexOf ( this . targetText ) !== - 1 ) { found = true ; change = lines [ i ] . replace ( this . targetText , this . replacementText ) ; if ( update ) { lines [ i ] = change ; } else { // log the line that would be edited. this . logger ( '*** File:   ' + filePath ) ; this . logger ( '@@@ Found:  ' + lines [ i ] ) ; this . logger ( '--- Change: ' + change ) ; } this . matchedFileCount ++ ; break ; } } if ( ! found && ! update ) { // log the file that would be omitted this . logger ( '*** Omitted: ' + filePath ) ; } if ( found && update ) { fs . writeFileSync ( filePath , lines . join ( '\\n' ) , { encoding : 'utf8' } ) ; // log the updated file this . logger ( '@@@ Updated: ' + filePath ) ; } this . totalFileCount ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private ---------------------------------------------------------------------------- [CODESPLIT] function extractEncoding ( headers ) { var type = headers [ \"content-type\" ] ; if ( ! type ) { return \"utf8\" ; } var split = type . split ( '=' ) ; return split . length == 2 ? split [ 1 ] : \"utf8\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts parts of a string beginning at the character at the specified position and returns the specified number of characters . The substr () does not change the original string . [CODESPLIT] function substr ( string , start , length ) { if ( ! isString ( string ) ) { return string ; } return string . substr ( start , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize an HTTP server [CODESPLIT] async function initHTTPServer ( { ENV = { } , HOST = '127.0.0.1' , PORT = 8080 , MAX_HEADERS_COUNT = 800 , KEEP_ALIVE_TIMEOUT = ms ( '5m' ) , TIMEOUT = ms ( '2m' ) , MAX_CONNECTIONS , httpRouter , log = noop , } ) { const sockets = ENV . DESTROY_SOCKETS ? new Set ( ) : { } . undef ; const httpServer = http . createServer ( httpRouter ) ; const listenPromise = new Promise ( resolve => { httpServer . listen ( PORT , HOST , ( ) => { log ( 'info' , ` ${ HOST } ${ PORT } ` ) ; resolve ( httpServer ) ; } ) ; } ) ; const errorPromise = new Promise ( ( resolve , reject ) => { httpServer . once ( 'error' , reject ) ; } ) ; httpServer . timeout = TIMEOUT ; httpServer . keepAliveTimeout = KEEP_ALIVE_TIMEOUT ; httpServer . maxHeadersCount = MAX_HEADERS_COUNT ; httpServer . maxConnections = MAX_CONNECTIONS ; if ( 'undefined' !== typeof MAX_CONNECTIONS ) { httpServer . maxConnections = MAX_CONNECTIONS ; } if ( ENV . DESTROY_SOCKETS ) { httpServer . on ( 'connection' , socket => { sockets . add ( socket ) ; socket . on ( 'close' , ( ) => { sockets . delete ( socket ) ; } ) ; } ) ; } return Promise . race ( [ listenPromise , errorPromise ] ) . then ( ( ) => ( { service : httpServer , errorPromise , dispose : ( ) => new Promise ( ( resolve , reject ) => { log ( 'debug' , 'Closing HTTP server.' ) ; // Avoid to keepalive connections on shutdown httpServer . timeout = 1 ; httpServer . keepAliveTimeout = 1 ; httpServer . close ( err => { if ( err ) { reject ( err ) ; return ; } log ( 'debug' , 'HTTP server closed' ) ; resolve ( ) ; } ) ; if ( ENV . DESTROY_SOCKETS ) { for ( const socket of sockets . values ( ) ) { socket . destroy ( ) ; } } } ) , } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort an array by the name of existing property and add a first element into array [CODESPLIT] function sortAndAddFirstElement ( array , sortBy , element ) { return _ ( array ) . sortBy ( sortBy ) . unshift ( element ) . value ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interface for building an object by configuration [CODESPLIT] function objectInterface ( config ) { return function ( obj ) { var result = { } ; for ( var i = 0 ; i < config . length ; i ++ ) { var OR , NEXT , REAL ; if ( ( OR = config [ i ] . split ( '/' ) ) && OR [ 1 ] ) { result [ OR [ 0 ] ] = obj [ OR [ 0 ] ] || Function ( 'return ' + OR [ 1 ] ) ( ) ; } else if ( ( NEXT = config [ i ] . split ( '|' ) ) && NEXT [ 1 ] ) { result [ NEXT [ 0 ] ] = Function ( 'return ' + NEXT [ 1 ] ) . call ( obj ) ; } else if ( ( REAL = config [ i ] . split ( ':' ) ) && REAL [ 1 ] ) { result [ REAL [ 0 ] ] = Function ( 'return ' + REAL [ 1 ] ) ( ) ; } else { result [ config [ i ] ] = obj [ config [ i ] ] ; } } return result ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiate the httpTransaction service @param { Object } services The services to inject @param { Number } [ services . TIMEOUT = 30000 ] A number indicating how many ms the transaction should take to complete before being cancelled . @param { Object } [ services . TRANSACTIONS = {} ] A hash of every current transactions @param { Function } services . time A timing function @param { Object } services . delay A delaying service @param { Function } [ services . log ] A logging function @param { Function } [ services . uniqueId ] A function returning unique identifiers @return { Promise<Function > } A promise of the httpTransaction function @example import { initHTTPTransaction } from swagger - http - router ; [CODESPLIT] function initHTTPTransaction ( { TIMEOUT = DEFAULT_TIMEOUT , TRANSACTIONS , log = noop , time , delay , uniqueId = createIncrementor ( ) , } ) { // Not using default value to always // get an empty object here and avoid // conflicts between instances spawned // with defaults TRANSACTIONS = TRANSACTIONS || { } ; log ( 'debug' , 'HTTP Transaction initialized.' ) ; return Promise . resolve ( httpTransaction ) ; /**\n   * Create a new HTTP transaction\n   * @param  {HTTPRequest}  req\n   * A raw NodeJS HTTP incoming message\n   * @param  {HTTPResponse} res\n   * A raw NodeJS HTTP response\n   * @return {Array}\n   * The normalized request and the HTTP\n   * transaction created in an array.\n   */ function httpTransaction ( req , res ) { let initializationPromise ; /* Architecture Note #3.1: New Transaction\n    The idea is to maintain a hash of each pending\n     transaction. To do so, we create a transaction\n     object that contains useful informations about\n     the transaction and we store it into the\n     `TRANSACTIONS` hash.\n\n    Each transaction has a unique id that is either\n     generated or picked up in the `Transaction-Id`\n     request header. This allows to trace\n     transactions end to end with that unique id.\n    */ return Promise . resolve ( ) . then ( ( ) => { const request = { url : req . url , method : req . method . toLowerCase ( ) , headers : req . headers , body : req , } ; const transaction = { protocol : req . connection . encrypted ? 'https' : 'http' , ip : ( req . headers [ 'x-forwarded-for' ] || '' ) . split ( ',' ) [ 0 ] || req . connection . remoteAddress , startInBytes : req . socket . bytesRead , startOutBytes : req . socket . bytesWritten , startTime : time ( ) , url : req . url , method : req . method , reqHeaders : req . headers , errored : false , } ; const delayPromise = delay . create ( TIMEOUT ) ; let id = req . headers [ 'transaction-id' ] || uniqueId ( ) ; // Handle bad client transaction ids if ( TRANSACTIONS [ id ] ) { initializationPromise = Promise . reject ( new HTTPError ( 400 , 'E_TRANSACTION_ID_NOT_UNIQUE' , id ) , ) ; id = uniqueId ( ) ; } else { initializationPromise = Promise . resolve ( ) ; } transaction . id = id ; TRANSACTIONS [ id ] = transaction ; return [ request , { id , start : startTransaction . bind ( null , { id , req , res , delayPromise } , initializationPromise , ) , catch : catchTransaction . bind ( null , { id , req , res } ) , end : endTransaction . bind ( null , { id , req , res , delayPromise } ) , } , ] ; } ) ; } function startTransaction ( { id , delayPromise } , initializationPromise , buildResponse , ) { /* Architecture Note #3.2: Transaction start\n    Once initiated, the transaction can be started. It\n     basically spawns a promise that will be resolved\n     to the actual response or rejected if the timeout\n     is reached.\n    */ return Promise . race ( [ initializationPromise . then ( ( ) => buildResponse ( ) ) , delayPromise . then ( ( ) => { throw new HTTPError ( 504 , 'E_TRANSACTION_TIMEOUT' , TIMEOUT , id ) ; } ) , ] ) ; } function catchTransaction ( { id , req } , err ) { /* Architecture Note #3.3: Transaction errors\n    Here we are simply casting and logging errors.\n     It is important for debugging but also for\n     ending the transaction properly if an error\n     occurs.\n    */ err = HTTPError . cast ( err , err . httpCode || 500 ) ; log ( 'error' , 'An error occured' , { guruMeditation : id , request : TRANSACTIONS [ id ] . protocol + '://' + ( req . headers . host || 'localhost' ) + TRANSACTIONS [ id ] . url , verb : req . method , status : err . httpCode , code : err . code , stack : err . stack , details : err . params , } ) ; TRANSACTIONS [ id ] . errored = true ; throw err ; } function endTransaction ( { id , req , res , delayPromise } , response ) { /* Architecture Note #3.4: Transaction end\n    We end the transaction by writing the final status\n     and headers and piping the response body if any.\n\n    The transaction can till error at that time but it\n     is too late for changing the response status so\n     we are just logging the event.\n     This could be handled with\n     [HTTP trailers](https://nodejs.org/api/http.html#http_response_addtrailers_headers)\n     but the lack of client side support for now is\n     preventing us to use them.\n\n     Once terminated, the transaction is removed\n      from the `TRANSACTIONS` hash.\n    */ return new Promise ( ( resolve , reject ) => { res . on ( 'error' , reject ) ; res . on ( 'finish' , resolve ) ; res . writeHead ( response . status , statuses [ response . status ] , Object . assign ( { } , response . headers , { 'Transaction-Id' : id } ) , ) ; if ( response . body && response . body . pipe ) { response . body . pipe ( res ) ; } else { res . end ( ) ; } } ) . catch ( err => { TRANSACTIONS [ id ] . errored = true ; log ( 'error' , 'An error occured' , { guruMeditation : id , request : TRANSACTIONS [ id ] . protocol + '://' + ( req . headers . host || 'localhost' ) + TRANSACTIONS [ id ] . url , method : req . method , stack : err . stack || err , } ) ; } ) . then ( ( ) => { TRANSACTIONS [ id ] . endTime = time ( ) ; TRANSACTIONS [ id ] . endInBytes = req . socket . bytesRead ; TRANSACTIONS [ id ] . endOutBytes = req . socket . bytesWritten ; TRANSACTIONS [ id ] . statusCode = response . status ; TRANSACTIONS [ id ] . resHeaders = response . headers || { } ; log ( 'info' , TRANSACTIONS [ id ] ) ; delete TRANSACTIONS [ id ] ; return delay . clear ( delayPromise ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new HTTP transaction [CODESPLIT] function httpTransaction ( req , res ) { let initializationPromise ; /* Architecture Note #3.1: New Transaction\n    The idea is to maintain a hash of each pending\n     transaction. To do so, we create a transaction\n     object that contains useful informations about\n     the transaction and we store it into the\n     `TRANSACTIONS` hash.\n\n    Each transaction has a unique id that is either\n     generated or picked up in the `Transaction-Id`\n     request header. This allows to trace\n     transactions end to end with that unique id.\n    */ return Promise . resolve ( ) . then ( ( ) => { const request = { url : req . url , method : req . method . toLowerCase ( ) , headers : req . headers , body : req , } ; const transaction = { protocol : req . connection . encrypted ? 'https' : 'http' , ip : ( req . headers [ 'x-forwarded-for' ] || '' ) . split ( ',' ) [ 0 ] || req . connection . remoteAddress , startInBytes : req . socket . bytesRead , startOutBytes : req . socket . bytesWritten , startTime : time ( ) , url : req . url , method : req . method , reqHeaders : req . headers , errored : false , } ; const delayPromise = delay . create ( TIMEOUT ) ; let id = req . headers [ 'transaction-id' ] || uniqueId ( ) ; // Handle bad client transaction ids if ( TRANSACTIONS [ id ] ) { initializationPromise = Promise . reject ( new HTTPError ( 400 , 'E_TRANSACTION_ID_NOT_UNIQUE' , id ) , ) ; id = uniqueId ( ) ; } else { initializationPromise = Promise . resolve ( ) ; } transaction . id = id ; TRANSACTIONS [ id ] = transaction ; return [ request , { id , start : startTransaction . bind ( null , { id , req , res , delayPromise } , initializationPromise , ) , catch : catchTransaction . bind ( null , { id , req , res } ) , end : endTransaction . bind ( null , { id , req , res , delayPromise } ) , } , ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Difference between dates which are passed in formats milliseconds days hours minutes [CODESPLIT] function dateDifference ( date1 , date2 , differenceType ) { var diffMilliseconds = Math . abs ( date1 - date2 ) ; switch ( differenceType ) { case 'days' : return dates . _getDaysDiff ( diffMilliseconds ) ; case 'hours' : return dates . _differenceInHours ( diffMilliseconds ) ; case 'minutes' : return dates . _differenceInMinutes ( diffMilliseconds ) ; case 'milliseconds' : return diffMilliseconds ; default : return { days : dates . _getDaysDiff ( diffMilliseconds ) , hours : dates . _getHoursDiff ( diffMilliseconds ) , minutes : dates . _getMinutesDiff ( diffMilliseconds ) , milliseconds : diffMilliseconds } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize an error handler for the HTTP router [CODESPLIT] function initErrorHandler ( { ENV = { } , DEBUG_NODE_ENVS = DEFAULT_DEBUG_NODE_ENVS , STRINGIFYERS = DEFAULT_STRINGIFYERS , } ) { return Promise . resolve ( errorHandler ) ; /**\n   * Handle an HTTP transaction error and\n   * map it to a serializable response\n   * @param  {String}  transactionId\n   * A raw NodeJS HTTP incoming message\n   * @param  {Object} responseSpec\n   * The response specification\n   * @param  {HTTPError} err\n   * The encountered error\n   * @return {Promise}\n   * A promise resolving when the operation\n   *  completes\n   */ function errorHandler ( transactionId , responseSpec , err ) { return Promise . resolve ( ) . then ( ( ) => { const response = { } ; response . status = err . httpCode || 500 ; response . headers = Object . assign ( { } , err . headers || { } , { // Avoid caching errors 'cache-control' : 'private' , // Fallback to the default stringifyer to always be // able to display errors 'content-type' : responseSpec && responseSpec . contentTypes [ 0 ] && STRINGIFYERS [ responseSpec . contentTypes [ 0 ] ] ? responseSpec . contentTypes [ 0 ] : Object . keys ( STRINGIFYERS ) [ 0 ] , } ) ; response . body = { error : { code : err . code || 'E_UNEXPECTED' , // Enjoy nerdy stuff: // https://en.wikipedia.org/wiki/Guru_Meditation guruMeditation : transactionId , } , } ; if ( ENV && DEBUG_NODE_ENVS . includes ( ENV . NODE_ENV ) ) { response . body . error . stack = err . stack ; response . body . error . params = err . params ; } return response ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Difference between now and date which is passed in formats milliseconds days hours minutes [CODESPLIT] function dateDifferenceFromNow ( date , differenceType ) { var now = new Date ( ) , diffMilliseconds = Math . abs ( date - now ) ; switch ( differenceType ) { case 'days' : return dates . _getDaysDiff ( diffMilliseconds ) ; case 'hours' : return dates . _differenceInHours ( diffMilliseconds ) ; case 'minutes' : return dates . _differenceInMinutes ( diffMilliseconds ) ; case 'milliseconds' : return diffMilliseconds ; default : return { days : dates . _getDaysDiff ( diffMilliseconds ) , hours : dates . _getHoursDiff ( diffMilliseconds ) , minutes : dates . _getMinutesDiff ( diffMilliseconds ) , milliseconds : diffMilliseconds } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize an HTTP router [CODESPLIT] function initHTTPRouter ( { ENV = { } , DEBUG_NODE_ENVS = DEFAULT_DEBUG_NODE_ENVS , BUFFER_LIMIT = DEFAULT_BUFFER_LIMIT , HANDLERS , API , PARSERS = DEFAULT_PARSERS , STRINGIFYERS = DEFAULT_STRINGIFYERS , DECODERS = DEFAULT_DECODERS , ENCODERS = DEFAULT_ENCODERS , QUERY_PARSER = strictQs , log = noop , httpTransaction , errorHandler , } ) { const bufferLimit = bytes . parse ( BUFFER_LIMIT ) ; const ajv = new Ajv ( { verbose : ENV && DEBUG_NODE_ENVS . includes ( ENV . NODE_ENV ) , } ) ; const consumableCharsets = Object . keys ( DECODERS ) ; const produceableCharsets = Object . keys ( ENCODERS ) ; const defaultResponseSpec = { contentTypes : Object . keys ( STRINGIFYERS ) , charsets : produceableCharsets , } ; return flattenSwagger ( API ) . then ( _createRouters . bind ( null , { HANDLERS , ajv } ) ) . then ( routers => { let handleFatalError ; log ( 'debug' , 'HTTP Router initialized.' ) ; return { service : httpRouter , fatalErrorPromise : { promise : new Promise ( ( resolve , reject ) => { handleFatalError = reject ; } ) , } , } ; /**\n       * Handle an HTTP incoming message\n       * @param  {HTTPRequest}  req\n       * A raw NodeJS HTTP incoming message\n       * @param  {HTTPResponse} res\n       * A raw NodeJS HTTP response\n       * @return {Promise}\n       * A promise resolving when the operation\n       *  completes\n       */ function httpRouter ( req , res ) { let operation ; let responseSpec = defaultResponseSpec ; return httpTransaction ( req , res ) . then ( ( [ request , transaction ] ) => transaction . start ( ( ) => Promise . resolve ( ) . then ( ( ) => { const method = request . method ; const path = request . url . split ( SEARCH_SEPARATOR ) [ 0 ] ; const search = request . url . substr ( path . length ) ; const parts = path . split ( '/' ) . filter ( a => a ) ; let [ result , pathParameters ] = routers [ method ] ? routers [ method ] . find ( parts ) : [ ] ; // Second chance for HEAD calls if ( ! result && 'head' === method ) { [ result , pathParameters ] = routers . get ? routers . get . find ( parts ) : [ ] ; } const { handler , operation : _operation_ , validators } = result || { } ; if ( ! handler ) { log ( 'debug' , 'No handler found for: ' , method , parts ) ; throw new HTTPError ( 404 , 'E_NOT_FOUND' , method , parts ) ; } operation = _operation_ ; return { search , pathParameters , validators , operation , handler , } ; } ) . then ( ( { search , pathParameters , validators , operation , handler , } ) => { const consumableMediaTypes = operation . consumes || API . consumes || [ ] ; const produceableMediaTypes = ( operation && operation . produces ) || API . produces || [ ] ; const bodySpec = extractBodySpec ( request , consumableMediaTypes , consumableCharsets , ) ; responseSpec = extractResponseSpec ( operation , request , produceableMediaTypes , produceableCharsets , ) ; return getBody ( { DECODERS , PARSERS , bufferLimit , } , operation , request . body , bodySpec , ) . then ( body => Object . assign ( body ? { body } : { } , pathParameters , QUERY_PARSER ( operation . parameters , search ) , filterHeaders ( operation . parameters , request . headers , ) , ) , ) . then ( parameters => { applyValidators ( operation , validators , parameters ) ; return parameters ; } ) . catch ( err => { throw HTTPError . cast ( err , 400 ) ; } ) . then ( executeHandler . bind ( null , operation , handler ) ) . then ( response => { if ( response . body ) { response . headers [ 'content-type' ] = response . headers [ 'content-type' ] || responseSpec . contentTypes [ 0 ] ; } // Check the stringifyer only when a schema is // specified const responseHasSchema = operation . responses && operation . responses [ response . status ] && operation . responses [ response . status ] . schema ; if ( responseHasSchema && ! STRINGIFYERS [ response . headers [ 'content-type' ] ] ) { return Promise . reject ( new HTTPError ( 500 , 'E_STRINGIFYER_LACK' , response . headers [ 'content-type' ] , ) , ) ; } if ( response . body ) { checkResponseCharset ( request , responseSpec , produceableCharsets , ) ; checkResponseMediaType ( request , responseSpec , produceableMediaTypes , ) ; } return response ; } ) ; } , ) , ) . catch ( transaction . catch ) . catch ( errorHandler . bind ( null , transaction . id , responseSpec ) ) . then ( response => { if ( response . body && 'head' === request . method ) { log ( 'warning' , 'Body stripped:' , response . body instanceof Stream ? 'Stream' : response . body , ) ; return Object . keys ( response ) . filter ( key => 'body' !== key ) . reduce ( ( cleanedResponse , key ) => { cleanedResponse [ key ] = response [ key ] ; return cleanedResponse ; } , { } ) ; } return response ; } ) // Here sendBody is not binded since we need // the `operation` value at the exact moment // of the then stage execution . then ( response => sendBody ( { DEBUG_NODE_ENVS , ENV , API , ENCODERS , STRINGIFYERS , log , ajv , } , operation , response , ) , ) . then ( transaction . end ) , ) . catch ( handleFatalError ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle an HTTP incoming message [CODESPLIT] function httpRouter ( req , res ) { let operation ; let responseSpec = defaultResponseSpec ; return httpTransaction ( req , res ) . then ( ( [ request , transaction ] ) => transaction . start ( ( ) => Promise . resolve ( ) . then ( ( ) => { const method = request . method ; const path = request . url . split ( SEARCH_SEPARATOR ) [ 0 ] ; const search = request . url . substr ( path . length ) ; const parts = path . split ( '/' ) . filter ( a => a ) ; let [ result , pathParameters ] = routers [ method ] ? routers [ method ] . find ( parts ) : [ ] ; // Second chance for HEAD calls if ( ! result && 'head' === method ) { [ result , pathParameters ] = routers . get ? routers . get . find ( parts ) : [ ] ; } const { handler , operation : _operation_ , validators } = result || { } ; if ( ! handler ) { log ( 'debug' , 'No handler found for: ' , method , parts ) ; throw new HTTPError ( 404 , 'E_NOT_FOUND' , method , parts ) ; } operation = _operation_ ; return { search , pathParameters , validators , operation , handler , } ; } ) . then ( ( { search , pathParameters , validators , operation , handler , } ) => { const consumableMediaTypes = operation . consumes || API . consumes || [ ] ; const produceableMediaTypes = ( operation && operation . produces ) || API . produces || [ ] ; const bodySpec = extractBodySpec ( request , consumableMediaTypes , consumableCharsets , ) ; responseSpec = extractResponseSpec ( operation , request , produceableMediaTypes , produceableCharsets , ) ; return getBody ( { DECODERS , PARSERS , bufferLimit , } , operation , request . body , bodySpec , ) . then ( body => Object . assign ( body ? { body } : { } , pathParameters , QUERY_PARSER ( operation . parameters , search ) , filterHeaders ( operation . parameters , request . headers , ) , ) , ) . then ( parameters => { applyValidators ( operation , validators , parameters ) ; return parameters ; } ) . catch ( err => { throw HTTPError . cast ( err , 400 ) ; } ) . then ( executeHandler . bind ( null , operation , handler ) ) . then ( response => { if ( response . body ) { response . headers [ 'content-type' ] = response . headers [ 'content-type' ] || responseSpec . contentTypes [ 0 ] ; } // Check the stringifyer only when a schema is // specified const responseHasSchema = operation . responses && operation . responses [ response . status ] && operation . responses [ response . status ] . schema ; if ( responseHasSchema && ! STRINGIFYERS [ response . headers [ 'content-type' ] ] ) { return Promise . reject ( new HTTPError ( 500 , 'E_STRINGIFYER_LACK' , response . headers [ 'content-type' ] , ) , ) ; } if ( response . body ) { checkResponseCharset ( request , responseSpec , produceableCharsets , ) ; checkResponseMediaType ( request , responseSpec , produceableMediaTypes , ) ; } return response ; } ) ; } , ) , ) . catch ( transaction . catch ) . catch ( errorHandler . bind ( null , transaction . id , responseSpec ) ) . then ( response => { if ( response . body && 'head' === request . method ) { log ( 'warning' , 'Body stripped:' , response . body instanceof Stream ? 'Stream' : response . body , ) ; return Object . keys ( response ) . filter ( key => 'body' !== key ) . reduce ( ( cleanedResponse , key ) => { cleanedResponse [ key ] = response [ key ] ; return cleanedResponse ; } , { } ) ; } return response ; } ) // Here sendBody is not binded since we need // the `operation` value at the exact moment // of the then stage execution . then ( response => sendBody ( { DEBUG_NODE_ENVS , ENV , API , ENCODERS , STRINGIFYERS , log , ajv , } , operation , response , ) , ) . then ( transaction . end ) , ) . catch ( handleFatalError ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns new line index which is right after characters beyound pos that editor will likely automatically close e . g . } ] and quotes [CODESPLIT] function offsetPastAutoClosed ( line , pos , options ) { // closing quote is allowed only as a next character if ( isQuote ( line . charCodeAt ( pos ) ) ) { pos ++ ; } // offset pointer until non-autoclosed character is found while ( isCloseBrace ( line . charCodeAt ( pos ) , options . syntax ) ) { pos ++ ; } return pos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns start offset ( left limit ) in line where we should stop looking for abbreviation : it’s nearest to pos location of prefix token [CODESPLIT] function getStartOffset ( line , pos , prefix ) { if ( ! prefix ) { return 0 ; } const stream = new StreamReader ( line ) ; const compiledPrefix = String ( prefix ) . split ( '' ) . map ( code ) ; stream . pos = pos ; let result ; while ( ! stream . sol ( ) ) { if ( consumePair ( stream , SQUARE_BRACE_R , SQUARE_BRACE_L ) || consumePair ( stream , CURLY_BRACE_R , CURLY_BRACE_L ) ) { continue ; } result = stream . pos ; if ( consumeArray ( stream , compiledPrefix ) ) { return result ; } stream . pos -- ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consumes full character pair if possible [CODESPLIT] function consumePair ( stream , close , open ) { const start = stream . pos ; if ( stream . eat ( close ) ) { while ( ! stream . sol ( ) ) { if ( stream . eat ( open ) ) { return true ; } stream . pos -- ; } } stream . pos = start ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consumes all character codes from given array right - to - left if possible [CODESPLIT] function consumeArray ( stream , arr ) { const start = stream . pos ; let consumed = false ; for ( let i = arr . length - 1 ; i >= 0 && ! stream . sol ( ) ; i -- ) { if ( ! stream . eat ( arr [ i ] ) ) { break ; } consumed = i === 0 ; } if ( ! consumed ) { stream . pos = start ; } return consumed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if given character code belongs to HTML identifier [CODESPLIT] function isIdent ( c ) { return c === COLON || c === DASH || isAlpha ( c ) || isNumber ( c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "> Controls merges and resolves all tasks from config files > and passed through opts . tasks . > > All opts are passed to [ execa - pro ] [] and to [ execa ] [] > so you can pass opts . stdio : inherit for example > to output the result of each command in the console useful for things like prompt inputs . > Resolving works recursively and support ESLint style presets through > the opts . extends . The extends property can be string ( the name of the preset > prefixed with hela - config - ) a function ( that is passed with { extends tasks } object ) > or an object containing another extends and / or tasks properties . > > Configuration is handled by [ @tunnckocore / pretty - config ] ( https : // github . com / tunnckoCore / pretty - config ) > which is pretty similar to the [ cosmiconfig ] [] package and so the config > files lookup order is : > - . helarc . { json yaml yml js } > - hela . config . js > - . hela . config . js > - . helarc - YAML or JSON syntax > - package . json - one of hela helaConfig or config . hela fields [CODESPLIT] async function hela ( opts ) { const options = Object . assign ( { argv : { } , prefix : 'hela-config-' , stdio : 'inherit' } , opts ) if ( options . tasks || ( options . presets || options . extends ) ) { return presetResolver ( options ) } return prettyConfig ( 'hela' , options ) . then ( ( config ) => { if ( ! config ) { throw new Error ( 'hela: no config' ) } return presetResolver ( Object . assign ( { } , config , options ) ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utils [CODESPLIT] function factory ( type , opts ) { return ( cmds , options ) => { const cmd = { exec : execa . exec , shell : execa . shell } return cmd [ type ] ( cmds , Object . assign ( { } , opts , options ) ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "todo : externalize as hela - resolver ? [CODESPLIT] function presetResolver ( opts ) { const presets = arrayify ( opts . presets || opts . extends ) if ( presets . length > 0 ) { const arg = Object . assign ( { } , opts ) const options = Object . assign ( { first : arg } , opts ) const tasks = resolvePlugins ( presets , options ) . reduce ( ( acc , preset ) => presetReducer ( acc , preset ) , { } ) return transformTasks ( opts , Object . assign ( { } , tasks , opts . tasks ) ) } return transformTasks ( opts , opts . tasks ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if ( !isNyc && !isCov && !isEslint ) { console . error ( hela : task $ { name } failed ) console . error ( er . stack || er . message ) } } [CODESPLIT] async function run ( ) { const pkg = await readJson ( path . join ( options . cwd , 'package.json' ) ) const tasks = await hela ( { pkg , ... options } ) const name = options . taskName if ( Object . keys ( tasks ) . length === 0 ) { throw new Error ( 'hela: no tasks' ) } const hasOwn = ( o , k ) => Object . prototype . hasOwnProperty . call ( o , k ) if ( ! hasOwn ( tasks , name ) ) { throw new Error ( ` ${ name } ` ) } return tasks [ name ] ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### default [CODESPLIT] function plugin ( options ) { if ( ! options ) throw new Error ( 'no options passed' ) if ( ! options . src ) throw new Error ( 'required: options.src' ) if ( ! options . dest ) throw new Error ( 'required: options.dest' ) if ( ! options . auth ) throw new Error ( 'required: options.auth' ) // if (options.cache !== undefined) cache = options.cache if ( options . invalidateCache ) { initCache ( ) . then ( ( ) => { dbg ( 'invalidating cache' ) fileCache . collection . clear ( ) valueCache . collection . clear ( ) } ) } const folder = new Folder ( options ) return folder . googleDrive . bind ( folder ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "don t change this ## _write this is where the parallel stream magic happens .. pay attention each time _write is called we either call next immediately ( if we haven t yet reached concurrency limit ) or we call next once the worker has finished . [CODESPLIT] function _write ( file , encoding , next ) { this . workers ++ vow . resolve ( file ) . then ( ( file ) => folder . downloadFile ( file ) ) . then ( ( file ) => folder . frontMatter ( file ) ) . then ( ( file ) => folder . storeFile ( file ) ) . catch ( dbg ) . then ( ( ) => { this . workers -- next ( ) } ) // if not at concurrency limit, call next immediately (don't wait for // worker to finish) if ( this . workers < this . concurrency ) { next ( ) next = ( ) => { } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### _doAuth [CODESPLIT] function _doAuth ( auth ) { if ( oauth ) return vow . resolve ( ) dbg ( 'doing oAuth2' ) const googleAuth = new GoogleAuth ( ) oauth = new googleAuth . OAuth2 ( auth . client_id , auth . client_secret , [ 'urn:ietf:wg:oauth:2.0:oob' , 'http://localhost' ] ) return vow . resolve ( ) . then ( ( ) => { // see if token has been recorded in config let configToken = config . get ( 'metalsmith-google-drive' ) . token // no idea why google auth needs the token to be writable, but whatever if ( configToken ) configToken = config . util . cloneDeep ( configToken ) // fall back to cache (params), then do token flow return configToken || valueCache . retrieve ( 'token' ) || _tokenFlow ( ) } ) . then ( ( token ) => { oauth . credentials = token } ) . catch ( ( err ) => { // if some failure occurred invalidate oauth object so we don't simply // try to use it next time. oauth = false return vow . reject ( err ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### _tokenFlow [CODESPLIT] function _tokenFlow ( ) { const defer = vow . defer ( ) let prompt const authUrl = oauth . generateAuthUrl ( { access_type : 'offline' , scope : [ 'https://www.googleapis.com/auth/drive.readonly' ] } ) console . log ( 'authorise metalsmith-google-drive by visiting: ' , authUrl ) prompt = readline . createInterface ( { input : process . stdin , output : process . stdout } ) prompt . question ( 'Enter the code from that page here (or \"ok\" to skip scrape): ' , ( code ) => { prompt . close ( ) if ( code === 'ok' ) return defer . reject ( 'skip' ) oauth . getToken ( code , ( err , result ) => { if ( err ) { dbg ( err ) defer . reject ( err ) } else { console . log ( '---------- snip ----------' ) console . log ( hjson . stringify ( { 'metalsmith-google-drive' : { token : result } } , { separator : true , spaces : 2 , bracesSameLine : true , quotes : 'all' } ) ) console . log ( '---------- snip ----------' ) console . log ( 'this token is cached automatically, but you can store' ) console . log ( 'it in a config file like config/local.js if you want.' ) valueCache . store ( 'token' , result ) defer . resolve ( result ) } } ) } ) return defer . promise ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pool for testing in place camelizeKeys [CODESPLIT] function onCycle ( event ) { if ( objectPool . length == 0 ) { throw new Error ( 'Pool ran out of objects' ) ; } console . log ( String ( event . target ) ) ; initPool ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * The only way to modify state is to trigger an action the modifer function is where you change state based on the type of an action [CODESPLIT] function modifier ( action , state ) { if ( action . type === 'example' ) { return extend ( state , { example : true } ) } else if ( action . type === 'title' ) { return extend ( state , { title : action . title } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load JSON data from a companion file and store in file data . [CODESPLIT] function json ( file ) { var filename = path . basename ( file . path , path . extname ( file . path ) ) + \".json\" ; return optional ( path . join ( path . dirname ( file . path ) , filename ) ) || { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Our Elevator implementation implements 3 states : - open : the elevator doors are opened - closed : the elevator doors are closed - moving : the elevator is moving towards a level [CODESPLIT] function ( ) { const self = this ; const TIME_PER_LEVEL = 1 * 1000 ; this . level = 0 ; this . stack = [ ] ; this . fsm = new Fsm ( ) ; /**\n   * The elevator is in a stationary state\n   * and its doors are opened.\n   */ const open = new Fsm . State ( { fsm : self . fsm , name : 'open' , onEntry : function ( ) { const state = this ; console . log ( 'Door opened at level' , self . level ) ; setTimeout ( function ( ) { state . transitionTo ( closed ) ; } , 2000 ) ; } , /**\n     * As the elevator's doors are currently opened\n     * we push any user request to go to\n     * a level on the level stack.\n     */ onEvent : function ( event ) { if ( event . name === 'goToLevel' && event . level !== self . level ) { self . pushLevel ( event . level ) ; } } } ) ; /**\n   * The elevator is in a stationary state\n   * and its doors are closed.\n   */ const closed = new Fsm . State ( { fsm : self . fsm , name : 'closed' , onEntry : function ( ) { console . log ( 'Door closed' ) ; // If there is a channel in the stack, // we move to that channel. if ( self . stack [ 0 ] ) { this . transitionTo ( moving ) ; } } , /**\n     * When the elevator's doors are closed,\n     * we wait for a request to move to another\n     * level.\n     */ onEvent : function ( event ) { if ( event . name === 'goToLevel' ) { if ( event . level === self . level ) { this . transitionTo ( open ) ; } else { self . pushLevel ( event . level ) ; this . transitionTo ( moving ) ; } } } } ) ; /**\n   * The elevator is currently moving from a\n   * level to another.\n   */ const moving = new Fsm . State ( { fsm : self . fsm , name : 'moving' , onEntry : function ( ) { const state = this ; const next = self . stack . shift ( ) ; console . log ( 'Moving to level' , next ) ; setTimeout ( function ( ) { console . log ( 'Reached level' , next ) ; self . level = next ; state . transitionTo ( open ) ; } , TIME_PER_LEVEL * Math . abs ( next - self . level ) ) ; } , /**\n     * As the elevator is currently moving and\n     * cannot change direction nor open the\n     * doors, we push any user request to go to\n     * a level on the level stack.\n     */ onEvent : function ( event ) { if ( event . name === 'goToLevel' ) { self . pushLevel ( event . level ) ; } } } ) ; // Starting the elevator in the `closed` state. this . fsm . start ( closed ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "As the elevator s doors are currently opened we push any user request to go to a level on the level stack . [CODESPLIT] function ( event ) { if ( event . name === 'goToLevel' && event . level !== self . level ) { self . pushLevel ( event . level ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When the elevator s doors are closed we wait for a request to move to another level . [CODESPLIT] function ( event ) { if ( event . name === 'goToLevel' ) { if ( event . level === self . level ) { this . transitionTo ( open ) ; } else { self . pushLevel ( event . level ) ; this . transitionTo ( moving ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encrypted content components [CODESPLIT] function decryptCBC ( encryptedComponents , keyDerivationInfo ) { // Extract the components const encryptedContent = encryptedComponents . content ; const iv = new Buffer ( encryptedComponents . iv , \"hex\" ) ; const salt = encryptedComponents . salt ; const hmacData = encryptedComponents . auth ; // Get HMAC tool const hmacTool = crypto . createHmac ( HMAC_ALGORITHM , keyDerivationInfo . hmac ) ; // Generate the HMAC hmacTool . update ( encryptedContent ) ; hmacTool . update ( encryptedComponents . iv ) ; hmacTool . update ( salt ) ; const newHmaxHex = hmacTool . digest ( \"hex\" ) ; // Check hmac for tampering if ( constantTimeCompare ( hmacData , newHmaxHex ) !== true ) { throw new Error ( \"Authentication failed while decrypting content\" ) ; } // Decrypt const decryptTool = crypto . createDecipheriv ( ENC_ALGORITHM_CBC , keyDerivationInfo . key , iv ) ; const decryptedText = decryptTool . update ( encryptedContent , \"base64\" , \"utf8\" ) ; return Promise . resolve ( ` ${ decryptedText } ${ decryptTool . final ( \"utf8\" ) } ` ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decrypt text using AES - GCM [CODESPLIT] function decryptGCM ( encryptedComponents , keyDerivationInfo ) { // Extract the components const encryptedContent = encryptedComponents . content ; const iv = new Buffer ( encryptedComponents . iv , \"hex\" ) ; const { auth : tagHex , salt } = encryptedComponents ; // Prepare tool const decryptTool = crypto . createDecipheriv ( ENC_ALGORITHM_GCM , keyDerivationInfo . key , iv ) ; // Add additional auth data decryptTool . setAAD ( new Buffer ( ` ${ encryptedComponents . iv } ${ keyDerivationInfo . salt } ` , \"utf8\" ) ) ; // Set auth tag decryptTool . setAuthTag ( new Buffer ( tagHex , \"hex\" ) ) ; // Perform decryption const decryptedText = decryptTool . update ( encryptedContent , \"base64\" , \"utf8\" ) ; return Promise . resolve ( ` ${ decryptedText } ${ decryptTool . final ( \"utf8\" ) } ` ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encrypt text using AES - CBC [CODESPLIT] function encryptCBC ( text , keyDerivationInfo , iv ) { return Promise . resolve ( ) . then ( ( ) => { const ivHex = iv . toString ( \"hex\" ) ; const encryptTool = crypto . createCipheriv ( ENC_ALGORITHM_CBC , keyDerivationInfo . key , iv ) ; const hmacTool = crypto . createHmac ( HMAC_ALGORITHM , keyDerivationInfo . hmac ) ; const { rounds } = keyDerivationInfo ; // Perform encryption let encryptedContent = encryptTool . update ( text , \"utf8\" , \"base64\" ) ; encryptedContent += encryptTool . final ( \"base64\" ) ; // Generate hmac hmacTool . update ( encryptedContent ) ; hmacTool . update ( ivHex ) ; hmacTool . update ( keyDerivationInfo . salt ) ; const hmacHex = hmacTool . digest ( \"hex\" ) ; // Output encrypted components return { mode : \"cbc\" , auth : hmacHex , iv : ivHex , salt : keyDerivationInfo . salt , rounds , content : encryptedContent } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encrypt text using AES - GCM [CODESPLIT] function encryptGCM ( text , keyDerivationInfo , iv ) { return Promise . resolve ( ) . then ( ( ) => { const ivHex = iv . toString ( \"hex\" ) ; const { rounds } = keyDerivationInfo ; const encryptTool = crypto . createCipheriv ( ENC_ALGORITHM_GCM , keyDerivationInfo . key , iv ) ; // Add additional auth data encryptTool . setAAD ( new Buffer ( ` ${ ivHex } ${ keyDerivationInfo . salt } ` , \"utf8\" ) ) ; // Perform encryption let encryptedContent = encryptTool . update ( text , \"utf8\" , \"base64\" ) ; encryptedContent += encryptTool . final ( \"base64\" ) ; // Handle authentication const tag = encryptTool . getAuthTag ( ) ; // Output encrypted components return { mode : \"gcm\" , iv : ivHex , salt : keyDerivationInfo . salt , rounds , content : encryptedContent , auth : tag . toString ( \"hex\" ) } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Salt generator [CODESPLIT] function generateSalt ( length ) { if ( length <= 0 ) { return Promise . reject ( new Error ( ` ${ length } ` ) ) ; } let output = \"\" ; while ( output . length < length ) { output += crypto . randomBytes ( 3 ) . toString ( \"base64\" ) ; if ( output . length > length ) { output = output . substr ( 0 , length ) ; } } return Promise . resolve ( output ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encrypted content components [CODESPLIT] function packEncryptedContent ( encryptedContent , iv , salt , auth , rounds , method ) { return [ encryptedContent , iv , salt , auth , rounds , method ] . join ( \"$\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unpack encrypted content components from an encrypted string [CODESPLIT] function unpackEncryptedContent ( encryptedContent ) { const [ content , iv , salt , auth , roundsRaw , methodRaw ] = encryptedContent . split ( \"$\" ) ; // iocane was originally part of Buttercup's core package and used defaults from that originally. // There will be 4 components for pre 0.15.0 archives, and 5 in newer archives. The 5th component // is the pbkdf2 round count, which is optional: const rounds = roundsRaw ? parseInt ( roundsRaw , 10 ) : PBKDF2_ROUND_DEFAULT ; // Originally only \"cbc\" was supported, but GCM was added in version 1 const method = methodRaw || \"cbc\" ; return { content , iv , salt , auth , rounds , method } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Derived key info [CODESPLIT] function deriveFromPassword ( pbkdf2Gen , password , salt , rounds , generateHMAC = true ) { if ( ! password ) { return Promise . reject ( new Error ( \"Failed deriving key: Password must be provided\" ) ) ; } if ( ! salt ) { return Promise . reject ( new Error ( \"Failed deriving key: Salt must be provided\" ) ) ; } if ( ! rounds || rounds <= 0 ) { return Promise . reject ( new Error ( \"Failed deriving key: Rounds must be greater than 0\" ) ) ; } const bits = generateHMAC ? ( PASSWORD_KEY_SIZE + HMAC_KEY_SIZE ) * 8 : PASSWORD_KEY_SIZE * 8 ; return pbkdf2Gen ( password , salt , rounds , bits ) . then ( derivedKeyData => derivedKeyData . toString ( \"hex\" ) ) . then ( function ( derivedKeyHex ) { const dkhLength = derivedKeyHex . length ; const keyBuffer = generateHMAC ? new Buffer ( derivedKeyHex . substr ( 0 , dkhLength / 2 ) , \"hex\" ) : new Buffer ( derivedKeyHex , \"hex\" ) ; const output = { salt : salt , key : keyBuffer , rounds : rounds } ; if ( generateHMAC ) { output . hmac = new Buffer ( derivedKeyHex . substr ( dkhLength / 2 , dkhLength / 2 ) , \"hex\" ) ; } return output ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The default PBKDF2 function [CODESPLIT] function pbkdf2 ( password , salt , rounds , bits ) { return new Promise ( ( resolve , reject ) => { deriveKey ( password , salt , rounds , bits / 8 , DERIVED_KEY_ALGORITHM , ( err , key ) => { if ( err ) { return reject ( err ) ; } return resolve ( key ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Node Constructor [CODESPLIT] function Node ( id , opts ) { var me = this this . id = id Object . defineProperty ( me , 'inner' , { value : opts . inner , enumerable : false , writable : true } ) Object . defineProperty ( me , 'outer' , { value : opts . outer , enumerable : false , writable : true } ) Object . defineProperty ( me , this . inner , { value : new Edge ( { inner : this . inner , outer : this . outer , id : id } ) , enumerable : false , writable : true } ) Object . defineProperty ( me , this . outer , { value : new Edge ( { inner : this . outer , outer : this . inner , id : id } ) , enumerable : false , writable : true } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new Edge with inner / outer edge names [CODESPLIT] function Edge ( opts ) { this . id = opts . id this . innerformat = opts . inner + '_%s' this . outerformat = opts . outer + '_%s' this . innerkey = format ( this . innerformat , this . id ) this . outerkey = format ( this . outerformat , this . id ) this [ opts . inner ] = function ( cb ) { this . all ( function ( error , array ) { if ( error ) return cb ( error ) if ( ! array || ! array . length ) return cb ( null , array || [ ] ) array = array . map ( function ( gid ) { return format ( this . innerformat , String ( gid ) ) } , this ) db . sunion ( array , cb ) } . bind ( this ) ) } this [ opts . outer ] = function ( cb ) { this . all ( function ( error , array ) { if ( error ) return cb ( error ) if ( ! array || ! array . length ) return cb ( null , array || [ ] ) array = array . map ( function ( gid ) { return format ( this . outerformat , gid ) } , this ) db . sunion ( array , cb ) } . bind ( this ) ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- type and value are in Ember > v2 . 8 - name is in Ember === 2 . 8 [CODESPLIT] function getDynamicSegments ( segments ) { return segments . filter ( item => item . type === 1 || ! ! item . name ) . map ( item => item . value || item . name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create transform stream to encode objects into Buffer . [CODESPLIT] function createEncodeStream ( schema ) { const stream = new BinaryStream ( { readableObjectMode : false , writableObjectMode : true , transform : transformEncode , } ) ; stream [ kschema ] = schema ; return stream ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create transform stream to decode binary data into object . [CODESPLIT] function createDecodeStream ( bufOrSchema ) { let schema = null ; const isBuffer = Buffer . isBuffer ( bufOrSchema ) ; if ( ! isBuffer ) { schema = bufOrSchema ; } const stream = new BinaryStream ( { transform : transformDecode , readableObjectMode : true , writableObjectMode : false , } ) ; stream [ kschema ] = schema ; if ( isBuffer ) { stream . append ( bufOrSchema ) ; } return stream ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The transform function for transform stream . [CODESPLIT] function transformEncode ( chunk , encoding , cb ) { try { encode ( chunk , this [ kschema ] , this ) ; const buf = this . slice ( ) ; this . consume ( buf . length ) ; cb ( null , buf ) ; } catch ( error ) { cb ( error ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The transform function for transform stream . [CODESPLIT] function transformDecode ( chunk , encoding , cb ) { this . append ( chunk ) ; try { while ( this . length > 0 ) { const transaction = new Transaction ( this ) ; const data = decode ( transaction , this [ kschema ] ) ; transaction . commit ( ) ; this . push ( data ) ; } cb ( ) ; } catch ( error ) { if ( error instanceof NotEnoughDataError ) { cb ( ) ; } else { cb ( error ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a binomial graph graph with n nodes . [CODESPLIT] function erdosRenyi ( GraphClass , options ) { if ( ! isGraphConstructor ( GraphClass ) ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid Graph constructor.' ) ; var order = options . order , probability = options . probability , rng = options . rng || Math . random ; var graph = new GraphClass ( ) ; // If user gave a size, we need to compute probability if ( typeof options . approximateSize === 'number' ) { var densityFunction = density [ graph . type + 'Density' ] ; probability = densityFunction ( order , options . approximateSize ) ; } if ( typeof order !== 'number' || order <= 0 ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid `order`. Should be a positive number.' ) ; if ( typeof probability !== 'number' || probability < 0 || probability > 1 ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid `probability`. Should be a number between 0 and 1. Or maybe you gave an `approximateSize` exceeding the graph\\'s density.' ) ; if ( typeof rng !== 'function' ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid `rng`. Should be a function.' ) ; for ( var i = 0 ; i < order ; i ++ ) graph . addNode ( i ) ; if ( probability <= 0 ) return graph ; if ( order > 1 ) { var iterator = combinations ( range ( order ) , 2 ) , path , step ; while ( ( step = iterator . next ( ) , ! step . done ) ) { path = step . value ; if ( graph . type !== 'directed' ) { if ( rng ( ) < probability ) graph . addUndirectedEdge ( path [ 0 ] , path [ 1 ] ) ; } if ( graph . type !== 'undirected' ) { if ( rng ( ) < probability ) graph . addDirectedEdge ( path [ 0 ] , path [ 1 ] ) ; if ( rng ( ) < probability ) graph . addDirectedEdge ( path [ 1 ] , path [ 0 ] ) ; } } } return graph ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a binomial graph graph with n nodes using a faster algorithm for sparse graphs . [CODESPLIT] function erdosRenyiSparse ( GraphClass , options ) { if ( ! isGraphConstructor ( GraphClass ) ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid Graph constructor.' ) ; var order = options . order , probability = options . probability , rng = options . rng || Math . random ; var graph = new GraphClass ( ) ; // If user gave a size, we need to compute probability if ( typeof options . approximateSize === 'number' ) { var densityFunction = density [ graph . type + 'Density' ] ; probability = densityFunction ( order , options . approximateSize ) ; } if ( typeof order !== 'number' || order <= 0 ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid `order`. Should be a positive number.' ) ; if ( typeof probability !== 'number' || probability < 0 || probability > 1 ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid `probability`. Should be a number between 0 and 1. Or maybe you gave an `approximateSize` exceeding the graph\\'s density.' ) ; if ( typeof rng !== 'function' ) throw new Error ( 'graphology-generators/random/erdos-renyi: invalid `rng`. Should be a function.' ) ; for ( var i = 0 ; i < order ; i ++ ) graph . addNode ( i ) ; if ( probability <= 0 ) return graph ; var w = - 1 , lp = Math . log ( 1 - probability ) , lr , v ; if ( graph . type !== 'undirected' ) { v = 0 ; while ( v < order ) { lr = Math . log ( 1 - rng ( ) ) ; w += 1 + ( ( lr / lp ) | 0 ) ; // Avoiding self loops if ( v === w ) { w ++ ; } while ( v < order && order <= w ) { w -= order ; v ++ ; // Avoiding self loops if ( v === w ) w ++ ; } if ( v < order ) graph . addDirectedEdge ( v , w ) ; } } w = - 1 ; if ( graph . type !== 'directed' ) { v = 1 ; while ( v < order ) { lr = Math . log ( 1 - rng ( ) ) ; w += 1 + ( ( lr / lp ) | 0 ) ; while ( w >= v && v < order ) { w -= v ; v ++ ; } if ( v < order ) graph . addUndirectedEdge ( v , w ) ; } } return graph ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////// source generators /////////////////////////////////////////// [CODESPLIT] function generateBLEPayloadParser ( profileData ) { var outputSrc = \"\" ; log ( \" ***************************************************************************\" ) ; log ( \"    Generating JavaScript source file for BLE Payload parser \" ) ; log ( \" ***************************************************************************\" ) ; outputSrc = outputSrc + addLicenseText ( ) ; outputSrc = outputSrc + \"//\" + \"\\r\\n\" + \"//  PayloadParser.js\" + \"\\r\\n\" + \"//\" + \"\\r\\n\" + \"//  Autogenerated source\" + \"\\r\\n\" + \"//\" + \"\\r\\n\" + \"// ---------------------------------\" + \"\\r\\n\" + \"//  BLE Payload parser \" + \"\\r\\n\" + \"// ---------------------------------\" + \"\\r\\n\" + \"\\r\\n\" + \" 'use strict'\" + \"\\r\\n\" + \" var Int64LE = require('int64-buffer').Int64LE; \" + \"\\r\\n\" + \" import DLog from '../common/DLog'; \" + \"\\r\\n\" + \" const dp =require('./PayloadDefs'); \" + \"\\r\\n\" + \"\\r\\n\" ; for ( var x = 0 ; x < profileData . Services . length ; x ++ ) { var service = profileData . Services [ x ] ; var serviceNameStr = prepareSrcString ( service . Name ) ; var svcNameSnakeStr = prepareSrcStringAsSnakeCase ( service . Name ) ; for ( var y = 0 ; y < service . Characteristics . length ; y ++ ) { var characteristic = service . Characteristics [ y ] ; var characteristicNameStr = prepareSrcString ( characteristic . Name ) ; var characteristicNameSnakeStr = prepareSrcStringAsSnakeCase ( characteristic . Name ) ; var chr_json_filename = \"chr_\" + characteristicNameSnakeStr ; outputSrc = outputSrc + \"  var \" + chr_json_filename + \"_JSON = require('../device_services/profile/chr/\" + chr_json_filename + \"'); \" + \"\\r\\n\" + \"  var \" + chr_json_filename + \"_uuid = \" + chr_json_filename + \"_JSON.Characteristic.uuid; \" + \"\\r\\n\" + \"  if(\" + chr_json_filename + \"_JSON.Characteristic.Value != undefined ){  \" + \"\\r\\n\" + \"  \t\tvar \" + chr_json_filename + \"_format = \" + chr_json_filename + \"_JSON.Characteristic.Value.Field.Format; \" + \"\\r\\n\" + \"  } \" + \"\\r\\n\" ; } } outputSrc = outputSrc + \"\\r\\n\" + \" var nPayloadParserObjCnt = 0; \" + \"\\r\\n\" + \" var instancePayloadParser = null; \" + \"\\r\\n\" + \" const BLE_CHARC_VALUE_MAX_LEN = 20; \" + \"\\r\\n\" + \"\\r\\n\" + \" export function getPayloadParserInstance() \" + \"\\r\\n\" + \" { \" + \"\\r\\n\" + \"     if(nPayloadParserObjCnt > 0 ) \" + \"\\r\\n\" + \"     { \" + \"\\r\\n\" + \"          DLog.printDebugMsg('Its a singleton class, returning existing instance of PayloadParser class '); \" + \"\\r\\n\" + \"         return instancePayloadParser; \" + \"\\r\\n\" + \"     } \" + \"\\r\\n\" + \"      nPayloadParserObjCnt++; \" + \"\\r\\n\" + \"      DLog.printDebugMsg('PayloadParser Object Count is ' + nPayloadParserObjCnt); \" + \"\\r\\n\" + \"     instancePayloadParser = new PayloadParser(); \" + \"\\r\\n\" + \"     return instancePayloadParser; \" + \"\\r\\n\" + \" } \" + \"\\r\\n\" + \"\\r\\n\" + \" class PayloadParser  { \" + \"\\r\\n\" + \"     constructor(props){ \" + \"\\r\\n\" + \"     } \" + \"\\r\\n\" + \"\\r\\n\" + \"     parse(svc_class_name,args) \" + \"\\r\\n\" + \"     { \" + \"\\r\\n\" + \"         switch(args.characteristic) \" + \"\\r\\n\" + \"         {  \" + \"\\r\\n\" ; for ( var x = 0 ; x < profileData . Services . length ; x ++ ) { var service = profileData . Services [ x ] ; var serviceNameStr = prepareSrcString ( service . Name ) ; var svcNameSnakeStr = prepareSrcStringAsSnakeCase ( service . Name ) ; for ( var y = 0 ; y < service . Characteristics . length ; y ++ ) { var characteristic = service . Characteristics [ y ] ; var characteristicNameStr = prepareSrcString ( characteristic . Name ) ; var characteristicNameSnakeStr = prepareSrcStringAsSnakeCase ( characteristic . Name ) ; var chr_json_filename = \"chr_\" + characteristicNameSnakeStr ; var pkt_chr_name = \"pkt_\" + characteristicNameSnakeStr ; outputSrc = outputSrc + \"\t\t\t  case \" + chr_json_filename + \"_uuid.toUpperCase() : \" + \"\\r\\n\" + \"                 DLog.printDebug(this,' Characteristics format is = '+ \" + chr_json_filename + \"_format );\" + \"\\r\\n\" + \"                 if( \" + chr_json_filename + \"_format == 'uint8' || \" + \"\\r\\n\" + \"                    \" + chr_json_filename + \"_format == 'uint16' || \" + \"\\r\\n\" + \"                    \" + chr_json_filename + \"_format == 'uint32' || \" + \"\\r\\n\" + \"                    \" + chr_json_filename + \"_format == 'uint64') \" + \"\\r\\n\" + \"                 {\" + \"\\r\\n\" + \"                     let \" + pkt_chr_name + \" = {\" + \"\\r\\n\" + \"                         \" + characteristicNameStr + \" : {\" + \"\\r\\n\" + \"                             'FMT':' ',\" + \"\\r\\n\" + \"                         }\" + \"\\r\\n\" + \"                     }\" + \"\\r\\n\" + \"                     \" + pkt_chr_name + \".\" + characteristicNameStr + \".FMT = \" + chr_json_filename + \"_format;\" + \"\\r\\n\" + \"                     return this.parseDatapayloadPkt(args.value, \" + pkt_chr_name + \");\" + \"\\r\\n\" + \"                 }\" + \"\\r\\n\" + \"                 else\" + \"\\r\\n\" + \"                 {\" + \"\\r\\n\" + \"                     if(dp.\" + pkt_chr_name + \" != undefined) {\" + \"\\r\\n\" + \"                         return this.parseDatapayloadPkt(args.value,dp.\" + pkt_chr_name + \");\" + \"\\r\\n\" + \"                     }\" + \"\\r\\n\" + \"                     break;\" + \"\\r\\n\" + \"                 } \" + \"\\r\\n\" ; } } outputSrc = outputSrc + \"             default : \" + \"\\r\\n\" + \"                 return null; \" + \"\\r\\n\" + \"         } \" + \"\\r\\n\" + \"         return null; \" + \"\\r\\n\" + \"     } \" + \"\\r\\n\" + \"\\r\\n\" + \"     parseDatapayloadPkt(packetArr, datapayloadDef)\" + \"\\r\\n\" + \"     { \" + \"\\r\\n\" + \"         var packetBytBuf  = this.byteArray2DVByteBuffer(packetArr); \" + \"\\r\\n\" + \"         if(packetBytBuf === null) \" + \"\\r\\n\" + \"         { \" + \"\\r\\n\" + \"             DLog.printDebug(this,'packetBytBuf is NUll '); \" + \"\\r\\n\" + \"             return 'parse_error'; \" + \"\\r\\n\" + \"         } \" + \"\\r\\n\" + \"\\r\\n\" + \"         var datapayloadStruct =  {}; \" + \"\\r\\n\" + \"         var totaldatapayloadStructKeys =  Object.keys(datapayloadStruct).length; \" + \"\\r\\n\" + \"         var totaldatapayloadStructValues =  Object.values(datapayloadStruct).length; \" + \"\\r\\n\" + \"         var totalFields = Object.keys(datapayloadDef).length; \" + \"\\r\\n\" + \"\\r\\n\" + \"         DLog.printDebug(this,'total datapayload Fields =  ' + totalFields + \" + \"\\r\\n\" + \"                         ' /totaldatapayloadStructKeys =  ' + totaldatapayloadStructKeys  + \" + \"\\r\\n\" + \"                         ' /totaldatapayloadStructValues =  ' + totaldatapayloadStructValues ); \" + \"\\r\\n\" + \"\\r\\n\" + \"         for (var [keyFieldName, valueFieldDef] of Object.entries(datapayloadDef)) { \" + \"\\r\\n\" + \"             datapayloadStruct[keyFieldName] = this.extractData(packetBytBuf, valueFieldDef); \" + \"\\r\\n\" + \"         } \" + \"\\r\\n\" + \"\\r\\n\" + \"         totaldatapayloadStructKeys =  Object.keys(datapayloadStruct).length \" + \"\\r\\n\" + \"         totaldatapayloadStructValues =  Object.values(datapayloadStruct).length; \" + \"\\r\\n\" + \"\\r\\n\" + \"         DLog.printDebug(this,'/totaldatapayloadStructKeys =  ' + totaldatapayloadStructKeys  +  \" + \"\\r\\n\" + \"                         ' /totaldatapayloadStructValues =  ' + totaldatapayloadStructValues );  \" + \"\\r\\n\" + \"         DLog.printDebug(this,datapayloadStruct);  \" + \"\\r\\n\" + \"\\r\\n\" + \"         return datapayloadStruct;  \" + \"\\r\\n\" + \"     } \" + \"\\r\\n\" + \"\\r\\n\" + \"     extractData(payloadDataBytBuf, payloadDataFieldDef) \" + \"\\r\\n\" + \"     { \" + \"\\r\\n\" + \"         let dataPos = payloadDataFieldDef.POS || 0; \" + \"\\r\\n\" + \"         let dataType = payloadDataFieldDef.FMT || 'uint8'; \" + \"\\r\\n\" + \"         let dataLenInBytes = payloadDataFieldDef.LEN || 1; \" + \"\\r\\n\" + \"\\r\\n\" + \"         DLog.printDebug(this,' payloadDataFieldDef =  ' + dataPos + '/' + dataType + '/' + dataLenInBytes); \" + \"\\r\\n\" + \"\\r\\n\" + \"         switch (dataType) { \" + \"\\r\\n\" + \"             case 'uint8': \" + \"\\r\\n\" + \"                 return payloadDataBytBuf.getUint8(dataPos, true); // LITTLE_ENDIAN  \" + \"\\r\\n\" + \"             case 'uint16': \" + \"\\r\\n\" + \"                 return payloadDataBytBuf.getUint16(dataPos, true); \" + \"\\r\\n\" + \"             case 'uint32': \" + \"\\r\\n\" + \"                 return payloadDataBytBuf.getUint32(dataPos, true); \" + \"\\r\\n\" + \"             case 'uint64': \" + \"\\r\\n\" + \"                 return null; \" + \"\\r\\n\" + \"             case 'string_ascii': \" + \"\\r\\n\" + \"                 return this.extractStringData(payloadDataBytBuf, dataPos, dataLenInBytes) \" + \"\\r\\n\" + \"             default: \" + \"\\r\\n\" + \"                 return null; \" + \"\\r\\n\" + \"         } \" + \"\\r\\n\" + \"     } \" + \"\\r\\n\" + \"\\r\\n\" + \"     extractStringData(payloadDataBytBuf, keyvalueSeekPos, keyvalueLen) { \" + \"\\r\\n\" + \"         var keyvalueStr = ''; \" + \"\\r\\n\" + \"         if(keyvalueLen > BLE_CHARC_VALUE_MAX_LEN) \" + \"\\r\\n\" + \"         { \" + \"\\r\\n\" + \"             keyvalueLen = BLE_CHARC_VALUE_MAX_LEN; \" + \"\\r\\n\" + \"         } \" + \"\\r\\n\" + \"\\r\\n\" + \"         var keyvalueSeekPos = 0; \" + \"\\r\\n\" + \"         for(var m=0;m<keyvalueLen;m++) \" + \"\\r\\n\" + \"         { \" + \"\\r\\n\" + \"              var keyvaluebyte     = payloadDataBytBuf.getUint8(keyvalueSeekPos, true); \" + \"\\r\\n\" + \"              keyvalueStr = keyvalueStr + String.fromCharCode(keyvaluebyte); \" + \"\\r\\n\" + \"              DLog.printDebug(this, 'keyvalueStr= ' + keyvalueStr); \" + \"\\r\\n\" + \"              keyvalueSeekPos++; \" + \"\\r\\n\" + \"         } \" + \"\\r\\n\" + \"         DLog.printDebug(this, 'keyvalueStr= ' + keyvalueStr); \" + \"\\r\\n\" + \"         return keyvalueStr; \" + \"\\r\\n\" + \"      }\" + \"\\r\\n\" + \"\\r\\n\" + \"     byteArray2DVByteBuffer(byteArray) \" + \"\\r\\n\" + \"     { \" + \"\\r\\n\" + \"         var byteArrayLen = byteArray.length; \" + \"\\r\\n\" + \"\\r\\n\" + \"         if(byteArrayLen < 1) \" + \"\\r\\n\" + \"         { \" + \"\\r\\n\" + \"             DLog.printDebug(this,'packet byte arr size is zero = ' + byteArrayLen); \" + \"\\r\\n\" + \"             return null; \" + \"\\r\\n\" + \"         } \" + \"\\r\\n\" + \"\\r\\n\" + \"         DLog.printDebug(this,'packet byte arr size = ' + byteArrayLen); \" + \"\\r\\n\" + \"\\r\\n\" + \"         var objUint8Array   = new Uint8Array(new ArrayBuffer(byteArrayLen)); \" + \"\\r\\n\" + \"         objUint8Array.set(byteArray); \" + \"\\r\\n\" + \"\\r\\n\" + \"         var dvByteBuf  = new DataView(objUint8Array.buffer); \" + \"\\r\\n\" + \"         for(var m=0;m<byteArrayLen;m++) \" + \"\\r\\n\" + \"         { \" + \"\\r\\n\" + \"             DLog.printDebug(this,'DVByteBuf = ' + dvByteBuf.getUint8(m)); \" + \"\\r\\n\" + \"         } \" + \"\\r\\n\" + \"         return dvByteBuf; \" + \"\\r\\n\" + \"     } \" + \"\\r\\n\" + \"   } \" + \"\\r\\n\" ; FileManager . CreateFile ( \".\\\\protocols\\\\PayloadParser.js\" , outputSrc ) ; log ( \"PayloadParser.js generated sucessfully\t\" ) ; log ( \" ---------------------------------------------------------------------\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "class Cli / //////////////////////// [CODESPLIT] function validateFiles ( files , stateLint ) { let ok = true for ( const file of files ) { try { ok = validate ( file , stateLint ) && ok } catch ( err ) { console . log ( ` ${ file } \\n \\t ${ err . message } ` ) ok = false } } // for ... return ok }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "validateFiles [CODESPLIT] function validate ( file , stateLint ) { const json = readAndParse ( file ) const problems = stateLint . validate ( json ) if ( problems . length ) { console . log ( ` ${ file } ` ) problems . forEach ( p => console . log ( ` \\t ${ p } ` ) ) } return ( problems . length === 0 ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "readlines [CODESPLIT] function showIfHelp ( args , description ) { const name = path . basename ( args [ 1 ] ) const opts = args . slice ( 2 ) if ( ! ( opts . length === 1 && [ '--help' , '-h' , '-?' ] . includes ( opts [ 0 ] ) ) ) { return false } console . log ( ` ${ name } ` ) console . log ( '' ) console . log ( description ) return true }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adjusts an axis default range [ h () + 1 1 ] if a NullValueSeparator is set [CODESPLIT] function getRange ( ) { if ( __ . nullValueSeparator == \"bottom\" ) { return [ h ( ) + 1 - __ . nullValueSeparatorPadding . bottom - __ . nullValueSeparatorPadding . top , 1 ] ; } else if ( __ . nullValueSeparator == \"top\" ) { return [ h ( ) + 1 , 1 + __ . nullValueSeparatorPadding . bottom + __ . nullValueSeparatorPadding . top ] ; } return [ h ( ) + 1 , 1 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "draw single cubic bezier curve [CODESPLIT] function single_curve ( d , ctx ) { var centroids = compute_centroids ( d ) ; var cps = compute_control_points ( centroids ) ; ctx . moveTo ( cps [ 0 ] . e ( 1 ) , cps [ 0 ] . e ( 2 ) ) ; for ( var i = 1 ; i < cps . length ; i += 3 ) { if ( __ . showControlPoints ) { for ( var j = 0 ; j < 3 ; j ++ ) { ctx . fillRect ( cps [ i + j ] . e ( 1 ) , cps [ i + j ] . e ( 2 ) , 2 , 2 ) ; } } ctx . bezierCurveTo ( cps [ i ] . e ( 1 ) , cps [ i ] . e ( 2 ) , cps [ i + 1 ] . e ( 1 ) , cps [ i + 1 ] . e ( 2 ) , cps [ i + 2 ] . e ( 1 ) , cps [ i + 2 ] . e ( 2 ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "draw single polyline [CODESPLIT] function color_path ( d , ctx ) { ctx . beginPath ( ) ; if ( ( __ . bundleDimension !== null && __ . bundlingStrength > 0 ) || __ . smoothness > 0 ) { single_curve ( d , ctx ) ; } else { single_path ( d , ctx ) ; } ctx . stroke ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "draw many polylines of the same color [CODESPLIT] function paths ( data , ctx ) { ctx . clearRect ( - 1 , - 1 , w ( ) + 2 , h ( ) + 2 ) ; ctx . beginPath ( ) ; data . forEach ( function ( d ) { if ( ( __ . bundleDimension !== null && __ . bundlingStrength > 0 ) || __ . smoothness > 0 ) { single_curve ( d , ctx ) ; } else { single_path ( d , ctx ) ; } } ) ; ctx . stroke ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function can be used for live updates of brushes . That is during the specification of a brush this method can be called to update the view . [CODESPLIT] function brushUpdated ( newSelection ) { __ . brushed = newSelection ; events . brush . call ( pc , __ . brushed ) ; pc . renderBrushed ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "data within extents [CODESPLIT] function selected ( ) { var actives = d3 . keys ( __ . dimensions ) . filter ( is_brushed ) , extents = actives . map ( function ( p ) { return brushes [ p ] . extent ( ) ; } ) ; // We don't want to return the full data set when there are no axes brushed. // Actually, when there are no axes brushed, by definition, no items are // selected. So, let's avoid the filtering and just return false. //if (actives.length === 0) return false; // Resolves broken examples for now. They expect to get the full dataset back from empty brushes if ( actives . length === 0 ) return __ . data ; // test if within range var within = { \"date\" : function ( d , p , dimension ) { if ( typeof __ . dimensions [ p ] . yscale . rangePoints === \"function\" ) { // if it is ordinal return extents [ dimension ] [ 0 ] <= __ . dimensions [ p ] . yscale ( d [ p ] ) && __ . dimensions [ p ] . yscale ( d [ p ] ) <= extents [ dimension ] [ 1 ] } else { return extents [ dimension ] [ 0 ] <= d [ p ] && d [ p ] <= extents [ dimension ] [ 1 ] } } , \"number\" : function ( d , p , dimension ) { if ( typeof __ . dimensions [ p ] . yscale . rangePoints === \"function\" ) { // if it is ordinal return extents [ dimension ] [ 0 ] <= __ . dimensions [ p ] . yscale ( d [ p ] ) && __ . dimensions [ p ] . yscale ( d [ p ] ) <= extents [ dimension ] [ 1 ] } else { return extents [ dimension ] [ 0 ] <= d [ p ] && d [ p ] <= extents [ dimension ] [ 1 ] } } , \"string\" : function ( d , p , dimension ) { return extents [ dimension ] [ 0 ] <= __ . dimensions [ p ] . yscale ( d [ p ] ) && __ . dimensions [ p ] . yscale ( d [ p ] ) <= extents [ dimension ] [ 1 ] } } ; return __ . data . filter ( function ( d ) { switch ( brush . predicate ) { case \"AND\" : return actives . every ( function ( p , dimension ) { return within [ __ . dimensions [ p ] . type ] ( d , p , dimension ) ; } ) ; case \"OR\" : return actives . some ( function ( p , dimension ) { return within [ __ . dimensions [ p ] . type ] ( d , p , dimension ) ; } ) ; default : throw new Error ( \"Unknown brush predicate \" + __ . brushPredicate ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the first dimension is directly left of the second dimension . [CODESPLIT] function consecutive ( first , second ) { var length = d3 . keys ( __ . dimensions ) . length ; return d3 . keys ( __ . dimensions ) . some ( function ( d , i ) { return ( d === first ) ? i + i < length && __ . dimensions [ i + 1 ] === second : false ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "function brushExtents () { var extents = {} ; d3 . keys ( __ . dimensions ) . forEach ( function ( d ) { var brush = brushes [ d ] ; if ( brush ! == undefined && !brush . empty () ) { var extent = brush . extent () ; extents [ d ] = extent ; } } ) ; return extents ; } [CODESPLIT] function brushFor ( axis ) { var brush = d3 . svg . multibrush ( ) ; brush . y ( __ . dimensions [ axis ] . yscale ) . on ( \"brushstart\" , function ( ) { if ( d3 . event . sourceEvent !== null ) { events . brushstart . call ( pc , __ . brushed ) ; d3 . event . sourceEvent . stopPropagation ( ) ; } } ) . on ( \"brush\" , function ( ) { brushUpdated ( selected ( ) ) ; } ) . on ( \"brushend\" , function ( ) { // d3.svg.multibrush clears extents just before calling 'brushend' // so we have to update here again. // This fixes issue #103 for now, but should be changed in d3.svg.multibrush // to avoid unnecessary computation. brushUpdated ( selected ( ) ) ; events . brushend . call ( pc , __ . brushed ) ; } ) . extentAdaption ( function ( selection ) { selection . style ( \"visibility\" , null ) . attr ( \"x\" , - 15 ) . attr ( \"width\" , 30 ) . style ( \"fill\" , \"rgba(255,255,255,0.25)\" ) . style ( \"stroke\" , \"rgba(0,0,0,0.6)\" ) ; } ) . resizeAdaption ( function ( selection ) { selection . selectAll ( \"rect\" ) . attr ( \"x\" , - 15 ) . attr ( \"width\" , 30 ) . style ( \"visibility\" , null ) . style ( \"fill\" , \"rgba(0,0,0,0.1)\" ) ; } ) ; brushes [ axis ] = brush ; return brush ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ 0 2 * PI ] - > [ - PI / 2 PI / 2 ] [CODESPLIT] function ( angle ) { var ret = angle ; if ( angle > Math . PI ) { ret = angle - 1.5 * Math . PI ; ret = angle - 1.5 * Math . PI ; } else { ret = angle - 0.5 * Math . PI ; ret = angle - 0.5 * Math . PI ; } return - ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "current iteration [CODESPLIT] function ( data ) { if ( data ) rq . data ( data ) ; rq . invalidate ( ) ; _clear ( ) ; rq . render ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logically converts a property and its value based on the flow direction context [CODESPLIT] function convertProperty ( originalKey , originalValue , isRtl ) { const key = getPropertyDoppelganger ( originalKey , isRtl ) const value = getValueDoppelganger ( key , originalValue , isRtl ) return { key , value } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logically gets the direction of the given property based on the flow direction context [CODESPLIT] function getPropertyDoppelganger ( property , isRtl ) { const convertedProperty = isRtl ? propertiesToConvert . rtl [ property ] : propertiesToConvert . ltr [ property ] return convertedProperty || property }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "let s try to keep the complexity down ... If we have to do this much more let s break this up / * eslint - disable complexity Logically converts the given value to the correct version based on the key and flow direction context [CODESPLIT] function getValueDoppelganger ( key , originalValue , isRtl ) { if ( isNullOrUndefined ( originalValue ) ) { return originalValue } const flowDirection = isRtl ? 'rtl' : 'ltr' if ( isObject ( originalValue ) ) { return convert ( originalValue , flowDirection ) // recurssion 🌀 } const { isLogical , logicallessValue , isImportant , importantlessValue , } = analyzeOriginalValue ( originalValue ) if ( canHaveLogical . includes ( key ) && ! isLogical ) { return originalValue } const isFourDirectionalShorthand = includes ( [ 'margin' , 'padding' , 'borderColor' , 'borderRadius' , 'borderStyle' , 'borderWidth' , ] , key , ) if ( isLogical && ! isRtl && ! isFourDirectionalShorthand && ! key . match ( / (background)|((t|T)ransformOrigin) / ) ) { return logicallessValue } const conversionMap = valuesToConvert [ flowDirection ] // The logical props and values changes the default way you write four-directional shorhands // so that the order of values is `block-start`, `inline-start`, `block-end` and `inline-end`, which, // for the `inline-*` sides, is the opposite of how they are written without the `logical` keyword if ( isLogical && isFourDirectionalShorthand ) { return isRtl ? logicallessValue : convertValues ( key , importantlessValue , conversionMap , isImportant , // Reversing `isRtl` like this is crooked, but for the time being, it is the easiest way to // address how values of four-directional shorthand properties with the `logical` keyword // should be handled according to the spec. ! isRtl , ) } return convertValues ( key , importantlessValue , conversionMap , isImportant , isRtl , ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * eslint - enable complexity [CODESPLIT] function analyzeOriginalValue ( originalValue ) { const isNum = isNumber ( originalValue ) const logicallessValue = isNum ? originalValue : originalValue . replace ( / ^\\s*logical\\s* / i , '' ) const isLogical = ! isNum && logicallessValue . length !== originalValue . length const importantlessValue = isNum ? logicallessValue : logicallessValue . replace ( / \\s*!important.*?$ / , '' ) const isImportant = ! isNum && importantlessValue . length !== logicallessValue . length return { isLogical , logicallessValue , isImportant , importantlessValue } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DirWatcher code adapted from Jeffrey Lin s original implementation : https : // github . com / jeffreylin / jsx_transformer_fun / blob / master / dirWatcher . js [CODESPLIT] function DirWatcher ( inputPath , persistent ) { assert . ok ( this instanceof DirWatcher ) ; var self = this ; var absPath = path . resolve ( inputPath ) ; if ( ! fs . statSync ( absPath ) . isDirectory ( ) ) { throw new Error ( inputPath + \"is not a directory!\" ) ; } EventEmitter . call ( self ) ; self . ready = false ; self . on ( \"ready\" , function ( ) { self . ready = true ; } ) ; Object . defineProperties ( self , { // Map of absDirPaths to fs.FSWatcher objects from fs.watch(). watchers : { value : { } } , dirContents : { value : { } } , rootPath : { value : absPath } , persistent : { value : ! ! persistent } } ) ; process . nextTick ( function ( ) { self . add ( absPath ) ; self . emit ( \"ready\" ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Content constructor takes an options object which * must * have either a body or data property and * may * have a type property indicating the media type . If there is no type attribute a default will be inferred . [CODESPLIT] function ( options ) { this . body = options . body ; this . data = options . data ; this . type = options . type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initialize the routes that the Express Application will serve [CODESPLIT] function init ( app , context , swagger ) { logger . log ( 'debug' , '%s|adding|routes|context=%s' + ( swagger ? \"|SWAGGER\" : \"\" ) , meta . module , context , meta ) ; if ( swagger ) { describeModels ( swagger ) ; swagger . addGET ( { 'spec' : { \"description\" : \"Text To Speech REST API\" , \"path\" : context + format + '/play/{voice}/{text}' , \"notes\" : \"The REST API /play/ transform a text phrase into a spoken audio stream playable through an HTML5 <audio> element. You can pre-generate the audio by calling the REST API /generate/ before calling this one, to have the audio start playing as soon as you call the /play/ API.\" , \"method\" : \"GET\" , \"summary\" : \"Transform a text phrase into an Audio Stream.\" , \"nickname\" : \"play\" , \"responseClass\" : \"BinaryAudioStream\" , \"produces\" : [ \"audio/mp4\" , \"application/json\" ] , \"params\" : [ swagger . params . path ( \"voice\" , \"A 'human' voice to use, to speak the phrase\" , \"string\" , { \"values\" : voices , \"valueType\" : \"LIST\" } , \"Alex\" ) , swagger . params . path ( \"text\" , \"The text phrase to be spoken.\" , \"string\" ) ] , \"errorResponses\" : [ fix ( swagger . errors . notFound ( 'voice' ) ) , fix ( swagger . errors . notFound ( 'text' ) ) , fix ( swagger . errors . invalid ( 'voice' ) ) ] } , 'action' : function ( req , res ) { logger . log ( 'debug' , '%s|say|voice=%s|text=%s' , meta . module , req . params . voice , req . params . text , meta ) ; if ( voices . indexOf ( req . params . voice ) < 0 ) { swagger . stopWithError ( res , { code : 400 , reason : 'The voice ' + req . params . voice + ' is not supported' } ) ; return ; } tts . play ( req . param ( 'text' , 'No text passed' ) , req . param ( 'voice' , voice ) , function ( err , data ) { if ( err ) { if ( ! err . code || ! err . reason ) err = { code : 500 , reason : util . inspect ( err ) } ; swagger . stopWithError ( res , err ) ; } else { res . writeHead ( 200 , { 'Content-Type' : 'audio/mp4' } ) ; res . end ( data ) ; } } ) ; } } ) . addPost ( { 'spec' : { \"description\" : \"Text To Speech REST API\" , \"path\" : context + format + '/generate' , \"notes\" : \"To avoid latency, when using the REST API /play/, you can pre-generate the audio on the server by calling this API.\" , \"method\" : \"POST\" , \"summary\" : \"Generate the audio on the server.\" , \"nickname\" : \"generate\" , \"responseClass\" : \"Status\" , \"params\" : [ swagger . params . body ( \"params\" , \"The text phrase to be pre-generated on the server\" , 'TextToSpeech' , '{\"voice\" : \"Alex\", \"text\":\"Hello world\", \"async\" : true}' ) ] , \"errorResponses\" : [ fix ( swagger . errors . notFound ( 'voice' ) ) , fix ( swagger . errors . notFound ( 'text' ) ) , fix ( swagger . errors . invalid ( 'voice' ) ) , fix ( swagger . errors . invalid ( 'async' ) ) ] } , 'action' : function ( req , res ) { if ( ! req . body ) { swagger . stopWithError ( res , { code : 400 , reason : 'The BODY of the request is empty' } ) ; return ; } logger . log ( 'debug' , '%s|generate|voice=%s|text=%s|async=%s' , meta . module , req . body . voice , req . body . text , req . body . async , meta ) ; if ( voices . indexOf ( req . body . voice ) < 0 ) { swagger . stopWithError ( res , { code : 400 , reason : 'The voice ' + req . params . voice + ' is not supported' } ) ; return ; } var async ; if ( typeof req . body . async != 'undefined' ) { if ( req . body . async === true || req . body . async === 'true' ) { async = true ; } else if ( req . body . async === false || req . body . async === 'false' ) { async = false ; } else { swagger . stopWithError ( res , { code : 400 , reason : 'The async must be true or false' } ) ; return ; } } else async = false ; tts . play ( req . param ( 'text' , 'No text passed' ) , req . param ( 'voice' , voice ) , function ( err ) { if ( async === false ) { if ( err ) { if ( ! err . code || ! err . reason ) err = { code : 500 , reason : util . inspect ( err ) } ; swagger . stopWithError ( res , err ) ; } else { res . writeHead ( 200 , { 'Content-Type' : 'application/json' } ) ; res . end ( '{\"result\":\"OK\",\"async\":false}' ) ; } } } ) ; if ( async ) { res . writeHead ( 200 , { 'Content-Type' : 'application/json' } ) ; res . end ( '{\"result\":\"OK\",\"async\":true}' ) ; } } } ) ; } else { router . add ( app , context + '/tts.json/play' , 'GET' , function ( req , res ) { tts . play ( req . param ( 'text' , 'No text passed' ) , req . param ( 'voice' , voice ) , function ( err , data ) { if ( err ) { res . writeHead ( 404 , { \"Content-Type\" : \"text/html\" } ) ; res . end ( '<html><body><pre>Unable to generate tts <br/>\\n' + err + '</pre></body></html>' ) ; } else { res . writeHead ( 200 , { 'Content-Type' : 'audio/mp4' } ) ; res . end ( data ) ; } } ) ; } ) ; router . add ( app , context + '/tts.json/generate' , 'POST' , function ( req , res ) { var async = req . param ( 'async' , 'true' ) === 'true' ? true : false ; tts . play ( req . param ( 'text' , 'No text passed' ) , req . param ( 'voice' , voice ) , function ( err ) { if ( async === false ) { if ( err ) { res . writeHead ( 404 , { 'Content-Type' : 'application/json' } ) ; res . end ( '{\"result\":\"FAILED\",\"async\":false,\"error\":' + JSON . stringify ( err ) + '}' ) ; } else { res . writeHead ( 200 , { 'Content-Type' : 'application/json' } ) ; res . end ( '{\"result\":\"OK\",\"async\":false}' ) ; } } } ) ; if ( async ) { res . writeHead ( 200 , { 'Content-Type' : 'application/json' } ) ; res . end ( '{\"result\":\"OK\",\"async\":true}' ) ; } } ) ; } tts . init ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ReadFileCache is an EventEmitter subclass that caches file contents in memory so that subsequent calls to readFileP return the same contents regardless of any changes in the underlying file . [CODESPLIT] function ReadFileCache ( sourceDir , charset ) { assert . ok ( this instanceof ReadFileCache ) ; assert . strictEqual ( typeof sourceDir , \"string\" ) ; this . charset = charset ; EventEmitter . call ( this ) ; Object . defineProperties ( this , { sourceDir : { value : sourceDir } , sourceCache : { value : { } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch the resource and call done when it is fetched [CODESPLIT] function done ( err , resource ) { totalRequestElapsed += ( ( new Date ( ) . getTime ( ) ) - started ) ; ++ totalRequests ; stats . avgFetchTime = parseInt ( totalRequestElapsed / totalRequests ) ; if ( err || verbose ) util . log ( 'cache|execute|done|err=' + err + '|result=' + ( resource ? 'found' : 'null' ) ) ; if ( err ) { ++ stats . failed ; } if ( ! err && defaultCacheTTL ) { // ttl ===  0 --> expire imediatly. if ( stats . inCache >= defaultCacheSize ) { weedOutCache ( ) ; } var now = new Date ( ) . getTime ( ) ; resourceCache [ key ] = { 'key' : key , 'epoch' : now , 'access' : now , 'expire' : defaultCacheTTL , 'hits' : 0 , 'data' : resource } ; ++ stats . inCache ; } var pendingRequests = requestQueue [ key ] ; delete requestQueue [ key ] ; for ( var i = 0 , size = pendingRequests . length ; i < size ; ++ i ) { if ( debug ) util . log ( 'cache|calling=' + i + '|err=' + err + '|resource=' + ( resource ? 'found' : 'null' ) ) ; if ( ! err && defaultCacheTTL ) { ++ resourceCache [ key ] . hits ; } pendingRequests [ i ] . call ( this , err , resource , resourceCache [ key ] ) ; -- stats . waiting ; } -- stats . fetching ; if ( stats . fetching === 0 && stats . waiting === 0 ) { self . emit ( 'stats' , stats ) ; } else { bufferedEmitter . call ( self , 'stats' , stats ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////// PUBLIC CLASS ////////////////////////////////// [CODESPLIT] function Cache ( size , ttl ) { defaultCacheSize = size || defaultCacheSize ; defaultCacheTTL = ttl || defaultCacheTTL ; if ( verbose ) util . log ( 'Cache|defaultCacheSize=' + defaultCacheSize + '|defaultCacheTTL=' + defaultCacheTTL ) ; if ( defaultCacheSize > 10000 ) { util . log ( 'Cache|WARNING|Weeding out a BIG (' + defaultCacheSize + ') cache when it is full can degrade the NODE server performance since it is not async' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents an instance of a gogs api [CODESPLIT] function API ( apiUrl , requester ) { var _this = this ; _this . apiUrl = apiUrl ; // Dependency injection. Allow a custom request module. var request = requester ? requester ( apiUrl ) : Requester ( apiUrl ) ; /**\n   * Creates a new user account\n   * @param user {object} the user to be created. Requires username, email, password\n   * @param authUser {object} the user authenticating this request. Requires token or username and password\n   * @param notify {boolean} send notification email to user\n   * @return {Promise<object>} the newly created user\n   */ _this . createUser = function ( user , authUser , notify ) { user . send_notify = notify ; return request ( 'admin/users' , authUser , user ) . then ( stat . checkCreatedResponse ) ; } ; /**\n   * Edits the details on an existing user account\n   * @param user {object} the user who's information will be updated. Requires username (note: the username cannot be changed)\n   * @param authUser {object} the user authenticating this request. Requires token or username and password\n   * @returns {Promise<object>} the updated user object\n     */ _this . editUser = function ( user , authUser ) { return request ( 'admin/users/' + user . username , authUser , user , 'PATCH' ) . then ( stat . checkStandardResponse ) ; } ; /**\n   * Deletes a user\n   * @param user {object} the user to delete. Requires username\n   * @param authUser {object} the user authenticating this request. Users cannot delete themselves. Requires token or username and password\n   * @returns {Promise} resolves if successful\n   */ _this . deleteUser = function ( user , authUser ) { if ( user . username === authUser . username ) { return Promise . reject ( 'Users cannot delete themselves!' ) ; } return request ( 'admin/users/' + user . username , authUser , null , 'DELETE' ) . then ( stat . checkNoContentResponse ) ; } ; /**\n   * Searches for users that match the query\n   * @param query {string}\n   * @param limit {int} the maximum number of results to return\n   * @param authUser {object} the user authenticating this request. If null the email fields will be empty in the result. Requires token or username and password\n   * @returns {Promise<array>} an array of user objects\n   */ _this . searchUsers = function ( query , limit , authUser ) { limit = limit || 10 ; // no zero limit allowed return request ( 'users/search?q=' + query + '&limit=' + limit , authUser ) . then ( stat . checkOkResponse ) ; } ; /**\n   * Retrieves a user\n   * @param user {object} the user to retrieve. Requires username\n   * @param authUser {object} the user to authenticate as. If null the email field in the response will be empty. Requires token or username and password\n   * @returns {Promise<object>} the found user object\n   */ _this . getUser = function ( user , authUser ) { return request ( 'users/' + user . username , authUser ) . then ( stat . checkStandardResponse ) ; } ; /**\n   * Searches for public repositories that match the query\n   * @param query {string}\n   * @param uid {int} the id of the user whose repositories will be searched. 0 will search all\n   * @param limit {int} the maximum number of results to return\n   * @returns {Promise<array>} an array of repository objects\n   */ _this . searchRepos = function ( query , uid , limit ) { uid = uid || 0 ; limit = limit || 10 ; return request ( 'repos/search?q=' + query + '&uid=' + uid + '&limit=' + limit ) . then ( stat . checkOkResponse ) ; } ; /**\n   * Creates a new repository for the user\n   * @param repo {object} the repository being created. Requires name, description, private\n   * @param user {object} the user creating the repository. Requires token or username and password\n   * @returns {Promise<object>} the new repository object\n     */ _this . createRepo = function ( repo , user ) { return request ( 'user/repos' , user , { name : repo . name , description : repo . description , private : repo . private } , null ) . then ( stat . checkCreatedResponse ) ; } ; /**\n   * Returns information about a single repository\n   * @param repo {object} the repository that will be retrieved. Requires full_name\n   * @param authUser {object} the user authenticating this request. Requires username, password or token\n   * @returns {Promise<object>} the repository object\n   */ _this . getRepo = function ( repo , authUser ) { return request ( 'repos/' + repo . full_name , authUser ) . then ( stat . checkStandardResponse ) ; } ; /**\n   * Returns an array of repositories this user has access to\n   * @param user {object} the user who's repositories will be listed. Requires token or username and password\n   * @returns {Promise<array>} an array of repository objects\n   */ _this . listRepos = function ( user ) { return request ( 'user/repos' , user ) . then ( stat . checkStandardResponse ) ; } ; /**\n   * Deletes a repository from the user\n   * @param repo {object} the repository to delete. Requires name\n   * @param user {object} the user that owns the repository. Requires token or username and password\n   * @returns {Promise} resolves if successful\n   */ _this . deleteRepo = function ( repo , user ) { return request ( 'repos/' + user . username + '/' + repo . name , user , null , 'DELETE' ) . then ( stat . checkNoContentResponse ) ; } ; /**\n   * Creates an authentication token for the user\n   * @param token {object} the token to be created. Requires name\n   * @param user {object} the user creating the token. Requires username, token or password\n   * @returns {Promise<object>} the new token object\n   */ _this . createToken = function ( token , user ) { return request ( 'users/' + user . username + '/tokens' , user , { name : token . name } ) . then ( stat . checkCreatedResponse ) ; } ; /**\n   * Returns an array of tokens the user has\n   * @param user {object} the user who's tokens will be listed. Requires username, password\n   * @returns {Promise<array>} an array of token objects\n   */ _this . listTokens = function ( user ) { return request ( 'users/' + user . username + '/tokens' , user ) . then ( stat . checkStandardResponse ) ; } ; /**\n   * Creates a public key for the user\n   * @param key {object} the key to be created. Requires title, key\n   * @param user {object} the user creating the key. Requires token or username and password\n   * @returns {Promise<object>} the new public key object\n   */ _this . createPublicKey = function ( key , user ) { return request ( 'user/keys' , user , { title : key . title , key : key . key } ) . then ( stat . checkCreatedResponse ) ; } ; /**\n   * Returns an array of public keys that belong to the user\n   * @param user {object} the user who's public keys will be listed. Requires username, token or password\n   * @returns {Promise<array>} an array of public key objects\n   */ _this . listPublicKeys = function ( user ) { return request ( 'users/' + user . username + '/keys' , user ) . then ( stat . checkStandardResponse ) ; } ; /**\n   * Returns the full details for a public key\n   * @param key {object} the key that will be retrieved. Requires id\n   * @param user {object} the user who's key will be retrieved. Requires token or username and password\n   * @returns {Promise<object>} the public key object\n   */ _this . getPublicKey = function ( key , user ) { return request ( 'user/keys/' + key . id , user ) . then ( stat . checkStandardResponse ) ; } ; /**\n   * Deletes a public key from the user\n   * @param key {object} the key to be deleted. Requires id\n   * @param user {object} the user who's key will be deleted. Requires token or username and password\n   * @returns {Promise} resolves if successful\n     */ _this . deletePublicKey = function ( key , user ) { return request ( 'user/keys/' + key . id , user , null , 'DELETE' ) . then ( stat . checkNoContentResponse ) ; } ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper that sorts by length giving priority to ones that start with ATG / AUG [CODESPLIT] function sortReadingFrames ( a , b ) { var aSort = a . length var bSort = b . length if ( bSort - aSort === 0 ) { var aStartCodon = a . slice ( 0 , 3 ) . toUpperCase ( ) . replace ( 'T' , 'U' ) var bStartCodon = b . slice ( 0 , 3 ) . toUpperCase ( ) . replace ( 'T' , 'U' ) if ( aStartCodon === 'AUG' ) { aSort ++ } if ( bStartCodon === 'AUG' ) { bSort ++ } } return bSort - aSort }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shred takes some options including a logger and request defaults . [CODESPLIT] function ( options ) { options = ( options || { } ) ; this . agent = options . agent ; this . defaults = options . defaults || { } ; this . log = options . logger || ( new Ax ( { level : \"info\" } ) ) ; this . _sharedCookieJar = new CookieJar ( ) ; this . logCurl = options . logCurl || false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this is a quick - and - dirty logger . there are other nicer loggers out there but the ones i found were also somewhat involved . this one has a Ruby logger type interface we can easily replace this provide the info debug etc . methods are the same . or we can change Haiku to use a more standard node . js interface [CODESPLIT] function ( level , message ) { var debug = ( level == \"debug\" || level == \"error\" ) ; if ( ! message ) { return message . toString ( ) ; } if ( typeof ( message ) == \"object\" ) { if ( message instanceof Error && debug ) { return message . stack ; } else { return inspect ( message ) ; } } else { return message . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Shred object itself constructs the Request object . You should rarely need to do this directly . [CODESPLIT] function ( options ) { this . log = options . logger ; this . cookieJar = options . cookieJar ; this . encoding = options . encoding ; this . logCurl = options . logCurl ; processOptions ( this , options || { } ) ; createRequest ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "in milliseconds [CODESPLIT] function ( timeout ) { var request = this , milliseconds = 0 ; ; if ( ! timeout ) return this ; if ( typeof timeout === \"number\" ) { milliseconds = timeout ; } else { milliseconds = ( timeout . milliseconds || 0 ) + ( 1000 * ( ( timeout . seconds || 0 ) + ( 60 * ( ( timeout . minutes || 0 ) + ( 60 * ( timeout . hours || 0 ) ) ) ) ) ) ; } this . _timeout = milliseconds ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "processOptions is called from the constructor to handle all the work associated with making sure we do our best to ensure we have a valid request . [CODESPLIT] function ( request , options ) { request . log . debug ( \"Processing request options ..\" ) ; // We'll use `request.emitter` to manage the `on` event handlers. request . emitter = ( new Emitter ) ; request . agent = options . agent ; // Set up the handlers ... if ( options . on ) { for ( var key in options . on ) { if ( options . on . hasOwnProperty ( key ) ) { request . emitter . on ( key , options . on [ key ] ) ; } } } // Make sure we were give a URL or a host if ( ! options . url && ! options . host ) { request . emitter . emit ( \"request_error\" , new Error ( \"No url or url options (host, port, etc.)\" ) ) ; return ; } // Allow for the [use of a proxy](http://www.jmarshall.com/easy/http/#proxies). if ( options . url ) { if ( options . proxy ) { request . url = options . proxy ; request . path = options . url ; } else { request . url = options . url ; } } // Set the remaining options. request . query = options . query || options . parameters || request . query ; request . method = options . method ; request . setHeader ( \"user-agent\" , options . agent || \"Shred\" ) ; request . setHeaders ( options . headers ) ; if ( request . cookieJar ) { var cookies = request . cookieJar . getCookies ( CookieAccessInfo ( request . host , request . path ) ) ; if ( cookies . length ) { var cookieString = request . getHeader ( 'cookie' ) || '' ; for ( var cookieIndex = 0 ; cookieIndex < cookies . length ; ++ cookieIndex ) { if ( cookieString . length && cookieString [ cookieString . length - 1 ] != ';' ) { cookieString += ';' ; } cookieString += cookies [ cookieIndex ] . name + '=' + cookies [ cookieIndex ] . value + ';' ; } request . setHeader ( \"cookie\" , cookieString ) ; } } // The content entity can be set either using the `body` or `content` attributes. if ( options . body || options . content ) { request . content = options . body || options . content ; } request . timeout = options . timeout ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "createRequest is also called by the constructor after processOptions . This actually makes the request and processes the response so createRequest is a bit of a misnomer . [CODESPLIT] function ( request ) { var timeout ; request . log . debug ( \"Creating request ..\" ) ; request . log . debug ( request ) ; var reqParams = { host : request . host , port : request . port , method : request . method , path : request . path + ( request . query ? '?' + request . query : \"\" ) , headers : request . getHeaders ( ) , // Node's HTTP/S modules will ignore this, but we are using the // browserify-http module in the browser for both HTTP and HTTPS, and this // is how you differentiate the two. scheme : request . scheme , // Use a provided agent.  'Undefined' is the default, which uses a global // agent. agent : request . agent } ; if ( request . logCurl ) { logCurl ( request ) ; } var http = request . scheme == \"http\" ? HTTP : HTTPS ; // Set up the real request using the selected library. The request won't be // sent until we call `.end()`. request . _raw = http . request ( reqParams , function ( response ) { request . log . debug ( \"Received response ..\" ) ; // We haven't timed out and we have a response, so make sure we clear the // timeout so it doesn't fire while we're processing the response. clearTimeout ( timeout ) ; // Construct a Shred `Response` object from the response. This will stream // the response, thus the need for the callback. We can access the response // entity safely once we're in the callback. response = new Response ( response , request , function ( response ) { // Set up some event magic. The precedence is given first to // status-specific handlers, then to responses for a given event, and then // finally to the more general `response` handler. In the last case, we // need to first make sure we're not dealing with a a redirect. var emit = function ( event ) { var emitter = request . emitter ; var textStatus = STATUS_CODES [ response . status ] ? STATUS_CODES [ response . status ] . toLowerCase ( ) : null ; if ( emitter . listeners ( response . status ) . length > 0 || emitter . listeners ( textStatus ) . length > 0 ) { emitter . emit ( response . status , response ) ; emitter . emit ( textStatus , response ) ; } else { if ( emitter . listeners ( event ) . length > 0 ) { emitter . emit ( event , response ) ; } else if ( ! response . isRedirect ) { emitter . emit ( \"response\" , response ) ; //console.warn(\"Request has no event listener for status code \" + response.status); } } } ; // Next, check for a redirect. We simply repeat the request with the URL // given in the `Location` header. We fire a `redirect` event. if ( response . isRedirect ) { request . log . debug ( \"Redirecting to \" + response . getHeader ( \"Location\" ) ) ; request . url = response . getHeader ( \"Location\" ) ; emit ( \"redirect\" ) ; createRequest ( request ) ; // Okay, it's not a redirect. Is it an error of some kind? } else if ( response . isError ) { emit ( \"error\" ) ; } else { // It looks like we're good shape. Trigger the `success` event. emit ( \"success\" ) ; } } ) ; } ) ; // We're still setting up the request. Next, we're going to handle error cases // where we have no response. We don't emit an error event because that event // takes a response. We don't response handlers to have to check for a null // value. However, we [should introduce a different event // type](https://github.com/spire-io/shred/issues/3) for this type of error. request . _raw . on ( \"error\" , function ( error ) { request . emitter . emit ( \"request_error\" , error ) ; } ) ; request . _raw . on ( \"socket\" , function ( socket ) { request . emitter . emit ( \"socket\" , socket ) ; } ) ; // TCP timeouts should also trigger the \"response_error\" event. request . _raw . on ( 'socket' , function ( ) { request . _raw . socket . on ( 'timeout' , function ( ) { // This should trigger the \"error\" event on the raw request, which will // trigger the \"response_error\" on the shred request. request . _raw . abort ( ) ; } ) ; } ) ; // We're almost there. Next, we need to write the request entity to the // underlying request object. if ( request . content ) { request . log . debug ( \"Streaming body: '\" + request . content . data . slice ( 0 , 59 ) + \"' ... \" ) ; request . _raw . write ( request . content . data ) ; } // Finally, we need to set up the timeout. We do this last so that we don't // start the clock ticking until the last possible moment. if ( request . timeout ) { timeout = setTimeout ( function ( ) { request . log . debug ( \"Timeout fired, aborting request ...\" ) ; request . _raw . abort ( ) ; request . emitter . emit ( \"timeout\" , request ) ; } , request . timeout ) ; } // The `.end()` method will cause the request to fire. Technically, it might // have already sent the headers and body. request . log . debug ( \"Sending request ...\" ) ; request . _raw . end ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set up some event magic . The precedence is given first to status - specific handlers then to responses for a given event and then finally to the more general response handler . In the last case we need to first make sure we re not dealing with a a redirect . [CODESPLIT] function ( event ) { var emitter = request . emitter ; var textStatus = STATUS_CODES [ response . status ] ? STATUS_CODES [ response . status ] . toLowerCase ( ) : null ; if ( emitter . listeners ( response . status ) . length > 0 || emitter . listeners ( textStatus ) . length > 0 ) { emitter . emit ( response . status , response ) ; emitter . emit ( textStatus , response ) ; } else { if ( emitter . listeners ( event ) . length > 0 ) { emitter . emit ( event , response ) ; } else if ( ! response . isRedirect ) { emitter . emit ( \"response\" , response ) ; //console.warn(\"Request has no event listener for status code \" + response.status); } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logs the curl command for the request . [CODESPLIT] function ( req ) { var headers = req . getHeaders ( ) ; var headerString = \"\" ; for ( var key in headers ) { headerString += '-H \"' + key + \": \" + headers [ key ] + '\" ' ; } var bodyString = \"\" if ( req . content ) { bodyString += \"-d '\" + req . content . body + \"' \" ; } var query = req . query ? '?' + req . query : \"\" ; console . log ( \"curl \" + \"-X \" + req . method . toUpperCase ( ) + \" \" + req . scheme + \"://\" + req . host + \":\" + req . port + req . path + query + \" \" + headerString + bodyString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a Response object . You should never have to do this directly . The Request object handles this getting the raw response object and passing it in here along with the request . The callback allows us to stream the response and then use the callback to let the request know when it s ready . [CODESPLIT] function ( raw , request , callback ) { var response = this ; this . _raw = raw ; // The `._setHeaders` method is \"private\"; you can't otherwise set headers on // the response. this . _setHeaders . call ( this , raw . headers ) ; // store any cookies if ( request . cookieJar && this . getHeader ( 'set-cookie' ) ) { var cookieStrings = this . getHeader ( 'set-cookie' ) ; var cookieObjs = [ ] , cookie ; for ( var i = 0 ; i < cookieStrings . length ; i ++ ) { var cookieString = cookieStrings [ i ] ; if ( ! cookieString ) { continue ; } if ( ! cookieString . match ( / domain\\= / i ) ) { cookieString += '; domain=' + request . host ; } if ( ! cookieString . match ( / path\\= / i ) ) { cookieString += '; path=' + request . path ; } try { cookie = new Cookie ( cookieString ) ; if ( cookie ) { cookieObjs . push ( cookie ) ; } } catch ( e ) { console . warn ( \"Tried to set bad cookie: \" + cookieString ) ; } } request . cookieJar . setCookies ( cookieObjs ) ; } this . request = request ; this . client = request . client ; this . log = this . request . log ; // Stream the response content entity and fire the callback when we're done. // Store the incoming data in a array of Buffers which we concatinate into one // buffer at the end.  We need to use buffers instead of strings here in order // to preserve binary data. var chunkBuffers = [ ] ; var dataLength = 0 ; raw . on ( \"data\" , function ( chunk ) { chunkBuffers . push ( chunk ) ; dataLength += chunk . length ; } ) ; raw . on ( \"end\" , function ( ) { var body ; if ( typeof Buffer === 'undefined' ) { // Just concatinate into a string body = chunkBuffers . join ( '' ) ; } else { // Initialize new buffer and add the chunks one-at-a-time. body = new Buffer ( dataLength ) ; for ( var i = 0 , pos = 0 ; i < chunkBuffers . length ; i ++ ) { chunkBuffers [ i ] . copy ( body , pos ) ; pos += chunkBuffers [ i ] . length ; } } var setBodyAndFinish = function ( body ) { response . _body = new Content ( { body : body , type : response . getHeader ( \"Content-Type\" ) } ) ; callback ( response ) ; } if ( zlib && response . getHeader ( \"Content-Encoding\" ) === 'gzip' ) { zlib . gunzip ( body , function ( err , gunzippedBody ) { if ( Iconv && response . request . encoding ) { body = Iconv . fromEncoding ( gunzippedBody , response . request . encoding ) ; } else { body = gunzippedBody . toString ( ) ; } setBodyAndFinish ( body ) ; } ) } else { if ( response . request . encoding ) { body = Iconv . fromEncoding ( body , response . request . encoding ) ; } setBodyAndFinish ( body ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The real getHeader function : get one or more headers or all of them if you don t ask for any specifics . [CODESPLIT] function ( object , names ) { var keys = ( names && names . length > 0 ) ? names : Object . keys ( $H ( object ) ) ; var hash = keys . reduce ( function ( hash , key ) { hash [ key ] = getHeader ( object , key ) ; return hash ; } , { } ) ; // Freeze the resulting hash so you don't mistakenly think you're modifying // the real headers. Object . freeze ( hash ) ; return hash ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add getters . [CODESPLIT] function ( constructor ) { constructor . prototype . getHeader = function ( name ) { return getHeader ( this , name ) ; } ; constructor . prototype . getHeaders = function ( ) { return getHeaders ( this , arguments ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add setters but as private methods . [CODESPLIT] function ( constructor ) { constructor . prototype . _setHeader = function ( key , value ) { return setHeader ( this , key , value ) ; } ; constructor . prototype . _setHeaders = function ( hash ) { return setHeaders ( this , hash ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add setters . [CODESPLIT] function ( constructor ) { constructor . prototype . setHeader = function ( key , value ) { return setHeader ( this , key , value ) ; } ; constructor . prototype . setHeaders = function ( hash ) { return setHeaders ( this , hash ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add both getters and setters . [CODESPLIT] function ( constructor ) { constructor . prototype . getHeader = function ( name ) { return getHeader ( this , name ) ; } ; constructor . prototype . getHeaders = function ( ) { return getHeaders ( this , arguments ) ; } ; constructor . prototype . setHeader = function ( key , value ) { return setHeader ( this , key , value ) ; } ; constructor . prototype . setHeaders = function ( hash ) { return setHeaders ( this , hash ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get correct codec for given encoding . [CODESPLIT] function ( encoding ) { var enc = encoding || \"utf8\" ; var codecOptions = undefined ; while ( 1 ) { if ( getType ( enc ) === \"String\" ) enc = enc . replace ( / [- ] / g , \"\" ) . toLowerCase ( ) ; var codec = iconv . encodings [ enc ] ; var type = getType ( codec ) ; if ( type === \"String\" ) { // Link to other encoding. codecOptions = { originalEncoding : enc } ; enc = codec ; } else if ( type === \"Object\" && codec . type != undefined ) { // Options for other encoding. codecOptions = codec ; enc = codec . type ; } else if ( type === \"Function\" ) // Codec itself. return codec ( codecOptions ) ; else throw new Error ( \"Encoding not recognized: '\" + encoding + \"' (searched as: '\" + enc + \"')\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Codepage single - byte encodings . [CODESPLIT] function ( options ) { // Prepare chars if needed if ( ! options . chars || ( options . chars . length !== 128 && options . chars . length !== 256 ) ) throw new Error ( \"Encoding '\" + options . type + \"' has incorrect 'chars' (must be of len 128 or 256)\" ) ; if ( options . chars . length === 128 ) options . chars = asciiString + options . chars ; if ( ! options . charsBuf ) { options . charsBuf = new Buffer ( options . chars , 'ucs2' ) ; } if ( ! options . revCharsBuf ) { options . revCharsBuf = new Buffer ( 65536 ) ; var defChar = iconv . defaultCharSingleByte . charCodeAt ( 0 ) ; for ( var i = 0 ; i < options . revCharsBuf . length ; i ++ ) options . revCharsBuf [ i ] = defChar ; for ( var i = 0 ; i < options . chars . length ; i ++ ) options . revCharsBuf [ options . chars . charCodeAt ( i ) ] = i ; } return { toEncoding : function ( str ) { str = ensureString ( str ) ; var buf = new Buffer ( str . length ) ; var revCharsBuf = options . revCharsBuf ; for ( var i = 0 ; i < str . length ; i ++ ) buf [ i ] = revCharsBuf [ str . charCodeAt ( i ) ] ; return buf ; } , fromEncoding : function ( buf ) { buf = ensureBuffer ( buf ) ; // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. var charsBuf = options . charsBuf ; var newBuf = new Buffer ( buf . length * 2 ) ; var idx1 = 0 , idx2 = 0 ; for ( var i = 0 , _len = buf . length ; i < _len ; i ++ ) { idx1 = buf [ i ] * 2 ; idx2 = i * 2 ; newBuf [ idx2 ] = charsBuf [ idx1 ] ; newBuf [ idx2 + 1 ] = charsBuf [ idx1 + 1 ] ; } return newBuf . toString ( 'ucs2' ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Codepage double - byte encodings . [CODESPLIT] function ( options ) { var table = options . table , key , revCharsTable = options . revCharsTable ; if ( ! table ) { throw new Error ( \"Encoding '\" + options . type + \"' has incorect 'table' option\" ) ; } if ( ! revCharsTable ) { revCharsTable = options . revCharsTable = { } ; for ( key in table ) { revCharsTable [ table [ key ] ] = parseInt ( key ) ; } } return { toEncoding : function ( str ) { str = ensureString ( str ) ; var strLen = str . length ; var bufLen = strLen ; for ( var i = 0 ; i < strLen ; i ++ ) if ( str . charCodeAt ( i ) >> 7 ) bufLen ++ ; var newBuf = new Buffer ( bufLen ) , gbkcode , unicode , defaultChar = revCharsTable [ iconv . defaultCharUnicode . charCodeAt ( 0 ) ] ; for ( var i = 0 , j = 0 ; i < strLen ; i ++ ) { unicode = str . charCodeAt ( i ) ; if ( unicode >> 7 ) { gbkcode = revCharsTable [ unicode ] || defaultChar ; newBuf [ j ++ ] = gbkcode >> 8 ; //high byte; newBuf [ j ++ ] = gbkcode & 0xFF ; //low byte } else { //ascii newBuf [ j ++ ] = unicode ; } } return newBuf ; } , fromEncoding : function ( buf ) { buf = ensureBuffer ( buf ) ; var bufLen = buf . length , strLen = 0 ; for ( var i = 0 ; i < bufLen ; i ++ ) { strLen ++ ; if ( buf [ i ] & 0x80 ) //the high bit is 1, so this byte is gbkcode's high byte.skip next byte i ++ ; } var newBuf = new Buffer ( strLen * 2 ) , unicode , gbkcode , defaultChar = iconv . defaultCharUnicode . charCodeAt ( 0 ) ; for ( var i = 0 , j = 0 ; i < bufLen ; i ++ , j += 2 ) { gbkcode = buf [ i ] ; if ( gbkcode & 0x80 ) { gbkcode = ( gbkcode << 8 ) + buf [ ++ i ] ; unicode = table [ gbkcode ] || defaultChar ; } else { unicode = gbkcode ; } newBuf [ j ] = unicode & 0xFF ; //low byte newBuf [ j + 1 ] = unicode >> 8 ; //high byte } return newBuf . toString ( 'ucs2' ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refactor into module ------------------------------------------ [CODESPLIT] function copyFile ( opts ) { var importStr , ext ; if ( ! opts ) return console . log ( 'incomplete options' ) ; ext = opts . ext ; if ( typeof ext === 'string' ) { ext = [ ext ] ; // turn string ext into array } // itterate through each file and process it ext . forEach ( function ( extension ) { var filename ; filename = opts . filename ; // handle sass paritals by prepending underscore if ( extension === '.scss' ) { importStr = \"@import '../pages/\" + opts . pageName + \"/\" + filename + \"';\\n\" fs . appendFileSync ( 'client/styles/_pages.scss' , importStr ) filename = \"_\" + filename ; } // copy from default folder to destination folder and rename any // variables that may be in each file fs . copy ( opts . from + filename + extension , opts . to + filename + extension , function ( err ) { handleError ( err ) ; replace ( opts . to + filename + extension , function ( data ) { var res , repl ; if ( opts . replaceWith ) { repl = opts . replaceWith ; res = data . replace ( / compName / g , changeCase . camelCase ( repl ) ) ; return res . replace ( / comp-name / g , changeCase . paramCase ( repl ) ) ; } else { res = data . replace ( / compName / g , nameCase . camel ) ; return res . replace ( / comp-name / g , nameCase . hyphen ) ; } } ) ; console . log ( '    Created:' , opts . to + opts . filename + extension ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the authentication parameter for the user Preference will be given to the token if it exists [CODESPLIT] function encodeUserAuth ( user ) { if ( ! user ) { return null ; } var token = user . token ; if ( token ) { var sha1 = typeof token === 'object' ? token . sha1 : token ; return 'token ' + sha1 ; } return 'Basic ' + base64 . encode ( user . username + ':' + user . password ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add a route to an express application [CODESPLIT] function addRoute ( app , route , method , destination ) { if ( method === 'GET' ) { app . get ( route , destination ) ; } else if ( method === 'POST' ) { app . post ( route , destination ) ; } else if ( method === 'PUT' ) { app . put ( route , destination ) ; } else if ( method === 'DELETE' ) { app . delete ( route , destination ) ; } else { throw new Error ( meta . module + '|addRoute|EXCEPTION|unknown method:\"' + method + '\"|expecter=GET,POST,PUT,DELETE' ) ; } logger . log ( 'debug' , '%s|add|method=%s|route=%s' , meta . module , method , route , meta ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add a route to an express application [CODESPLIT] function add ( app , route , method , destination ) { var methods ; if ( typeof ( method ) === 'string' ) { methods = method . split ( ',' ) ; } else if ( typeof ( method ) === 'object' ) { // array methods = method ; } else { throw new Error ( meta . module + '|add|EXCEPTION|unknown method:\"' + typeof ( method ) + '\"|expecter=string,object(array)' ) ; } for ( var i = 0 ; i < methods . length ; ++ i ) { addRoute ( app , route , methods [ i ] , destination ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Copy the boilerplate in the templates init folder to the user s root project folder . Creates a router and client folder . The project name is used for removing original boilerplate . Examples : require ( . / init ) . init ( myProjectName ) ; projectName - the { String } name of the user s meteor project [CODESPLIT] function ( projectName ) { var self = this ; this . projectName = projectName ; this . projDir = './' + projectName + '/' ; this . packages = this . projDir + '.meteor/packages' ; this . _runTerminalCommand ( 'meteor create ' + projectName , function ( ) { // after command is finished router . create ( self . projDir ) ; self . _copyTemplate ( ) ; self . _removeOriginalMeteorFiles ( projectName ) ; self . _removeUnwantedPackages ( ) ; self . _addPackagesToPackagesFile ( ) ; puts ( '\\n-------------------------------------------' ) ; puts ( '  type cd %s to navigate to project' , projectName ) ; puts ( '  then the meteor command to start a server' ) ; puts ( '-------------------------------------------\\n' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private : Run a command on the command line . command - the { String } command to run callback - a { Function } to call when complete [CODESPLIT] function ( command , callback ) { var exec = require ( 'child_process' ) . exec ; exec ( command , function ( err ) { if ( err ) puts ( 'exec error: ' + err ) ; callback . call ( this ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private : Copy the boilerplate from templates directory and place it in the user s project root directory . Remove . gitkeep when done [CODESPLIT] function ( ) { fs . copySync ( this . initSource , this . projDir ) ; fs . removeSync ( this . projDir + 'client/.gitkeep' ) ; fs . removeSync ( this . projDir + 'server/.gitkeep' ) ; puts ( '    Created: .jshintrc' ) ; puts ( '    Created: .jshintignore' ) ; puts ( '    Created: makefile' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private : Removes the original foo . html foo . js and foo . css files that Meteor creates after a meteor create foo command [CODESPLIT] function ( ) { fs . removeSync ( this . projDir + this . projectName + '.js' ) ; fs . removeSync ( this . projDir + this . projectName + '.html' ) ; fs . removeSync ( this . projDir + this . projectName + '.css' ) ; puts ( '    Removed: original boilerplate' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private : Look at packages file and remove package if present . Stream packages file replace then overwrite original file . packageName - The { String } name of the package [CODESPLIT] function ( packageName ) { var oldPackages , newPackages ; oldPackages = fs . readFileSync ( this . packages , { encoding : 'utf-8' } ) ; newPackages = oldPackages . replace ( packageName + '\\n' , '' ) ; fs . writeFileSync ( this . packages , newPackages ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Copy routes . js from templates folder into users both / folder . If file already exists it will not be overwritten . [CODESPLIT] function ( projPath ) { // handle calling create outside of project and inside var rootPath = ( projPath ) ? projPath : './' ; // create both folder if it doesn't already exisit fs . mkdirsSync ( rootPath ) ; // bail if router already exists if ( fs . existsSync ( rootPath + 'both/routes.js' ) ) return ; // copy router.js from templates/ to project/both/controllers fs . copySync ( this . routeSrc , rootPath + 'both/routes.js' ) ; console . log ( '    Created: both/routes.js' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Append the correct route into routes . js . The routes file is examined for the end - routes marker and it is removed . The new route is inserted onto the end of the file and the marker is re - appended . resName - The { String } name of the controller action eg index show [CODESPLIT] function ( resName , action ) { var route , newContent , oldFileStr , newFileStr , res ; resName = resName || '' ; res = require ( './parse_name' ) ( resName ) // set correct route for the required action // TODO Pascal case namespaces, camelcase routes switch ( action ) { case 'index' : route = \"  this.route('\" + res . camelPlural + \"',     { path: '/\" + resName + \"',          controller: \" + res . pascalPlural + \"Controller.Index });\" ; break ; case 'new' : route = \"  this.route('\" + res . camelPlural + \"New',  { path: '/\" + resName + \"/new',      controller: \" + res . pascalPlural + \"Controller.New });\" ; break ; case 'show' : route = \"  this.route('\" + res . camelPlural + \"Show', { path: '/\" + resName + \"/:id',      controller: \" + res . pascalPlural + \"Controller.Show });\" ; break ; case 'edit' : route = \"  this.route('\" + res . camelPlural + \"Edit', { path: '/\" + resName + \"/edit/:id', controller: \" + res . pascalPlural + \"Controller.Edit });\" ; break ; case 'comment_line' : route = \"  // \" + resName + \" routes\" ; break ; case 'blank_line' : route = \"\" ; break ; default : route = \"  this.route('UNKNOWN', { path: '/', controller: UNKNOWN.index });\" ; break ; } // read routes.js from users folder and save to string // concat new route together oldFileStr = fs . readFileSync ( this . routeDest , { encoding : 'utf-8' } ) ; newContent = route + \"\\n\" + this . terminateRoute ; // insert new content into current routes.js string // write new content to file `routes/controllers/resource_name.js` newFileStr = oldFileStr . replace ( this . beforeEndOfRouter , newContent ) ; fs . writeFileSync ( this . routeDest , newFileStr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public : Creates a controller file & appends any type of controller needed . If no options are passed in it will create all router and CRUD controllers resName - The { String } name of the resource passed in from command line opts - The options generated from a Commander command entry . [CODESPLIT] function ( resName , opts ) { // TODO ensure resName is always snake case this . contrFile = this . controllerPath + resName + '.js' ; this . resName = resName ; this . opts = opts ; // if no args passed in, created all routes if ( ! opts . index && ! opts . new && ! opts . show && ! opts . edit && ! opts . create && ! opts . update && ! opts . destroy ) { this . opts . all = true ; } this . _createBaseController ( ) ; // add a comment line before adding new routes require ( './router' ) . appendRoute ( resName , 'comment_line' ) ; // print 'created' if file doesn't exist yet (created on first append) if ( ! fs . existsSync ( this . contrFile ) ) { console . log ( '    Created: ' + this . contrFile ) ; } // Append Iron Router Controllers if ( opts . index || opts . all ) { this . _appendController ( 'index' ) ; require ( './page' ) . run ( this . resName , { index : true } ) ; } if ( opts . new || opts . all ) { this . _appendController ( 'new' ) ; require ( './page' ) . run ( resName , { 'new' : true } ) ; } if ( opts . show || opts . all ) { this . _appendController ( 'show' ) ; require ( './page' ) . run ( resName , { show : true } ) ; } if ( opts . edit || opts . all ) { this . _appendController ( 'edit' ) ; require ( './page' ) . run ( resName , { edit : true } ) ; } // Append data Controllers if ( opts . create || opts . all ) { this . _appendController ( 'create' ) ; } if ( opts . update || opts . all ) { this . _appendController ( 'update' ) ; } if ( opts . destroy || opts . all ) { this . _appendController ( 'destroy' ) ; } // add blank line to routes.js after controller routes require ( './router' ) . appendRoute ( null , 'blank_line' ) ; // instantiate and add namespace for this resource if needed new ( require ( './namespace' ) ) ( ) . add ( resName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private : Streams controller template from templates folder renames any template variables with lib / rename . js and appends the new processed template into user s controller folder both / controller / posts . js . If this file does not exist it will be created . A route is appended to routes . js . action - The { String } name of the controller action eg index show [CODESPLIT] function ( action ) { var templateStr = fs . readFileSync ( this . contrTemplates + action + '.js' , { encoding : 'utf-8' } ) ; // rename template variables and append to controller file templateStr = require ( './rename' ) ( this . resName , templateStr ) ; fs . appendFileSync ( this . contrFile , templateStr ) ; // add a route for new controller if ( action !== 'create' && action !== 'update' && action !== 'destroy' ) { require ( './router' ) . appendRoute ( this . resName , action ) ; console . log ( '    Added Route: ' + this . resName + \" \" + action ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private : Copy base app controller from templates dir to user project folder both / controllers / app . js Will not overwrite existing file . [CODESPLIT] function ( ) { if ( fs . existsSync ( this . controllerPath + '_app.js' ) ) return ; fs . copySync ( this . contrTemplates + '_app.js' , this . controllerPath + '_app.js' ) ; console . log ( '    Created: ' + this . controllerPath + '_app.js' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates a Vec4 object . [CODESPLIT] function Vec4 ( ) { switch ( arguments . length ) { case 1 : // array or VecN argument var argument = arguments [ 0 ] ; this . x = argument . x || argument [ 0 ] || 0.0 ; this . y = argument . y || argument [ 1 ] || 0.0 ; this . z = argument . z || argument [ 2 ] || 0.0 ; this . w = argument . w || argument [ 3 ] || 0.0 ; break ; case 4 : // individual component arguments this . x = arguments [ 0 ] ; this . y = arguments [ 1 ] ; this . z = arguments [ 2 ] ; this . w = arguments [ 3 ] || 0.0 ; break ; default : this . x = 0.0 ; this . y = 0.0 ; this . z = 0.0 ; this . w = 0.0 ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new EConstructor with the formatted format as a first argument . [CODESPLIT] function create ( EConstructor ) { FormattedError . displayName = EConstructor . displayName || EConstructor . name return FormattedError function FormattedError ( format ) { if ( format ) { format = formatter . apply ( null , arguments ) } return new EConstructor ( format ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates a Mat44 object . [CODESPLIT] function Mat44 ( that ) { that = that || [ 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 ] ; if ( that instanceof Array ) { this . data = that ; } else { this . data = new Array ( 16 ) ; this . data [ 0 ] = that . data [ 0 ] ; this . data [ 1 ] = that . data [ 1 ] ; this . data [ 2 ] = that . data [ 2 ] ; this . data [ 3 ] = that . data [ 3 ] ; this . data [ 4 ] = that . data [ 4 ] ; this . data [ 5 ] = that . data [ 5 ] ; this . data [ 6 ] = that . data [ 6 ] ; this . data [ 7 ] = that . data [ 7 ] ; this . data [ 8 ] = that . data [ 8 ] ; this . data [ 9 ] = that . data [ 9 ] ; this . data [ 10 ] = that . data [ 10 ] ; this . data [ 11 ] = that . data [ 11 ] ; this . data [ 12 ] = that . data [ 12 ] ; this . data [ 13 ] = that . data [ 13 ] ; this . data [ 14 ] = that . data [ 14 ] ; this . data [ 15 ] = that . data [ 15 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Discovery object . The options object is optional . Supported options are : - port - Set the port the service listens on for announcements default : 44201 - bindAddr - bind to an address - dgramType - Either udp4 or udp6 default : udp4 . - timeOutInt - duration of time between timeout checks in ms . Default 1000 . [CODESPLIT] function Discovery ( options ) { var self = this ; if ( options && ! is . obj ( options ) ) debug ( 'Dicovery constructor bad options argument: ' + inspect ( options ) ) ; // Create a dgram socket and bind it self . dgramType = ( options && options . dgramType ) ? options . dgramType . toLowerCase ( ) : DEFAULT_DGRAM_TYPE ; self . reuseaddr = ( options && options . reuseaddr ) ? options . reuseaddr : DEFAULT_REUSE_ADDR ; self . socket = dgram . createSocket ( { type : self . dgramType , reuseAddr : self . reuseaddr } ) ; self . port = ( options && options . port ) ? options . port : DEFAULT_UDP_PORT ; self . bindAddr = ( options && options . bindAddr ) ? options . bindAddr : undefined ; self . socket . bind ( self . port , self . bindAddr ) ; // create an interval task to check for announcements that have timed out self . timeOutInt = ( options && options . timeOutInt ) ? options . timeOutInt : DEFAULT_TIMEOUT ; self . timeOutId = setInterval ( function ( ) { self . handleTimeOut ( ) ; } , self . timeOutInt ) ; // listen and listen for multicast packets self . socket . on ( 'listening' , function ( ) { self . socket . addMembership ( MULTICAST_ADDRESS ) ; } ) ; // handle any announcements, here we just do the formatting self . socket . on ( 'message' , function ( message , rinfo ) { if ( message ) { var obj = objToJson . jsonParse ( message . toString ( ) ) ; if ( ! obj ) { debug ( 'bad announcement: ' + message . toString ( ) ) ; return ; } // the received message was either an event or an announcement if ( obj . eventName ) self . emit ( GLOBAL_EVENT_NAME , obj . eventName , obj . data ) ; else self . handleAnnouncement ( obj , rinfo ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "编译 [CODESPLIT] function plugin ( options , callback ) { options = options || { } ; return function ( style ) { if ( options . resolveUrl !== false ) { style . define ( 'url' , stylus . resolver ( ) ) ; } style . use ( rider ( { implicit : options . implicit } ) ) ; style . on ( 'end' , postprocessor ( options , callback ) ) ; if ( options . husl ) { // define husl & huslp style . define ( 'husl' , function ( H , S , L , A ) { var rgb = husl . _rgbPrepare ( husl . _conv . husl . rgb ( [ H . val , S . val , L . val ] ) ) ; var a = ( A !== undefined ? A . val : 1 ) ; return new stylus . nodes . RGBA ( rgb [ 0 ] , rgb [ 1 ] , rgb [ 2 ] , a ) ; } ) ; style . define ( 'huslp' , function ( H , S , L , A ) { var rgb = husl . _rgbPrepare ( husl . _conv . huslp . rgb ( [ H . val , S . val , L . val ] ) ) ; var a = ( A !== undefined ? A . val : 1 ) ; return new stylus . nodes . RGBA ( rgb [ 0 ] , rgb [ 1 ] , rgb [ 2 ] , a ) ; } ) ; } if ( options . use ) { style . use ( options . use ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates a Vec2 object . [CODESPLIT] function Vec2 ( ) { switch ( arguments . length ) { case 1 : // array or VecN argument var argument = arguments [ 0 ] ; this . x = argument . x || argument [ 0 ] || 0.0 ; this . y = argument . y || argument [ 1 ] || 0.0 ; break ; case 2 : // individual component arguments this . x = arguments [ 0 ] ; this . y = arguments [ 1 ] ; break ; default : this . x = 0 ; this . y = 0 ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates a Quaternion object . [CODESPLIT] function Quaternion ( ) { switch ( arguments . length ) { case 1 : // array or Quaternion argument var argument = arguments [ 0 ] ; if ( argument . w !== undefined ) { this . w = argument . w ; } else if ( argument [ 0 ] !== undefined ) { this . w = argument [ 0 ] ; } else { this . w = 1.0 ; } this . x = argument . x || argument [ 1 ] || 0.0 ; this . y = argument . y || argument [ 2 ] || 0.0 ; this . z = argument . z || argument [ 3 ] || 0.0 ; break ; case 4 : // individual component arguments this . w = arguments [ 0 ] ; this . x = arguments [ 1 ] ; this . y = arguments [ 2 ] ; this . z = arguments [ 3 ] ; break ; default : this . w = 1 ; this . x = 0 ; this . y = 0 ; this . z = 0 ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Wrapper around Node which adds the current node ( and parent if available ) to the message . [CODESPLIT] function wrap ( fn ) { return wrapped function wrapped ( node , parent ) { try { fn ( node , parent ) } catch ( error ) { if ( ! error [ ID ] ) { error [ ID ] = true error . message += ': `' + view ( node ) + '`' if ( parent ) { error . message += ' in `' + view ( parent ) + '`' } } throw error } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Assert . [CODESPLIT] function unist ( node ) { var type var children var value var key var index var length assert . ok ( object ( node ) , 'node should be an object' ) type = node . type children = node . children value = node . value assert . ok ( 'type' in node , 'node should have a type' ) assert . strictEqual ( typeof type , 'string' , '`type` should be a string' ) assert . notStrictEqual ( type , '' , '`type` should not be empty' ) if ( value != null ) { assert . strictEqual ( typeof value , 'string' , '`value` should be a string' ) } location ( node . position ) for ( key in node ) { if ( defined . indexOf ( key ) === - 1 ) { vanilla ( key , node [ key ] ) } } if ( children != null ) { assert . ok ( array ( children ) , '`children` should be an array' ) index = - 1 length = children . length while ( ++ index < length ) { exports ( children [ index ] , node ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Assert value ( which lives at key ) can be stringified and re - parsed to the same ( deep ) value . [CODESPLIT] function vanilla ( key , value ) { try { assert . deepStrictEqual ( value , JSON . parse ( JSON . stringify ( value ) ) ) } catch ( error ) { assert . fail ( 'non-specced property `' + key + '` should be JSON' ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Stringify a value to inspect it . Tries JSON . stringify () and if that fails uses String () instead . If stringify () works . [CODESPLIT] function view ( value ) { try { /* eslint-disable no-else-return */ /* istanbul ignore else - Browser. */ if ( inspect ) { return inspect ( value , { colors : false } ) } else { return JSON . stringify ( value ) } } catch ( error ) { /* istanbul ignore next - Cyclical. */ return String ( value ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Assert node is a parent node . [CODESPLIT] function parent ( node ) { unist ( node ) assert . strictEqual ( 'value' in node , false , 'parent should not have `value`' ) assert . ok ( 'children' in node , 'parent should have `children`' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Assert node is a text node . [CODESPLIT] function text ( node ) { unist ( node ) assert . strictEqual ( 'children' in node , false , 'text should not have `children`' ) assert . ok ( 'value' in node , 'text should have `value`' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Assert node is a Unist node but neither parent nor text . [CODESPLIT] function empty ( node ) { unist ( node ) assert . strictEqual ( 'value' in node , false , 'void should not have `value`' ) assert . strictEqual ( 'children' in node , false , 'void should not have `children`' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Assert location is a Unist Location . [CODESPLIT] function location ( location ) { if ( location != null ) { assert . ok ( object ( location ) , '`position` should be an object' ) position ( location . start , 'position.start' ) position ( location . end , 'position.end' ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Assert location is a Unist Location . [CODESPLIT] function position ( position , name ) { if ( position != null ) { assert . ok ( object ( position ) , '`' + name + '` should be an object' ) if ( position . line != null ) { assert . ok ( 'line' in position , '`' + name + '` should have numeric `line`' ) assert . ok ( position . line >= 1 , '`' + name + '.line` should be gte `1`' ) } if ( position . column != null ) { assert . ok ( 'column' in position , '`' + name + '` should have numeric `column`' ) assert . ok ( position . column >= 1 , '`' + name + '.column` should be gte `1`' ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates a Vec3 object . [CODESPLIT] function Vec3 ( ) { switch ( arguments . length ) { case 1 : // array or VecN argument var argument = arguments [ 0 ] ; this . x = argument . x || argument [ 0 ] || 0.0 ; this . y = argument . y || argument [ 1 ] || 0.0 ; this . z = argument . z || argument [ 2 ] || 0.0 ; break ; case 3 : // individual component arguments this . x = arguments [ 0 ] ; this . y = arguments [ 1 ] ; this . z = arguments [ 2 ] ; break ; default : this . x = 0.0 ; this . y = 0.0 ; this . z = 0.0 ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor [CODESPLIT] function Snackbar ( data , options , callback ) { if ( data !== \"\" ) { this . options = this . activateOptions ( options ) ; this . data = data ; this . callback = callback ; this . start ( ) ; this . snackbar ( ) ; } else { console . warn ( \"SnackbarLight: You can not create a empty snackbar please give it a string.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create container for the snackbar [CODESPLIT] function ( ) { if ( ! document . getElementById ( \"snackbar-container\" ) ) { var snackbarContainer = document . createElement ( \"div\" ) ; snackbarContainer . setAttribute ( \"id\" , \"snackbar-container\" ) ; document . body . appendChild ( snackbarContainer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Timer [CODESPLIT] function ( callback , delay ) { var remaining = delay ; this . timer = { // Create random timer id timerId : Math . round ( Math . random ( ) * 1000 ) , pause : function ( ) { // Clear the timeout window . clearTimeout ( this . timerId ) ; // Set the remaining to what time remains remaining -= new Date ( ) - start ; } , resume : function ( ) { start = new Date ( ) ; // Clear the timeout window . clearTimeout ( this . timerId ) ; // Set the timeout again this . timerId = window . setTimeout ( callback , remaining ) ; } , } ; // Start the timer this . timer . resume ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "snackbar [CODESPLIT] function ( ) { var __self = this , snackbar = document . createElement ( \"div\" ) ; // Put the snackbar inside the snackbar container document . getElementById ( \"snackbar-container\" ) . appendChild ( snackbar ) ; // Set the html inside the snackbar snackbar . innerHTML = this . getData ( ) ; // Set the class of the snackbar snackbar . setAttribute ( \"class\" , \"snackbar\" ) ; // Wait to set the active class so animations will be activated setTimeout ( function ( ) { snackbar . setAttribute ( \"class\" , \"snackbar \" + __self . options . activeClass ) ; } , 50 ) ; // If the timeout is false the snackbar will not be destroyed after some time // only when the user clicks on it if ( this . options . timeout !== false ) { // Start the timer this . timer ( function ( ) { snackbar . setAttribute ( \"class\" , \"snackbar\" ) ; __self . destroy ( snackbar ) ; } , this . options . timeout ) ; } // Add the event listeners this . listeners ( snackbar ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Activate the listeners [CODESPLIT] function ( element ) { var __self = this ; // Adding event listener for when user clicks on the snackbar to remove it element . addEventListener ( \"click\" , function ( ) { if ( typeof __self . callback == \"function\" ) { __self . callback ( ) ; } element . setAttribute ( \"class\" , \"snackbar\" ) ; __self . destroy ( element ) ; } ) ; // Stopping the timer when user hovers on the snackbar element . addEventListener ( \"mouseenter\" , function ( ) { __self . timer . pause ( ) ; } ) ; element . addEventListener ( \"mouseout\" , function ( ) { __self . timer . resume ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare the options to the default ones . [CODESPLIT] function ( newOptions ) { var __self = this , options = newOptions || { } ; for ( var opt in this . options ) { if ( __self . options . hasOwnProperty ( opt ) && ! options . hasOwnProperty ( opt ) ) { options [ opt ] = __self . options [ opt ] ; } } return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Install function for Vue [CODESPLIT] function ( Vue ) { var __self = this ; Vue . prototype . $snackbar = { } ; Vue . prototype . $snackbar . create = function ( data , options , callback ) { __self . create ( data , options , callback ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Converts a private key to WIF format [CODESPLIT] function privKeyToWIF ( privKey ) { var toCompressed = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : false ; var wif = arguments . length > 2 && arguments [ 2 ] !== undefined ? arguments [ 2 ] : zconfig . mainnet . wif ; if ( toCompressed ) privKey = privKey + '01' ; return bs58check . encode ( Buffer . from ( wif + privKey , 'hex' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns private key s public Key [CODESPLIT] function privKeyToPubKey ( privKey ) { var toCompressed = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : false ; var pkBuffer = Buffer . from ( privKey , 'hex' ) ; var publicKey = secp256k1 . publicKeyCreate ( pkBuffer , toCompressed ) ; return publicKey . toString ( 'hex' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Given a WIF format pk convert it back to the original pk [CODESPLIT] function WIFToPrivKey ( wifPk ) { var og = bs58check . decode ( wifPk , 'hex' ) . toString ( 'hex' ) ; og = og . substr ( 2 , og . length ) ; // remove WIF format ('80') // remove the '01' at the end to 'compress it' during WIF conversion if ( og . length > 64 ) { og = og . substr ( 0 , 64 ) ; } return og ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Given a list of public keys create a M - of - N redeemscript [CODESPLIT] function mkMultiSigRedeemScript ( pubKeys , M , N ) { // https://github.com/ZencashOfficial/zen/blob/b7a7c4c4199f5e9f49868631fe5f2f6de6ba4f9a/src/script/standard.cpp#L411 if ( M > N && M <= 1 ) throw new Error ( 'Invalid Multi Sig Type' ) ; var OP_1 = Buffer . from ( zopcodes . OP_1 , 'hex' ) ; var OP_START = ( OP_1 . readInt8 ( 0 ) + ( M - 1 ) ) . toString ( 16 ) ; var OP_END = ( OP_1 . readInt8 ( 0 ) + ( N - 1 ) ) . toString ( 16 ) ; return OP_START + pubKeys . map ( function ( x ) { return zbufferutils . getPushDataLength ( x ) + x ; } ) . join ( '' ) + OP_END + zopcodes . OP_CHECKMULTISIG ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Reference : http : // www . soroushjp . com / 2014 / 12 / 20 / bitcoin - multisig - the - hard - way - understanding - raw - multisignature - bitcoin - transactions / Given the multi sig redeem script return the corresponding address [CODESPLIT] function multiSigRSToAddress ( redeemScript ) { var scriptHash = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : zconfig . mainnet . scriptHash ; // Protocol: RIPEMD160(SHA256(script)) var s256 = zcrypto . sha256 ( Buffer . from ( redeemScript , 'hex' ) ) ; var r160 = zcrypto . ripemd160 ( Buffer . from ( s256 , 'hex' ) ) ; return bs58check . encode ( Buffer . from ( scriptHash + r160 , 'hex' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates a Transform object . [CODESPLIT] function Transform ( that ) { that = that || { } ; if ( that . data instanceof Array ) { // Mat33 or Mat44, extract transform components that = that . decompose ( ) ; this . rotation = that . rotation ; this . translation = that . translation || new Vec3 ( ) ; this . scale = that . scale ; } else { // set individual components, by value this . rotation = that . rotation ? new Quaternion ( that . rotation ) : new Quaternion ( ) ; this . translation = that . translation ? new Vec3 ( that . translation ) : new Vec3 ( ) ; if ( typeof that . scale === 'number' ) { this . scale = new Vec3 ( that . scale , that . scale , that . scale ) ; } else { this . scale = that . scale ? new Vec3 ( that . scale ) : new Vec3 ( 1 , 1 , 1 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "打包组件成js和css文件 [CODESPLIT] function vuePack ( file , encoding , callback ) { if ( ! file ) { throw new PluginError ( 'gulp-vue-pack' , 'file不存在');   } if ( file . isStream ( ) ) { throw new PluginError ( 'gulp-vue-pack' , '只支持.vue文件');   } if ( ! file . contents ) { //非文件,是目录 callback ( ) ; return ; } let fileName = path . basename ( file . path , \".vue\" ) ; let fileContent = file . contents . toString ( encoding ) ; let contents = parseVueToContents ( fileContent , fileName , path . dirname ( file . path ) ) ; let fpath = path . dirname ( file . path ) ; this . push ( createFile ( file . base , file . cwd , fpath , fileName + \".js\" , contents . js ) ) ; //如果css文件无内容，则不生成css文件 if ( contents . css . length > 0 ) { this . push ( createFile ( file . base , file . cwd , fpath , fileName + \".css\" , contents . css ) ) ; } callback ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将vue文件中的内容，进行转换，生成多页引用的vue [CODESPLIT] function convertToJSContent ( script , template , style , fileName , filePath ) { if ( ! script ) { return \"\" ; } //兼容 windows filePath = filePath . replace ( / \\\\ / g , \"/\" ) ; let jsFileContent = ` ` ; if ( style && style . length > 0 ) { jsFileContent += ` ` + fileName + ` \\n ` ; } jsFileContent += processJavascript ( fileName , script , processTemplate ( template ) , style , filePath ) ; jsFileContent += \"\\n\\nglobal.\" + fileName + \" = \" + fileName + \";\\n\\n\" ; //伪造ES6格式的VUE组件 jsFileContent += \"global.__FORGE_ES6_VUE_COMPONENTS__['\" + filePath + \"/\" + fileName + \".vue']=\" + fileName + \";\\n\" ; jsFileContent += \"Vue.component('vue\" + fileName . replace ( / ([A-Z]) / g , \"-$1\" ) . toLowerCase ( ) + \"', \" + fileName + \");\\n\\n\" ; jsFileContent += \"\\n}(window, Vue));\" ; return jsFileContent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "处理js 将es6写的带export的部分转换成普通的组件定义 [CODESPLIT] function processJavascript ( fileName , script , processedTemplate , style , filePath ) { script = script . replace ( VUE_COMPONENT_IMPORT_REG , function ( matchedLine , variableName , vuePath , index , contents ) { return \"var \" + variableName + \" = global.__FORGE_ES6_VUE_COMPONENTS__['\" + path . resolve ( filePath , vuePath ) . replace ( / \\\\ / g , \"/\" ) + \"']\" ; } ) ; script = script . replace ( SCRIPT_REPLACER_REG , \"var \" + fileName + \" = Vue.extend(\" ) ; script += \");\\n\" ; script += fileName + \".options.template = \" + processedTemplate ; // script = script.replace(/__gvptemplate/m, processedTemplate); return script ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates a Triangle object . [CODESPLIT] function Triangle ( ) { switch ( arguments . length ) { case 1 : // array or object argument var arg = arguments [ 0 ] ; this . a = new Vec3 ( arg [ 0 ] || arg . a ) ; this . b = new Vec3 ( arg [ 1 ] || arg . b ) ; this . c = new Vec3 ( arg [ 2 ] || arg . c ) ; break ; case 3 : // individual vector arguments this . a = new Vec3 ( arguments [ 0 ] ) ; this . b = new Vec3 ( arguments [ 1 ] ) ; this . c = new Vec3 ( arguments [ 2 ] ) ; break ; default : this . a = new Vec3 ( 0 , 0 , 0 ) ; this . b = new Vec3 ( 1 , 0 , 0 ) ; this . c = new Vec3 ( 1 , 1 , 0 ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * More info : https : // github . com / ZencashOfficial / zen / blob / master / src / script / standard . cpp#L377 Given an address generates a pubkeyhash replay type script needed for the transaction [CODESPLIT] function mkPubkeyHashReplayScript ( address , blockHeight , blockHash ) { var pubKeyHash = arguments . length > 3 && arguments [ 3 ] !== undefined ? arguments [ 3 ] : zconfig . mainnet . pubKeyHash ; // Get lengh of pubKeyHash (so we know where to substr later on) var addrHex = bs58check . decode ( address ) . toString ( 'hex' ) ; // Cut out pubKeyHash var subAddrHex = addrHex . substring ( pubKeyHash . length , addrHex . length ) ; // Minimal encoding var blockHeightBuffer = Buffer . alloc ( 4 ) ; blockHeightBuffer . writeUInt32LE ( blockHeight , 0 ) ; if ( blockHeightBuffer [ 3 ] === 0x00 ) { blockHeightBuffer = blockHeightBuffer . slice ( 0 , 3 ) ; } var blockHeightHex = blockHeightBuffer . toString ( 'hex' ) ; // block hash is encoded in little indian var blockHashHex = Buffer . from ( blockHash , 'hex' ) . reverse ( ) . toString ( 'hex' ) ; // '14' is the length of the subAddrHex (in bytes) return zopcodes . OP_DUP + zopcodes . OP_HASH160 + zbufferutils . getPushDataLength ( subAddrHex ) + subAddrHex + zopcodes . OP_EQUALVERIFY + zopcodes . OP_CHECKSIG + zbufferutils . getPushDataLength ( blockHashHex ) + blockHashHex + zbufferutils . getPushDataLength ( blockHeightHex ) + blockHeightHex + zopcodes . OP_CHECKBLOCKATHEIGHT ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Given an address generates a script hash replay type script needed for the transaction [CODESPLIT] function mkScriptHashReplayScript ( address , blockHeight , blockHash ) { var addrHex = bs58check . decode ( address ) . toString ( 'hex' ) ; var subAddrHex = addrHex . substring ( 4 , addrHex . length ) ; // Cut out the '00' (we also only want 14 bytes instead of 16) var blockHeightBuffer = Buffer . alloc ( 4 ) ; blockHeightBuffer . writeUInt32LE ( blockHeight , 0 ) ; if ( blockHeightBuffer [ 3 ] === 0x00 ) { blockHeightBuffer = blockHeightBuffer . slice ( 0 , 3 ) ; } var blockHeightHex = blockHeightBuffer . toString ( 'hex' ) ; // Need to reverse it var blockHashHex = Buffer . from ( blockHash , 'hex' ) . reverse ( ) . toString ( 'hex' ) ; return zopcodes . OP_HASH160 + zbufferutils . getPushDataLength ( subAddrHex ) + subAddrHex + zopcodes . OP_EQUAL + zbufferutils . getPushDataLength ( blockHashHex ) + blockHashHex + zbufferutils . getPushDataLength ( blockHeightHex ) + blockHeightHex + zopcodes . OP_CHECKBLOCKATHEIGHT ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Given an address generates an output script [CODESPLIT] function addressToScript ( address , blockHeight , blockHash ) { // P2SH replay starts with a 's', or 'r' if ( address [ 1 ] === 's' || address [ 1 ] === 'r' ) { return mkScriptHashReplayScript ( address , blockHeight , blockHash ) ; } // P2PKH-replay is a replacement for P2PKH return mkPubkeyHashReplayScript ( address , blockHeight , blockHash ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Serializes a TXOBJ into hex string [CODESPLIT] function serializeTx ( txObj ) { var serializedTx = '' ; var _buf16 = Buffer . alloc ( 4 ) ; // Version _buf16 . writeUInt16LE ( txObj . version , 0 ) ; serializedTx += _buf16 . toString ( 'hex' ) ; // History serializedTx += zbufferutils . numToVarInt ( txObj . ins . length ) ; txObj . ins . map ( function ( i ) { // Txids and vouts _buf16 . writeUInt16LE ( i . output . vout , 0 ) ; serializedTx += Buffer . from ( i . output . hash , 'hex' ) . reverse ( ) . toString ( 'hex' ) ; serializedTx += _buf16 . toString ( 'hex' ) ; // Script Signature // Doesn't work for length > 253 .... serializedTx += zbufferutils . getPushDataLength ( i . script ) ; serializedTx += i . script ; // Sequence serializedTx += i . sequence ; } ) ; // Outputs serializedTx += zbufferutils . numToVarInt ( txObj . outs . length ) ; txObj . outs . map ( function ( o ) { // Write 64bit buffers // JS only supports 56 bit // https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/src/bufferutils.js#L25 var _buf32 = Buffer . alloc ( 8 ) ; // Satohis _buf32 . writeInt32LE ( o . satoshis & - 1 , 0 ) ; _buf32 . writeUInt32LE ( Math . floor ( o . satoshis / 0x100000000 ) , 4 ) ; // ScriptPubKey serializedTx += _buf32 . toString ( 'hex' ) ; serializedTx += zbufferutils . getPushDataLength ( o . script ) ; serializedTx += o . script ; } ) ; // Locktime _buf16 . writeUInt16LE ( txObj . locktime , 0 ) ; serializedTx += _buf16 . toString ( 'hex' ) ; return serializedTx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Creates a raw transaction [CODESPLIT] function createRawTx ( history , recipients , blockHeight , blockHash ) { var txObj = { locktime : 0 , version : 1 , ins : [ ] , outs : [ ] } ; txObj . ins = history . map ( function ( h ) { return { output : { hash : h . txid , vout : h . vout } , script : '' , prevScriptPubKey : h . scriptPubKey , sequence : 'ffffffff' } ; } ) ; txObj . outs = recipients . map ( function ( o ) { return { script : addressToScript ( o . address , blockHeight , blockHash ) , satoshis : o . satoshis } ; } ) ; return txObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Gets signature for the vin script [CODESPLIT] function getScriptSignature ( privKey , signingTx , hashcode ) { // Buffer var _buf16 = Buffer . alloc ( 4 ) ; _buf16 . writeUInt16LE ( hashcode , 0 ) ; var signingTxHex = serializeTx ( signingTx ) ; var signingTxWithHashcode = signingTxHex + _buf16 . toString ( 'hex' ) ; // Sha256 it twice, according to spec var msg = zcrypto . sha256x2 ( Buffer . from ( signingTxWithHashcode , 'hex' ) ) ; // Signing it var rawsig = secp256k1 . sign ( Buffer . from ( msg , 'hex' ) , Buffer . from ( privKey , 'hex' ) , { canonical : true } ) ; // Convert it to DER format // Appending 01 to it cause // ScriptSig = <varint of total sig length> <SIG from code, including appended 01 SIGNHASH> <length of pubkey (0x21 or 0x41)> <pubkey> // https://bitcoin.stackexchange.com/a/36481 var signatureDER = Buffer . from ( rawsig . toDER ( ) ) . toString ( 'hex' ) + '01' ; return signatureDER ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Signs the raw transaction [CODESPLIT] function signTx ( _txObj , i , privKey ) { var compressPubKey = arguments . length > 3 && arguments [ 3 ] !== undefined ? arguments [ 3 ] : false ; var hashcode = arguments . length > 4 && arguments [ 4 ] !== undefined ? arguments [ 4 ] : zconstants . SIGHASH_ALL ; // Make a copy var txObj = JSON . parse ( JSON . stringify ( _txObj ) ) ; // Prepare our signature // Get script from the current tx input var script = txObj . ins [ i ] . prevScriptPubKey ; // Populate current tx in with the prevScriptPubKey var signingTx = signatureForm ( txObj , i , script , hashcode ) ; // Get script signature var scriptSig = getScriptSignature ( privKey , signingTx , hashcode ) ; // Chuck it back into txObj and add pubkey // Protocol: // PUSHDATA // signature data and SIGHASH_ALL // PUSHDATA // public key data var pubKey = zaddress . privKeyToPubKey ( privKey , compressPubKey ) ; txObj . ins [ i ] . script = zbufferutils . getPushDataLength ( scriptSig ) + scriptSig + zbufferutils . getPushDataLength ( pubKey ) + pubKey ; return txObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Gets signatures needed for multi - sign tx [CODESPLIT] function multiSign ( _txObj , i , privKey , redeemScript ) { var hashcode = arguments . length > 4 && arguments [ 4 ] !== undefined ? arguments [ 4 ] : zconstants . SIGHASH_ALL ; // Make a copy var txObj = JSON . parse ( JSON . stringify ( _txObj ) ) ; // Populate current tx.ins[i] with the redeemScript var signingTx = signatureForm ( txObj , i , redeemScript , hashcode ) ; return getScriptSignature ( privKey , signingTx , hashcode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Applies the signatures to the transaction object NOTE : You NEED to supply the signatures in order . E . g . You made sigAddr1 with priv1 priv3 priv2 You can provide signatures of ( priv1 priv2 ) ( priv3 priv2 ) ... But not ( priv2 priv1 ) [CODESPLIT] function applyMultiSignatures ( _txObj , i , signatures , redeemScript ) { // Make a copy var txObj = JSON . parse ( JSON . stringify ( _txObj ) ) ; var redeemScriptPushDataLength = zbufferutils . getPushDataLength ( redeemScript ) ; // Lmao no idea, just following the source code if ( redeemScriptPushDataLength . length > 2 ) { if ( redeemScriptPushDataLength . length === 6 ) { redeemScriptPushDataLength = redeemScriptPushDataLength . slice ( 2 , 4 ) ; } } // http://www.soroushjp.com/2014/12/20/bitcoin-multisig-the-hard-way-understanding-raw-multisignature-bitcoin-transactions/ txObj . ins [ i ] . script = zopcodes . OP_0 + signatures . map ( function ( x ) { return zbufferutils . getPushDataLength ( x ) + x ; } ) . join ( '' ) + zopcodes . OP_PUSHDATA1 + redeemScriptPushDataLength + redeemScript ; return txObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if str matches the given pattern . [CODESPLIT] function bash ( str , pattern , options ) { if ( typeof str !== 'string' ) { throw new TypeError ( 'expected a string' ) ; } if ( typeof pattern !== 'string' ) { throw new TypeError ( 'expected a string' ) ; } if ( isWindows ( ) ) { throw new Error ( 'bash-match does not work on windows' ) ; } try { var opts = createOptions ( pattern , options ) ; var res = spawn . sync ( getBashPath ( ) , cmd ( str , pattern , opts ) , opts ) ; var err = toString ( res . stderr ) ; if ( err ) { return handleError ( err , opts ) ; } return ! ! toString ( res . stdout ) ; } catch ( err ) { return handleError ( err , opts ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the command to use [CODESPLIT] function cmd ( str , pattern , options ) { var valid = [ 'dotglob' , 'extglob' , 'failglob' , 'globstar' , 'nocaseglob' , 'nullglob' ] ; var args = [ ] ; for ( var key in options ) { if ( options . hasOwnProperty ( key ) && valid . indexOf ( key ) !== - 1 ) { args . push ( '-O' , key ) ; } } args . push ( '-c' , 'IFS=$\"\\n\"; if [[ \"' + str + '\" = ' + pattern + ' ]]; then echo true; fi' ) ; return args ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shallow clone and create options [CODESPLIT] function createOptions ( pattern , options ) { if ( options && options . normalized === true ) return options ; var opts = extend ( { cwd : process . cwd ( ) } , options ) ; if ( opts . nocase === true ) opts . nocaseglob = true ; if ( opts . nonull === true ) opts . nullglob = true ; if ( opts . dot === true ) opts . dotglob = true ; if ( ! opts . hasOwnProperty ( 'globstar' ) && pattern . indexOf ( '**' ) !== - 1 ) { opts . globstar = true ; } if ( ! opts . hasOwnProperty ( 'extglob' ) && isExtglob ( pattern ) ) { opts . extglob = true ; } opts . normalized = true ; return opts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get bash path [CODESPLIT] function getBashPath ( ) { if ( bashPath ) return bashPath ; if ( fs . existsSync ( '/usr/local/bin/bash' ) ) { bashPath = '/usr/local/bin/bash' ; } else if ( fs . existsSync ( '/bin/bash' ) ) { bashPath = '/bin/bash' ; } else { bashPath = 'bash' ; } return bashPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if ( left < = p < = right ) . False otherwise . [CODESPLIT] function isBetween ( p , left , right ) { if ( p >= left && p <= right ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Copyright ( c ) 2014 Jan Blaha [CODESPLIT] function ( reporter , definition ) { this . reporter = reporter this . definition = definition this . reporter . beforeRenderListeners . add ( definition . name , this , Statistics . prototype . handleBeforeRender ) this . reporter . afterRenderListeners . add ( definition . name , this , Statistics . prototype . handleAfterRender ) this . _defineEntities ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Converts a Z secret key to a transmission key [CODESPLIT] function zSecretKeyToTransmissionKey ( a_sk ) { var sk_enc = prf . PRF_addr_sk_enc ( Buffer . from ( a_sk , 'hex' ) ) ; // Curve 25519 clamping sk_enc [ 0 ] &= 248 ; sk_enc [ 32 ] &= 127 ; sk_enc [ 31 ] |= 64 ; return Buffer . from ( sodium . crypto_scalarmult_base ( sk_enc ) ) . toString ( 'hex' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------- [CODESPLIT] function changeEvent ( event ) { var srcPattern = new RegExp ( '/.*(?=/' + config . source + ')/' ) ; log ( 'File ' + event . path . replace ( srcPattern , '' ) + ' ' + event . type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides in memory storage and regular flush to disk . [CODESPLIT] function Memory ( options ) { options = options || { } ; var self = this ; self . flush = options . db . _db . _memory . flush || false ; self . flushInterval = options . db . _db . _memory . flushInterval || 10000 ; self . flushFile = options . file ; self . memoryTable = [ ] ; console . log ( 'Data will be handled using \\'Memory\\' driver' ) ; // :S yeah we need to load it synchronously otherwise it might be loaded after the first insert var content = util . fileSystem . readSync ( self . flushFile ) ; self . set ( content ) ; if ( self . flush ) { console . log ( '\\'Memory\\' driver will flush data every %sms' , self . flushInterval ) ; // set interval to flush setInterval ( function flushToDisk ( ) { util . fileSystem . lock ( self . flushFile , function afterLock ( err ) { if ( err ) { throw err ; } self . get ( function afterGet ( err , inMemoryContent ) { if ( err ) { util . fileSystem . unlock ( self . flushFile ) ; throw err ; } util . fileSystem . write ( self . flushFile , inMemoryContent , function afterWrite ( err ) { util . fileSystem . unlock ( self . flushFile ) ; if ( err ) { throw err ; } } ) ; } ) ; } ) ; } , self . flushInterval ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "START : Module logic start [CODESPLIT] function VarStreamWriter ( callback , options ) { this . lastContext = '' ; this . callback = callback ; // Output stream callback\r this . options = options ; this . imbricatedArrayEntries = new Array ( ) ; this . scopes = new Array ( ) ; this . contexts = new Array ( ) ; this . previousContext = '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "removes the items from craftable if result is picked up [CODESPLIT] function deductcost ( ) { var cost = [ ] ; if ( ! giving . have || giving . have . length < 1 ) return ; // flatten var cost = [ ] ; for ( var i = 0 ; i < giving . have . length ; i ++ ) { for ( var j = 0 ; j < giving . have [ i ] . length ; j ++ ) { cost . push ( giving . have [ i ] [ j ] ) ; } } if ( typeof cost [ 0 ] === 'string' ) cost = [ cost ] ; function deduct ( from , amt ) { var current = parseInt ( from . getAttribute ( 'data-quantity' ) ) ; current -= amt ; from . setAttribute ( 'data-quantity' , current ) ; updateAmounts ( from ) ; if ( current < 1 ) { from . setAttribute ( 'data-type' , 'none' ) ; from . innerHTML = '' ; } } [ ] . forEach . call ( craftable . querySelectorAll ( 'li' ) , function ( li , i ) { var row = Math . floor ( i / 3 ) ; var has = ( li . getAttribute ( 'data-type' ) || 'none' ) . toLowerCase ( ) ; for ( var c = 0 ; c < cost . length ; c ++ ) { if ( cost [ c ] [ 0 ] . toLowerCase ( ) === has ) { var price = cost [ c ] [ 1 ] ; cost . splice ( c , 1 ) ; deduct ( li , price ) ; return false ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides the most common I / O operations . [CODESPLIT] function DataHandler ( options ) { options = options || { } ; var dataHandler = options . db . _db . _driver || 'disk' ; switch ( dataHandler ) { // load the driver to be used just once case 'memory' : this . dataHandlerDriver = new Memory ( options ) ; break ; case 'disk' : default : this . dataHandlerDriver = new Disk ( options ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "START : Module logic start Constructor [CODESPLIT] function VarStreamReader ( scope , prop , options ) { // Keep a ref to the root scope\r this . rootScope = { root : scope , prop : prop } ; // Save the options\r this . options = options ; // Store current scopes for backward references\r this . previousNodes = [ ] ; // The parse state\r this . state = PARSE_NEWLINE ; // The current values\r this . leftValue = '' ; this . rightValue = '' ; this . operator = '' ; this . escaped = ESC_NONE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor [CODESPLIT] function VarStream ( rootObject , rootProperty , options ) { var self = this ; // Ensure new were used\r if ( ! ( this instanceof VarStream ) ) { return new VarStream ( rootObject , rootProperty , options ) ; } // Ensure we had root object and property\r if ( ! ( rootObject instanceof Object ) ) { throw new Error ( 'No root object provided.' ) ; } if ( 'string' !== typeof rootProperty || ootProperty  =  ')   \r throw new Error ( 'No root property name given.' ) ; } // Parent constructor\r DuplexStream . call ( this ) ; this . _varstreamReader = new VarStreamReader ( rootObject , rootProperty , options ? options & VarStreamReader . OPTIONS : 0 ) ; this . _varstreamWriter = new VarStreamWriter ( function ( str ) { self . push ( new Buffer ( str , 'utf8' ) ) ; } , options ? options & VarStreamWriter . OPTIONS : 0 ) ; // Parse input\r this . _write = function _write ( chunk , encoding , done ) { this . _varstreamReader . read ( chunk . toString ( encoding !== 'buffer' ? encoding : 'utf8' ) ) ; done ( ) ; } ; // Output data\r this . _read = function _read ( ) { this . _varstreamWriter . write ( rootObject [ rootProperty ] ) ; this . push ( null ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "descend a specific node or descend all [CODESPLIT] function ( sub_node ) { if ( sub_node ) { walk ( sub_node , depth + 1 ) ; } else if ( node . pages ) { node . pages . forEach ( function ( sub_node , name ) { walk ( sub_node , depth + 1 ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * :: export type NodejsVersion = { version : string ; date : string ; files : string [] ; modules : string ; lts : boolean | string ; } ; [CODESPLIT] function find ( list /* : NodejsVersion[] */ , version /* : string */ ) /* : NodejsVersion */ { for ( let v = 0 , vLength = list . length ; v < vLength ; v += 1 ) { const candidate = list [ v ] if ( candidate . version === version ) { return candidate } } throw new Error ( ` ${ version } ` ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor [CODESPLIT] function Duplexer ( options , writableStream , readableStream ) { const _this = this ; // Ensure new were used if ( ! ( this instanceof Duplexer ) ) { return new ( Duplexer . bind . apply ( Duplexer , // eslint-disable-line [ Duplexer ] . concat ( [ ] . slice . call ( arguments , 0 ) ) ) ) ( ) ; } // Mapping args if ( isStream ( options ) ) { readableStream = writableStream ; writableStream = options ; options = { } ; } else { options = options || { } ; } this . _reemitErrors = 'boolean' === typeof options . reemitErrors ? options . reemitErrors : true ; delete options . reemitErrors ; // Checking arguments if ( ! isStream ( writableStream , 'Writable' , 'Duplex' ) ) { throw new Error ( 'The writable stream must be an instanceof Writable or Duplex.' ) ; } if ( ! isStream ( readableStream , 'Readable' ) ) { throw new Error ( 'The readable stream must be an instanceof Readable.' ) ; } // Parent constructor Stream . Duplex . call ( this , options ) ; // Save streams refs this . _writable = writableStream ; this . _readable = readableStream ; // Internal state this . _waitDatas = false ; this . _hasDatas = false ; if ( 'undefined' == typeof this . _readable . _readableState ) { this . _readable = new Stream . Readable ( { objectMode : options . objectMode || false , } ) . wrap ( this . _readable ) ; } if ( this . _reemitErrors ) { this . _writable . on ( 'error' , err => { _this . emit ( 'error' , err ) ; } ) ; this . _readable . on ( 'error' , err => { _this . emit ( 'error' , err ) ; } ) ; } this . _writable . on ( 'drain' , ( ) => { _this . emit ( 'drain' ) ; } ) ; this . once ( 'finish' , ( ) => { _this . _writable . end ( ) ; } ) ; this . _writable . once ( 'finish' , ( ) => { _this . end ( ) ; } ) ; this . _readable . on ( 'readable' , ( ) => { _this . _hasDatas = true ; if ( _this . _waitDatas ) { _this . _pushAll ( ) ; } } ) ; this . _readable . once ( 'end' , ( ) => { _this . push ( null ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers dependencies that can be provided to the function [CODESPLIT] function ( provides ) { if ( _ . isArray ( provides ) ) { this . _arguments = this . _provides = ( ! this . _provides ) ? provides : this . _provides . concat ( provides ) ; } else { this . _provides = _ . extend ( { } , this . _provides , provides ) ; this . _arguments = _ . map ( this . deps , function ( key ) { return this . _provides [ key ] ; } , this ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the function [CODESPLIT] function ( context , callback ) { if ( arguments . length === 1 ) { callback = context ; context = this . _context ; } if ( this . isAsync ) { // clone the arguments so this.call can be reused with different callbacks var asyncArgs = this . _arguments . slice ( ) ; // push the callback onto the new arguments array asyncArgs . push ( callback ) ; // call the function this . fn . apply ( context , asyncArgs ) ; } else { // if the function isn't async, allow it to be called with or without a callback if ( callback ) { // If a callback is provided, it must use the error-first arguments pattern. // The return value of the function will be the second argument. try { callback ( null , this . fn . apply ( context , this . _arguments ) ) ; } catch ( e ) { callback ( e ) ; } } else { // If no callback is provided simply return the result of the function return this . fn . apply ( context , this . _arguments ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies the function iterator to each item in arr in parallel . [CODESPLIT] function each ( arr , callback ) { var wrapper = this ; if ( this . isAsync ) { return async . each ( arr , function ( item , cb ) { wrapper . call ( item , cb ) ; } , callback ) ; } else { arr . each ( function ( item ) { wrapper . call ( item ) ; } ) ; if ( callback ) { callback ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the results of interating the function on each item in an array . [CODESPLIT] function map ( arr , callback ) { var wrapper = this ; if ( this . isAsync ) { async . map ( arr , function ( item , cb ) { wrapper . call ( item , cb ) ; } , callback ) ; } else { callback ( null , arr . map ( function ( item ) { return wrapper . call ( item ) ; } ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "force wrap to true defining events callback [CODESPLIT] function ( selectedDates , dateStr , instance ) { that . setProperty ( \"dateValue\" , selectedDates , true ) ; that . fireOnChange ( { selectedDates : selectedDates , dateStr : dateStr , instance : instance } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////// EVENTS HANDLING ////////////////////////////////////////////////// [CODESPLIT] function ( selectedDates , dateStr , instance ) { this . fireOnChange ( { selectedDates : selectedDates , dateStr : dateStr , instance : instance } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "XOR128 pseudo - random number generator . This is based off of algorithm found on the XORSHIFT wiki here : http : // en . wikipedia . org / wiki / Xorshift . Also the code ensures all numbers are handled as unsigned 32bit integers and is consistent with the C ++ example provided xor128 . cpp [CODESPLIT] function XOR128 ( x , y , z , w ) { if ( ( x && x < 1 ) || ( y && y < 1 ) || ( z && z < 1 ) || ( w && w < 1 ) ) { throw new Error ( 'Invalid Seed' ) ; } this . x = x ? x : Math . random ( ) * 4294967296 ; this . y = y ? y : Math . random ( ) * 4294967296 ; this . z = z ? z : Math . random ( ) * 4294967296 ; this . w = w ? w : Math . random ( ) * 4294967296 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "init options [CODESPLIT] function initOptions ( options ) { var defaultOptions = { root : process . cwd ( ) , port : '3333' , style : path . resolve ( __dirname , '../public/screen.css' ) , dtpl : path . resolve ( __dirname , '../public/dir_template.html' ) , ftpl : path . resolve ( __dirname , '../public/file_template.html' ) , view : 'details' , silent : false } ; return merge ( defaultOptions , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start server with provided options [CODESPLIT] function startServer ( options ) { options = initOptions ( options ) ; var app = connect ( ) , root = options . root , TEST = process . env . TEST , isSilent = options . silent || TEST ; if ( ! isSilent ) { app . use ( log ) ; } var smOpts = { } ; var smOptMap = { ftpl : 'template' , style : 'style' } ; Object . keys ( smOptMap ) . forEach ( function ( key ) { if ( options [ key ] !== undefined ) smOpts [ smOptMap [ key ] ] = options [ key ] ; } ) ; // serve markdown file app . use ( serveMarkdown ( root , smOpts ) ) ; // common files app . use ( serveStatic ( root , { index : [ 'index.html' ] } ) ) ; // serve directory app . use ( serveIndex ( root , { icon : true , template : options . dtpl , stylesheet : options . style , view : options . view } ) ) ; debug ( 'server run in ' + ( process . env . TEST ? 'TEST' : 'PRODUCTION' ) + ' mode' ) if ( ! TEST ) { app . listen ( options . port ) ; showSuccessInfo ( options ) ; } return app ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "show server starting information [CODESPLIT] function showSuccessInfo ( options ) { // server start success if ( options . silent ) return ; console . log ( chalk . blue ( 'serve start Success: ' ) + '\\n' + chalk . green ( '\\t url   ' ) + chalk . grey ( 'http://127.0.0.1:' ) + chalk . red ( options . port ) + chalk . grey ( '/' ) + '\\n' + chalk . green ( '\\t serve ' ) + chalk . grey ( options . root ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "simple log middleware output the access log [CODESPLIT] function log ( req , res , next ) { console . log ( '[' + chalk . grey ( ts ( ) ) + '] ' + chalk . white ( decodeURI ( req . url ) ) ) ; next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "type = get | set [CODESPLIT] function ( valueToSet , type , iface , propertyKeys ) { type = type . toLowerCase ( ) ; propertyKeys . forEach ( function ( propertyKey ) { if ( type == 'get' ) valueToSet [ 'Get' + propertyKey ] = function ( callback ) { iface . getProperty ( propertyKey , callback ) ; } else valueToSet [ 'Set' + propertyKey ] = function ( value , callback ) { iface . setProperty ( propertyKey , value , callback ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "MD5 [CODESPLIT] function md5 ( data ) { var md5sum = crypto . createHash ( 'md5' ) ; md5sum . update ( data ) ; return md5sum . digest ( 'hex' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sendpulse API initialization [CODESPLIT] function init ( user_id , secret , storage ) { API_USER_ID = user_id ; API_SECRET = secret ; TOKEN_STORAGE = storage ; var hashName = md5 ( API_USER_ID + '::' + API_SECRET ) ; if ( fs . existsSync ( TOKEN_STORAGE + hashName ) ) { TOKEN = fs . readFileSync ( TOKEN_STORAGE + hashName , { encoding : 'utf8' } ) ; } if ( ! TOKEN . length ) { getToken ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Form and send request to API service [CODESPLIT] function sendRequest ( path , method , data , useToken , callback ) { var headers = { } headers [ 'Content-Type' ] = 'application/json' ; headers [ 'Content-Length' ] = Buffer . byteLength ( JSON . stringify ( data ) ) ; if ( useToken && TOKEN . length ) { headers [ 'Authorization' ] = 'Bearer ' + TOKEN ; } if ( method === undefined ) { method = 'POST' ; } if ( useToken === undefined ) { useToken = false ; } var options = { //uri: API_URL, path : '/' + path , port : 443 , hostname : API_URL , method : method , headers : headers , } ; var req = https . request ( options , function ( response ) { var str = '' ; response . on ( 'data' , function ( chunk ) { if ( response . statusCode == 401 ) { getToken ( ) ; sendRequest ( path , method , data , true , callback ) ; } else { str += chunk ; } } ) ; response . on ( 'end' , function ( ) { if ( response . statusCode != 401 ) { try { var answer = JSON . parse ( str ) ; } catch ( ex ) { var answer = returnError ( ) ; } callback ( answer ) ; } } ) ; } ) ; req . write ( JSON . stringify ( data ) ) ; req . end ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get token and store it [CODESPLIT] function getToken ( ) { var data = { grant_type : 'client_credentials' , client_id : API_USER_ID , client_secret : API_SECRET } sendRequest ( 'oauth/access_token' , 'POST' , data , false , saveToken ) ; function saveToken ( data ) { TOKEN = data . access_token ; var hashName = md5 ( API_USER_ID + '::' + API_SECRET ) ; fs . writeFileSync ( TOKEN_STORAGE + hashName , TOKEN ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Form error object [CODESPLIT] function returnError ( message ) { var data = { is_error : 1 } ; if ( message !== undefined && message . length ) { data [ 'message' ] = message } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create address book [CODESPLIT] function createAddressBook ( callback , bookName ) { if ( ( bookName === undefined ) || ( ! bookName . length ) ) { return callback ( returnError ( \"Empty book name\" ) ) ; } var data = { bookName : bookName } ; sendRequest ( 'addressbooks' , 'POST' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Edit address book name [CODESPLIT] function editAddressBook ( callback , id , bookName ) { if ( ( id === undefined ) || ( bookName === undefined ) || ( ! bookName . length ) ) { return callback ( returnError ( \"Empty book name or book id\" ) ) ; } var data = { name : bookName } ; sendRequest ( 'addressbooks/' + id , 'PUT' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove address book [CODESPLIT] function removeAddressBook ( callback , id ) { if ( id === undefined ) { return callback ( returnError ( 'Empty book id' ) ) ; } sendRequest ( 'addressbooks/' + id , 'DELETE' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get information about book [CODESPLIT] function getBookInfo ( callback , id ) { if ( id === undefined ) { return callback ( returnError ( 'Empty book id' ) ) ; } sendRequest ( 'addressbooks/' + id , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List email addresses from book [CODESPLIT] function getEmailsFromBook ( callback , id ) { if ( id === undefined ) { return callback ( returnError ( 'Empty book id' ) ) ; } sendRequest ( 'addressbooks/' + id + '/emails' , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add new emails to address book [CODESPLIT] function addEmails ( callback , id , emails ) { if ( ( id === undefined ) || ( emails === undefined ) || ( ! emails . length ) ) { return callback ( returnError ( \"Empty email or book id\" ) ) ; } var data = { emails : serialize ( emails ) } ; sendRequest ( 'addressbooks/' + id + '/emails' , 'POST' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get information about email address from book [CODESPLIT] function getEmailInfo ( callback , id , email ) { if ( ( id === undefined ) || ( email === undefined ) || ( ! email . length ) ) { return callback ( returnError ( \"Empty email or book id\" ) ) ; } sendRequest ( 'addressbooks/' + id + '/emails/' + email , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get cost of campaign based on address book [CODESPLIT] function campaignCost ( callback , id ) { if ( id === undefined ) { return callback ( returnError ( 'Empty book id' ) ) ; } sendRequest ( 'addressbooks/' + id + '/cost' , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get list of campaigns [CODESPLIT] function listCampaigns ( callback , limit , offset ) { var data = { } if ( limit === undefined ) { limit = null ; } else { data [ 'limit' ] = limit ; } if ( offset === undefined ) { offset = null ; } else { data [ 'offset' ] = offset ; } sendRequest ( 'campaigns' , 'GET' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get information about campaign [CODESPLIT] function getCampaignInfo ( callback , id ) { if ( id === undefined ) { return callback ( returnError ( 'Empty book id' ) ) ; } sendRequest ( 'campaigns/' + id , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get campaign statistic by countries [CODESPLIT] function campaignStatByCountries ( callback , id ) { if ( id === undefined ) { return callback ( returnError ( 'Empty book id' ) ) ; } sendRequest ( 'campaigns/' + id + '/countries' , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get campaign statistic by referrals [CODESPLIT] function campaignStatByReferrals ( callback , id ) { if ( id === undefined ) { return callback ( returnError ( 'Empty book id' ) ) ; } sendRequest ( 'campaigns/' + id + '/referrals' , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create new campaign [CODESPLIT] function createCampaign ( callback , senderName , senderEmail , subject , body , bookId , name , attachments ) { if ( ( senderName === undefined ) || ( ! senderName . length ) || ( senderEmail === undefined ) || ( ! senderEmail . length ) || ( subject === undefined ) || ( ! subject . length ) || ( body === undefined ) || ( ! body . length ) || ( bookId === undefined ) ) { return callback ( returnError ( 'Not all data.' ) ) ; } if ( name === undefined ) { name = '' ; } if ( attachments === undefined ) { attachments = '' ; } if ( attachments . length ) { attachments = serialize ( attachments ) ; } var data = { sender_name : senderName , sender_email : senderEmail , //subject: encodeURIComponent(subject), //subject: urlencode(subject), subject : subject , body : base64 ( body ) , list_id : bookId , name : name , attachments : attachments } sendRequest ( 'campaigns' , 'POST' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cancel campaign [CODESPLIT] function cancelCampaign ( callback , id ) { if ( id === undefined ) { return callback ( returnError ( 'Empty campaign id' ) ) ; } sendRequest ( 'campaigns/' + id , 'DELETE' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add new sender [CODESPLIT] function addSender ( callback , senderName , senderEmail ) { if ( ( senderEmail === undefined ) || ( ! senderEmail . length ) || ( senderName === undefined ) || ( ! senderName . length ) ) { return callback ( returnError ( 'Empty sender name or email' ) ) ; } var data = { email : senderEmail , name : senderName } sendRequest ( 'senders' , 'POST' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove sender [CODESPLIT] function removeSender ( callback , senderEmail ) { if ( ( senderEmail === undefined ) || ( ! senderEmail . length ) ) { return callback ( returnError ( 'Empty email' ) ) ; } var data = { email : senderEmail } sendRequest ( 'senders' , 'DELETE' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Activate sender using code [CODESPLIT] function activateSender ( callback , senderEmail , code ) { if ( ( senderEmail === undefined ) || ( ! senderEmail . length ) || ( code === undefined ) || ( ! code . length ) ) { return callback ( returnError ( 'Empty email or activation code' ) ) ; } var data = { code : code } sendRequest ( 'senders/' + senderEmail + '/code' , 'POST' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Request mail with activation code [CODESPLIT] function getSenderActivationMail ( callback , senderEmail ) { if ( ( senderEmail === undefined ) || ( ! senderEmail . length ) ) { return callback ( returnError ( 'Empty email' ) ) ; } sendRequest ( 'senders/' + senderEmail + '/code' , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get global information about email [CODESPLIT] function getEmailGlobalInfo ( callback , email ) { if ( ( email === undefined ) || ( ! email . length ) ) { return callback ( returnError ( 'Empty email' ) ) ; } sendRequest ( 'emails/' + email , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove email from all books [CODESPLIT] function removeEmailFromAllBooks ( callback , email ) { if ( ( email === undefined ) || ( ! email . length ) ) { return callback ( returnError ( 'Empty email' ) ) ; } sendRequest ( 'emails/' + email , 'DELETE' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get email statistic by all campaigns [CODESPLIT] function emailStatByCampaigns ( callback , email ) { if ( ( email === undefined ) || ( ! email . length ) ) { return callback ( returnError ( 'Empty email' ) ) ; } sendRequest ( 'emails/' + email + '/campaigns' , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add email to blacklist [CODESPLIT] function addToBlackList ( callback , emails , comment ) { if ( ( emails === undefined ) || ( ! emails . length ) ) { return callback ( returnError ( 'Empty email' ) ) ; } if ( comment === undefined ) { comment = '' ; } var data = { emails : base64 ( emails ) , comment : comment } sendRequest ( 'blacklist' , 'POST' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove emails from blacklist [CODESPLIT] function removeFromBlackList ( callback , emails ) { if ( ( emails === undefined ) || ( ! emails . length ) ) { return callback ( returnError ( 'Empty emails' ) ) ; } var data = { emails : base64 ( emails ) , } sendRequest ( 'blacklist' , 'DELETE' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get balance [CODESPLIT] function getBalance ( callback , currency ) { if ( currency === undefined ) { var url = 'balance' ; } else { var url = 'balance/' + currency . toUpperCase ( ) ; } sendRequest ( url , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SMTP : get list of emails [CODESPLIT] function smtpListEmails ( callback , limit , offset , fromDate , toDate , sender , recipient ) { if ( limit === undefined ) { limit = 0 ; } if ( offset === undefined ) { offset = 0 ; } if ( fromDate === undefined ) { fromDate = '' ; } if ( toDate === undefined ) { toDate = '' ; } if ( sender === undefined ) { sender = '' ; } if ( recipient === undefined ) { recipient = '' ; } var data = { limit : limit , offset : offset , from : fromDate , to : toDate , sender : sender , recipient : recipient } sendRequest ( 'smtp/emails' , 'GET' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get information about email by id [CODESPLIT] function smtpGetEmailInfoById ( callback , id ) { if ( ( id === undefined ) || ( ! id . length ) ) { return callback ( returnError ( 'Empty id' ) ) ; } sendRequest ( 'smtp/emails/' + id , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SMTP : add emails to unsubscribe list [CODESPLIT] function smtpUnsubscribeEmails ( callback , emails ) { if ( emails === undefined ) { return callback ( returnError ( 'Empty emails' ) ) ; } var data = { emails : serialize ( emails ) } sendRequest ( 'smtp/unsubscribe' , 'POST' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SMTP : add new domain [CODESPLIT] function smtpAddDomain ( callback , email ) { if ( ( email === undefined ) || ( ! email . length ) ) { return callback ( returnError ( 'Empty email' ) ) ; } var data = { email : email } sendRequest ( 'smtp/domains' , 'POST' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SMTP : verify domain [CODESPLIT] function smtpVerifyDomain ( callback , email ) { if ( ( email === undefined ) || ( ! email . length ) ) { return callback ( returnError ( 'Empty email' ) ) ; } sendRequest ( 'smtp/domains/' + email , 'GET' , { } , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SMTP : send mail [CODESPLIT] function smtpSendMail ( callback , email ) { if ( email === undefined ) { return callback ( returnError ( 'Empty email data' ) ) ; } email [ 'html' ] = base64 ( email [ 'html' ] ) ; var data = { email : serialize ( email ) } ; sendRequest ( 'smtp/emails' , 'POST' , data , true , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse options [CODESPLIT] function getOpt ( resHtml , outputPath ) { if ( commandLine . minifyall ) { console . log ( '' ) ; console . log ( 'minify all. Process may take a few minutes with large file.' ) ; console . log ( '' ) ; minifyFile ( resHtml , outputPath ) ; } else { console . log ( '' ) ; console . log ( 'Output file name : ' + outputPath ) ; console . log ( '' ) ; writeFile ( resHtml , outputPath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "minify the result [CODESPLIT] function minifyFile ( resHtml , outputPath ) { var resHtml = minify ( resHtml , opt , function ( err ) { if ( err ) { console . error ( 'error will processing file.' ) ; } } ) ; console . log ( '' ) ; console . log ( 'Output file name : ' + outputPath ) ; console . log ( '' ) ; writeFile ( resHtml , outputPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write result to file [CODESPLIT] function writeFile ( resHtml , outputPath ) { fs . writeFile ( outputPath , resHtml , function ( err ) { if ( err ) { console . log ( '' ) ; console . log ( 'File error: ' + err + '. Exit.' ) ; } else { console . log ( '' ) ; console . log ( 'All done. Exit.' . green ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : If extends other interfaces then concatenate schemas from those order sets precedence ( first is overrides ) . Then superimpose given schema on top of these . [CODESPLIT] function ( params ) { // Schema defines fields and can be used for validation and form generation (optional) this . schema = params . schema ; // The name of the interface, this should be unique this . name = params . name ; // Additional properties that aren't exposed as form data, in the future this might be  // used to check that objects fulfill the implementation this . members = params . members ; this . interfaceId = uuid . v4 ( ) ; // console.log(\"[SCHEMA] Created interface [\" + this.name + \"] with id: \" + this.interfaceId); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function AdapterRegistryException ( message , context ) { this . message = message ; this . name = \"AdapterRegistryException\" ; this . context = context ; this . stack = ( new Error ( ) ) . stack ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a cookie instance . [CODESPLIT] function Cookie ( options ) { this . options = options || { } ; this . options . expires = typeof this . options . expires === 'number' ? this . options . expires : 30 ; this . options . path = this . options . path !== undefined ? this . options . path : '/' ; this . options . secure = typeof this . options . secure === 'boolean' ? this . options . secure : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a cookie value . [CODESPLIT] function set ( key , value , options ) { options = options || this . options ; var days = parseInt ( options . expires || - 1 ) ; if ( value !== undefined && typeof value !== 'function' ) { var t = new Date ( ) ; t . setDate ( ( t . getDate ( ) + days ) ) ; var res = ( document . cookie = [ this . encode ( key ) , '=' , this . stringify ( value ) , // use expires attribute, max-age is not supported by IE options . expires ? '; expires=' + t . toUTCString ( ) : '' , options . path ? '; path=' + options . path : '' , options . domain ? '; domain=' + options . domain : '' , options . secure ? '; secure' : '' ] . join ( '' ) ) ; return res ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a cookie value . [CODESPLIT] function get ( key , value ) { var i , parts , name , cookie ; var result = key ? undefined : { } ; /* istanbul ignore next */ var cookies = ( document . cookie || '' ) . split ( '; ' ) ; for ( i = 0 ; i < cookies . length ; i ++ ) { parts = cookies [ i ] . split ( '=' ) ; name = this . decode ( parts . shift ( ) ) ; cookie = parts . join ( '=' ) ; if ( key && key === name ) { // if second argument (value) is a function it's a converter result = this . read ( cookie , value ) ; break ; } // prevent storing a cookie that we couldn't decode if ( ! key && ( cookie = this . read ( cookie ) ) !== undefined ) { result [ name ] = cookie ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete a cookie value . [CODESPLIT] function del ( key , options ) { if ( ! options ) { options = { } ; for ( var z in this . options ) { options [ z ] = this . options [ z ] ; } } options . expires = - 1 ; this . set ( key , '' , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear all stored cookies optionally keeping the keys in the except array . [CODESPLIT] function clear ( except , options ) { var keys = this . get ( ) , z ; except = except || [ ] ; for ( z in keys ) { if ( ~ except . indexOf ( z ) ) { continue ; } this . del ( z , options ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Curry a binary function . [CODESPLIT] function curry2 ( fn , self ) { var out = function ( ) { if ( arguments . length === 0 ) return out return arguments . length > 1 ? fn . apply ( self , arguments ) : bind . call ( fn , self , arguments [ 0 ] ) } out . uncurry = function uncurry ( ) { return fn } return out }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * list can be either [[ x y ] [ x y ]] or [ x y ] [CODESPLIT] function createTouchList ( target , list ) { if ( Array . isArray ( list ) && list [ 0 ] && ! Array . isArray ( list [ 0 ] ) ) { list = [ list ] ; } list = list . map ( function ( entry , index ) { var x = entry [ 0 ] ; var y = entry [ 1 ] ; var id = entry [ 2 ] || index ; return createTouch ( x , y , target , id ) ; } ) ; return document . createTouchList . apply ( document , list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "http : // stackoverflow . com / questions / 7056026 / variation - of - e - touches - e - targettouches - and - e - changedtouches [CODESPLIT] function initTouchEvent ( touchEvent , type , touches ) { var touch1 = touches [ 0 ] ; return touchEvent . initTouchEvent ( //touches touches , //targetTouches touches , //changedTouches touches , //type type , //view window , //screenX touch1 . screenX , //screenY touch1 . screenY , //clientX touch1 . clientX , //clientY touch1 . clientY , //ctrlKey false , //altKey false , //shiftKey false , //metaKey false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@public @memberOf { app . Unit } @method [CODESPLIT] function ( ) { if ( _ . isObject ( this . cache ) ) { return this . cache ; } if ( _ . has ( this . app . caches , this . cache ) ) { return this . app . caches [ this . cache ] ; } throw new errors . NoSuchCacheError ( f ( 'You should define app.caches[%j] interface' , this . cache ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- Utils -- Shortcut for creating an icon button within a viewer . [CODESPLIT] function createIconButton ( viewerElm , css , eventType ) { const buttonElm = $ . create ( 'div' , { 'class' : css } ) $ . listen ( buttonElm , { 'click' : ( event ) => { event . preventDefault ( ) if ( event . buttons === 0 ) { $ . dispatch ( viewerElm , eventType ) } } } ) return buttonElm }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@class Context [CODESPLIT] function Context ( params , logger ) { /**\n     * @public\n     * @memberOf {Context}\n     * @property\n     * @type {Object}\n     * */ this . params = params ; /**\n     * @public\n     * @memberOf {Context}\n     * @property\n     * @type {Object}\n     * */ this . result = new Obus ( ) ; /**\n     * @public\n     * @memberOf {Context}\n     * @property\n     * @type {Object}\n     * */ this . errors = new Obus ( ) ; /**\n     * @public\n     * @memberOf {Context}\n     * @property\n     * @type {Logger}\n     * */ this . logger = logger ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* END : Utility Functions ** * START : Classes used by compiled templates ** [CODESPLIT] function ContextStack ( dict , tpl ) { this [ cache_stack ] = [ ] ; this . tpl = tpl ; this . push ( util . global ) ; if ( tpl . fallback !== U ) { this . hasFallback = true ; this . fallback = tpl . fallback ; } switch ( util . ntype ( dict ) ) { case 'object' : this . push ( dict ) ; break ; case 'array' : dict [ fn_var . dict ] ? dict . map ( this . push , this ) : this . push ( dict ) ; break ; default : ! util . exists ( dict ) || this . push ( dict ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* END : Classes used by compiled templates ** * START : create template methods ** [CODESPLIT] function aggregatetNonEmpty ( res , str ) { util . empty ( str ) || res . push ( str ) ; return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@class Track [CODESPLIT] function Track ( app , logger ) { /**\n     * @public\n     * @memberOf {Track}\n     * @property\n     * @type {String}\n     * */ this . id = this . _createId ( ) ; /**\n     * TODO Deprecate?\n     *\n     * @public\n     * @memberOf {Track}\n     * @property\n     * @type {Logger}\n     * */ this . logger = logger ; /**\n     * @public\n     * @memberOf {Track}\n     * @property\n     * @type {Object}\n     * */ this . params = { } ; /**\n     * @protected\n     * @memberOf {Track}\n     * @property\n     * @type {Core}\n     * */ this . _app = app ; /**\n     * @public\n     * @memberOf {Track}\n     * @property\n     * @type {Object}\n     * */ this . calls = { } ; /**\n     * @protected\n     * @memberOf {Track}\n     * @property\n     * @type {Boolean}\n     * */ this . _isFlushed = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clone behaviour for gallery items used when creating a helper for the purpose of sorting . [CODESPLIT] function cloneGalleryItem ( inst , element ) { // Clone the element const clone = element . cloneNode ( true ) // Remove id attribute to avoid unwanted duplicates clone . removeAttribute ( 'id' ) // Add a helper class clone . classList . add ( 'mh-gallery-item--sort-helper' ) return clone }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@class FistError @extends Error [CODESPLIT] function FistError ( code , msg ) { var err = new Error ( f ( '(%s) %s' , code , msg ) ) ; err . name = this . name ; Error . captureStackTrace ( err , this . constructor ) ; /**\n     * @public\n     * @memberOf {FistError}\n     * @property\n     * @type {String}\n     * */ this . code = code ; /**\n     * @public\n     * @memberOf {FistError}\n     * @property\n     * @type {String}\n     * */ this . message = err . message ; /**\n     * @public\n     * @memberOf {FistError}\n     * @property\n     * @type {String}\n     * */ this . stack = err . stack ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@class Connect @extends Track [CODESPLIT] function Connect ( app , logger , req , res ) { /**\n     * @public\n     * @memberOf {Connect}\n     * @property\n     * @type {IncomingMessage}\n     * */ this . req = req ; /**\n     * @public\n     * @memberOf {Connect}\n     * @property\n     * @type {ServerResponse}\n     * */ this . res = res ; //  TODO give connect and track same signature Track . call ( this , app , logger ) ; /**\n     * @public\n     * @memberOf {Connect}\n     * @property\n     * @type {String}\n     * */ this . route = null ; /**\n     * @public\n     * @memberOf {Connect}\n     * @property\n     * @type {Array<String>}\n     * */ this . matches = [ ] ; /**\n     * @public\n     * @memberOf {Connect}\n     * @property\n     * @type {Number}\n     * */ this . routeIndex = - 1 ; /**\n     * @private\n     * @memberOf {Connect}\n     * @property\n     * @type {Object}\n     * */ this . _url = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "upload or update file function [CODESPLIT] function ( localFilePath ) { let contentType = mime . lookup ( localFilePath ) ; let standerFilePath = localFilePath . replace ( / \\\\ / g , '/' ) ; fs . readFile ( localFilePath , function ( readFileErr , fileData ) { if ( readFileErr ) { throw readFileErr ; } const putConfig = { Bucket : bucket . Name , Body : fileData , Key : standerFilePath , ContentType : contentType , AccessControlAllowOrigin : options . AccessControlAllowOrigin || '*' , CacheControl : options . CacheControl || 'no-cache' , Expires : options . Expires || null } ; if ( options . contentEncoding ) { putConfig . ContentEncoding = options . contentEncoding ; } oss . putObject ( putConfig , function ( putObjectErr ) { if ( putObjectErr ) { console . error ( 'error:' , putObjectErr ) ; return putObjectErr ; } console . log ( 'upload success: ' + localFilePath ) ; if ( bucketPaths . indexOf ( standerFilePath ) === - 1 ) { bucketPaths . push ( standerFilePath ) ; } if ( localPaths . indexOf ( standerFilePath ) === - 1 ) { localPaths . push ( standerFilePath ) ; } //refresh cdn if ( options . oss . autoRefreshCDN && cdn ) { if ( options . cdn . refreshQuota < 1 ) { console . error ( 'There is no refresh cdn url quota today.' ) ; return ; } let cdnDomain = '' ; if ( / ^http / . test ( options . cdn . domain ) ) { cdnDomain = options . cdn . domain . replace ( / ^https?:?\\/?\\/? / , '' ) ; options . cdn . secure === undefined && ( options . cdn . secure = / ^https / . test ( options . cdn . domein ) ) ; } else { cdnDomain = options . cdn . domain ; } let cdnObjectPath = url . format ( { protocol : options . oss . secure ? 'https' : 'http' , hostname : cdnDomain , pathname : standerFilePath } ) ; options . debug && console . log ( 'Refreshing CDN file: ' , cdnObjectPath ) ; cdn . refreshObjectCaches ( { ObjectType : 'File' , ObjectPath : cdnObjectPath } , function ( refreshCDNErr ) { if ( refreshCDNErr ) { console . error ( 'refresh cdn error: ' , refreshCDNErr ) ; } else { options . cdn . refreshQuota -- ; console . log ( 'Refresh cdn file success: ' , cdnObjectPath ) ; } } ) ; } } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "delete bucket file function [CODESPLIT] function ( filePath ) { let standerPath = filePath . replace ( / \\\\ / g , '/' ) ; oss . deleteObject ( { Bucket : bucket . Name , Key : standerPath } , function ( err ) { if ( err ) { console . log ( 'error:' , err ) ; return err ; } let bucketIndex = bucketPaths . indexOf ( standerPath ) ; if ( bucketIndex !== - 1 ) { bucketPaths . splice ( bucketIndex , 1 ) ; } let localIndex = localPaths . indexOf ( standerPath ) ; if ( localIndex !== - 1 ) { localPaths . splice ( localIndex , 1 ) ; } console . log ( 'delete success:' + standerPath ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@class Runtime @extends Context [CODESPLIT] function Runtime ( unit , track , parent , args , done ) { // Create lite context to provide an interface to check execution parameters var context = new Context . Lite ( ) . // add default context params addParams ( unit . params ) . // add track's params addParams ( track . params ) . // add local args addParams ( args ) ; /**\n     * Runtime identity is a part of cacheKey and memorization key\n     *\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {String}\n     * */ this . identity = unit . identify ( track , context ) ; /**\n     * Invoking unit\n     *\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {Unit}\n     * */ this . unit = unit ; /**\n     * Request handling runtime\n     *\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {Track}\n     * */ this . track = track ; /**\n     * The dependant Runtime\n     *\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {Runtime}\n     * */ this . parent = parent ; /**\n     * Finish listener\n     *\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {Function}\n     * */ this . done = done ; /**\n     * The number of dependencies remaining to resolve\n     *\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {Number}\n     * */ this . pathsLeft = 0 ; /**\n     * The array of dependency identities\n     *\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {Array}\n     * */ this . keys = [ ] ; /**\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {Date}\n     * */ this . creationDate = 0 ; /**\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {*}\n     * */ this . value = undefined ; /**\n     * The status of current runtime\n     *\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {Number}\n     * */ this . statusBits = 0 ; /**\n     * Runtime context\n     *\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {Context}\n     * */ this . context = context ; /**\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {Array<Runtime>}\n     * */ this . listeners = [ ] ; /**\n     * @public\n     * @memberOf {Runtime}\n     * @property\n     * @type {String}\n     * */ this . cacheKey = unit . app . params . name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup and return dispatch function . The dispatch function will call the relevant action handler . [CODESPLIT] function setupDispatch ( { actions : actionHandlers = { } , schemas = { } , services = { } , middlewares = [ ] , identOptions = { } } ) { const getService = setupGetService ( schemas , services ) let dispatch = async ( action ) => { debug ( 'Dispatch: %o' , action ) return handleAction ( action , { schemas , services , dispatch , identOptions , getService } , actionHandlers ) } if ( middlewares . length > 0 ) { dispatch = compose ( ... middlewares ) ( dispatch ) } return dispatch }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get next time for a schedule . Will never return the current time even if it is valid for the schedule unless allowNow is true . [CODESPLIT] function nextSchedule ( schedule , allowNow = false ) { if ( schedule ) { try { const dates = later . schedule ( schedule ) . next ( 2 ) return nextDate ( dates , allowNow ) } catch ( error ) { throw TypeError ( 'Invalid schedule definition' ) } } return null }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete several items from a service based on the given payload . [CODESPLIT] async function deleteFn ( action , { getService } = { } ) { debug ( 'Action: DELETE' ) const { type , id , service : serviceId , endpoint } = action . payload const service = ( typeof getService === 'function' ) ? getService ( type , serviceId ) : null if ( ! service ) { return createUnknownServiceError ( type , serviceId , 'DELETE' ) } const data = prepareData ( action . payload ) if ( data . length === 0 ) { return createError ( ` ${ service . id } ` , 'noaction' ) } const endpointDebug = ( endpoint ) ? ` ${ endpoint } ` : ` ${ type } ${ id } ` debug ( 'DELETE: Delete from service \\'%s\\' at %s.' , service . id , endpointDebug ) const { response } = await service . send ( appendToAction ( action , { data } ) ) return ( response . status === 'ok' ) ? { status : 'ok' } : response }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize and map a request to an action and map and serialize its response . [CODESPLIT] async function request ( action , { getService , dispatch } ) { debug ( 'Action: REQUEST' ) const { type , service : serviceId = null , endpoint } = action . payload const service = getService ( type , serviceId ) if ( ! service ) { return createUnknownServiceError ( type , serviceId , 'GET' ) } const endpointDebug = ( endpoint ) ? ` ${ endpoint } ` : ` ${ type } ` debug ( 'REQUEST: Fetch from service %s at %s' , service . id , endpointDebug ) const { response } = await service . receive ( action , dispatch ) return response }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an ident item from service based on the meta . ident object on the action . [CODESPLIT] async function getIdent ( { payload , meta } , { getService , identOptions = { } } ) { if ( ! meta . ident ) { return createError ( 'GET_IDENT: The request has no ident' , 'noaction' ) } const { type } = identOptions if ( ! type ) { return createError ( 'GET_IDENT: Integreat is not set up with authentication' , 'noaction' ) } const service = getService ( type ) if ( ! service ) { return createUnknownServiceError ( type , null , 'GET_IDENT' ) } const propKeys = preparePropKeys ( identOptions . props ) const params = prepareParams ( meta . ident , propKeys ) if ( ! params ) { return createError ( 'GET_IDENT: The request has no ident with id or withToken' , 'noaction' ) } const { response } = await service . send ( { type : 'GET' , payload : { type , ... params } , meta : { ident : { root : true } } } ) return prepareResponse ( response , payload , propKeys ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an Integreat instance with a dispatch method . Use the dispatch method for sending actions to services for retrieving typed items and updating data . [CODESPLIT] function integreat ( { schemas : typeDefs , services : serviceDefs , mappings = [ ] , auths : authDefs = [ ] , ident : identOptions = { } } , { adapters = { } , authenticators = { } , filters = { } , transformers = { } , actions = { } } = { } , middlewares = [ ] ) { if ( ! serviceDefs || ! typeDefs ) { throw new TypeError ( 'Call integreat with at least services and schemas' ) } // Merge custom actions with built-in actions actions = { ... builtinActions , ... actions } // Setup schemas object from type defs const schemas = R . compose ( R . indexBy ( R . prop ( 'id' ) ) , R . map ( schema ) ) ( typeDefs ) const pluralTypes = Object . keys ( schemas ) . reduce ( ( plurals , type ) => ( { ... plurals , [ schemas [ type ] . plural ] : type } ) , { } ) // Setup auths object from auth defs const auths = authDefs . reduce ( ( auths , def ) => ( def ) ? { ... auths , [ def . id ] : { authenticator : authenticators [ def && def . authenticator ] , options : def . options , authentication : null } } : auths , { } ) // Setup services object from service defs. const services = R . compose ( R . indexBy ( R . prop ( 'id' ) ) , R . map ( createService ( { adapters , auths , transformers , schemas , setupMapping : setupMapping ( { filters , transformers , schemas , mappings } ) } ) ) ) ( serviceDefs ) // Return Integreat instance return { version , schemas , services , identType : identOptions . type , /**\n     * Function for dispatching actions to Integreat. Will be run through the\n     * chain of middlewares before the relevant action handler is called.\n     * @param {Object} action - The action to dispatch\n     * @returns {Promise} Promise of result object\n     */ dispatch : setupDispatch ( { actions , services , schemas , middlewares , identOptions } ) , /**\n     * Adds the `listener` function to the service's emitter for events with the\n     * given `eventName` name.\n     */ on ( eventName , serviceId , listener ) { const service = services [ serviceId ] if ( service && service . on ) { service . on ( eventName , listener ) } } , /**\n     * Return schema type from its plural form.\n     */ typeFromPlural ( plural ) { return pluralTypes [ plural ] } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a queuable action from a schedule definition . [CODESPLIT] function scheduleToAction ( def ) { if ( ! def ) { return null } const id = def . id || null const schedule = parseSchedule ( def . schedule ) const nextTime = nextSchedule ( schedule , true ) return { ... def . action , meta : { id , schedule , queue : ( nextTime ) ? nextTime . getTime ( ) : true } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authorize data in Integreat s internal data format according to the setting of the relevant schema ( s ) . The provided access object may be coming from authorizeRequest () and if this is refused already this method will refuse right away . [CODESPLIT] function authorizeItem ( item , access , { schemas , action , requireAuth } ) { const { ident , status } = access if ( status === 'refused' ) { return false } if ( ! item || ( ident && ident . root ) ) { return true } const schema = schemas [ item . type ] const scheme = getScheme ( schema , action ) return authorizeWithScheme ( item , scheme , ident , requireAuth ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get several items from a service based on the given action object . [CODESPLIT] async function get ( action , { getService } = { } ) { const { type , service : serviceId = null , onlyMappedValues = false , endpoint } = action . payload const service = ( typeof getService === 'function' ) ? getService ( type , serviceId ) : null if ( ! service ) { return createUnknownServiceError ( type , serviceId , 'GET' ) } const id = getIdFromPayload ( action . payload ) // Do individual gets for array of ids, if there is no collection scoped endpoint if ( Array . isArray ( id ) && ! hasCollectionEndpoint ( service . endpoints ) ) { return getIndividualItems ( id , action , getService ) } const endpointDebug = ( endpoint ) ? ` ${ endpoint } ` : ` ${ type } ${ id } ` debug ( 'GET: Fetch from service %s at %s' , service . id , endpointDebug ) const { response } = await service . send ( appendToAction ( action , { id , onlyMappedValues } ) ) return response }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send the request with the adapter and return the response . Will serialize any data in the request and normalize any data in the response . The access object on the request must have status granted and will be returned on the response object . [CODESPLIT] function sendRequest ( { adapter , serviceId } ) { return async ( { request , response , connection } ) => { if ( response ) { return response } try { response = await adapter . send ( request , connection ) return { ... response , access : request . access } } catch ( error ) { return createError ( ` ${ serviceId } ${ error } ` ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a schema with the given id and service . [CODESPLIT] function schema ( { id , plural , service , attributes : attrDefs , relationships : relDefs , access , internal = false } ) { const attributes = { ... expandFields ( attrDefs || { } ) , id : { type : 'string' } , type : { type : 'string' } , createdAt : { type : 'date' } , updatedAt : { type : 'date' } } const relationships = expandFields ( relDefs || { } ) const defaultAttrs = prepareDefaultAttrs ( attributes , attrDefs ) const defaultRels = prepareDefaultRels ( relationships , relDefs ) const castFn = cast ( { id , attributes , relationships , defaultAttrs , defaultRels } ) return { id , plural : plural || ` ${ id } ` , service , internal , attributes , relationships , access , /**\n     * Will cast the given data according to the type. Attributes will be\n     * coerced to the right format, relationships will be expanded to\n     * relationship objects, and object properties will be moved from\n     * `attributes` or be set with defaults.\n     * @param {Object} data - The data to cast\n     * @param {boolean} onlyMappedValues - Will use defaults if true\n     * @returns {Object} Returned data in the format expected from the schema\n     */ cast ( data , { onlyMappedValues = false } = { } ) { return mapAny ( ( data ) => castFn ( data , { onlyMappedValues } ) , data ) } , /**\n     * Will create a query object for a relationship, given the relationship id\n     * and a data item to get field values from.\n     *\n     * If the relationship is set up with a query definition object, each prop\n     * of this object references field ids in the given data item. The returned\n     * query object will have these ids replaced with actual field values.\n     *\n     * @param {string} relId - The id of a relationship\n     * @param {Object} data - A data item to get field values from.\n     * @returns {Object} Query object\n     */ castQueryParams ( relId , data ) { return castQueryParams ( relId , data , { relationships } ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return item mapper object with fromService and toService . [CODESPLIT] function mapping ( { filters , transformers , schemas = { } , mappings : mappingsArr = [ ] } = { } ) { const mappings = mappingsArr . reduce ( ( mappings , def ) => ( { ... mappings , [ def . id ] : def } ) , { } ) const createPipelineFn = createPipeline ( filters , transformers , schemas , mappings ) return ( mapping , overrideType ) => { const { id , type , schema , pipeline } = createPipelineFn ( mapping , overrideType ) if ( ! pipeline ) { return null } const mapper = mapTransform ( [ fwd ( 'data' ) , ... pipeline , rev ( set ( 'data' ) ) ] ) return { id , type , schema , /**\n       * Map data from a service with attributes and relationships.\n       * @param {Object} data - The service item to map from\n       * @param {Object} options - onlyMappedValues\n       * @returns {Object} Target item\n       */ fromService ( data , { onlyMappedValues = true } = { } ) { return data ? ensureArray ( ( onlyMappedValues ) ? mapper . onlyMappedValues ( data ) : mapper ( data ) ) : [ ] } , /**\n       * Map data to a service with attributes and relationships.\n       * @param {Object} data - The data item to map\n       * @param {Object} target - Optional object to map to data on\n       * @returns {Object} Mapped data\n       */ toService ( data , target = null ) { const mapped = mapper . rev . onlyMappedValues ( data ) return ( ( target ? Array . isArray ( target ) ? [ ... target ] . concat ( mapped ) : mergeDeepWith ( concatOrRight , target , mapped ) : mapped ) || null ) } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map the data going _to_ the service . Everything is handled by the mappings but this method make sure that the right types are mapped . [CODESPLIT] function mapFromService ( ) { return ( { response , request , responseMapper , mappings } ) => { if ( response . status !== 'ok' ) { return response } const type = request . params . type || Object . keys ( mappings ) const { onlyMappedValues , unmapped = false } = request . params if ( unmapped ) { return response } const { data , status = response . status , error , paging , params } = mapWithEndpoint ( responseMapper , response , request . action ) if ( status !== 'ok' ) { return removeDataProp ( { ... response , status , error } ) } const mapType = ( type ) => ( mappings [ type ] ) ? mappings [ type ] . fromService ( { ... request , data } , { onlyMappedValues } ) : [ ] return { ... response , status , ... ( ( paging ) ? { paging } : { } ) , ... ( ( params ) ? { params } : { } ) , data : ( data ) ? flatten ( mapAny ( mapType , type ) ) : undefined } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this emits the data events on the watcher emitter for all fds [CODESPLIT] function ( tailInfo ) { var z = this ; if ( tailInfo ) { z . q . push ( tailInfo ) ; } var ti ; //for all changed fds fire readStream for ( var i = 0 ; i < z . q . length ; ++ i ) { ti = z . q [ i ] ; if ( ti . reading ) { //still reading file continue ; } if ( ! z . tails [ ti . stat . ino ] ) { //remove timed out file tail from q z . q . splice ( i , 1 ) ; -- i ; continue ; } //truncated if ( ti . stat . size < ti . pos ) { ti . pos = 0 ; } var len = ti . stat . size - ti . pos ; //remove from queue because im doing this work. z . q . splice ( i , 1 ) ; -- i ; z . readTail ( ti , len ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return the total line buffer length from all active tails [CODESPLIT] function ( ) { var z = this ; var l = 0 ; Object . keys ( z . tails ) . forEach ( function ( k ) { l += ( z . tails [ k ] . buf || '' ) . length ; } ) ; return l ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare pipeline by replacing keys with functions or function objects from the collection object and remove anything that is not functions or function objects . [CODESPLIT] function preparePipeline ( pipeline , collection = { } ) { pipeline = [ ] . concat ( pipeline ) const replaceWithFunction = ( key ) => ( typeof key === 'string' ) ? collection [ key ] : key const isFunctionOrObject = ( obj ) => obj && [ 'function' , 'object' ] . includes ( typeof obj ) return pipeline . map ( replaceWithFunction ) . filter ( isFunctionOrObject ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare reverse pipeline by either running the revPipeline through the regular preparePipeline () or – if revPipeline is not set - pick . rev () functions from the fwdPipeline . [CODESPLIT] function prepareRevPipeline ( revPipeline , fwdPipeline , collection ) { return ( revPipeline ) ? preparePipeline ( revPipeline , collection ) : fwdPipeline . map ( ( fn ) => ( fn . rev ) ? fn . rev : null ) . filter ( Boolean ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cast query params according to type [CODESPLIT] function castQueryParams ( relId , data , { relationships } ) { const relationship = relationships [ relId ] if ( ! relationship . query ) { return { } } return Object . keys ( relationship . query ) . reduce ( ( params , key ) => { const value = getField ( data , relationship . query [ key ] ) if ( value === undefined ) { throw new TypeError ( 'Missing value for query param' ) } return { ... params , [ key ] : value } } , { } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set up Integreat queue interface . [CODESPLIT] function setupQueue ( queue ) { let dispatch = null let subscribed = false return { queue , /**\n     * Set dispatch function to use for dequeuing\n     */ setDispatch ( dispatchFn ) { dispatch = dispatchFn if ( ! subscribed && typeof dispatch === 'function' ) { queue . subscribe ( dispatch ) subscribed = true } } , /**\n     * Middleware interface for Integreat. Will push queuable actions to queue,\n     * and pass the rest on to the next() function.\n     *\n     * @param {function} next - The next middleware\n     * @returns {Object} A response object\n     */ middleware ( next ) { return middleware ( next , queue ) } , /**\n     * Schedule actions from the given defs.\n     * Actions are enqueued with a timestamp, and are ran at the\n     * set time.\n     * @param {array} defs - An array of schedule definitions\n     * @returns {array} Array of returned responses\n     */ async schedule ( defs ) { return schedule ( defs , queue ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get metadata for a service based on the given action object . [CODESPLIT] async function getMeta ( { payload , meta } , { getService } ) { debug ( 'Action: GET_META' ) const { service : serviceId , endpoint , keys } = payload const id = ` ${ serviceId } ` const service = getService ( null , serviceId ) if ( ! service ) { debug ( ` ${ serviceId } ` ) return createError ( ` ${ serviceId } ` ) } const type = service . meta const metaService = getService ( type ) if ( ! metaService ) { return createError ( ` ${ service . id } ${ service . meta } ` ) } const endpointDebug = ( endpoint ) ? ` ${ endpoint } ` : ` ${ type } ${ id } ` debug ( 'GET_META: Get meta %s for service \\'%s\\' on service \\'%s\\' at %s' , keys , service . id , metaService . id , endpointDebug ) const { response } = await metaService . send ( { type : 'GET' , payload : { keys , type , id , endpoint } , meta : { ident : meta . ident } } ) if ( response . status === 'ok' ) { const { data } = response const meta = prepareMeta ( keys , data [ 0 ] . attributes ) return { ... response , data : { service : serviceId , meta } } } else { return response } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set several items to a service based on the given action object . [CODESPLIT] async function set ( action , { getService , schemas } ) { debug ( 'Action: SET' ) const { service : serviceId , data , endpoint , onlyMappedValues = true } = action . payload const type = extractType ( action , data ) const id = extractId ( data ) const service = getService ( type , serviceId ) if ( ! service ) { return createUnknownServiceError ( type , serviceId , 'SET' ) } const endpointDebug = ( endpoint ) ? ` ${ endpoint } ` : '' debug ( 'SET: Send to service %s %s' , service . id , endpointDebug ) const { response , authorizedRequestData } = await service . send ( appendToAction ( action , { id , type , onlyMappedValues } ) ) return mergeRequestAndResponseData ( response , authorizedRequestData ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cast item [CODESPLIT] function cast ( { id , attributes , relationships , defaultAttrs , defaultRels } ) { return ( data , { onlyMappedValues } ) => { if ( ! data ) { return undefined } const attrs = castAttributes ( data . attributes , attributes , ( onlyMappedValues ) ? { } : { ... defaultAttrs } ) if ( ! onlyMappedValues ) { setDates ( attrs ) } const rels = castRelationships ( data . relationships , relationships , ( onlyMappedValues ) ? { } : { ... defaultRels } ) const castId = data . id || attrs . id || uuid ( ) delete attrs . id const casted = { id : castId , type : id , attributes : attrs , relationships : rels } if ( data . isNew ) { casted . isNew = true } if ( data . isDeleted ) { casted . isDeleted = true } return casted } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set metadata on a service based on the given action object . [CODESPLIT] async function setMeta ( { payload , meta } , { getService } ) { debug ( 'Action: SET_META' ) const { service : serviceId , meta : metaAttrs , endpoint } = payload const id = ` ${ serviceId } ` const service = getService ( null , serviceId ) if ( ! service ) { debug ( ` ${ serviceId } ` ) return createError ( ` ${ serviceId } ` ) } const type = service . meta const metaService = getService ( type ) if ( ! metaService ) { debug ( ` ${ service . id } ${ service . meta } ` ) return { status : 'noaction' } } const endpointDebug = ( endpoint ) ? ` ${ endpoint } ` : ` ${ type } ${ id } ` debug ( 'SET_META: Send metadata %o for service \\'%s\\' on service \\'%s\\' %s' , metaAttrs , service . id , metaService . id , endpointDebug ) const data = { id , type , attributes : metaAttrs } const { response } = await metaService . send ( { type : 'SET' , payload : { keys : Object . keys ( metaAttrs ) , type , id , data , endpoint , onlyMappedValues : true } , meta : { ident : meta . ident } } ) return response }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a group of specifications into JSON Schema . [CODESPLIT] function exportToJSONSchema ( expSpecifications , baseSchemaURL , baseTypeURL , flat = false ) { const namespaceResults = { } ; const endOfTypeURL = baseTypeURL [ baseTypeURL . length - 1 ] ; if ( endOfTypeURL !== '#' && endOfTypeURL !== '/' ) { baseTypeURL += '/' ; } for ( const ns of expSpecifications . namespaces . all ) { const lastLogger = logger ; logger = logger . child ( { shrId : ns . namespace } ) ; try { logger . debug ( 'Exporting namespace.' ) ; if ( flat ) { const { schemaId , schema } = flatNamespaceToSchema ( ns , expSpecifications . dataElements , baseSchemaURL , baseTypeURL ) ; namespaceResults [ schemaId ] = schema ; } else { const { schemaId , schema } = namespaceToSchema ( ns , expSpecifications . dataElements , baseSchemaURL , baseTypeURL ) ; namespaceResults [ schemaId ] = schema ; } logger . debug ( 'Finished exporting namespace.' ) ; } finally { logger = lastLogger ; } } return namespaceResults ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a namespace into a JSON Schema . [CODESPLIT] function namespaceToSchema ( ns , dataElementsSpecs , baseSchemaURL , baseTypeURL ) { const dataElements = dataElementsSpecs . byNamespace ( ns . namespace ) ; const schemaId = ` ${ baseSchemaURL } ${ namespaceToURLPathSegment ( ns . namespace ) } ` ; let schema = { $schema : 'http://json-schema.org/draft-04/schema#' , id : schemaId , title : \"TODO: Figure out what the title should be.\" , definitions : { } } ; const entryRef = makeRef ( new Identifier ( 'shr.base' , 'Entry' ) , ns , baseSchemaURL ) ; if ( ns . description ) { schema . description = ns . description ; } const nonEntryEntryTypeField = { $ref : makeRef ( new Identifier ( 'shr.base' , 'EntryType' ) , ns , baseSchemaURL ) } ; const defs = dataElements . sort ( function ( l , r ) { return l . identifier . name . localeCompare ( r . identifier . name ) ; } ) ; const entryRefs = [ ] ; for ( const def of defs ) { const lastLogger = logger ; logger = logger . child ( { shrId : def . identifier . fqn } ) ; try { logger . debug ( 'Exporting element' ) ; let schemaDef = { type : 'object' , properties : { } } ; let wholeDef = schemaDef ; const tbdParentDescriptions = [ ] ; let requiredProperties = [ ] ; let needsEntryType = false ; if ( def . isEntry || def . basedOn . length ) { wholeDef = { allOf : [ ] } ; let hasEntryParent = false ; for ( const supertypeId of def . basedOn ) { if ( supertypeId instanceof TBD ) { if ( supertypeId . text ) { tbdParentDescriptions . push ( supertypeId . text ) ; } else { tbdParentDescriptions . push ( 'TBD' ) ; } } else { const parent = dataElementsSpecs . findByIdentifier ( supertypeId ) ; if ( ! parent ) { logger . error ( 'Could not find definition for %s which is a supertype of %s' , supertypeId , def ) ; } else { hasEntryParent = hasEntryParent || parent . isEntry ; } wholeDef . allOf . push ( { $ref : makeRef ( supertypeId , ns , baseSchemaURL ) } ) ; } } if ( def . isEntry && ( ! hasEntryParent ) ) { wholeDef . allOf . splice ( 0 , 0 , { $ref : entryRef } ) ; } wholeDef . allOf . push ( schemaDef ) ; } else { needsEntryType = true ; } const tbdFieldDescriptions = [ ] ; if ( def . value ) { if ( def . value . inheritance !== INHERITED ) { let { value , required , tbd } = convertDefinition ( def . value , dataElementsSpecs , ns , baseSchemaURL , baseTypeURL ) ; if ( required ) { requiredProperties . push ( 'Value' ) ; } schemaDef . properties . Value = value ; if ( tbd ) { schemaDef . properties . Value . description = def . value . text ? ( 'TBD: ' + def . value . text ) : tbdValueToString ( def . value ) ; } } } if ( def . fields . length ) { const fieldNameMap = { } ; const clashingNames = { } ; for ( const field of def . fields ) { if ( ! ( field instanceof TBD ) ) { if ( ! isValidField ( field ) ) { continue ; } else if ( field . inheritance === INHERITED ) { if ( fieldNameMap [ field . identifier . name ] ) { logger . error ( ` ` , fieldNameMap [ field . identifier . name ] . fqn , field . identifier . fqn ) ; clashingNames [ field . identifier . name ] = true ; } else { fieldNameMap [ field . identifier . name ] = field . identifier ; } continue ; } if ( fieldNameMap [ field . identifier . name ] ) { logger . error ( ` ` , fieldNameMap [ field . identifier . name ] . fqn , field . identifier . fqn ) ; clashingNames [ field . identifier . name ] = true ; continue ; } else { fieldNameMap [ field . identifier . name ] = field . identifier ; } } const card = field . effectiveCard ; if ( card && card . isZeroedOut ) { continue ; } let { value , required , tbd } = convertDefinition ( field , dataElementsSpecs , ns , baseSchemaURL , baseTypeURL ) ; if ( tbd ) { tbdFieldDescriptions . push ( tbdValueToString ( field ) ) ; continue ; } if ( field . identifier . fqn === 'shr.base.EntryType' ) { needsEntryType = false ; } schemaDef . properties [ field . identifier . name ] = value ; if ( required ) { requiredProperties . push ( field . identifier . name ) ; } } for ( const clashingName in clashingNames ) { delete schemaDef . properties [ clashingName ] ; } requiredProperties = requiredProperties . filter ( propName => ! ( propName in clashingNames ) ) ; } else if ( ! def . value ) { schemaDef . type = 'object' ; schemaDef . description = 'Empty DataElement?' ; } let descriptionList = [ ] ; if ( def . description ) { descriptionList . push ( def . description ) ; } if ( def . concepts . length ) { wholeDef . concepts = def . concepts . map ( ( concept ) => makeConceptEntry ( concept ) ) ; } if ( tbdParentDescriptions . length ) { tbdParentDescriptions [ 0 ] = 'TBD Parents: ' + tbdParentDescriptions [ 0 ] ; descriptionList = descriptionList . concat ( tbdParentDescriptions ) ; } if ( tbdFieldDescriptions . length ) { tbdFieldDescriptions [ 0 ] = 'TBD Fields: ' + tbdFieldDescriptions [ 0 ] ; descriptionList = descriptionList . concat ( tbdFieldDescriptions ) ; } if ( descriptionList . length ) { wholeDef . description = descriptionList . join ( '\\n' ) ; } if ( needsEntryType ) { schemaDef . properties [ 'EntryType' ] = nonEntryEntryTypeField ; if ( def . identifier . fqn !== 'shr.base.EntryType' ) { requiredProperties . push ( 'EntryType' ) ; } } if ( requiredProperties . length ) { schemaDef . required = requiredProperties ; } schema . definitions [ def . identifier . name ] = wholeDef ; if ( def . isEntry && ( ! def . isAbstract ) ) { entryRefs . push ( { $ref : makeRef ( def . identifier , ns , baseSchemaURL ) } ) ; } } finally { logger = lastLogger ; } } if ( entryRefs . length ) { schema . type = 'object' ; schema . anyOf = entryRefs ; } return { schemaId , schema } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a namespace into a flat JSON Schema . [CODESPLIT] function flatNamespaceToSchema ( ns , dataElementsSpecs , baseSchemaURL , baseTypeURL ) { const dataElements = dataElementsSpecs . byNamespace ( ns . namespace ) ; const schemaId = ` ${ baseSchemaURL } ${ namespaceToURLPathSegment ( ns . namespace ) } ` ; let schema = { $schema : 'http://json-schema.org/draft-04/schema#' , id : schemaId , title : \"TODO: Figure out what the title should be.\" , definitions : { } } ; const expandedEntry = makeExpandedEntryDefinitions ( ns , baseSchemaURL ) ; if ( ns . description ) { schema . description = ns . description ; } const defs = dataElements . sort ( function ( l , r ) { return l . identifier . name . localeCompare ( r . identifier . name ) ; } ) ; const entryRefs = [ ] ; for ( const def of defs ) { let schemaDef = { type : 'object' , properties : { } } ; let wholeDef = schemaDef ; const tbdParentDescriptions = [ ] ; let requiredProperties = [ ] ; if ( def . isEntry ) { requiredProperties = expandedEntry . required . slice ( ) ; } const tbdFieldDescriptions = [ ] ; if ( def . value ) { let { value , required , tbd } = convertDefinition ( def . value , dataElementsSpecs , ns , baseSchemaURL , baseTypeURL ) ; if ( required ) { requiredProperties . push ( 'Value' ) ; } schemaDef . properties . Value = value ; if ( tbd ) { schemaDef . properties . Value . description = def . value . text ? ( 'TBD: ' + def . value . text ) : tbdValueToString ( def . value ) ; } } if ( def . fields . length ) { for ( const field of def . fields ) { if ( ! ( field instanceof TBD ) && ! isValidField ( field ) ) { continue ; } const card = field . effectiveCard ; if ( card && card . isZeroedOut ) { continue ; } let { value , required , tbd } = convertDefinition ( field , dataElementsSpecs , ns , baseSchemaURL , baseTypeURL ) ; if ( tbd ) { tbdFieldDescriptions . push ( tbdValueToString ( field ) ) ; continue ; } const fieldName = field . identifier . name ; schemaDef . properties [ fieldName ] = value ; if ( required && ( requiredProperties . indexOf ( fieldName ) === - 1 ) ) { requiredProperties . push ( fieldName ) ; } } if ( def . isEntry ) { for ( const name in expandedEntry . properties ) { if ( ! ( name in schemaDef . properties ) ) { schemaDef . properties [ name ] = expandedEntry . properties [ name ] ; } } } } else if ( ! def . value ) { schemaDef . type = 'object' ; schemaDef . description = 'Empty DataElement?' ; } let descriptionList = [ ] ; if ( def . description ) { descriptionList . push ( def . description ) ; } if ( def . concepts . length ) { wholeDef . concepts = def . concepts . map ( ( concept ) => makeConceptEntry ( concept ) ) ; } if ( tbdParentDescriptions . length ) { tbdParentDescriptions [ 0 ] = 'TBD Parents: ' + tbdParentDescriptions [ 0 ] ; descriptionList = descriptionList . concat ( tbdParentDescriptions ) ; } if ( tbdFieldDescriptions . length ) { tbdFieldDescriptions [ 0 ] = 'TBD Fields: ' + tbdFieldDescriptions [ 0 ] ; descriptionList = descriptionList . concat ( tbdFieldDescriptions ) ; } if ( descriptionList . length ) { wholeDef . description = descriptionList . join ( '\\n' ) ; } if ( requiredProperties . length ) { schemaDef . required = requiredProperties ; } schema . definitions [ def . identifier . name ] = wholeDef ; if ( def . isEntry && ( ! def . isAbstract ) ) { entryRefs . push ( { $ref : makeRef ( def . identifier , ns , baseSchemaURL ) } ) ; } } if ( entryRefs . length ) { schema . type = 'object' ; schema . anyOf = entryRefs ; } return { schemaId , schema } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a JSON Schema reference to the specified type . [CODESPLIT] function makeRef ( id , enclosingNamespace , baseSchemaURL ) { if ( id . namespace === enclosingNamespace . namespace ) { return '#/definitions/' + id . name ; } else { return makeShrDefinitionURL ( id , baseSchemaURL ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translates a constraint path into a valid path for the JSON Schema . [CODESPLIT] function extractConstraintPath ( constraint , valueDef , dataElementSpecs ) { if ( constraint . onValue ) { return extractUnnormalizedConstraintPath ( constraint , valueDef , dataElementSpecs ) ; } else if ( constraint . path . length > 0 && constraint . path [ constraint . path . length - 1 ] . isValueKeyWord ) { // Essentially the same as above, when onValue is never checked again, so just chop it off // treat it like above.  TODO: Determine if this is really the right approach. const simpleConstraint = constraint . clone ( ) ; simpleConstraint . path = simpleConstraint . path . slice ( 0 , simpleConstraint . path . length - 1 ) ; return extractUnnormalizedConstraintPath ( simpleConstraint , valueDef , dataElementSpecs ) ; } if ( ! constraint . hasPath ( ) ) { return { path : [ ] } ; } let currentDef = dataElementSpecs . findByIdentifier ( valueDef . effectiveIdentifier ) ; const normalizedPath = [ ] ; let target = null ; for ( let i = 0 ; i < constraint . path . length ; i += 1 ) { const pathId = constraint . path [ i ] ; target = null ; if ( pathId . namespace === PRIMITIVE_NS ) { if ( i !== constraint . path . length - 1 ) { logger . error ( 'Encountered a constraint path containing a primitive %s at index %d that was not the leaf: %s' , pathId , i , constraint . toString ( ) ) ; return { } ; } if ( ! currentDef . value ) { logger . error ( 'Encountered a constraint path with a primitive leaf %s on an element that lacked a value: %s' , pathId , constraint . toString ( ) ) ; return { } ; } if ( currentDef . value instanceof ChoiceValue ) { target = findOptionInChoice ( currentDef . value , pathId , dataElementSpecs ) ; if ( ! target ) { logger . error ( 'Encountered a constraint path with a primitive leaf %s on an element with a mismatched value: %s on valueDef %s' , pathId , constraint . toString ( ) , valueDef . toString ( ) ) ; return { } ; } } else if ( ! pathId . equals ( currentDef . value . identifier ) ) { logger . error ( 'Encountered a constraint path with a primitive leaf %s on an element with a mismatched value: %s on valueDef %s' , pathId , constraint . toString ( ) , valueDef . toString ( ) ) ; return { } ; } else { target = currentDef . value ; } normalizedPath . push ( 'Value' ) ; } else { const newDef = dataElementSpecs . findByIdentifier ( pathId ) ; if ( ! newDef ) { logger . error ( 'Cannot resolve element definition for %s on constraint %s. ERROR_CODE:12029' , pathId , constraint . toString ( ) ) ; return { } ; } // See if the current definition has a value of the specified type. if ( currentDef . value ) { if ( currentDef . value instanceof ChoiceValue ) { target = findOptionInChoice ( currentDef . value , pathId , dataElementSpecs ) ; } else if ( pathId . equals ( currentDef . value . identifier ) || checkHasBaseType ( currentDef . value . identifier , pathId , dataElementSpecs ) ) { target = currentDef . value ; normalizedPath . push ( 'Value' ) ; } } if ( ! target ) { if ( ! currentDef . fields || ! currentDef . fields . length ) { logger . error ( 'Element %s lacked any fields or a value that matched %s as part of constraint %s' , currentDef . identifier . fqn , pathId , constraint . toString ( ) ) ; return { } ; } else { target = currentDef . fields . find ( ( field ) => pathId . equals ( field . identifier ) ) ; if ( ! target ) { // It's possible that the field is actually defined as an \"includes type\" constraint on a list. // In this case, do nothing, because right now there isn't a valid way to represent further constraints // on includesType elements in the schema. if ( valueDef . constraintsFilter . includesType . constraints . some ( c => c . isA . equals ( pathId ) ) ) { logger . warn ( 'Cannot enforce constraint %s on Element %s since %s refers to an type introduced by an \"includesType\" constraint' , constraint . toString ( ) , currentDef . identifier . fqn , pathId ) ; } else { logger . error ( 'Element %s lacked a field or a value that matched %s as part of constraint %s' , currentDef . identifier . fqn , pathId , constraint . toString ( ) ) ; } return { } ; } normalizedPath . push ( pathId . name ) ; } } currentDef = newDef ; } } return { path : normalizedPath , target } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a concept into a code entry for the schema . ( Codes are also represented as Concepts in the object model . ) [CODESPLIT] function makeConceptEntry ( concept ) { if ( concept instanceof TBD ) { const ret = { code : 'TBD' , codeSystem : 'urn:tbd' } ; if ( concept . text ) { ret . displayText = concept . text ; } return ret ; } else { const ret = { code : concept . code , codeSystem : concept . system } ; if ( concept . display ) { ret . displayText = concept . display ; } return ret ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if a value or one of its ancestors is or was a list . [CODESPLIT] function isOrWasAList ( value ) { if ( value . card . isList ) { return true ; } const cardConstraints = value . constraintsFilter . own . card . constraints ; return cardConstraints . some ( ( oneCard ) => oneCard . isList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches the aggregate options of a choice for the specified option . [CODESPLIT] function findOptionInChoice ( choice , optionId , dataElementSpecs ) { // First look for a direct match for ( const option of choice . aggregateOptions ) { if ( optionId . equals ( option . identifier ) ) { return option ; } } // Then look for a match on one of the selected options's base types // E.g., if choice has Quantity but selected option is IntegerQuantity for ( const option of choice . aggregateOptions ) { if ( checkHasBaseType ( optionId , option . identifier , dataElementSpecs ) ) { return option ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stealing from shr - expand Determine if a type supports a code constraint . [CODESPLIT] function supportsCodeConstraint ( identifier , dataElementSpecs ) { if ( CODE . equals ( identifier ) || checkHasBaseType ( identifier , new Identifier ( 'shr.core' , 'Coding' ) , dataElementSpecs ) || checkHasBaseType ( identifier , new Identifier ( 'shr.core' , 'CodeableConcept' ) , dataElementSpecs ) ) { return true ; } const element = dataElementSpecs . findByIdentifier ( identifier ) ; if ( element . value ) { if ( element . value instanceof IdentifiableValue ) { return CODE . equals ( element . value . identifier ) || checkHasBaseType ( element . value . identifier , new Identifier ( 'shr.core' , 'Coding' ) , dataElementSpecs ) || checkHasBaseType ( element . value . identifier , new Identifier ( 'shr.core' , 'CodeableConcept' ) , dataElementSpecs ) ; } else if ( element . value instanceof ChoiceValue ) { for ( const value of element . value . aggregateOptions ) { if ( value instanceof IdentifiableValue ) { if ( CODE . equals ( value . identifier ) || checkHasBaseType ( value . identifier , new Identifier ( 'shr.core' , 'Coding' ) , dataElementSpecs ) || checkHasBaseType ( value . identifier , new Identifier ( 'shr.core' , 'CodeableConcept' ) , dataElementSpecs ) ) { return true ; } } } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Action to delete expired items . [CODESPLIT] async function expire ( { payload , meta = { } } , { dispatch } ) { const { service } = payload const { ident } = meta if ( ! service ) { return createError ( ` ` ) } if ( ! payload . endpoint ) { return createError ( ` ${ service } ` ) } if ( ! payload . type ) { return createError ( ` ${ service } ` ) } const response = await getExpired ( payload , ident , dispatch ) return deleteExpired ( response , service , ident , dispatch ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "All Operations implement the same Interface : [CODESPLIT] function Set ( target , attribute , value ) { this . type = 'Set' this . target = target this . attribute = attribute this . value = value this . hasEffect = true // Can become effectless upon transformation }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Name operation [CODESPLIT] function Name ( name , action , val ) { this . type = 'Name' this . name = name this . action = action this . value = val }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility functions [CODESPLIT] function parseCell ( cell ) { var match = cell . match ( / ([a-z]+)([0-9]+) / i ) if ( ! match ) throw new Error ( 'invalid cell id ' + cell ) return [ column . fromStr ( match [ 1 ] ) , parseInt ( match [ 2 ] ) ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms a range against an array of ops [CODESPLIT] function transformRange ( range , ops ) { var rangeComps = range . split ( ':' ) , newRange var start = rangeComps [ 0 ] ops . forEach ( op => start = transformRangeAnchor ( start , op , /*isStart:*/ true ) ) var end = rangeComps [ 1 ] ops . forEach ( op => end = transformRangeAnchor ( end , op , /*isStart:*/ false ) ) if ( start === end ) return start return start + ':' + end }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms a range anchor taking into account whether it s the start or end [CODESPLIT] function transformRangeAnchor ( target , op , isStart ) { var thisCell = parseCell ( target ) if ( op instanceof InsertCol ) { var otherCell = parseCell ( op . newCol ) if ( otherCell [ 0 ] <= thisCell [ 0 ] ) return column . fromInt ( thisCell [ 0 ] + 1 ) + thisCell [ 1 ] } else if ( op instanceof DeleteCol ) { var otherCell = parseCell ( op . col ) if ( otherCell [ 0 ] < thisCell [ 0 ] ) return column . fromInt ( thisCell [ 0 ] - 1 ) + thisCell [ 1 ] if ( otherCell [ 0 ] === thisCell [ 0 ] ) { // Spreadsheet selection is different from text selection: // While text selection ends in the first *not* selected char ( \"foo| |bar\" => 3,4) // ... spreadsheet selection ends in the last selected cell. Thus we need to // differentiate between start and end. Shame on those who didn't think about this! if ( ! isStart ) return column . fromInt ( thisCell [ 0 ] - 1 ) + thisCell [ 1 ] } } else if ( op instanceof InsertRow ) { var otherCell = parseCell ( op . newRow ) if ( otherCell [ 1 ] <= thisCell [ 1 ] ) return column . fromInt ( thisCell [ 0 ] ) + ( thisCell [ 1 ] + 1 ) } else if ( op instanceof DeleteRow ) { var otherCell = parseCell ( op . col ) if ( otherCell [ 1 ] < thisCell [ 1 ] ) return column . fromInt ( thisCell [ 0 ] ) + ( thisCell [ 1 ] - 1 ) if ( otherCell [ 1 ] === thisCell [ 1 ] ) { if ( ! isStart ) return column . fromInt ( thisCell [ 0 ] ) + ( thisCell [ 1 ] - 1 ) } } // If nothing has returned already then this anchor doesn't change return target }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the first matching endpoint from an array of endpoints that has already been sortert with higher specificity first . Type should match before scope which should match before action but the order here is taken care of by the required sorting . [CODESPLIT] function matchEndpoint ( endpoints ) { return ( { type , payload , meta } ) => endpoints . find ( ( endpoint ) => matchId ( endpoint , { type , payload } ) && matchType ( endpoint , { type , payload } ) && matchScope ( endpoint , { type , payload } ) && matchAction ( endpoint , { type , payload } ) && matchParams ( endpoint , { type , payload } ) && matchFilters ( endpoint , { type , payload , meta } ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an action object . [CODESPLIT] function createAction ( type , payload = { } , meta ) { if ( ! type ) { return null } const action = { type , payload } if ( meta ) { action . meta = meta } return action }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authorize the request according to the setting on the relevant schema . Sets the access object with status property specifying whether access is granted or refused and returns the request . [CODESPLIT] function authorizeRequest ( { schemas } ) { return ( { request } ) => { const { access = { } , params = { } , action } = request const { ident = null } = access if ( ident && ident . root ) { return authItemsAndWrap ( request , { status : 'granted' , ident , scheme : 'root' } , schemas ) } if ( ! params . type ) { return authItemsAndWrap ( request , { status : 'granted' , ident , scheme : null } , schemas ) } const requireAuth = ! ! request . auth const schema = schemas [ params . type ] const scheme = getScheme ( schema , action ) const status = ( doAuth ( scheme , ident , requireAuth ) ) ? 'granted' : 'refused' return authItemsAndWrap ( request , { status , ident , scheme } , schemas ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Complete missing props and allow only expected props on the request object . [CODESPLIT] function requestFromAction ( { type : action , payload , meta = { } } , { endpoint , schemas = { } } = { } ) { const { data , ... params } = payload const { ident = null } = meta const typePlural = getPluralType ( params . type , schemas ) return { action , params , data , endpoint : ( endpoint && endpoint . options ) || null , access : { ident } , meta : { typePlural } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get service from type or service id . [CODESPLIT] function getService ( schemas , services ) { return ( type , service ) => { if ( ! service && schemas [ type ] ) { service = schemas [ type ] . service } return services [ service ] || null } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Action to sync from one service to another . [CODESPLIT] async function sync ( { payload , meta = { } } , { dispatch } ) { debug ( 'Action: SYNC' ) const fromParams = await generateFromParams ( payload , meta , dispatch ) const toParams = generateToParams ( payload , fromParams ) const lastSyncedAt = new Date ( ) const results = await Promise . all ( fromParams . map ( getFromService ( dispatch , payload . type , meta ) ) ) if ( results . some ( ( result ) => result . status !== 'ok' ) ) { return ( results . length === 1 ) ? results [ 0 ] : createError ( makeErrorString ( results ) ) } const data = flatten ( results . map ( ( result ) => result . data ) ) . filter ( Boolean ) if ( data . length === 0 && payload . syncNoData !== true ) { return createError ( ` ${ fromParams [ 0 ] . service } ` , 'noaction' ) } return Promise . all ( [ ... createSetMetas ( fromParams , lastSyncedAt , meta . ident , dispatch ) , dispatch ( action ( 'SET' , { data , ... toParams } , { ... meta , queue : true } ) ) ] ) . then ( ( responses ) => { return { status : 'ok' , data : responses } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Task api that configures and loads gulp tasks . [CODESPLIT] function ( gulp , cwd , config ) { if ( util . isNullOrUndefined ( gulp ) ) { throw 'gulp must be defined' ; } /**\n   * Configuration options that will be injected into every gulp task.\n   *\n   * @type {Object}\n   */ this . _config = config || { } , /**\n   * Current working directory that path calculations should be relative to.\n   *\n   * @type {String}\n   */ this . _cwd = cwd || __dirname ; /**\n   * Actual path of this file relative to the defined working directory.\n   *\n   * @type {String}\n   */ this . _root = path . relative ( this . _cwd , __dirname ) ; /**\n   * Gulp instance. All tasks get injected the same gulp instances.\n   *\n   * @type {Gulp}\n   */ this . _gulp = gulp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "black white and gray ( buggy? ) are not included [CODESPLIT] function ( ) { this . _colors = [ 'red' , 'green' , 'yellow' , 'blue' , 'magenta' , 'cyan' , 'white' , 'black' ] this . _colors_num = this . _colors . length this . _backgrounds = [ ] for ( var i = 0 ; i < this . _colors_num ; i ++ ) { this . _backgrounds [ i ] = 'bg' + this . _colors [ i ] . charAt ( 0 ) . toUpperCase ( ) + this . _colors [ i ] . slice ( 1 ) } this . _skip = [ 'black' , 'white' , 'bgBlack' , 'bgWhite' ] this . _skip_num = this . _skip . length - 1 this . _next = 0 this . _prev = - 1 this . options = { color_space : false , gap : 1 , space_color : null } this . wrapper = { bg : this . ponyfy ( true ) , r : this . ponyfy ( ) , add : this . addorskip ( 'add' ) , skip : this . addorskip ( 'skip' ) , options : ( opts ) => { for ( let i in options ) { if ( opts [ i ] ) { this . options [ i ] = opts [ i ] continue } for ( let j in opts ) { if ( options [ i ] . alias && ~ options [ i ] . alias . indexOf ( j ) ) { this . options [ i ] = opts [ j ] break } } } return this . wrapper } , colors : ( ) => this . colors ( ) , reset : ( ) => { this . _skip = [ 'black' , 'white' , 'bgBlack' , 'bgWhite' ] return this . wrapper } , _colors : this . _colors , _backgrounds : this . _backgrounds } return this . wrapper }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wrapper to pass bg [CODESPLIT] function ( bg ) { bg = bg ? bg : false return ( ... args ) => { return this . output ( args . join ( ' ' ) , this . colors ( bg ) ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Babel external helper module injector . [CODESPLIT] function ( browserify , name , source ) { if ( utility . isNullOrUndefined ( browserify ) ) { throw 'browserify must be defined.' ; } if ( ! utility . isNonEmptyString ( name ) ) { throw 'name must be defined.' ; } if ( utility . isNullOrUndefined ( source ) ) { throw 'source must be defined.' ; } this . _browserify = browserify ; this . _name = name ; this . _source = source ; this . _hasModule = false ; this . _hasResolver = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strategy constructor . [CODESPLIT] function Strategy ( options , verify ) { options = options || { } ; if ( ! options . baseURI ) { throw new TypeError ( 'EveSeatStrategy requires a baseURI option' ) ; } // Remove trailing slash if provided options . baseURI = options . baseURI . replace ( / \\/$ / , '' ) ; options . authorizationURL = options . baseURI + '/oauth2/authorize' ; options . tokenURL = options . baseURI + '/oauth2/token' ; this . _userProfileURL = options . baseURI + '/oauth2/profile' ; OAuth2Strategy . call ( this , options , verify ) ; this . name = 'eveseat' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map the data coming _from_ the service . Everything is handled by the mappings but this method make sure that the right types are mapped . [CODESPLIT] function mapToService ( ) { return ( { request , requestMapper , mappings } ) => { const data = mapData ( request . data , request , mappings ) return { ... request , data : applyEndpointMapper ( data , request , requestMapper ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Router - allows client - > router - > server ( or client - > router< - client ) connectivity . This class is meant to help when a server is unable to handle maximum number of connections . [CODESPLIT] function Router ( options ) { var self = this ; self . frontend = new Server ( { port : options . port , auth : options . auth || options . secret , certificates : options . certificates , routing : true } ) // connect to relay destination\r if ( options . client ) { self . backend = new Client ( { address : options . client . address , auth : options . client . auth || options . client . secret || options . auth || options . secret , certificates : options . certificates || options . client . certificates , //node: options.node,\r designation : 'router' , routes : self . frontend . streams } ) } else if ( options . server ) { self . backend = new Server ( { port : options . server . port , auth : options . server . auth || options . server . secret || options . auth || options . secret , certificates : options . certificates || options . server . certificates , routes : self . frontend . streams } ) } else throw new Error ( \"iris-rpc::Router() requires client or server\" ) self . frontend . on ( 'connect' , function ( address , uuid , stream ) { self . backend . dispatch ( { op : 'rpc::online' , uuid : uuid } ) ; } ) self . frontend . on ( 'disconnect' , function ( uuid , stream ) { self . backend . dispatch ( { op : 'rpc::offline' , uuid : uuid } ) ; } ) self . backend . on ( 'connect' , function ( address , uuid , stream ) { self . frontend . dispatch ( { op : 'rpc::online' , uuid : uuid } ) ; } ) self . backend . on ( 'disconnect' , function ( uuid , stream ) { self . frontend . dispatch ( { op : 'rpc::offline' , uuid : uuid } ) ; } ) self . frontend . digest ( function ( msg , uuid , stream ) { msg . _r = { uuid : uuid , designation : stream . designation , uuid : stream . uuid } self . backend . dispatch ( msg ) ; } ) self . backend . digest ( function ( msg , uuid ) { self . frontend . dispatch ( msg . _uuid , msg ) ; } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process messages from Facebook Messenger . [CODESPLIT] async function processMessengerBody ( body , context ) { const allMessages = getAllMessages ( body ) if ( ! allMessages || ! allMessages . length ) return false context = context || { } for ( let message of allMessages ) { message = _ . cloneDeep ( message ) const messageContext = Object . assign ( { } , context ) try { for ( let plugin of middleware ) { await plugin ( message , messageContext ) } } catch ( error ) { const logError = ( messageContext . log && messageContext . log . error instanceof Function ) ? messageContext . log . error : console . error logError ( 'Error running middleware' , error ) } } return true }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a function for mapping app properties onto the given prop namespace . [CODESPLIT] function create ( prop ) { if ( typeof prop !== 'string' ) { throw new Error ( 'expected the first argument to be a string.' ) ; } return function ( app ) { if ( this . isRegistered ( 'base-' + prop ) ) return ; // map config var config = utils . mapper ( app ) // store/data . map ( 'store' , store ( app . store ) ) . map ( 'data' ) // options . map ( 'enable' ) . map ( 'disable' ) . map ( 'option' ) . alias ( 'options' , 'option' ) // get/set . map ( 'set' ) . map ( 'del' ) // Expose `prop` (config) on the instance app . define ( prop , proxy ( config ) ) ; // Expose `process` on app[prop] app [ prop ] . process = config . process ; } ; function store ( app ) { if ( ! app ) return { } ; var mapper = utils . mapper ( app ) ; app . define ( prop , proxy ( mapper ) ) ; return mapper ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Proxy to support app . config as a function or object with methods allowing the user to do either of the following : [CODESPLIT] function proxy ( config ) { function fn ( key , val ) { if ( typeof val === 'string' ) { config . alias . apply ( config , arguments ) ; return config ; } if ( typeof key === 'string' ) { config . map . apply ( config , arguments ) ; return config ; } if ( ! utils . isObject ( key ) ) { throw new TypeError ( 'expected key to be a string or object' ) ; } for ( var prop in key ) { fn ( prop , key [ prop ] ) ; } return config ; } fn . __proto__ = config ; return fn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private functions [CODESPLIT] function ( proto , parentProto ) { proto . _initHooks = [ ] ; proto . _destroyHooks = [ ] ; // add method for calling all init hooks proto . callInitHooks = function ( ) { if ( this . _initHooksCalled ) { return ; } if ( parentProto ) { parentProto . callInitHooks . call ( this ) ; } this . _initHooksCalled = true ; for ( var i = 0 , len = proto . _initHooks . length ; i < len ; i ++ ) { proto . _initHooks [ i ] . call ( this ) ; } } ; // add method for calling all destroy hooks proto . callDestroyHooks = function ( ) { if ( this . _destroyHooksCalled ) { return ; } if ( parentProto . callDestroyHooks ) { parentProto . callDestroyHooks . call ( this ) ; } this . _destroyHooksCalled = true ; for ( var i = 0 , len = proto . _destroyHooks . length ; i < len ; i ++ ) { proto . _destroyHooks [ i ] . call ( this ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects features and bind them to the node density [CODESPLIT] function ElementMatrix ( top ) { CommanalityMatrix . call ( this , top ) ; this . row ( ' ' ) ; this . collum ( ' ' ) ; this . classlist = top . root . classlist ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "node - s3 - encode - url [CODESPLIT] function publicS3URI ( string ) { return encodeURIComponent ( string ) . replace ( / %20 / img , '+' ) . replace ( / %2F / img , '/' ) . replace ( / \\\" / img , \"%22\" ) . replace ( / \\# / img , \"%23\" ) . replace ( / \\$ / img , \"%24\" ) . replace ( / \\& / img , \"%26\" ) . replace ( / \\' / img , \"%27\" ) . replace ( / \\( / img , \"%28\" ) . replace ( / \\) / img , \"%29\" ) . replace ( / \\, / img , \"%2C\" ) . replace ( / \\: / img , \"%3A\" ) . replace ( / \\; / img , \"%3B\" ) . replace ( / \\= / img , \"%3D\" ) . replace ( / \\? / img , \"%3F\" ) . replace ( / \\@ / img , \"%40\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse a string in the format topic [ : data ] where data is valid JSON [CODESPLIT] function parsePayload ( message ) { const messageParts = message && message . match ( / ^([^:]+)(?::(.*))? / ) if ( ! messageParts ) return { topic : undefined , data : undefined } const topic = messageParts [ 1 ] let data = messageParts [ 2 ] if ( data ) { try { data = JSON . parse ( data ) } catch ( error ) { data = undefined } } return { topic , data } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save expected file [CODESPLIT] function ( done ) { fs . writeFile ( path . resolve ( __dirname , '../../test/reallife/expected/' + item . key + '.json' ) , JSON . stringify ( { 'title' : item . title , 'text' : item . text } , null , '\\t' ) + '\\n' , done ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save source file [CODESPLIT] function ( done ) { fs . writeFile ( path . resolve ( __dirname , '../../test/reallife/source/' + item . key + '.html' ) , SOURCES [ item . key ] , done ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save labeled flag [CODESPLIT] function ( done ) { datamap [ item . index ] . labeled = true ; fs . writeFile ( path . resolve ( __dirname , '../../test/reallife/datamap.json' ) , JSON . stringify ( datamap , null , '\\t' ) + '\\n' , done ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A secret little gem you can use to print out the subtree : ) [CODESPLIT] function attrStringify ( attr ) { var names = Object . keys ( attr ) ; var str = '' ; for ( var i = 0 , l = names . length ; i < l ; i ++ ) { str += names [ i ] + '=\"' + attr [ names [ i ] ] . slice ( 0 , 20 ) + ( attr [ names [ i ] ] . length > 20 ? '...' : '' ) + '\" ' ; } return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform tree to nlcst . [CODESPLIT] function toNLCST ( tree , file , Parser ) { var parser var location var results var doc // Warn for invalid parameters. if ( ! tree || ! tree . type ) { throw new Error ( 'hast-util-to-nlcst expected node' ) } if ( ! file || ! file . messages ) { throw new Error ( 'hast-util-to-nlcst expected file' ) } // Construct parser. if ( ! Parser ) { throw new Error ( 'hast-util-to-nlcst expected parser' ) } if ( ! position . start ( tree ) . line || ! position . start ( tree ) . column ) { throw new Error ( 'hast-util-to-nlcst expected position on nodes' ) } location = vfileLocation ( file ) doc = String ( file ) parser = 'parse' in Parser ? Parser : new Parser ( ) // Transform HAST into NLCST tokens, and pass these into `parser.parse` to // insert sentences, paragraphs where needed. results = [ ] find ( tree ) return { type : 'RootNode' , children : results , position : { start : location . toPosition ( 0 ) , end : location . toPosition ( doc . length ) } } function find ( node ) { var children = node . children if ( node . type === 'root' ) { findAll ( children ) } else if ( is ( node ) && ! ignored ( node ) ) { if ( is ( node , EXPLICIT ) ) { // Explicit paragraph. add ( node ) } else if ( is ( node , FLOW_ACCEPTING ) ) { // Slightly simplified version of: // https://html.spec.whatwg.org/#paragraphs implicit ( flattenAll ( children ) ) } else { // Dig deeper. findAll ( children ) } } } function findAll ( children ) { var length = children . length var index = - 1 while ( ++ index < length ) { find ( children [ index ] ) } } function flatten ( node ) { if ( is ( node , [ 'a' , 'ins' , 'del' , 'map' ] ) ) { return flattenAll ( node . children ) } return node } function flattenAll ( children ) { var results = [ ] var length = children . length var index = - 1 while ( ++ index < length ) { results = results . concat ( flatten ( children [ index ] ) ) } return results } function add ( node ) { var result = ( 'length' in node ? all : one ) ( node ) if ( result . length !== 0 ) { results . push ( parser . tokenizeParagraph ( result ) ) } } function implicit ( children ) { var length = children . length + 1 var index = - 1 var viable = false var start = - 1 var child while ( ++ index < length ) { child = children [ index ] if ( child && phrasing ( child ) ) { if ( start === - 1 ) { start = index } if ( ! viable && ! embedded ( child ) && ! whitespace ( child ) ) { viable = true } } else if ( child && start === - 1 ) { find ( child ) start = index + 1 } else { ; ( viable ? add : findAll ) ( children . slice ( start , index ) ) if ( child ) { find ( child ) } viable = false start = - 1 } } } // Convert `node` (hast) to nlcst. function one ( node ) { var type = node . type var tagName = type === 'element' ? node . tagName : null var change var replacement if ( type === 'text' ) { change = true replacement = parser . tokenize ( node . value ) } else if ( tagName === 'wbr' ) { change = true replacement = [ parser . tokenizeWhiteSpace ( ' ' ) ] } else if ( tagName === 'br' ) { change = true replacement = [ parser . tokenizeWhiteSpace ( '\\n' ) ] } else if ( sourced ( node ) ) { change = true replacement = [ parser . tokenizeSource ( textContent ( node ) ) ] } else if ( type === 'root' || ! ignored ( node ) ) { replacement = all ( node . children ) } else { return } if ( ! change ) { return replacement } return patch ( replacement , location , location . toOffset ( position . start ( node ) ) ) } // Convert all `children` (HAST) to NLCST. function all ( children ) { var length = children && children . length var index = - 1 var result = [ ] var child while ( ++ index < length ) { child = one ( children [ index ] ) if ( child ) { result = result . concat ( child ) } } return result } // Patch a position on each node in `nodes`.  `offset` is the offset in // `file` this run of content starts at. // // Note that NLCST nodes are concrete, meaning that their starting and ending // positions can be inferred from their content. function patch ( nodes , location , offset ) { var length = nodes . length var index = - 1 var start = offset var children var node var end while ( ++ index < length ) { node = nodes [ index ] children = node . children if ( children ) { patch ( children , location , start ) } end = start + toString ( node ) . length node . position = { start : location . toPosition ( start ) , end : location . toPosition ( end ) } start = end } return nodes } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert node ( hast ) to nlcst . [CODESPLIT] function one ( node ) { var type = node . type var tagName = type === 'element' ? node . tagName : null var change var replacement if ( type === 'text' ) { change = true replacement = parser . tokenize ( node . value ) } else if ( tagName === 'wbr' ) { change = true replacement = [ parser . tokenizeWhiteSpace ( ' ' ) ] } else if ( tagName === 'br' ) { change = true replacement = [ parser . tokenizeWhiteSpace ( '\\n' ) ] } else if ( sourced ( node ) ) { change = true replacement = [ parser . tokenizeSource ( textContent ( node ) ) ] } else if ( type === 'root' || ! ignored ( node ) ) { replacement = all ( node . children ) } else { return } if ( ! change ) { return replacement } return patch ( replacement , location , location . toOffset ( position . start ( node ) ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert all children ( HAST ) to NLCST . [CODESPLIT] function all ( children ) { var length = children && children . length var index = - 1 var result = [ ] var child while ( ++ index < length ) { child = one ( children [ index ] ) if ( child ) { result = result . concat ( child ) } } return result }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associations [CODESPLIT] function ( source , target , alias , type ) { if ( Util . isnt . Class ( source ) || Util . isnt . Class ( target ) || Util . isnt . String ( alias ) || ! alias || Association . types . indexOf ( type ) === - 1 ) { return false ; } this . id = Util . uniqId ( ) ; this . source = source ; this . target = target ; this . alias = Util . String . capitalize ( alias ) ; this . type = type ; return this . complete ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Node General abstaction between all node types The rule is that this should contain the most obviouse implementation [CODESPLIT] function Node ( type , parent ) { this . type = type ; this . parent = parent ; this . root = parent ? parent . root : this ; this . identifyer = parent ? ( ++ parent . root . _counter ) : 0 ; // The specific constructor will set another value if necessary this . _textLength = 0 ; this . tags = 0 ; this . density = - 1 ; this . children = [ ] ; this . _text = '' ; this . _textCompiled = false ; this . _noneStyleText = '' ; this . _noneStyleTextCompiled = false ; this . blocky = false ; this . blockyChildren = false ; this . inTree = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TextNode has a parent and a text containter [CODESPLIT] function TextNode ( parent , text ) { Node . call ( this , 'text' , parent ) ; // A text node has no children instead it has a text container this . children = null ; this . _text = text ; this . _noneStyleText = text ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ElementNode has a parent tagname and attributes [CODESPLIT] function ElementNode ( parent , tagname , attributes ) { Node . call ( this , 'element' , parent ) ; // Since this is an element there will minimum one tag this . tags = ( tagname === 'br' || tagname === 'wbr' ) ? 0 : 1 ; // Element nodes also has a tagname and an attribute collection this . tagname = tagname ; this . attr = attributes ; this . classes = attributes . hasOwnProperty ( 'class' ) ? attributes [ 'class' ] . trim ( ) . split ( WHITE_SPACE ) : [ ] ; // Add node to the classlist this . root . classlist . addNode ( this ) ; this . _blockySelfCache = domHelpers . BLOCK_ELEMENTS . hasOwnProperty ( tagname ) ; this . _countTagnames = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "extended class with the new prototype [CODESPLIT] function ( ) { var r ; // Recall as new if new isn't provided :) if ( Util . isnt . instanceof ( NewClass , this ) ) { return ClassUtil . construct ( NewClass , arguments ) ; } // call the constructor if ( Util . is . Function ( this . initialize ) ) { r = this . initialize . apply ( this , arguments ) ; } // call all constructor hooks this . callInitHooks ( ) ; return typeof r != 'undefined' ? r : this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Distribute content to the cssfiles object [CODESPLIT] function distribute ( filename , content ) { content = content ; fs . appendFile ( filename , content + \"\\n\" ) ; log ( rulecount + ': Append to ' + filename + ' -> ' + content ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detect weather a selector should be extracted or not [CODESPLIT] function detectTakeout ( selectors ) { var properties = { takeout : false } ; options . takeout . forEach ( function ( takeout ) { selectors . forEach ( function ( selector ) { if ( selector . indexOf ( takeout . ruleprefix ) === 0 ) { properties . takeout = true ; properties . filename = takeout . filename ; } } ) ; } ) ; return properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function is made by the following requirements : x > 5 y = 1 f ( x ) = a * sqrt ( x ) + b * x^2 + c f ( 2 ) = 0 . 2 f ( 5 ) = 1 f ( 5 ) = 0 [CODESPLIT] function wordcountScore ( x ) { if ( x > 5 ) return 1 ; else return Math . min ( 1 , 2.27 * Math . sqrt ( x ) - 0.0507 * Math . pow ( x , 2 ) - 2.808 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function is made by the following requirements : x > 5 y = 1 f ( x ) = a * sqrt ( x ) + b * x^2 + c f ( 0 ) = 0 . 2 f ( 5 ) = 1 f ( 5 ) = 0 [CODESPLIT] function linebreakScore ( x ) { if ( x > 5 ) return 1 ; else return Math . min ( 1 , 0.477 * Math . sqrt ( x ) - 0.0106 * Math . pow ( x , 2 ) + 0.2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function is made by the following requirements : : x < 0 . 01 y = 0 . 5 : x > 0 . 1 y = 1 : f ( x ) otherwise The f ( x ) polynomium is made so it follows : : f ( 0 . 01 ) = 0 . 5 : f ( 0 . 01 ) = 0 : f ( 0 . 1 ) = 1 : f ( 0 . 1 ) = 0 [CODESPLIT] function adjustLiklihood ( x ) { if ( x < 0.01 ) return 0.5 ; else if ( x > 0.1 ) return 1 ; else return Math . min ( 1 , - 1371 * Math . pow ( x , 3 ) + 226 * Math . pow ( x , 2 ) - 4.11 * x + 0.52 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create tuple that [CODESPLIT] function parseLineByLine ( text ) { var lines = text . trim ( ) . split ( \"\\n\" ) ; var bookmarks = lines . splice ( 0 , lines . length * 3 / 4 ) ; return { bookmarks : bookmarks , lines : lines } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The exposed API used in all . js [CODESPLIT] function CommonalityInterface ( MatrixConstructor , top ) { this . top = top ; this . length = null ; this . matrix = null ; this . MatrixConstructor = MatrixConstructor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Some abstact API for the commanality matrix [CODESPLIT] function CommanalityMatrix ( classlist ) { // space will identify a text node and/or an element node without any classnames this . rowKeys = { } ; this . rowNames = [ ] ; this . collumKeys = { } ; this . collumNames = [ ] ; this . nodeMatrix = [ ] ; this . summaryMatrix = [ ] ; this . dim = [ 0 , 0 ] ; this . bestIndex = [ - 1 , - 1 ] ; this . _bestNodes = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extend the rows or the collums [CODESPLIT] function arrayVector ( size ) { var vec = new Array ( size ) ; for ( var i = 0 ; i < size ; i ++ ) vec [ i ] = [ ] ; return vec ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds and attribute matching function complexity is for uncomfirmed performace sake [CODESPLIT] function buildAttributeMatcher ( match ) { var keys = Object . keys ( match ) ; var jskey , i , l ; var transform = '' ; var bool = '' ; transform = 'transform = {\\n' ; for ( i = 0 , l = keys . length ; i < l ; i ++ ) { jskey = JSON . stringify ( keys [ i ] ) ; transform += '  ' + jskey + ': attr.hasOwnProperty(' + jskey + ') ? attr[' + jskey + '].toLowerCase() : false' ; if ( i !== l - 1 ) transform += ',' ; transform += '\\n' ; } transform += '};\\n' ; bool = 'return !!(' ; for ( i = 0 , l = keys . length ; i < l ; i ++ ) { jskey = JSON . stringify ( keys [ i ] ) ; if ( i > 0 ) bool += '    ||    ' ; bool += ' ( transform[' + jskey + ']' ; if ( Array . isArray ( match [ keys [ i ] ] ) ) { bool += ' && ( ' ; for ( var j = 0 , s = match [ keys [ i ] ] . length ; j < s ; j ++ ) { if ( j > 0 ) bool += ' || ' ; if ( typeof match [ keys [ i ] ] [ j ] === 'string' ) { bool += 'transform[' + jskey + '] === \\'' + match [ keys [ i ] ] [ j ] . toLowerCase ( ) + '\\'' ; } else if ( util . isRegExp ( match [ keys [ i ] ] [ j ] ) ) { bool += 'match[' + jskey + '][' + j + '].test(transform[' + jskey + '])' ; } } bool += ' )' ; } bool += ' ) \\n' ; } bool += '         );' ; var anonymous = new Function ( 'attr' , 'match' , transform + '\\n' + bool ) ; return function ( attr ) { return anonymous ( attr , match ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if container a is a container of b [CODESPLIT] function containerOf ( a , b ) { while ( b = b . parent ) { if ( a === b ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the common parent of a and b [CODESPLIT] function commonParent ( a , b ) { if ( a === b ) { return a ; } else if ( containerOf ( a , b ) ) { return a ; } else if ( containerOf ( b , a ) ) { return b ; } else { // This will happen at some point, since the root is a container of // everything while ( b = b . parent ) { if ( containerOf ( b , a ) ) return b ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse style attribute intro object [CODESPLIT] function styleParser ( style ) { style = style || '' ; var tokens = style . trim ( ) . split ( / \\s*(?:;|:)\\s* / ) ; var output = { } ; for ( var i = 1 , l = tokens . length ; i < l ; i += 2 ) { output [ tokens [ i - 1 ] ] = tokens [ i ] ; } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the tree distance between a and b [CODESPLIT] function treeDistance ( a , b ) { if ( a === b ) return 0 ; var parent = commonParent ( a , b ) ; var aParent = a ; var aCount = 0 ; var bParent = b ; var bCount = 0 ; if ( parent !== a ) { while ( parent !== aParent . parent ) { aCount += 1 ; aParent = aParent . parent ; } } else { bCount += 1 ; } if ( parent !== b ) { while ( parent !== bParent . parent ) { bCount += 1 ; bParent = bParent . parent ; } } else { aCount += 1 ; } var abCount = 0 ; if ( parent !== a && parent !== b ) { abCount = Math . abs ( parent . children . indexOf ( aParent ) - parent . children . indexOf ( bParent ) ) ; } return aCount + bCount + abCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "module [CODESPLIT] function ( casper , pos ) { this . _pos = pos || { timestamp : Date . now ( ) , coords : { longitude : 0 , latitude : 0 , accuracy : 0 } } ; this . _casper = casper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Lexer for the given file and options . [CODESPLIT] function Lexer ( file , options ) { this . options = utils . extend ( { } , options ) ; this . file = file ; this . regex = new RegexCache ( ) ; this . names = [ ] ; this . ast = { tags : { } , type : 'root' , name : 'root' , nodes : [ ] } ; this . unknown = { tags : [ ] , blocks : [ ] } ; this . known = { tags : [ 'extends' , 'layout' ] , blocks : [ 'block' ] } ; this . delimiters = { variable : [ '{{' , '}}' ] , block : [ '{%' , '%}' ] , es6 : [ '${' , '}' ] , } ; this . tokens = [ this . ast ] ; this . errors = [ ] ; this . stack = [ ] ; this . stash = [ ] ; this . lexers = { } ; this . fns = [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create default delimiters and tags [CODESPLIT] function ( ) { if ( this . isInitialized ) return ; this . isInitialized = true ; var lexer = this ; this . lineno = 1 ; this . column = 1 ; this . lexed = '' ; this . file = utils . normalize ( this . file ) ; this . file . orig = this . file . contents ; this . input = this . file . contents . toString ( ) ; this . file . ast = this . ast ; this . file . ast . variables = { } ; this . file . ast . blocks = { } ; this . input = this . input . split ( '{% body %}' ) . join ( '{% block \"body\" %}{% endblock %}' ) ; if ( this . file . extends ) { this . prependNode ( this . file , 'extends' ) ; } /**\n     * Tags\n     */ this . captureTag ( 'extends' ) ; this . captureTag ( 'layout' ) ; /**\n     * Block tags\n     */ this . captureBlock ( 'block' ) ; /**\n     * Captures\n     */ this . capture ( 'text' , utils . negateDelims ( this . delimiters ) ) ; this . capture ( 'newline' , / ^\\n+ / ) ; this . capture ( 'es6' , / ^\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\} / ) ; this . capture ( 'variable' , / ^\\{{2,}([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}{2,} / ) ; this . capture ( 'escape' , / ^\\\\(.) / ) ; this . capture ( 'space' , / ^[ \\t]+ / ) ; /**\n     * Custom helpers\n     */ var helpers = this . options . helpers || { } ; if ( utils . isObject ( helpers ) ) { helpers = Object . keys ( helpers ) ; } helpers . forEach ( function ( key ) { lexer . known . blocks . push ( key ) ; lexer . captureBlock ( key ) ; } ) ; /**\n     * Add other names to return un-rendered\n     */ var matches = this . input . match ( / \\{%\\s*([^%}]+) / g ) ; var names = utils . getNames ( matches ) ; names . tags . forEach ( function ( key ) { if ( ! utils . isRegistered ( lexer , key ) ) { lexer . unknown . tags . push ( key ) ; lexer . captureTag ( key ) ; } } ) ; names . blocks . forEach ( function ( key ) { if ( ! utils . isRegistered ( lexer , key ) ) { lexer . unknown . blocks . push ( key ) ; lexer . captureBlock ( key ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set an error message with the current line number and column . [CODESPLIT] function ( msg ) { var message = this . file . relative + ' line:' + this . lineno + ' column:' + this . column + ': ' + msg ; var err = new Error ( message ) ; err . reason = msg ; err . line = this . lineno ; err . column = this . column ; err . source = this . input ; err . path = this . file . path ; if ( this . options . silent ) { this . errors . push ( err ) ; } else { throw err ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mark position and patch node . position . [CODESPLIT] function ( ) { var start = { line : this . lineno , column : this . column } ; var self = this ; return function ( node ) { utils . define ( node , 'position' , new Position ( start , self ) ) ; return node ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Capture type with the given regex . [CODESPLIT] function ( type , regex ) { var cached = this . regex . create ( type , regex ) ; var lexer = this ; var fn = this . lexers [ type ] = function ( ) { var pos = lexer . position ( ) ; var m = lexer . match ( cached . val ) ; if ( ! m || ! m [ 0 ] ) return ; var parent = lexer . prev ( ) ; var node = pos ( { type : type , val : m [ 0 ] } ) ; utils . define ( node , 'parent' , parent ) ; utils . define ( node , 'rawArgs' , m [ 1 ] ) ; utils . define ( node , 'args' , function ( ) { return utils . parseArgs ( m [ 1 ] ) ; } ) ; parent . nodes . push ( node ) ; } ; this . addLexer ( fn ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a lexer for the given variable type . [CODESPLIT] function ( type ) { var cached = this . regex . createVariable ( type ) ; var file = this . file ; var lexer = this ; var fn = this . lexers [ type ] = function ( ) { var pos = lexer . position ( ) ; var m = lexer . match ( cached . strict ) ; if ( ! m ) return ; var parent = this . prev ( ) ; var node = pos ( { type : type , known : utils . has ( lexer . known . tags , type ) , val : m [ 0 ] . trim ( ) } ) ; parent . known = node . known ; var nodes = parent . nodes ; Object . defineProperty ( file . ast . variables , type , { configurable : true , set : function ( val ) { nodes = val ; } , get : function ( ) { return nodes ; } } ) ; Object . defineProperty ( parent , 'nodes' , { configurable : true , set : function ( val ) { nodes = val ; } , get : function ( ) { return nodes ; } } ) ; utils . define ( node , 'parent' , parent ) ; parent . nodes . push ( node ) ; } ; this . addLexer ( fn ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a tag lexer for the given type . [CODESPLIT] function ( type ) { this . ast . tags [ type ] = null ; this . names . push ( type ) ; var cached = this . regex . createTag ( type ) ; var file = this . file ; var lexer = this ; var fn = this . lexers [ type ] = function ( ) { var pos = lexer . position ( ) ; var m = lexer . match ( cached . strict ) ; if ( ! m ) return ; var name = utils . getName ( m [ 1 ] ) ; if ( this . options . strict ) { var isKnown = utils . has ( lexer . known . tags , type ) ; if ( isKnown && file . hasOwnProperty ( type ) && ! file . hasOwnProperty ( 'isParsed' ) ) { throw new Error ( ` ${ type } ` ) ; } } file [ type ] = name ; lexer . ast . tags [ type ] = name ; lexer . createNode ( type , name , m , pos ) ; } ; this . addLexer ( fn ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push AST node type onto parent . nodes [CODESPLIT] function ( type , name , m , pos ) { var parent = this . prev ( ) ; var val = m [ 1 ] ; var tok = { type : 'args' , val : val } ; var node = pos ( { type : type , name : name , known : utils . has ( this . known . tags , type ) , val : val . trim ( ) , nodes : [ tok ] } ) ; utils . define ( node , 'parent' , parent ) ; utils . define ( tok , 'parent' , node ) ; parent . nodes . push ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an opening tag lexer for block name . [CODESPLIT] function ( type ) { this . names . push ( type ) ; var cached = this . regex . createOpen ( type ) ; var file = this . file ; var lexer = this ; return function ( ) { var pos = lexer . position ( ) ; var m = lexer . match ( cached . strict ) ; if ( ! m ) return ; var name = utils . getName ( m [ 1 ] ) ; var action = utils . getAction ( m [ 1 ] ) ; var val = m [ 0 ] ; if ( ! name && lexer . options [ type ] && lexer . options [ type ] . args === 'required' ) { throw new Error ( ` ${ type } ${ m [ 0 ] } ` ) ; } if ( ! name ) name = 'unnamed' ; var node = pos ( { type : ` ${ type } ` , known : utils . has ( lexer . known . blocks , type ) , name : name , val : val . trim ( ) } ) ; var parent = lexer . prev ( ) ; if ( parent && parent . name && parent . name !== 'root' ) { name = parent . name + '.' + name ; } var block = { type : type , name : name , known : node . known , action : action , nodes : [ node ] } ; utils . define ( node , 'parent' , block ) ; utils . define ( block , 'parent' , parent ) ; block . rawArgs = m [ 1 ] ; block . args = utils . parseArgs ( m [ 1 ] ) ; Object . defineProperty ( file . ast . blocks [ type ] , name , { configurable : true , enumerable : true , set : function ( val ) { block = val ; } , get : function ( ) { return block ; } } ) ; parent . nodes . push ( block ) ; lexer . tokens . push ( block ) ; return block ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a closing tag lexer for block name . [CODESPLIT] function ( type ) { var cached = this . regex . createClose ( type ) ; var file = this . file ; var lexer = this ; return function ( ) { var pos = lexer . position ( ) ; var m = lexer . match ( cached . strict ) ; if ( ! m ) return ; var block = lexer . tokens . pop ( ) ; if ( typeof block === 'undefined' || block . type !== type ) { throw new Error ( ` ${ type } ` ) ; } if ( block . name === 'body' ) { lexer . ast . isLayout = true ; file . ast . isLayout = true ; } var nodes = block . nodes ; Object . defineProperty ( file . ast . blocks , block . name , { configurable : true , set : function ( val ) { nodes = val ; } , get : function ( ) { return nodes ; } } ) ; Object . defineProperty ( block , 'nodes' , { configurable : true , set : function ( val ) { nodes = val ; } , get : function ( ) { return nodes ; } } ) ; var tok = pos ( { known : block . known , type : ` ${ type } ` , val : m [ 0 ] . trim ( ) } ) ; utils . define ( block , 'position' , tok . position ) ; utils . define ( tok , 'parent' , block ) ; block . nodes . push ( tok ) ; return block ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a block lexer with opening and closing tags for the given name . [CODESPLIT] function ( type ) { this . file . ast . blocks [ type ] = this . file . ast . blocks [ type ] || { } ; this . addLexer ( this . captureOpen ( type ) ) ; this . addLexer ( this . captureClose ( type ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unshift node prop onto the AST [CODESPLIT] function ( file , prop ) { return this . createNode ( prop , file [ prop ] , ` ${ prop } ${ file [ prop ] } ` , this . position ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update lineno and column based on str . [CODESPLIT] function ( str , len ) { var lines = str . match ( / \\n / g ) ; if ( lines ) this . lineno += lines . length ; var i = str . lastIndexOf ( '\\n' ) ; this . column = ~ i ? len - i : this . column + len ; this . lexed += str ; this . consume ( str , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match regex return captures and update the cursor position by match [ 0 ] length . [CODESPLIT] function ( regex ) { var m = regex . exec ( this . input ) ; if ( m ) { this . updatePosition ( m [ 0 ] , m [ 0 ] . length ) ; return m ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run lexers to advance the curson position [CODESPLIT] function ( ) { var len = this . fns . length ; var idx = - 1 ; while ( ++ idx < len ) { this . fns [ idx ] . call ( this ) ; if ( ! this . input ) { break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the next AST token [CODESPLIT] function ( ) { while ( this . input ) { var prev = this . input ; this . advance ( ) ; if ( this . input && prev === this . input ) { throw new Error ( ` ${ this . input . substr ( 0 , 10 ) } ` ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tokenize the given string . [CODESPLIT] function ( file ) { debug ( 'lexing <%s>' , this . file . path ) ; if ( file ) this . file = file ; this . init ( ) ; while ( this . input ) this . next ( ) ; return this . ast ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hook for showing the automatic message [CODESPLIT] function notifyHook ( e ) { message_count ++ ; var message ; if ( ! options . enabled ) { return ; } if ( ! e ) { return ; } if ( e && e . length === 1 ) { e = e [ 0 ] ; } if ( / Task .* failed\\. / . test ( e . message ) ) { message = e . message ; } else if ( e . message && e . stack ) { message = exception ( e ) ; } else { message = e + '' ; } if ( message_count > 0 && message === 'Aborted due to warnings.' ) { // skip unhelpful message because there was probably another one that was more helpful return ; } // shorten message by removing full path // TODO - make a global replace message = message . replace ( cwd , '' ) . replace ( '\\x07' , '' ) ; return notify ( { title : options . title + ( grunt . task . current . nameArgs ? ' ' + grunt . task . current . nameArgs : '' ) , message : message } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pauses the timer [CODESPLIT] function ( ) { if ( this . _initialized && this . _isPaused ) { return false ; } this . _isPaused = true ; raf . cancel ( this . _requestID ) ; this . _pauseTime = now ( ) ; this . _onPause ( ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "resumes the timer [CODESPLIT] function ( ) { if ( this . _initialized && ! this . _isPaused ) { return false ; } var pauseDuration ; this . _isPaused = false ; this . _prevTime = now ( ) ; pauseDuration = this . _prevTime - this . _pauseTime ; this . _onResume ( pauseDuration ) ; this . _requestID = raf . request ( this . _tick ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Methods [CODESPLIT] function createServer ( options , callback ) { if ( options && options . cert && options . key ) { return https . createServer ( options , callback ) ; } return http . createServer ( callback || null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Methods [CODESPLIT] function createProxy ( api , obj , methods ) { return new Proxy ( obj , { get ( target , name ) { if ( methods . includes ( name ) ) { return ( params , callback ) => { const inject = Object . assign ( { chat_id : obj . id } , params ) ; return api . method ( name , inject , callback ) ; } ; } return target [ name ] ; } , set ( ) { return new Error ( 'Cannot change `chat` or `user`.' ) ; } , } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "IS ARRAY - LIKE // FUNCTION : isArrayLike ( value ) Validates if a value is array - like . [CODESPLIT] function isArrayLike ( value ) { return ( value !== void 0 && value !== null && typeof value !== 'function' && isInteger ( value . length ) && value . length >= 0 && value . length <= MAX ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render loop [CODESPLIT] function render ( ) { shell . context . cache . clear ( ) ; shell . context . setViewport ( ) ; GLOW . defaultCamera . update ( ) shell . context . enableDepthTest ( true ) ; if ( params . cullCW ) { shell . context . enableCulling ( true , { frontFace : GL . CW , cullFace : GL . BACK } ) ; } else if ( params . cullCCW ) { shell . context . enableCulling ( true , { frontFace : GL . CCW , cullFace : GL . BACK } ) ; } else { shell . context . enableCulling ( false ) ; } shell . context . clear ( ) ; shell . events . emit ( \"render\" ) ; utils . nextFrame ( render ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function create ( opts , cb ) { // \"use strict\" ; var params = [ 'create' , '-f' ] ; /*\n     immediately add some options to the create procedure\n     done by adding argument -o option=value\n     the opts.options parameter is an array of objects, or a single object\n\n     opts.options = { property: String, value: String }\n\n     OR:\n\n     opts.options = [ { property: String, value: String }, { property: String, value: String } ]\n\n     */ if ( opts . options ) { if ( opts . options . length ) { //opts.options is an array for ( var x = 0 ; x < opts . options . length ; x ++ ) { params . push ( '-o' , opts . options [ x ] . property + \"=\" + opts . options [ x ] . value ) ; } } else { //opts.options is a single object params . push ( '-o' , opts . options . property + \"=\" + opts . options . value ) ; } } if ( opts . mountpoint ) { params . push ( '-m' , opts . mountpoint ) ; } params . push ( opts . name ) ; if ( opts . devices . length ) { params = params . concat ( opts . devices ) ; } else { var devices = opts . devices . split ( / \\s+ / ) ; params = params . concat ( devices ) ; } zpool ( params , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function add ( opts , cb ) { \"use strict\" ; var params = [ 'add' , '-f' ] ; params . push ( opts . name ) ; //devices is an array or a string of devices if ( opts . devices . length ) { params = params . concat ( opts . devices ) ; } else { var devices = opts . devices . split ( / \\s+ / ) ; params = params . concat ( devices ) ; } zpool ( params , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function destroy ( opts , cb ) { \"use strict\" ; var params = [ 'destroy' , '-f' ] ; params . push ( opts . name ) ; zpool ( params , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function list ( opts , cb ) { //list the statistics from a (specific) pool. -o option is NOT available \"use strict\" ; if ( typeof opts === 'function' ) { cb = opts ; opts = undefined ; } var params = [ 'list' , '-H' ] ; if ( opts && opts . name ) { params . push ( opts . name ) ; } zpool ( params , function ( err , stdout ) { if ( cb && typeof cb === 'function' ) { if ( err ) { cb ( err ) ; return ; } var lines = util . compact ( stdout . split ( '\\n' ) ) ; var list = lines . map ( function ( x ) { return new ZPool ( x ) ; } ) ; cb ( err , list ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a temporary directory . [CODESPLIT] function mktmpdir ( prefixSuffix , tmpdir , callback , onend ) { if ( 'function' == typeof prefixSuffix ) { onend = tmpdir ; callback = prefixSuffix ; tmpdir = null ; prefixSuffix = null ; } else if ( 'function' == typeof tmpdir ) { onend = callback ; callback = tmpdir ; tmpdir = null ; } prefixSuffix = prefixSuffix || 'd' ; onend = onend || function ( ) { } ; tmpname . create ( prefixSuffix , tmpdir , function ( err , path , next ) { if ( err ) return callback ( err ) ; fs . mkdir ( path , 0700 , next ) ; } , function ( err , path ) { if ( err ) return callback ( err ) ; callback ( null , path , function ( err ) { if ( ! path ) return onend ( err ) ; rimraf ( path , function ( _err ) { onend ( err || _err , path ) ; } ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function list ( opts , cb ) { \"use strict\" ; if ( typeof opts === 'function' ) { cb = opts ; opts = undefined ; } var params = [ 'list' , '-H' ] ; if ( opts && opts . type ) { params . push ( '-t' ) ; params . push ( opts . type ) ; } if ( opts && opts . sort ) { params . push ( '-s' ) ; params . push ( opts . sort ) ; } if ( opts && opts . recursive ) { params . push ( '-r' ) ; } if ( opts && opts . name ) { params . push ( opts . name ) ; } zfs ( params , function ( err , stdout ) { if ( cb && typeof cb === 'function' ) { if ( err ) { cb ( err ) ; return ; } var lines = util . compact ( stdout . split ( '\\n' ) ) ; var list = lines . map ( function ( x ) { return new ZFS ( x ) ; } ) ; cb ( err , list ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function get ( opts , cb ) { \"use strict\" ; var params = [ 'get' , '-pH' ] ; if ( opts . source ) { params . push ( '-s' , opts . source ) ; } params . push ( opts . property ) ; if ( opts . name ) { params . push ( opts . name ) ; } zfs ( params , function ( err , stdout ) { if ( cb && typeof cb === 'function' ) { if ( err ) return cb ( err ) ; var lines = util . compact ( stdout . split ( '\\n' ) ) ; var list = lines . map ( function ( x ) { return new util . Property ( x ) ; } ) ; cb ( err , list ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function destroy ( opts , cb ) { \"use strict\" ; var params = [ 'destroy' ] ; if ( opts . recursive ) { params . push ( '-r' ) ; } params . push ( opts . name ) ; zfs ( params , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function create ( opts , cb ) { \"use strict\" ; var params = [ 'create' ] ; if ( opts . options ) { if ( opts . options . length ) { //opts.options is an array for ( var x = 0 ; x < opts . options . length ; x ++ ) { params . push ( '-o' , opts . options [ x ] . property + \"=\" + opts . options [ x ] . value ) ; } } else { //opts.options is a single object params . push ( '-o' , opts . options . property + \"=\" + opts . options . value ) ; } } if ( opts . size ) { params . push ( '-V' , util . parseNumber ( opts . size ) ) ; } params . push ( opts . name ) ; zfs ( params , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set a specific option for a given dataset [CODESPLIT] function set ( opts , cb ) { \"use strict\" ; var params = [ 'set' ] ; params . push ( opts . property + \"=\" + opts . value ) ; params . push ( opts . name ) ; zfs ( params , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function snapshot ( opts , cb ) { \"use strict\" ; var params = [ 'snapshot' ] ; if ( opts . recursive ) { params . push ( '-r' ) ; } params . push ( opts . dataset + '@' + opts . name ) ; zfs ( params , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function clone ( opts , cb ) { \"use strict\" ; var params = [ 'clone' ] ; params . push ( opts . snapshot , opts . dataset ) ; zfs ( params , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function mount ( opts , cb ) { \"use strict\" ; var params = [ 'mount' ] ; if ( opts . overlay ) { params . push ( '-O' ) ; } if ( opts . options ) { if ( opts . options . length ) { //opts.options is an array for ( var x = 0 ; x < opts . options . length ; x ++ ) { params . push ( '-o' , opts . options [ x ] ) ; } } else { //opts.options is a single object, callback err and return cb ( { error : 'invalid argu: the options should be a string array' } ) ; return ; } } if ( opts . dataset ) { params . push ( opts . dataset ) ; } else { params . push ( '-a' ) ; } zfs ( params , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function unmount ( opts , cb ) { \"use strict\" ; var params = [ 'unmount' ] ; if ( opts . force ) { params . push ( '-f' ) ; } if ( opts . name ) { params . push ( opts . name ) ; } else { params . push ( '-a' ) ; } zfs ( params , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function send ( opts , cb ) { \"use strict\" ; var params = [ 'send' ] ; if ( opts . replication ) { params . push ( '-R' ) ; } if ( opts . deduplicate ) { params . push ( '-D' ) ; } if ( opts . properties ) { params . push ( '-p' ) ; } if ( opts . noop ) { params . push ( '-n' ) ; } if ( opts . parsable ) { params . push ( '-P' ) ; } if ( opts . verbose ) { params . push ( '-v' ) ; } if ( opts . incremental ) { if ( opts . intermediary ) { params . push ( '-I' ) ; } else { params . push ( '-i' ) ; } params . push ( opts . incremental ) ; } params . push ( opts . snapshot ) ; spawnzfs ( params , function ( err , child ) { if ( err ) { return cb ( err ) ; } var buffer = [ ] ; var sendStream = child . stdout ; child . stderr . on ( 'data' , function ( data ) { data = data . toString ( ) ; buffer . push ( data ) ; if ( opts . verbose ) { sendStream . emit ( 'verbose' , data ) ; } //only keep last 5 lines if ( buffer . length > 5 ) { buffer . shift ( ) ; } } ) ; child . once ( 'exit' , function ( code ) { if ( code !== 0 ) { var message = 'Send Error:' + util . compact ( buffer . join ( '\\n' ) . split ( '\\n' ) ) . join ( '; ' ) . trim ( ) ; var err = new Error ( message ) ; err . code = code ; sendStream . emit ( 'error' , err ) ; } } ) ; return cb ( null , sendStream ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function receive ( opts , cb ) { \"use strict\" ; var params = [ 'receive' ] ; if ( opts . verbose ) { params . push ( '-v' ) ; } if ( opts . noop ) { params . push ( '-n' ) ; } if ( opts . force ) { params . push ( '-F' ) ; } if ( opts . unmounted ) { params . push ( '-u' ) ; } if ( opts . d ) { params . push ( '-d' ) ; } if ( opts . e ) { params . push ( '-e' ) ; } params . push ( opts . dataset ) ; spawnzfs ( params , function ( err , child ) { if ( err ) { return cb ( err ) ; } var buffer = [ ] ; var receiveStream = child . stdin ; child . stderr . on ( 'data' , function ( data ) { data = data . toString ( ) ; buffer . push ( data ) ; if ( opts . verbose ) { receiveStream . emit ( 'verbose' , data ) ; } //only keep last 5 lines if ( buffer . length > 5 ) { buffer . shift ( ) ; } } ) ; child . once ( 'exit' , function ( code ) { if ( code !== 0 ) { var message = 'Receive Error: ' + util . compact ( buffer . join ( '\\n' ) . split ( '\\n' ) ) . join ( '; ' ) . trim ( ) ; var err = new Error ( message ) ; err . code = code ; receiveStream . emit ( 'error' , err ) ; } } ) ; return cb ( null , receiveStream ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is not valid for simpleStrings [CODESPLIT] function copyString ( buffer , length , offsetBegin , offsetEnd ) { if ( length > 2048 ) { return buffer . toString ( 'utf-8' , offsetBegin , offsetEnd ) ; } var string = '' ; while ( offsetBegin < offsetEnd ) { string += String . fromCharCode ( buffer [ offsetBegin ++ ] ) ; } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is not UTF - 8 compliant [CODESPLIT] function parseSimpleString ( parser ) { var offset = parser . offset ; var length = parser . buffer . length ; var string = '' ; while ( offset < length ) { var c1 = parser . buffer [ offset ++ ] ; if ( c1 === 13 ) { var c2 = parser . buffer [ offset ++ ] ; if ( c2 === 10 ) { parser . offset = offset ; return string ; } string += String . fromCharCode ( c1 ) + String . fromCharCode ( c2 ) ; continue ; } string += String . fromCharCode ( c1 ) ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build base config [CODESPLIT] function getBaseConfig ( isProd ) { // get library details from JSON config const libraryEntryPoint = path . join ( 'src' , LIBRARY_DESC . entry ) ; // generate webpack base config return { entry : [ // \"babel-polyfill\", path . join ( __dirname , libraryEntryPoint ) , ] , output : { devtoolLineToLine : true , pathinfo : true , } , module : { preLoaders : [ { test : / \\.js$ / , exclude : / (node_modules|bower_components) / , loader : \"eslint-loader\" , } , ] , loaders : [ { exclude : / (node_modules|bower_components) / , loader : \"babel-loader\" , plugins : [ \"transform-runtime\" , ] , query : { presets : [ \"es2015\" , \"stage-0\" , \"stage-1\" , \"stage-2\" , ] , cacheDirectory : false , } , test : / \\.js$ / , } , ] , } , eslint : { configFile : './.eslintrc' , } , resolve : { root : path . resolve ( './src' ) , extensions : [ '' , '.js' ] , } , devtool : isProd ? \"source-map\" /* null*/ : \"source-map\" /* '#eval-source-map'*/ , debug : ! isProd , plugins : isProd ? [ new webpack . DefinePlugin ( { 'process.env' : { NODE_ENV : '\"production\"' } } ) , new UglifyJsPlugin ( { compress : { warnings : true } , minimize : true , sourceMap : true , } ) , // Prod plugins here ] : [ new webpack . DefinePlugin ( { 'process.env' : { NODE_ENV : '\"development\"' } } ) , new UglifyJsPlugin ( { compress : { warnings : true } , minimize : true , sourceMap : true , } ) , // Dev plugins here ] , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Methods @private Returns info about raw updates from Telegram Bot API [CODESPLIT] function getUpdateInfo ( update ) { /** Is it chosen inline or edited message/post */ let isChosen = false ; let isEdited = false ; /** Raw and formatted names of update */ let original = '' ; let name = '' ; if ( update . message ) { name = 'message' ; original = 'message' ; } else if ( update . edited_message ) { isEdited = true ; original = 'edited_message' ; name = 'message' ; } else if ( update . channel_post ) { original = 'channel_post' ; name = 'post' ; } else if ( update . edited_channel_post ) { isEdited = true ; original = 'edited_channel_post' ; name = 'post' ; } else if ( update . inline_query ) { original = 'inline_query' ; name = 'inline' ; } else if ( update . chosen_inline_result ) { isChosen = true ; original = 'chosen_inline_result' ; name = 'inline' ; } else if ( update . callback_query ) { original = 'callback_query' ; name = 'callback' ; } return { isChosen , isEdited , original , name } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------- [CODESPLIT] function attachStreamToSocket ( readStream , socketWriteStream , callback , usePipe = false ) { if ( ! usePipe ) { _attachStreamToSocket ( readStream , socketWriteStream , callback ) ; } else { readStream . pipe ( socketWriteStream , { end : false } ) ; readStream . once ( 'end' , ( ) => { readStream . unpipe ( ) ; callback ( ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public function to notify [CODESPLIT] function postNotification ( options , cb ) { options . title = removeColor ( options . title ) ; options . message = removeColor ( options . message ) ; if ( ! options . message ) { return cb && cb ( ! options . message && 'Message is required' ) ; } if ( ! notifyPlatform ) { notifyPlatform = choosePlatform ( ) ; } function resetPreviousTimer ( newMessage ) { previousMessage = newMessage ; clearTimeout ( previousMessageTimer ) ; previousMessageTimer = setTimeout ( function ( ) { previousMessage = false ; } , previousMessageTimeoutMS ) ; } if ( options . message === previousMessage ) { resetPreviousTimer ( options . message ) ; if ( typeof cb === 'function' ) { cb ( err ) ; } return ; } resetPreviousTimer ( options . message ) ; options . debug = debug ( notifyPlatform . name ) ; //for debug logging return notifyPlatform . notify ( options , function ( err ) { if ( err ) { options . debug ( { return_code : err } ) ; } if ( typeof cb === 'function' ) { cb ( err ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Compiler with the given options . [CODESPLIT] function Compiler ( file , options ) { this . options = options || { } ; this . parser = new Parser ( file , options ) ; this . compilers = { } ; this . files = [ ] ; this . file = file ; this . files = [ this . file ] ; this . result = '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render [CODESPLIT] function dry ( file , options ) { debug ( 'rendering <%s>' , file . path ) ; var opts = utils . extend ( { } , options ) ; dry . parse ( file , opts ) ; dry . compile ( file , opts ) ; file . fn ( opts . locals ) ; return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds numbers to a base name until it finds a unique database key [CODESPLIT] function generateUsername ( base ) { base = base . toLowerCase ( ) ; var entries = [ ] ; var finalName ; return userDB . allDocs ( { startkey : base , endkey : base + '\\uffff' , include_docs : false } ) . then ( function ( results ) { if ( results . rows . length === 0 ) { return BPromise . resolve ( base ) ; } for ( var i = 0 ; i < results . rows . length ; i ++ ) { entries . push ( results . rows [ i ] . id ) ; } if ( entries . indexOf ( base ) === - 1 ) { return BPromise . resolve ( base ) ; } var num = 0 ; while ( ! finalName ) { num ++ ; if ( entries . indexOf ( base + num ) === - 1 ) { finalName = base + num ; } } return BPromise . resolve ( finalName ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function to initialize a session following authentication from a socialAuth provider [CODESPLIT] function initSession ( req , res , next ) { var provider = getProvider ( req . path ) ; return user . createSession ( req . user . _id , provider , req ) . then ( function ( mySession ) { return BPromise . resolve ( { error : null , session : mySession , link : null } ) ; } ) . then ( function ( results ) { var template ; if ( config . getItem ( 'testMode.oauthTest' ) ) { template = fs . readFileSync ( path . join ( __dirname , '../templates/oauth/auth-callback-test.ejs' ) , 'utf8' ) ; } else { template = fs . readFileSync ( path . join ( __dirname , '../templates/oauth/auth-callback.ejs' ) , 'utf8' ) ; } var html = ejs . render ( template , results ) ; res . status ( 200 ) . send ( html ) ; } , function ( err ) { return next ( err ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function to initialize a session following authentication from a socialAuth provider [CODESPLIT] function initTokenSession ( req , res , next ) { var provider = getProviderToken ( req . path ) ; return user . createSession ( req . user . _id , provider , req ) . then ( function ( mySession ) { return BPromise . resolve ( mySession ) ; } ) . then ( function ( session ) { res . status ( 200 ) . json ( session ) ; } , function ( err ) { return next ( err ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called after an account has been succesfully linked [CODESPLIT] function linkSuccess ( req , res , next ) { var provider = getProvider ( req . path ) ; var result = { error : null , session : null , link : provider } ; var template ; if ( config . getItem ( 'testMode.oauthTest' ) ) { template = fs . readFileSync ( path . join ( __dirname , '../templates/oauth/auth-callback-test.ejs' ) , 'utf8' ) ; } else { template = fs . readFileSync ( path . join ( __dirname , '../templates/oauth/auth-callback.ejs' ) , 'utf8' ) ; } var html = ejs . render ( template , result ) ; res . status ( 200 ) . send ( html ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called after an account has been succesfully linked using access_token provider [CODESPLIT] function linkTokenSuccess ( req , res , next ) { var provider = getProviderToken ( req . path ) ; res . status ( 200 ) . json ( { ok : true , success : util . capitalizeFirstLetter ( provider ) + ' successfully linked' , provider : provider } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles errors if authentication fails [CODESPLIT] function oauthErrorHandler ( err , req , res , next ) { var template ; if ( config . getItem ( 'testMode.oauthTest' ) ) { template = fs . readFileSync ( path . join ( __dirname , '../templates/oauth/auth-callback-test.ejs' ) , 'utf8' ) ; } else { template = fs . readFileSync ( path . join ( __dirname , '../templates/oauth/auth-callback.ejs' ) , 'utf8' ) ; } var html = ejs . render ( template , { error : err . message , session : null , link : null } ) ; console . error ( err ) ; if ( err . stack ) { console . error ( err . stack ) ; } res . status ( 400 ) . send ( html ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles errors if authentication from access_token provider fails [CODESPLIT] function tokenAuthErrorHandler ( err , req , res , next ) { var status ; if ( req . user && req . user . _id ) { status = 403 ; } else { status = 401 ; } console . error ( err ) ; if ( err . stack ) { console . error ( err . stack ) ; delete err . stack ; } res . status ( status ) . json ( err ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Framework to register OAuth providers with passport [CODESPLIT] function registerProvider ( provider , configFunction ) { provider = provider . toLowerCase ( ) ; var configRef = 'providers.' + provider ; if ( config . getItem ( configRef + '.credentials' ) ) { var credentials = config . getItem ( configRef + '.credentials' ) ; credentials . passReqToCallback = true ; var options = config . getItem ( configRef + '.options' ) || { } ; configFunction . call ( null , credentials , passport , authHandler ) ; router . get ( '/' + provider , passportCallback ( provider , options , 'login' ) ) ; router . get ( '/' + provider + '/callback' , passportCallback ( provider , options , 'login' ) , initSession , oauthErrorHandler ) ; if ( ! config . getItem ( 'security.disableLinkAccounts' ) ) { router . get ( '/link/' + provider , passport . authenticate ( 'bearer' , { session : false } ) , passportCallback ( provider , options , 'link' ) ) ; router . get ( '/link/' + provider + '/callback' , passport . authenticate ( 'bearer' , { session : false } ) , passportCallback ( provider , options , 'link' ) , linkSuccess , oauthErrorHandler ) ; } console . log ( provider + ' loaded.' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A shortcut to register OAuth2 providers that follow the exact accessToken refreshToken pattern . [CODESPLIT] function registerOAuth2 ( providerName , Strategy ) { registerProvider ( providerName , function ( credentials , passport , authHandler ) { passport . use ( new Strategy ( credentials , function ( req , accessToken , refreshToken , profile , done ) { authHandler ( req , providerName , { accessToken : accessToken , refreshToken : refreshToken } , profile ) . asCallback ( done ) ; } ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a provider that accepts an access_token directly from the client skipping the popup window and callback This is for supporting Cordova native IOS and Android apps as well as other devices [CODESPLIT] function registerTokenProvider ( providerName , Strategy ) { providerName = providerName . toLowerCase ( ) ; var configRef = 'providers.' + providerName ; if ( config . getItem ( configRef + '.credentials' ) ) { var credentials = config . getItem ( configRef + '.credentials' ) ; credentials . passReqToCallback = true ; var options = config . getItem ( configRef + '.options' ) || { } ; // Configure the Passport Strategy passport . use ( providerName + '-token' , new Strategy ( credentials , function ( req , accessToken , refreshToken , profile , done ) { authHandler ( req , providerName , { accessToken : accessToken , refreshToken : refreshToken } , profile ) . asCallback ( done ) ; } ) ) ; router . post ( '/' + providerName + '/token' , passportTokenCallback ( providerName , options ) , initTokenSession , tokenAuthErrorHandler ) ; if ( ! config . getItem ( 'security.disableLinkAccounts' ) ) { router . post ( '/link/' + providerName + '/token' , passport . authenticate ( 'bearer' , { session : false } ) , passportTokenCallback ( providerName , options ) , linkTokenSuccess , tokenAuthErrorHandler ) ; } console . log ( providerName + '-token loaded.' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is called after a user has successfully authenticated with a provider If a user is authenticated with a bearer token we will link an account otherwise log in auth is an object containing access_token and optionally refresh_token [CODESPLIT] function authHandler ( req , provider , auth , profile ) { if ( req . user && req . user . _id && req . user . key ) { return user . linkSocial ( req . user . _id , provider , auth , profile , req ) ; } else { return user . socialAuth ( provider , auth , profile , req ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures the passport . authenticate for the given provider passing in options Operation is login or link [CODESPLIT] function passportCallback ( provider , options , operation ) { return function ( req , res , next ) { var theOptions = extend ( { } , options ) ; if ( provider === 'linkedin' ) { theOptions . state = true ; } var accessToken = req . query . bearer_token || req . query . state ; if ( accessToken && ( stateRequired . indexOf ( provider ) > - 1 || config . getItem ( 'providers.' + provider + '.stateRequired' ) === true ) ) { theOptions . state = accessToken ; } theOptions . callbackURL = getLinkCallbackURLs ( provider , req , operation , accessToken ) ; theOptions . session = false ; passport . authenticate ( provider , theOptions ) ( req , res , next ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures the passport . authenticate for the given access_token provider passing in options [CODESPLIT] function passportTokenCallback ( provider , options ) { return function ( req , res , next ) { var theOptions = extend ( { } , options ) ; theOptions . session = false ; passport . authenticate ( provider + '-token' , theOptions ) ( req , res , next ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the provider name from a callback path [CODESPLIT] function getProvider ( pathname ) { var items = pathname . split ( '/' ) ; var index = items . indexOf ( 'callback' ) ; if ( index > 0 ) { return items [ index - 1 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the provider name from a callback path for access_token strategy [CODESPLIT] function getProviderToken ( pathname ) { var items = pathname . split ( '/' ) ; var index = items . indexOf ( 'token' ) ; if ( index > 0 ) { return items [ index - 1 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requires that the user have the specified role [CODESPLIT] function requireRole ( requiredRole ) { return function ( req , res , next ) { if ( ! req . user ) { return next ( superloginError ) ; } var roles = req . user . roles ; if ( ! roles || ! roles . length || roles . indexOf ( requiredRole ) === - 1 ) { res . status ( forbiddenError . status ) ; res . json ( forbiddenError ) ; } else { next ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escapes any characters that are illegal in a CouchDB database name using percent codes inside parenthesis Example : My . name [CODESPLIT] function getLegalDBName ( input ) { input = input . toLowerCase ( ) ; var output = encodeURIComponent ( input ) ; output = output . replace ( / \\. / g , '%2E' ) ; output = output . replace ( / ! / g , '%21' ) ; output = output . replace ( / ~ / g , '%7E' ) ; output = output . replace ( / \\* / g , '%2A' ) ; output = output . replace ( / ' / g , '%27' ) ; output = output . replace ( / \\( / g , '%28' ) ; output = output . replace ( / \\) / g , '%29' ) ; output = output . replace ( / \\- / g , '%2D' ) ; output = output . toLowerCase ( ) ; output = output . replace ( / (%..) / g , function ( esc ) { esc = esc . substr ( 1 ) ; return '(' + esc + ')' ; } ) ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "BPromise . config ( { warnings : false } ) ; [CODESPLIT] function FileAdapter ( config ) { var sessionsRoot = config . getItem ( 'session.file.sessionsRoot' ) ; this . _sessionFolder = path . join ( process . env . PWD , sessionsRoot ) ; console . log ( 'File Adapter loaded' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wire up rotation controls [CODESPLIT] function ( ) { var foundLayer = null ; $ . each ( projectedTiles , function ( layerName , layer ) { if ( map . hasLayer ( layer ) ) { foundLayer = layer ; } } ) ; return foundLayer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public Functions [CODESPLIT] function ( tileLayer ) { if ( this . options . changingMap ) { return false ; } // Check for existing layer if ( this . _usingTileProjection ( tileLayer ) ) { console . log ( \"That tile layer is already active.\" ) ; } else { // Drop base tile layers this . _dropTileLayers ( ) ; this . _update ( tileLayer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manually remove layers before destroying map . See https : // github . com / Leaflet / Leaflet / issues / 2718 [CODESPLIT] function ( ) { for ( var i in this . _layers ) { this . removeLayer ( this . _layers [ i ] ) ; } L . Map . prototype . remove . call ( this ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private Functions [CODESPLIT] function ( crs , options ) { var resolutions = [ ] ; for ( var zoom = options . minZoom ; zoom <= options . maxZoom ; zoom ++ ) { resolutions . push ( options . maxResolution / Math . pow ( 2 , zoom ) ) ; } return new L . Proj . CRS ( crs , options . proj4def , { origin : options . origin , resolutions : resolutions , bounds : options . projectedBounds } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use default CRS classes for common codes fallback to custom for all other codes . [CODESPLIT] function ( crs , options ) { switch ( crs ) { case \"EPSG:3857\" : return L . CRS . EPSG3857 ; case \"EPSG:3395\" : return L . CRS . EPSG3395 ; case \"EPSG:4326\" : return L . CRS . EPSG4326 ; default : return this . _defineMapCRS ( crs , options ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This recurses through all the map s layers to update layer positions after their positions moved . [CODESPLIT] function ( group ) { var map = this ; if ( group . eachLayer ) { group . eachLayer ( function ( layer ) { map . _updateAllLayers ( layer ) ; } ) ; } else { if ( group . redraw ) { group . redraw ( ) ; } else if ( group . update ) { group . update ( ) ; } else { console . log ( \"Don't know how to update\" , group ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes an array of markers and adds them in bulk [CODESPLIT] function ( layersArray ) { var fg = this . _featureGroup , npg = this . _nonPointGroup , chunked = this . options . chunkedLoading , chunkInterval = this . options . chunkInterval , chunkProgress = this . options . chunkProgress , newMarkers , i , l , m ; if ( this . _map ) { var offset = 0 , started = ( new Date ( ) ) . getTime ( ) ; var process = L . bind ( function ( ) { var start = ( new Date ( ) ) . getTime ( ) ; for ( ; offset < layersArray . length ; offset ++ ) { if ( chunked && offset % 200 === 0 ) { // every couple hundred markers, instrument the time elapsed since processing started: var elapsed = ( new Date ( ) ) . getTime ( ) - start ; if ( elapsed > chunkInterval ) { break ; // been working too hard, time to take a break :-) } } m = layersArray [ offset ] ; //Not point data, can't be clustered if ( ! m . getLatLng ) { npg . addLayer ( m ) ; continue ; } if ( this . hasLayer ( m ) ) { continue ; } this . _addLayer ( m , this . _maxZoom ) ; //If we just made a cluster of size 2 then we need to remove the other marker from the map (if it is) or we never will if ( m . __parent ) { if ( m . __parent . getChildCount ( ) === 2 ) { var markers = m . __parent . getAllChildMarkers ( ) , otherMarker = markers [ 0 ] === m ? markers [ 1 ] : markers [ 0 ] ; fg . removeLayer ( otherMarker ) ; } } } if ( chunkProgress ) { // report progress and time elapsed: chunkProgress ( offset , layersArray . length , ( new Date ( ) ) . getTime ( ) - started ) ; } if ( offset === layersArray . length ) { //Update the icons of all those visible clusters that were affected this . _featureGroup . eachLayer ( function ( c ) { if ( c instanceof L . MarkerCluster && c . _iconNeedsUpdate ) { c . _updateIcon ( ) ; } } ) ; this . _topClusterLevel . _recursivelyAddChildrenToMap ( null , this . _zoom , this . _currentShownBounds ) ; } else { setTimeout ( process , this . options . chunkDelay ) ; } } , this ) ; process ( ) ; } else { newMarkers = [ ] ; for ( i = 0 , l = layersArray . length ; i < l ; i ++ ) { m = layersArray [ i ] ; //Not point data, can't be clustered if ( ! m . getLatLng ) { npg . addLayer ( m ) ; continue ; } if ( this . hasLayer ( m ) ) { continue ; } newMarkers . push ( m ) ; } this . _needsClustering = this . _needsClustering . concat ( newMarkers ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes an array of markers and removes them in bulk [CODESPLIT] function ( layersArray ) { var i , l , m , fg = this . _featureGroup , npg = this . _nonPointGroup ; if ( ! this . _map ) { for ( i = 0 , l = layersArray . length ; i < l ; i ++ ) { m = layersArray [ i ] ; this . _arraySplice ( this . _needsClustering , m ) ; npg . removeLayer ( m ) ; } return this ; } for ( i = 0 , l = layersArray . length ; i < l ; i ++ ) { m = layersArray [ i ] ; if ( ! m . __parent ) { npg . removeLayer ( m ) ; continue ; } this . _removeLayer ( m , true , true ) ; if ( fg . hasLayer ( m ) ) { fg . removeLayer ( m ) ; if ( m . setOpacity ) { m . setOpacity ( 1 ) ; } } } //Fix up the clusters and markers on the map this . _topClusterLevel . _recursivelyAddChildrenToMap ( null , this . _zoom , this . _currentShownBounds ) ; fg . eachLayer ( function ( c ) { if ( c instanceof L . MarkerCluster ) { c . _updateIcon ( ) ; } } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override FeatureGroup . getBounds as it doesn t work [CODESPLIT] function ( ) { var bounds = new L . LatLngBounds ( ) ; if ( this . _topClusterLevel ) { bounds . extend ( this . _topClusterLevel . _bounds ) ; } for ( var i = this . _needsClustering . length - 1 ; i >= 0 ; i -- ) { bounds . extend ( this . _needsClustering [ i ] . getLatLng ( ) ) ; } bounds . extend ( this . _nonPointGroup . getBounds ( ) ) ; return bounds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overrides LayerGroup . eachLayer [CODESPLIT] function ( method , context ) { var markers = this . _needsClustering . slice ( ) , i ; if ( this . _topClusterLevel ) { this . _topClusterLevel . getAllChildMarkers ( markers ) ; } for ( i = markers . length - 1 ; i >= 0 ; i -- ) { method . call ( context , markers [ i ] ) ; } this . _nonPointGroup . eachLayer ( method , context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overrides LayerGroup . getLayer WARNING : Really bad performance [CODESPLIT] function ( id ) { var result = null ; this . eachLayer ( function ( l ) { if ( L . stamp ( l ) === id ) { result = l ; } } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the given layer is in this MarkerClusterGroup [CODESPLIT] function ( layer ) { if ( ! layer ) { return false ; } var i , anArray = this . _needsClustering ; for ( i = anArray . length - 1 ; i >= 0 ; i -- ) { if ( anArray [ i ] === layer ) { return true ; } } anArray = this . _needsRemoving ; for ( i = anArray . length - 1 ; i >= 0 ; i -- ) { if ( anArray [ i ] === layer ) { return false ; } } return ! ! ( layer . __parent && layer . __parent . _group === this ) || this . _nonPointGroup . hasLayer ( layer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Zoom down to show the given layer ( spiderfying if necessary ) then calls the callback [CODESPLIT] function ( layer , callback ) { var showMarker = function ( ) { if ( ( layer . _icon || layer . __parent . _icon ) && ! this . _inZoomAnimation ) { this . _map . off ( 'moveend' , showMarker , this ) ; this . off ( 'animationend' , showMarker , this ) ; if ( layer . _icon ) { callback ( ) ; } else if ( layer . __parent . _icon ) { var afterSpiderfy = function ( ) { this . off ( 'spiderfied' , afterSpiderfy , this ) ; callback ( ) ; } ; this . on ( 'spiderfied' , afterSpiderfy , this ) ; layer . __parent . spiderfy ( ) ; } } } ; if ( layer . _icon && this . _map . getBounds ( ) . contains ( layer . getLatLng ( ) ) ) { //Layer is visible ond on screen, immediate return callback ( ) ; } else if ( layer . __parent . _zoom < this . _map . getZoom ( ) ) { //Layer should be visible at this zoom level. It must not be on screen so just pan over to it this . _map . on ( 'moveend' , showMarker , this ) ; this . _map . panTo ( layer . getLatLng ( ) ) ; } else { var moveStart = function ( ) { this . _map . off ( 'movestart' , moveStart , this ) ; moveStart = null ; } ; this . _map . on ( 'movestart' , moveStart , this ) ; this . _map . on ( 'moveend' , showMarker , this ) ; this . on ( 'animationend' , showMarker , this ) ; layer . __parent . zoomToBounds ( ) ; if ( moveStart ) { //Never started moving, must already be there, probably need clustering however showMarker . call ( this ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overrides FeatureGroup . onAdd [CODESPLIT] function ( map ) { this . _map = map ; var i , l , layer ; if ( ! isFinite ( this . _map . getMaxZoom ( ) ) ) { throw \"Map has no maxZoom specified\" ; } this . _featureGroup . onAdd ( map ) ; this . _nonPointGroup . onAdd ( map ) ; if ( ! this . _gridClusters ) { this . _generateInitialClusters ( ) ; } for ( i = 0 , l = this . _needsRemoving . length ; i < l ; i ++ ) { layer = this . _needsRemoving [ i ] ; this . _removeLayer ( layer , true ) ; } this . _needsRemoving = [ ] ; //Remember the current zoom level and bounds this . _zoom = this . _map . getZoom ( ) ; this . _currentShownBounds = this . _getExpandedVisibleBounds ( ) ; this . _map . on ( 'zoomend' , this . _zoomEnd , this ) ; this . _map . on ( 'moveend' , this . _moveEnd , this ) ; if ( this . _spiderfierOnAdd ) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely this . _spiderfierOnAdd ( ) ; } this . _bindEvents ( ) ; //Actually add our markers to the map: l = this . _needsClustering ; this . _needsClustering = [ ] ; this . addLayers ( l ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overrides FeatureGroup . onRemove [CODESPLIT] function ( map ) { map . off ( 'zoomend' , this . _zoomEnd , this ) ; map . off ( 'moveend' , this . _moveEnd , this ) ; this . _unbindEvents ( ) ; //In case we are in a cluster animation this . _map . _mapPane . className = this . _map . _mapPane . className . replace ( ' leaflet-cluster-anim' , '' ) ; if ( this . _spiderfierOnRemove ) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely this . _spiderfierOnRemove ( ) ; } //Clean up all the layers we added to the map this . _hideCoverage ( ) ; this . _featureGroup . onRemove ( map ) ; this . _nonPointGroup . onRemove ( map ) ; this . _featureGroup . clearLayers ( ) ; this . _map = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the given object from the given array [CODESPLIT] function ( anArray , obj ) { for ( var i = anArray . length - 1 ; i >= 0 ; i -- ) { if ( anArray [ i ] === obj ) { anArray . splice ( i , 1 ) ; return true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function for removing a marker from everything . dontUpdateMap : set to true if you will handle updating the map manually ( for bulk functions ) [CODESPLIT] function ( marker , removeFromDistanceGrid , dontUpdateMap ) { var gridClusters = this . _gridClusters , gridUnclustered = this . _gridUnclustered , fg = this . _featureGroup , map = this . _map ; //Remove the marker from distance clusters it might be in if ( removeFromDistanceGrid ) { for ( var z = this . _maxZoom ; z >= 0 ; z -- ) { if ( ! gridUnclustered [ z ] . removeObject ( marker , map . project ( marker . getLatLng ( ) , z ) ) ) { break ; } } } //Work our way up the clusters removing them as we go if required var cluster = marker . __parent , markers = cluster . _markers , otherMarker ; //Remove the marker from the immediate parents marker list this . _arraySplice ( markers , marker ) ; while ( cluster ) { cluster . _childCount -- ; if ( cluster . _zoom < 0 ) { //Top level, do nothing break ; } else if ( removeFromDistanceGrid && cluster . _childCount <= 1 ) { //Cluster no longer required //We need to push the other marker up to the parent otherMarker = cluster . _markers [ 0 ] === marker ? cluster . _markers [ 1 ] : cluster . _markers [ 0 ] ; //Update distance grid gridClusters [ cluster . _zoom ] . removeObject ( cluster , map . project ( cluster . _cLatLng , cluster . _zoom ) ) ; gridUnclustered [ cluster . _zoom ] . addObject ( otherMarker , map . project ( otherMarker . getLatLng ( ) , cluster . _zoom ) ) ; //Move otherMarker up to parent this . _arraySplice ( cluster . __parent . _childClusters , cluster ) ; cluster . __parent . _markers . push ( otherMarker ) ; otherMarker . __parent = cluster . __parent ; if ( cluster . _icon ) { //Cluster is currently on the map, need to put the marker on the map instead fg . removeLayer ( cluster ) ; if ( ! dontUpdateMap ) { fg . addLayer ( otherMarker ) ; } } } else { cluster . _recalculateBounds ( ) ; if ( ! dontUpdateMap || ! cluster . _icon ) { cluster . _updateIcon ( ) ; } } cluster = cluster . __parent ; } delete marker . __parent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Default functionality [CODESPLIT] function ( cluster ) { var childCount = cluster . getChildCount ( ) ; var c = ' marker-cluster-' ; if ( childCount < 10 ) { c += 'small' ; } else if ( childCount < 100 ) { c += 'medium' ; } else { c += 'large' ; } return new L . DivIcon ( { html : '<div><span>' + childCount + '</span></div>' , className : 'marker-cluster' + c , iconSize : new L . Point ( 40 , 40 ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Zoom : Zoom to start adding at ( Pass this . _maxZoom to start at the bottom ) [CODESPLIT] function ( layer , zoom ) { var gridClusters = this . _gridClusters , gridUnclustered = this . _gridUnclustered , markerPoint , z ; if ( this . options . singleMarkerMode ) { layer . options . icon = this . options . iconCreateFunction ( { getChildCount : function ( ) { return 1 ; } , getAllChildMarkers : function ( ) { return [ layer ] ; } } ) ; } //Find the lowest zoom level to slot this one in for ( ; zoom >= 0 ; zoom -- ) { markerPoint = this . _map . project ( layer . getLatLng ( ) , zoom ) ; // calculate pixel position //Try find a cluster close by var closest = gridClusters [ zoom ] . getNearObject ( markerPoint ) ; if ( closest ) { closest . _addChild ( layer ) ; layer . __parent = closest ; return ; } //Try find a marker close by to form a new cluster with closest = gridUnclustered [ zoom ] . getNearObject ( markerPoint ) ; if ( closest ) { var parent = closest . __parent ; if ( parent ) { this . _removeLayer ( closest , false ) ; } //Create new cluster with these 2 in it var newCluster = new L . MarkerCluster ( this , zoom , closest , layer ) ; gridClusters [ zoom ] . addObject ( newCluster , this . _map . project ( newCluster . _cLatLng , zoom ) ) ; closest . __parent = newCluster ; layer . __parent = newCluster ; //First create any new intermediate parent clusters that don't exist var lastParent = newCluster ; for ( z = zoom - 1 ; z > parent . _zoom ; z -- ) { lastParent = new L . MarkerCluster ( this , z , lastParent ) ; gridClusters [ z ] . addObject ( lastParent , this . _map . project ( closest . getLatLng ( ) , z ) ) ; } parent . _addChild ( lastParent ) ; //Remove closest from this zoom level and any above that it is in, replace with newCluster for ( z = zoom ; z >= 0 ; z -- ) { if ( ! gridUnclustered [ z ] . removeObject ( closest , this . _map . project ( closest . getLatLng ( ) , z ) ) ) { break ; } } return ; } //Didn't manage to cluster in at this zoom, record us as a marker here and continue upwards gridUnclustered [ zoom ] . addObject ( layer , markerPoint ) ; } //Didn't get in anything, add us to the top this . _topClusterLevel . _addChild ( layer ) ; layer . __parent = this . _topClusterLevel ; return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enqueue code to fire after the marker expand / contract has happened [CODESPLIT] function ( fn ) { this . _queue . push ( fn ) ; if ( ! this . _queueTimeout ) { this . _queueTimeout = setTimeout ( L . bind ( this . _processQueue , this ) , 300 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the maps visible bounds expanded in each direction by the size of the screen ( so the user cannot see an area we do not cover in one pan ) [CODESPLIT] function ( ) { if ( ! this . options . removeOutsideVisibleBounds ) { return this . getBounds ( ) ; } var map = this . _map , bounds = map . getBounds ( ) , sw = bounds . _southWest , ne = bounds . _northEast , latDiff = L . Browser . mobile ? 0 : Math . abs ( sw . lat - ne . lat ) , lngDiff = L . Browser . mobile ? 0 : Math . abs ( sw . lng - ne . lng ) ; return new L . LatLngBounds ( new L . LatLng ( sw . lat - latDiff , sw . lng - lngDiff , true ) , new L . LatLng ( ne . lat + latDiff , ne . lng + lngDiff , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shared animation code [CODESPLIT] function ( layer , newCluster ) { if ( newCluster === layer ) { this . _featureGroup . addLayer ( layer ) ; } else if ( newCluster . _childCount === 2 ) { newCluster . _addToMap ( ) ; var markers = newCluster . getAllChildMarkers ( ) ; this . _featureGroup . removeLayer ( markers [ 0 ] ) ; this . _featureGroup . removeLayer ( markers [ 1 ] ) ; } else { newCluster . _updateIcon ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively retrieve all child markers of this cluster [CODESPLIT] function ( storageArray ) { storageArray = storageArray || [ ] ; for ( var i = this . _childClusters . length - 1 ; i >= 0 ; i -- ) { this . _childClusters [ i ] . getAllChildMarkers ( storageArray ) ; } for ( var j = this . _markers . length - 1 ; j >= 0 ; j -- ) { storageArray . push ( this . _markers [ j ] ) ; } return storageArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Zoom to the minimum of showing all of the child markers or the extents of this cluster [CODESPLIT] function ( ) { var childClusters = this . _childClusters . slice ( ) , map = this . _group . _map , boundsZoom = map . getBoundsZoom ( this . _bounds ) , zoom = this . _zoom + 1 , mapZoom = map . getZoom ( ) , i ; //calculate how far we need to zoom down to see all of the markers while ( childClusters . length > 0 && boundsZoom > zoom ) { zoom ++ ; var newClusters = [ ] ; for ( i = 0 ; i < childClusters . length ; i ++ ) { newClusters = newClusters . concat ( childClusters [ i ] . _childClusters ) ; } childClusters = newClusters ; } if ( boundsZoom > zoom ) { this . _group . _map . setView ( this . _latlng , zoom ) ; } else if ( boundsZoom <= mapZoom ) { //If fitBounds wouldn't zoom us down, zoom us down instead this . _group . _map . setView ( this . _latlng , mapZoom + 1 ) ; } else { this . _group . _map . fitBounds ( this . _bounds ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expand our bounds and tell our parent to [CODESPLIT] function ( marker ) { var addedCount , addedLatLng = marker . _wLatLng || marker . _latlng ; if ( marker instanceof L . MarkerCluster ) { this . _bounds . extend ( marker . _bounds ) ; addedCount = marker . _childCount ; } else { this . _bounds . extend ( addedLatLng ) ; addedCount = 1 ; } if ( ! this . _cLatLng ) { // when clustering, take position of the first point as the cluster center this . _cLatLng = marker . _cLatLng || addedLatLng ; } // when showing clusters, take weighted average of all points as cluster center var totalCount = this . _childCount + addedCount ; //Calculate weighted latlng for display if ( ! this . _wLatLng ) { this . _latlng = this . _wLatLng = new L . LatLng ( addedLatLng . lat , addedLatLng . lng ) ; } else { this . _wLatLng . lat = ( addedLatLng . lat * addedCount + this . _wLatLng . lat * this . _childCount ) / totalCount ; this . _wLatLng . lng = ( addedLatLng . lng * addedCount + this . _wLatLng . lng * this . _childCount ) / totalCount ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "exceptBounds : If set don t remove any markers / clusters in it [CODESPLIT] function ( previousBounds , zoomLevel , exceptBounds ) { var m , i ; this . _recursively ( previousBounds , - 1 , zoomLevel - 1 , function ( c ) { //Remove markers at every level for ( i = c . _markers . length - 1 ; i >= 0 ; i -- ) { m = c . _markers [ i ] ; if ( ! exceptBounds || ! exceptBounds . contains ( m . _latlng ) ) { c . _group . _featureGroup . removeLayer ( m ) ; if ( m . setOpacity ) { m . setOpacity ( 1 ) ; } } } } , function ( c ) { //Remove child clusters at just the bottom level for ( i = c . _childClusters . length - 1 ; i >= 0 ; i -- ) { m = c . _childClusters [ i ] ; if ( ! exceptBounds || ! exceptBounds . contains ( m . _latlng ) ) { c . _group . _featureGroup . removeLayer ( m ) ; if ( m . setOpacity ) { m . setOpacity ( 1 ) ; } } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the given functions recursively to this and child clusters boundsToApplyTo : a L . LatLngBounds representing the bounds of what clusters to recurse in to zoomLevelToStart : zoom level to start running functions ( inclusive ) zoomLevelToStop : zoom level to stop running functions ( inclusive ) runAtEveryLevel : function that takes an L . MarkerCluster as an argument that should be applied on every level runAtBottomLevel : function that takes an L . MarkerCluster as an argument that should be applied at only the bottom level [CODESPLIT] function ( boundsToApplyTo , zoomLevelToStart , zoomLevelToStop , runAtEveryLevel , runAtBottomLevel ) { var childClusters = this . _childClusters , zoom = this . _zoom , i , c ; if ( zoomLevelToStart > zoom ) { //Still going down to required depth, just recurse to child clusters for ( i = childClusters . length - 1 ; i >= 0 ; i -- ) { c = childClusters [ i ] ; if ( boundsToApplyTo . intersects ( c . _bounds ) ) { c . _recursively ( boundsToApplyTo , zoomLevelToStart , zoomLevelToStop , runAtEveryLevel , runAtBottomLevel ) ; } } } else { //In required depth if ( runAtEveryLevel ) { runAtEveryLevel ( this ) ; } if ( runAtBottomLevel && this . _zoom === zoomLevelToStop ) { runAtBottomLevel ( this ) ; } //TODO: This loop is almost the same as above if ( zoomLevelToStop > zoom ) { for ( i = childClusters . length - 1 ; i >= 0 ; i -- ) { c = childClusters [ i ] ; if ( boundsToApplyTo . intersects ( c . _bounds ) ) { c . _recursively ( boundsToApplyTo , zoomLevelToStart , zoomLevelToStop , runAtEveryLevel , runAtBottomLevel ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Given an array of latlngs compute a convex hull as an array of latlngs [CODESPLIT] function ( latLngs ) { // find first baseline var maxLat = false , minLat = false , maxPt = null , minPt = null , i ; for ( i = latLngs . length - 1 ; i >= 0 ; i -- ) { var pt = latLngs [ i ] ; if ( maxLat === false || pt . lat > maxLat ) { maxPt = pt ; maxLat = pt . lat ; } if ( minLat === false || pt . lat < minLat ) { minPt = pt ; minLat = pt . lat ; } } var ch = [ ] . concat ( this . buildConvexHull ( [ minPt , maxPt ] , latLngs ) , this . buildConvexHull ( [ maxPt , minPt ] , latLngs ) ) ; return ch ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "show spiral instead of circle from this marker count upwards . 0 - > always spiral ; Infinity - > always circle [CODESPLIT] function ( ) { if ( this . _group . _spiderfied === this || this . _group . _inZoomAnimation ) { return ; } var childMarkers = this . getAllChildMarkers ( ) , group = this . _group , map = group . _map , center = map . latLngToLayerPoint ( this . _latlng ) , positions ; this . _group . _unspiderfy ( ) ; this . _group . _spiderfied = this ; //TODO Maybe: childMarkers order by distance to center if ( childMarkers . length >= this . _circleSpiralSwitchover ) { positions = this . _generatePointsSpiral ( childMarkers . length , center ) ; } else { center . y += 10 ; //Otherwise circles look wrong positions = this . _generatePointsCircle ( childMarkers . length , center ) ; } this . _animationSpiderfy ( childMarkers , positions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non Animated versions of everything [CODESPLIT] function ( childMarkers , positions ) { var group = this . _group , map = group . _map , fg = group . _featureGroup , i , m , leg , newPos ; for ( i = childMarkers . length - 1 ; i >= 0 ; i -- ) { newPos = map . layerPointToLatLng ( positions [ i ] ) ; m = childMarkers [ i ] ; m . _preSpiderfyLatlng = m . _latlng ; m . setLatLng ( newPos ) ; if ( m . setZIndexOffset ) { m . setZIndexOffset ( 1000000 ) ; //Make these appear on top of EVERYTHING } fg . addLayer ( m ) ; leg = new L . Polyline ( [ this . _latlng , newPos ] , { weight : 1.5 , color : '#222' } ) ; map . addLayer ( leg ) ; m . _spiderLeg = leg ; } this . setOpacity ( 0.3 ) ; group . fire ( 'spiderfied' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the given layer is currently being spiderfied then we unspiderfy it so it isn t on the map anymore etc [CODESPLIT] function ( layer ) { if ( layer . _spiderLeg ) { this . _featureGroup . removeLayer ( layer ) ; layer . setOpacity ( 1 ) ; //Position will be fixed up immediately in _animationUnspiderfy layer . setZIndexOffset ( 0 ) ; this . _map . removeLayer ( layer . _spiderLeg ) ; delete layer . _spiderLeg ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the tile layer that has a key containing projection [CODESPLIT] function ( projection ) { for ( var key in projectedTiles ) { if ( projectedTiles . hasOwnProperty ( key ) ) { if ( key . indexOf ( projection ) !== - 1 ) { return projectedTiles [ key ] ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the tile layer that has a key containing projection [CODESPLIT] function ( projection ) { for ( var key in tiles ) { if ( tiles . hasOwnProperty ( key ) ) { if ( key . indexOf ( projection ) !== - 1 ) { return tiles [ key ] ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Have to create a separate marker for each map else weirdness happens [CODESPLIT] function addToMap ( location , map ) { var marker = L . marker ( location . coordinates ) ; marker . addTo ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "avoid loading features South of 45N . Errors will occur when loading Antarctic data . [CODESPLIT] function ( featureData , layer ) { var coords = featureData . geometry . coordinates ; return boundsLimit . contains ( L . latLng ( [ coords [ 1 ] , coords [ 0 ] ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "avoid loading features South of 45N . Errors will occur when loading Antarctic data . [CODESPLIT] function ( featureData , layer ) { var bbox = featureData . geometry . bbox ; var llBounds = L . latLngBounds ( [ bbox [ 1 ] , bbox [ 0 ] ] , [ bbox [ 3 ] , bbox [ 2 ] ] ) ; return boundsLimit . contains ( llBounds ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interpolate the page path with pagination variables . [CODESPLIT] function interpolate ( path , data ) { return path . replace ( / :(\\w+) / g , function ( match , param ) { return data [ param ] } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a get pages utility for people to use when rendering . [CODESPLIT] function createPagesUtility ( pages , index ) { return function getPages ( number ) { var offset = Math . floor ( number / 2 ) var start , end if ( index + offset >= pages . length ) { start = Math . max ( 0 , pages . length - number ) end = pages . length } else { start = Math . max ( 0 , index - offset ) end = Math . min ( start + number , pages . length ) } return pages . slice ( start , end ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helper engine that can use a template from a string [CODESPLIT] function ( ) { var templates = { data : { } } ; var stringTemplateSource = function ( template ) { this . text = function ( value ) { if ( arguments . length === 0 ) { return templates [ template ] ; } templates [ template ] = value ; } ; } ; var templateEngine = new ko . nativeTemplateEngine ( ) ; templateEngine . makeTemplateSource = function ( template ) { return new stringTemplateSource ( template ) ; } ; templateEngine . addTemplate = function ( key , value ) { templates [ key ] = value ; } ; return templateEngine ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "::: PRIVATE FUNCTIONS [CODESPLIT] function beforeChild ( parserState , compilerState , result , checkParent ) { var _isDomMethod = checkParent !== true ? isDomMethod ( compilerState ) : isParentDomMethod ( compilerState ) ; var _numAttributes = checkParent !== true ? numAttributes ( parserState ) : numParentAttributes ( parserState ) ; var _numChildren = checkParent !== true ? numChildren ( parserState ) : numParentChildren ( parserState ) ; var _isTopLevelChild = checkParent !== true ? parserState . childCounts . length > 1 : parserState . childCounts . length > 2 ; if ( _isTopLevelChild === true ) { if ( _numAttributes <= 0 ) { if ( _numChildren <= 1 ) { if ( _isDomMethod !== true ) { // React.createElement(\"tag\", result . push ( \",\" ) ; } // React.createElement(\"tag\", null, // React.DOM.tag(null, result . push ( \"null\" ) ; result . push ( \",\" ) ; } else { // React.createElement(\"tag\", {\"attr\":\"value\"}, sibling, // React.DOM.tag({\"attr\":\"value\"}, sibling, result . push ( \",\" ) ; } } else { // React.createElement(\"tag\", {\"attr\":\"value\"}, // React.DOM.tag({\"attr\":\"value\"}, result . push ( \"}\" ) ; result . push ( \",\" ) ; } } // If top-level node with siblings else if ( _numChildren > 1 ) { // React.createElement(…), // React.DOM.tag(…), // \"text\", result . push ( \",\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Job retry specification [CODESPLIT] function Job ( collection , data ) { this . collection = collection ; if ( data ) { // Convert plain object to JobData type data . __proto__ = JobData . prototype ; this . data = data ; } else { this . data = new JobData ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Options for a new worker [CODESPLIT] function Worker ( queues , options ) { options || ( options = { } ) ; this . empty = 0 ; this . queues = queues || [ ] ; this . interval = options . interval || 5000 ; this . callbacks = options . callbacks || { } ; this . strategies = options . strategies || { } ; this . universal = options . universal || false ; // Default retry strategies this . strategies . linear || ( this . strategies . linear = linear ) ; this . strategies . exponential || ( this . strategies . exponential = exponential ) ; // This worker will only process jobs of this priority or higher this . minPriority = options . minPriority ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "uploader [CODESPLIT] function Uploader ( options ) { if ( typeof options !== 'object' ) { throw new TypeError ( 'options must be an object' ) ; } this . $el = this . _getElement ( options . el ) ; this . _elType = this . $el . tagName . toLowerCase ( ) ; // if ( options . name && typeof options . name !== 'string' ) { throw new TypeError ( 'options `name` must be a string' ) ; } if ( options . url && typeof options . url !== 'string' ) { throw new TypeError ( 'options `url` must be a string' ) ; } if ( options . method && typeof options . method !== 'string' ) { throw new TypeError ( 'options `method` must be a string' ) ; } if ( options . headers && typeof options . headers !== 'object' ) { throw new TypeError ( 'options `headers` must be an object' ) ; } // this . files = [ ] ; this . method = options . method || 'POST' ; this . name = options . name || 'file' ; this . url = options . url || null ; this . headers = options . headers || { } ; // EE3 EE3 . call ( this ) ; // error listener this . on ( 'error' , this . _onError . bind ( this ) ) ; // check support this . _checkSupport ( ) ; // attach to $el this . _attach ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generic drag event handler [CODESPLIT] function handleDragEvents ( e ) { e . stopPropagation ( ) ; e . preventDefault ( ) ; return this . emit ( e . type , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recodeの内容を、Excel上のカラム表示（A B ... ）にあわせてオブジェクトに格納し返却する。 [CODESPLIT] function formatRecordByColumnLabel ( recode ) { const recodeBuffer = { } ; recode . forEach ( function ( value , index ) { recodeBuffer [ new Ordinal ( index + 1 ) . toAlphabet ( ) ] = value ; } ) ; return recodeBuffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recordの内容を、mappingで対応づけられたKey名にあわせてオブジェクトに格納し返却する。 [CODESPLIT] function formatRecordByMapping ( recode , mapping ) { return Object . keys ( mapping ) . reduce ( ( formatted , keyName ) => { if ( mapping [ keyName ] !== 0 ) { formatted [ keyName ] = recode [ new Ordinal ( mapping [ keyName ] ) . toNumber ( ) - 1 ] ; } return formatted ; } , { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Device Object [CODESPLIT] function ( deviceInfo ) { this . _handle = deviceInfo . _handle ; this . address = deviceInfo . _handle ; this . name = deviceInfo . name ; this . serviceUUIDs = deviceInfo . uuids ; this . adData = deviceInfo . adData ; this . connected = false ; this . services = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Service Object [CODESPLIT] function ( serviceInfo ) { this . _handle = serviceInfo . _handle ; this . uuid = serviceInfo . uuid ; this . primary = serviceInfo . primary ; this . includedServices = { } ; this . characteristics = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Characteristic Object [CODESPLIT] function ( characteristicInfo ) { this . _handle = characteristicInfo . _handle ; this . uuid = characteristicInfo . uuid ; this . properties = characteristicInfo . properties ; this . descriptors = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Plugin function [CODESPLIT] function streamifyGulp ( pluginStream ) { var inputStream = new Stream . Transform ( { objectMode : true } ) ; var outputStream = new Stream . Transform ( { objectMode : true } ) ; var duplex = new Duplexer ( { objectMode : true } , inputStream , outputStream ) ; // Accepting functions returning streams if ( 'function' === typeof pluginStream ) { pluginStream = pluginStream ( ) ; } // Listening for plugin errors and reemit pluginStream . on ( 'error' , function ( error ) { duplex . emit ( 'error' , error ) ; } ) ; // Change files contents from stream to buffer and write to the plugin stream inputStream . _transform = function ( file , unused , cb ) { // Buffering the file stream var originalStream ; var buf ; var bufstream ; if ( file . isNull ( ) || file . isBuffer ( ) ) { inputStream . push ( file ) ; return cb ( ) ; } file . wasStream = true ; originalStream = file . contents ; buf = new Buffer ( 0 ) ; bufstream = new Stream . Writable ( ) ; // Buffer the stream bufstream . _write = function ( chunk , encoding , cb2 ) { buf = Buffer . concat ( [ buf , chunk ] , buf . length + chunk . length ) ; cb2 ( ) ; } ; // When buffered bufstream . once ( 'finish' , function ( ) { // Send the buffer wrapped in a file file . contents = buf ; inputStream . push ( file ) ; cb ( ) ; } ) ; originalStream . pipe ( bufstream ) ; } ; // Change files contents from buffer to stream and write to the output stream outputStream . _transform = function ( file , unused , cb ) { var buf ; var newStream ; if ( file . isNull ( ) || ! file . wasStream ) { outputStream . push ( file ) ; return cb ( ) ; } delete file . wasStream ; // Get the transformed buffer buf = file . contents ; newStream = new Stream . Readable ( ) ; // Write the buffer only when datas are needed newStream . _read = function ( ) { // Write the content back to the stream newStream . push ( buf ) ; newStream . push ( null ) ; } ; // Pass the file out file . contents = newStream ; outputStream . push ( file ) ; cb ( ) ; } ; outputStream . _flush = function ( cb ) { setImmediate ( function ( ) { // Old streams WTF if ( ! pluginStream . _readableState ) { outputStream . emit ( 'end' ) ; duplex . emit ( 'end' ) ; } } ) ; cb ( ) ; } ; inputStream . pipe ( pluginStream ) . pipe ( outputStream ) ; return duplex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "More reliable indexOf courtesy of [CODESPLIT] function ( value ) { if ( value != value || value === 0 ) { for ( var i = this . length ; i -- && ! is ( this [ i ] , value ) ; ) { } } else { i = [ ] . indexOf . call ( this , value ) ; } return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A wrapper for the tor process containing its ChildProcess port number and data directory . [CODESPLIT] function Tor ( child , port , dir ) { this . process = child ; this . port = port ; this . dir = dir ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Array containing the included locations . [CODESPLIT] function getIncluded ( ) { var args = config . files ( ) . included || getDefaultArgs ( ) || getPackageJsonArgs ( ) || getBowerJsonArgs ( ) || [ ] ; return _expandGlobs ( args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Array of default paths . [CODESPLIT] function getDefaultArgs ( ) { var results = [ ] ; DEFAULT_PATHS . forEach ( function ( dir ) { if ( fs . existsSync ( dir ) ) results . push ( dir ) ; } ) ; return results . length == 0 ? null : results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks package . json for possible paths [CODESPLIT] function getPackageJsonArgs ( ) { var results = [ ] ; var config = _loadJson ( 'package.json' ) ; if ( config . main ) results = results . concat ( getMainFieldAsArray ( config . main ) ) ; if ( config . files ) results = results . concat ( config . files ) ; return results . length == 0 ? null : results . filter ( _uniqfilter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks bower . json for possible paths [CODESPLIT] function getBowerJsonArgs ( ) { var results = [ ] ; var config = _loadJson ( 'bower.json' ) ; if ( config . main ) results = results . concat ( getMainFieldAsArray ( config . main ) ) ; return results . length == 0 ? null : results . filter ( _uniqfilter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Array of the files mentioned in a main field If the value is noted without . js at the end it is appended . [CODESPLIT] function getMainFieldAsArray ( main ) { if ( main . constructor === Array ) { return main ; } else { if ( fs . existsSync ( main ) ) { return [ main ] ; } else if ( fs . existsSync ( main + '.js' ) ) { return [ main + '.js' ] ; } else { return [ ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether a symbol is a function and is the only symbol exported by a module ( as in module . exports = function () {} ; ) . [CODESPLIT] function isModuleFunction2 ( doclet ) { return doclet . longname && doclet . longname === doclet . name && doclet . longname . indexOf ( 'module:' ) === 0 && doclet . kind === 'function' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve all of the following types of members from a set of doclets : [CODESPLIT] function getMembers2 ( data ) { var find = function ( data , spec ) { return data ( spec ) . get ( ) ; } ; var members = { classes : find ( data , { kind : 'class' } ) , externals : find ( data , { kind : 'external' } ) , events : find ( data , { kind : 'event' } ) , globals : find ( data , { kind : [ 'member' , 'function' , 'constant' , 'typedef' ] , memberof : { isUndefined : true } } ) , mixins : find ( data , { kind : 'mixin' } ) , modules : find ( data , { kind : 'module' } ) , namespaces : find ( data , { kind : 'namespace' } ) , typedef : find ( data , { kind : 'typedef' , isTSEnum : { is : true } } ) , callbacks : find ( data , { kind : 'typedef' , isTSEnum : { isUndefined : true } } ) } ; // functions that are also modules (as in \"module.exports = function() {};\") are not globals members . globals = members . globals . filter ( function ( doclet ) { if ( isModuleFunction2 ( doclet ) ) { return false ; } return true ; } ) ; return members ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * xperiments [CODESPLIT] function ( field , reverse , primer ) { var key = function ( x ) { return primer ? primer ( x [ field ] ) : x [ field ] } ; return function ( a , b ) { var A = key ( a ) , B = key ( b ) ; return ( ( A < B ) ? - 1 : ( ( A > B ) ? 1 : 0 ) ) * [ - 1 , 1 ] [ + ! ! reverse ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the navigation sidebar . [CODESPLIT] function buildNav ( members ) { var seen = { } ; var nav = navigationMaster ; if ( members . modules . length ) { members . modules . sort ( sort_by ( 'longname' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . modules . forEach ( function ( m ) { if ( ! hasOwnProp . call ( seen , m . longname ) ) { nav . module . members . push ( linkto ( m . longname , m . name ) ) ; } seen [ m . longname ] = true ; } ) ; } if ( members . externals . length ) { members . externals . sort ( sort_by ( 'longname' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . externals . forEach ( function ( e ) { if ( ! hasOwnProp . call ( seen , e . longname ) ) { nav . external . members . push ( linkto ( e . longname , e . name . replace ( / (^\"|\"$) / g , '' ) ) ) ; } seen [ e . longname ] = true ; } ) ; } if ( members . classes . length ) { members . classes . sort ( sort_by ( 'longname' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . classes . forEach ( function ( c ) { if ( ! hasOwnProp . call ( seen , c . longname ) ) { nav . class . members . push ( { link : linkto ( c . longname , c . longname ) , namespace : c } ) ; } seen [ c . longname ] = true ; } ) ; } /*\n\t if ( members.events.length ) {\n\n\t members.events.forEach( function ( e ) {\n\t if ( !hasOwnProp.call( seen, e.longname ) ) {\n\n\t nav.event.members.push( linkto( e.longname, e.name ) );\n\n\t }\n\t seen[e.longname] = true;\n\t } );\n\n\t }*/ if ( members . typedef . length ) { members . typedef . forEach ( function ( td ) { if ( ! hasOwnProp . call ( seen , td . longname ) ) { nav . typedef . members . push ( { link : linkto ( td . name , td . name ) , namespace : { longname : td . longname } } ) ; } seen [ td . longname ] = true ; } ) ; } if ( members . callbacks . length ) { members . callbacks . forEach ( function ( cb ) { if ( ! hasOwnProp . call ( seen , cb . longname ) ) { nav . callbacks . members . push ( { link : linkto ( cb . longname , cb . longname . split ( '#' ) [ 0 ] ) , namespace : { longname : cb . longname } } ) ; } seen [ cb . longname ] = true ; } ) ; } if ( members . namespaces . length ) { members . namespaces . sort ( sort_by ( 'longname' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . namespaces . forEach ( function ( n ) { if ( ! hasOwnProp . call ( seen , n . longname ) ) { nav . namespace . members . push ( { link : linkto ( n . longname , n . longname ) , namespace : n } ) ; } seen [ n . longname ] = true ; } ) ; } if ( members . mixins . length ) { members . mixins . sort ( sort_by ( 'longname' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . mixins . forEach ( function ( m ) { if ( ! hasOwnProp . call ( seen , m . longname ) ) { nav . mixin . members . push ( linkto ( m . longname , m . longname ) ) ; } seen [ m . longname ] = true ; } ) ; } if ( members . tutorials . length ) { members . tutorials . sort ( sort_by ( 'name' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . tutorials . forEach ( function ( t ) { nav . tutorial . members . push ( tutoriallink ( t . name ) ) ; } ) ; } if ( members . globals . length ) { members . globals . sort ( sort_by ( 'longname' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . globals . forEach ( function ( g ) { if ( g . kind !== 'typedef' && ! hasOwnProp . call ( seen , g . longname ) ) { nav . global . members . push ( linkto ( g . longname , g . longname ) ) ; } seen [ g . longname ] = true ; } ) ; } var topLevelNav = [ ] ; _ . each ( nav , function ( entry , name ) { if ( entry . members . length > 0 && name !== \"index\" ) { topLevelNav . push ( { title : entry . title , link : entry . link , members : entry . members } ) ; } } ) ; nav . topLevelNav = topLevelNav ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes absolute paths from JSON output and inject some relevant metadata e . g . language . [CODESPLIT] function ( objects , inch_args ) { var cwd = process . cwd ( ) ; var excluded = config . files ( ) . excluded || [ ] ; var data = { language : 'javascript' , client_name : 'inchjs' , args : inch_args , client_version : \"\" + inch_config . version , git_repo_url : getGitRepoURL ( ) } ; if ( process . env . TRAVIS ) { data [ 'travis' ] = true ; data [ 'travis_job_id' ] = process . env . TRAVIS_JOB_ID ; data [ 'travis_commit' ] = process . env . TRAVIS_COMMIT ; data [ 'travis_repo_slug' ] = process . env . TRAVIS_REPO_SLUG ; } data [ 'branch_name' ] = getGitBranchName ( ) ; data [ 'objects' ] = objects . filter ( includeObjectFilter ) . map ( function ( item ) { return prepareCodeObject ( item , cwd ) ; } ) . filter ( function ( item ) { return ! excludeObjectIfMatch ( item , excluded ) ; } ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An HTTP Agent for proxying requests through Tor using SOCKS5 . [CODESPLIT] function TorAgent ( opts ) { if ( ! ( this instanceof TorAgent ) ) { return new TorAgent ( ) ; } http . Agent . call ( this , opts ) ; this . socksHost = opts . socksHost || 'localhost' ; this . socksPort = opts . socksPort || 9050 ; this . defaultPort = 80 ; // Used when invoking TorAgent.create this . tor = opts . tor ; // Prevent protocol check, wrap destroy this . protocol = null ; this . defaultDestroy = this . destroy ; this . destroy = this . destroyWrapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------ Constructor [CODESPLIT] function ( element , options ) { this . $element = $ ( element ) ; this . options = $ . extend ( true , { } , $ . fn . typeahead . defaults , options ) ; this . $menu = $ ( this . options . menu ) . appendTo ( 'body' ) ; this . shown = false ; // Method overrides     this . eventSupported = this . options . eventSupported || this . eventSupported ; this . grepper = this . options . grepper || this . grepper ; this . highlighter = this . options . highlighter || this . highlighter ; this . lookup = this . options . lookup || this . lookup ; this . matcher = this . options . matcher || this . matcher ; this . render = this . options . render || this . render ; this . select = this . options . select || this . select ; this . sorter = this . options . sorter || this . sorter ; this . source = this . options . source || this . source ; if ( ! this . source . length ) { var ajax = this . options . ajax ; if ( typeof ajax === 'string' ) { this . ajax = $ . extend ( { } , $ . fn . typeahead . defaults . ajax , { url : ajax } ) ; } else { this . ajax = $ . extend ( { } , $ . fn . typeahead . defaults . ajax , ajax ) ; } if ( ! this . ajax . url ) { this . ajax = null ; } } this . listen ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------ Handle AJAX source [CODESPLIT] function ( ) { var that = this , query = that . $element . val ( ) ; if ( query === that . query ) { return that ; } // Query changed that . query = query ; // Cancel last timer if set if ( that . ajax . timerId ) { clearTimeout ( that . ajax . timerId ) ; that . ajax . timerId = null ; } if ( ! query || query . length < that . ajax . triggerLength ) { // Cancel the ajax callback if in progress if ( that . ajax . xhr ) { that . ajax . xhr . abort ( ) ; that . ajax . xhr = null ; that . ajaxToggleLoadClass ( false ) ; } return that . shown ? that . hide ( ) : that ; } // Query is good to send, set a timer that . ajax . timerId = setTimeout ( function ( ) { $ . proxy ( that . ajaxExecute ( query ) , that ) } , that . ajax . timeout ) ; return that ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------ Execute an AJAX request [CODESPLIT] function ( query ) { this . ajaxToggleLoadClass ( true ) ; // Cancel last call if already in progress if ( this . ajax . xhr ) this . ajax . xhr . abort ( ) ; var params = this . ajax . preDispatch ? this . ajax . preDispatch ( query ) : { query : query } ; var jAjax = ( this . ajax . method === \"post\" ) ? $ . post : $ . get ; this . ajax . xhr = jAjax ( this . ajax . url , params , $ . proxy ( this . ajaxLookup , this ) ) ; this . ajax . timerId = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------ Perform a lookup in the AJAX results [CODESPLIT] function ( data ) { var items ; this . ajaxToggleLoadClass ( false ) ; if ( ! this . ajax . xhr ) return ; if ( this . ajax . preProcess ) { data = this . ajax . preProcess ( data ) ; } // Save for selection retreival this . ajax . data = data ; items = this . grepper ( this . ajax . data ) ; if ( ! items || ! items . length ) { return this . shown ? this . hide ( ) : this ; } this . ajax . xhr = null ; return this . render ( items . slice ( 0 , this . options . items ) ) . show ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------ Search source [CODESPLIT] function ( event ) { var that = this , items ; if ( that . ajax ) { that . ajaxer ( ) ; } else { that . query = that . $element . val ( ) ; if ( ! that . query ) { return that . shown ? that . hide ( ) : that ; } items = that . grepper ( that . source ) ; if ( ! items || ! items . length ) { return that . shown ? that . hide ( ) : that ; } return that . render ( items . slice ( 0 , that . options . items ) ) . show ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------ Filters relevent results [CODESPLIT] function ( data ) { var that = this , items ; if ( data && data . length && ! data [ 0 ] . hasOwnProperty ( that . options . display ) ) { return null ; } items = $ . grep ( data , function ( item ) { return that . matcher ( item [ that . options . display ] , item ) ; } ) ; return this . sorter ( items ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------ Sorts the results [CODESPLIT] function ( items ) { var that = this , beginswith = [ ] , caseSensitive = [ ] , caseInsensitive = [ ] , item ; while ( item = items . shift ( ) ) { if ( ! item [ that . options . display ] . toLowerCase ( ) . indexOf ( this . query . toLowerCase ( ) ) ) { beginswith . push ( item ) ; } else if ( ~ item [ that . options . display ] . indexOf ( this . query ) ) { caseSensitive . push ( item ) ; } else { caseInsensitive . push ( item ) ; } } return beginswith . concat ( caseSensitive , caseInsensitive ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------ Highlights the match ( es ) within the results [CODESPLIT] function ( item ) { var query = this . query . replace ( / [\\-\\[\\]{}()*+?.,\\\\\\^$|#\\s] / g , '\\\\$&' ) ; return item . replace ( new RegExp ( '(' + query + ')' , 'ig' ) , function ( $1 , match ) { return '<strong>' + match + '</strong>' ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------ Renders the results list [CODESPLIT] function ( items ) { var that = this ; items = $ ( items ) . map ( function ( i , item ) { i = $ ( that . options . item ) . attr ( 'data-value' , item [ that . options . val ] ) ; i . find ( 'a' ) . html ( that . highlighter ( item [ that . options . display ] , item ) ) ; return i [ 0 ] ; } ) ; items . first ( ) . addClass ( 'active' ) ; this . $menu . html ( items ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------ Selects the next result [CODESPLIT] function ( event ) { var active = this . $menu . find ( '.active' ) . removeClass ( 'active' ) ; var next = active . next ( ) ; if ( ! next . length ) { next = $ ( this . $menu . find ( 'li' ) [ 0 ] ) ; } next . addClass ( 'active' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------ Handles a key being pressed [CODESPLIT] function ( e ) { e . stopPropagation ( ) ; if ( ! this . shown ) { return ; } switch ( e . keyCode ) { case 9 : // tab case 13 : // enter case 27 : // escape e . preventDefault ( ) ; break ; case 38 : // up arrow e . preventDefault ( ) ; this . prev ( ) ; break ; case 40 : // down arrow e . preventDefault ( ) ; this . next ( ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------ Handles cursor exiting the textbox [CODESPLIT] function ( e ) { var that = this ; e . stopPropagation ( ) ; e . preventDefault ( ) ; setTimeout ( function ( ) { if ( ! that . $menu . is ( ':focus' ) ) { that . hide ( ) ; } } , 150 ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs a local version of Inch . [CODESPLIT] function run ( inch_args , options ) { var callback = function ( filename ) { LocalInch . run ( inch_args || [ 'suggest' ] , filename , noop ) ; } if ( options . dry_run ) callback = noop ; retriever . run ( PathExtractor . extractPaths ( inch_args ) , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "train [CODESPLIT] function ( options , callback ) { var data = options . data ; var target = options . target ; var features = options . features ; var featureTypes = options . featureTypes ; featureTypes . forEach ( function ( f ) { if ( [ 'number' , 'category' ] . indexOf ( f ) === - 1 ) { callback ( new Error ( 'Unrecognized feature type' ) ) ; return ; } } ) ; var targets = unique ( data . map ( function ( d ) { return d [ d . length - 1 ] ; } ) ) ; this . features = features ; this . targets = targets ; this . target = target var classify = this . classify . bind ( this ) var model = { features : this . features , targets : this . targets , // model is the generated tree structure model : this . _c45 ( data , target , features , featureTypes , 0 ) , classify : function ( sample ) { return classify ( this . model , sample ) } , toJSON : function ( ) { return JSON . stringify ( this . model ) } } ; this . model = model . model callback ( null , model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "shutdown puts it into power saving sleep mode . call with false to wake it up . [CODESPLIT] function shutdown ( addr , b ) { if ( addr < 0 || addr >= maxDevices ) throw 'address out of range' ; if ( b ) spiTransfer ( addr , OP_SHUTDOWN , 0 ) ; else spiTransfer ( addr , OP_SHUTDOWN , 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets the number of pixels per row pretty much always 8 for most devices . [CODESPLIT] function setScanLimit ( addr , limit ) { if ( addr < 0 || addr >= maxDevices ) return ; //console.log(\"OP_SCANLIMIT\"); if ( limit >= 0 && limit < 8 ) spiTransfer ( addr , OP_SCANLIMIT , limit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets the brightness of the LEDs 0 to 15 [CODESPLIT] function setBrightness ( addr , intensity ) { if ( addr < 0 || addr >= maxDevices ) return ; if ( typeof intensity == 'undefined' ) return ; intensity = constrain ( intensity , 0 , 15 ) ; spiTransfer ( addr , OP_INTENSITY , intensity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "clears the entire display [CODESPLIT] function clearDisplay ( addr ) { if ( addr < 0 || addr >= maxDevices ) throw 'address out of range' ; var offset ; offset = addr * 8 ; for ( var i = 0 ; i < 8 ; i ++ ) { status [ offset + i ] = 0 ; spiTransfer ( addr , i + 1 , status [ offset + i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Display a hexadecimal digit on a 7 - Segment Display Params : addr address of the display digit the position of the digit on the display ( 0 .. 7 ) value the value to be displayed . ( 0x00 .. 0x0F ) dp sets the decimal point . [CODESPLIT] function setDigit ( addr , digit , value , dp ) { if ( addr < 0 || addr >= maxDevices ) throw 'address out of range' ; if ( digit < 0 || digit > 7 ) throw 'invalid digit number' ; if ( value < 0 || value > 15 ) throw 'number out of range' ; var offset = addr * 8 ; var v = charTable [ value ] ; //.toString(16)];  if ( dp ) v |= 0x80 ; // set the decimal point bit if necessary status [ offset + digit ] = v ; spiTransfer ( addr , digit + 1 , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pos is passed in as 0 to 7 0 on the left 7 on the right [CODESPLIT] function showNumber ( addr , num , decimalplaces , mindigits , leftjustified , pos , dontclear ) { if ( addr < 0 || addr >= maxDevices ) throw 'address out of range' ; num = formatNumber ( num , decimalplaces , mindigits ) ; // internally, pos is 0 on the right, so we set defaults, and convert if ( typeof pos === 'undefined' ) { if ( leftjustified ) { pos = 7 ; } else { pos = 0 ; } } else pos = 7 - pos ; // get rid of the decimal place but remember where it was var decimalplace ; if ( num . indexOf ( '.' ) < 0 ) decimalplace = - 1 ; else { decimalplace = num . length - num . indexOf ( '.' ) - 1 ; num = num . split ( '.' ) . join ( '' ) ; } if ( leftjustified ) { pos -= ( num . length - 1 ) ; } for ( var i = 0 ; i < 8 ; i ++ ) { var offset = i + pos ; var char = num . charAt ( num . length - 1 - i ) ; if ( ( offset < 8 && offset >= 0 ) && ( ! dontclear || char != '' ) ) { if ( char == '-' ) setChar ( addr , offset , char , i > 0 && i == decimalplace ) ; else setDigit ( addr , offset , parseInt ( char ) , i > 0 && i == decimalplace ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function setChar ( addr , digit , char , dp ) { if ( addr < 0 || addr >= maxDevices ) throw 'address out of range' ; if ( digit < 0 || digit > 7 ) throw 'invalid digit number' ; var offset = addr * 8 ; var v = charTable [ char ] || charTable [ char . toLowerCase ( ) ] ; //.toString(16)];  if ( dp ) v |= 0x80 ; // set the decimal point bit if necessary status [ offset + digit ] = v ; spiTransfer ( addr , digit + 1 , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a Redux compatible wrapper around a Feathers service . [CODESPLIT] function reduxifyService ( app , route ) { var _handleActions ; var name = arguments . length > 2 && arguments [ 2 ] !== undefined ? arguments [ 2 ] : route ; var options = arguments . length > 3 && arguments [ 3 ] !== undefined ? arguments [ 3 ] : { } ; var debug = ( 0 , _debug2 . default ) ( 'reducer:' + name ) ; debug ( 'route ' + route ) ; var defaults = { isError : 'isError' , isLoading : 'isLoading' , isSaving : 'isSaving' , isFinished : 'isFinished' , data : 'data' , queryResult : 'queryResult' , store : 'store' , PENDING : 'PENDING' , FULFILLED : 'FULFILLED' , REJECTED : 'REJECTED' } ; var opts = Object . assign ( { } , defaults , options ) ; var SERVICE_NAME = 'SERVICES_' + name . toUpperCase ( ) + '_' ; var service = app . service ( route ) ; if ( ! service ) { debug ( 'redux: Feathers service \\'' + route + ' does not exist.' ) ; throw Error ( 'Feathers service \\'' + route + ' does not exist.' ) ; } var reducerForServiceMethod = function reducerForServiceMethod ( actionType , ifLoading , isFind ) { var _ref ; return _ref = { } , _defineProperty ( _ref , actionType + '_' + opts . PENDING , function undefined ( state , action ) { var _extends2 ; debug ( 'redux:' + actionType + '_' + opts . PENDING , action ) ; return _extends ( { } , state , ( _extends2 = { } , _defineProperty ( _extends2 , opts . isError , null ) , _defineProperty ( _extends2 , opts . isLoading , ifLoading ) , _defineProperty ( _extends2 , opts . isSaving , ! ifLoading ) , _defineProperty ( _extends2 , opts . isFinished , false ) , _defineProperty ( _extends2 , opts . data , null ) , _defineProperty ( _extends2 , opts . queryResult , state [ opts . queryResult ] || null ) , _extends2 ) ) ; } ) , _defineProperty ( _ref , actionType + '_' + opts . FULFILLED , function undefined ( state , action ) { var _extends3 ; debug ( 'redux:' + actionType + '_' + opts . FULFILLED , action ) ; return _extends ( { } , state , ( _extends3 = { } , _defineProperty ( _extends3 , opts . isError , null ) , _defineProperty ( _extends3 , opts . isLoading , false ) , _defineProperty ( _extends3 , opts . isSaving , false ) , _defineProperty ( _extends3 , opts . isFinished , true ) , _defineProperty ( _extends3 , opts . data , ! isFind ? action . payload : null ) , _defineProperty ( _extends3 , opts . queryResult , isFind ? action . payload : state [ opts . queryResult ] || null ) , _extends3 ) ) ; } ) , _defineProperty ( _ref , actionType + '_' + opts . REJECTED , function undefined ( state , action ) { var _extends4 ; debug ( 'redux:' + actionType + '_' + opts . REJECTED , action ) ; return _extends ( { } , state , ( _extends4 = { } , _defineProperty ( _extends4 , opts . isError , action . payload ) , _defineProperty ( _extends4 , opts . isLoading , false ) , _defineProperty ( _extends4 , opts . isSaving , false ) , _defineProperty ( _extends4 , opts . isFinished , true ) , _defineProperty ( _extends4 , opts . data , null ) , _defineProperty ( _extends4 , opts . queryResult , isFind ? null : state [ opts . queryResult ] || null ) , _extends4 ) ) ; } ) , _ref ; } ; // ACTION TYPES var FIND = SERVICE_NAME + 'FIND' ; var GET = SERVICE_NAME + 'GET' ; var CREATE = SERVICE_NAME + 'CREATE' ; var UPDATE = SERVICE_NAME + 'UPDATE' ; var PATCH = SERVICE_NAME + 'PATCH' ; var REMOVE = SERVICE_NAME + 'REMOVE' ; var RESET = SERVICE_NAME + 'RESET' ; var STORE = SERVICE_NAME + 'STORE' ; return { // ACTION CREATORS // Note: action.payload in reducer will have the value of .data below find : ( 0 , _reduxActions . createAction ) ( FIND , function ( p ) { return { promise : service . find ( p ) , data : undefined } ; } ) , get : ( 0 , _reduxActions . createAction ) ( GET , function ( id , p ) { return { promise : service . get ( id , p ) } ; } ) , create : ( 0 , _reduxActions . createAction ) ( CREATE , function ( d , p ) { return { promise : service . create ( d , p ) } ; } ) , update : ( 0 , _reduxActions . createAction ) ( UPDATE , function ( id , d , p ) { return { promise : service . update ( id , d , p ) } ; } ) , patch : ( 0 , _reduxActions . createAction ) ( PATCH , function ( id , d , p ) { return { promise : service . patch ( id , d , p ) } ; } ) , remove : ( 0 , _reduxActions . createAction ) ( REMOVE , function ( id , p ) { return { promise : service . remove ( id , p ) } ; } ) , reset : ( 0 , _reduxActions . createAction ) ( RESET ) , store : ( 0 , _reduxActions . createAction ) ( STORE , function ( store ) { return store ; } ) , on : function on ( event , data , fcn ) { return function ( dispatch , getState ) { fcn ( event , data , dispatch , getState ) ; } ; } , // REDUCER reducer : ( 0 , _reduxActions . handleActions ) ( Object . assign ( { } , reducerForServiceMethod ( FIND , true , true ) , reducerForServiceMethod ( GET , true ) , reducerForServiceMethod ( CREATE , false ) , reducerForServiceMethod ( UPDATE , false ) , reducerForServiceMethod ( PATCH , false ) , reducerForServiceMethod ( REMOVE , false ) , // reset status if no promise is pending _defineProperty ( { } , RESET , function ( state , action ) { var _extends5 ; debug ( 'redux:' + RESET , action ) ; if ( state [ opts . isLoading ] || state [ opts . isSaving ] ) { return state ; } return _extends ( { } , state , ( _extends5 = { } , _defineProperty ( _extends5 , opts . isError , null ) , _defineProperty ( _extends5 , opts . isLoading , false ) , _defineProperty ( _extends5 , opts . isSaving , false ) , _defineProperty ( _extends5 , opts . isFinished , false ) , _defineProperty ( _extends5 , opts . data , null ) , _defineProperty ( _extends5 , opts . queryResult , action . payload ? state [ opts . queryResult ] : null ) , _defineProperty ( _extends5 , opts . store , null ) , _extends5 ) ) ; } ) , // update store _defineProperty ( { } , STORE , function ( state , action ) { debug ( 'redux:' + STORE , action ) ; return _extends ( { } , state , _defineProperty ( { } , opts . store , action . payload ) ) ; } ) ) , ( _handleActions = { } , _defineProperty ( _handleActions , opts . isError , null ) , _defineProperty ( _handleActions , opts . isLoading , false ) , _defineProperty ( _handleActions , opts . isSaving , false ) , _defineProperty ( _handleActions , opts . isFinished , false ) , _defineProperty ( _handleActions , opts . data , null ) , _defineProperty ( _handleActions , opts . queryResult , null ) , _defineProperty ( _handleActions , opts . store , null ) , _handleActions ) ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles down an example . Async examples call an imaginary done function once they re done . [CODESPLIT] function getExampleCode ( comment ) { var expectedResult = comment . expectedResult ; var isAsync = comment . isAsync ; var testCase = comment . testCase ; if ( isAsync ) { return '\\nfunction cb(err, result) {' + 'if(err) return done(err);' + 'result.should.eql(' + expectedResult + ');' + 'done();' + '}\\n' + 'var returnValue = ' + testCase + ';' + 'if(returnValue && returnValue.then && typeof returnValue.then === \\'function\\') {' + 'returnValue.then(cb.bind(null, null), cb);' + '}' ; } else { return '(' + testCase + ').should.eql(' + expectedResult + ');' ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "HMAC - based Extract - and - Expand Key Derivation Function ( HKDF ) [CODESPLIT] function hkdf ( ikm , length , { salt = '' , info = '' , hash = 'SHA-256' } = { } ) { hash = hash . toLowerCase ( ) . replace ( '-' , '' ) ; // 0. Hash length const hash_len = hash_length ( hash ) ; // 1. extract const prk = hkdf_extract ( hash , hash_len , ikm , salt ) ; // 2. expand return hkdf_expand ( hash , hash_len , prk , length , info ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A simple wrapper around node s http ( s ) request . [CODESPLIT] function request ( method , path , body , callback ) { var stream ; // Body is optional if ( typeof body === 'function' && typeof callback === 'undefined' ) { callback = body ; body = undefined ; } // Return a stream if no callback is specified if ( ! callback ) { stream = new EventEmitter ( ) ; stream . setEncoding = function ( ) { throw new Error ( \"This stream is always utf8\" ) ; } ; } function errorHandler ( err ) { if ( callback ) { callback ( err ) ; } if ( stream ) { stream . emit ( 'error' , err ) ; } } var headers = { \"Host\" : uri . host } ; // add the authorization header if provided and using https if ( uri . auth ) { headers [ \"Authorization\" ] = \"Basic \" + new Buffer ( uri . auth , \"ascii\" ) . toString ( \"base64\" ) ; } if ( body ) { body = JSON . stringify ( body ) ; headers [ \"Content-Length\" ] = Buffer . byteLength ( body ) ; headers [ \"Content-Type\" ] = \"application/json\" ; } var options = { host : uri . hostname , method : method , path : path , port : uri . port , headers : headers } ; var request = uri . protocolHandler . request ( options , function ( response ) { response . setEncoding ( 'utf8' ) ; var body = \"\" ; response . on ( 'data' , function ( chunk ) { if ( callback ) { body += chunk ; } if ( stream ) { stream . emit ( 'data' , chunk ) ; } } ) ; response . on ( 'end' , function ( ) { if ( callback ) { try { var parsedBody = JSON . parse ( body ) ; callback ( null , parsedBody ) ; } catch ( err ) { callback ( err ) ; } } if ( stream ) { stream . emit ( 'end' ) ; } } ) ; response . on ( 'error' , errorHandler ) ; } ) ; request . on ( 'error' , errorHandler ) ; if ( body ) { request . write ( body , 'utf8' ) ; } request . end ( ) ; return stream ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Class to implement inner working of plugin . [CODESPLIT] function ( options ) { \"use strict\" ; if ( ( options . setter && options . setter . indexOf ( '.' ) > - 1 ) || ( options . getter && options . getter . indexOf ( '.' ) > - 1 ) ) { throw new Error ( 'Getter (' + options . getter + ') and setter (' + options . setter + ') methods cannot be nested, so they cannot contain dot(.)' ) ; } this . options = Joi . attempt ( options , optionsSchema ) ; this . locales = this . getAvailableLocales ( ) ; this . default = this . options . default || this . locales [ 0 ] ; //this.callback   = this.getCallback(this.options.callback); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks synchroniously if given file or directory exists . Returns true or false . [CODESPLIT] function fileExists ( path , shouldBeDir ) { \"use strict\" ; try { var lstat = fs . lstatSync ( path ) ; if ( shouldBeDir && lstat . isDirectory ( ) ) { return true ; } if ( ! shouldBeDir && lstat . isFile ( ) ) { return true ; } } catch ( err ) { return false ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hapi plugin function which adds i18n support to request and response objects . [CODESPLIT] async function ( server , options ) { try { var internal = new Internal ( options ) ; } catch ( err ) { throw new Boom ( err ) ; } /**\n         * @module exposed\n         * @description\n         * Exposed functions and attributes are listed under exposed name.\n         * To access those attributes `request.server.plugins['hapi-locale']` can be used.\n         * @example\n         * var locales = request.server.plugins['hapi-locale'].getLocales(); // ['tr_TR', 'en_US'] etc.\n         */ /**\n         * Returns all available locales as an array.\n         * @name getLocales\n         * @function\n         * @returns {Array.<string>}    - Array of locales.\n         * @example\n         * var locales = request.server.plugins['hapi-locale'].getLocales(); // ['tr_TR', 'en_US'] etc.\n         */ server . expose ( 'getLocales' , function getLocales ( ) { return internal . locales ; } ) ; /**\n         * Returns default locale.\n         * @name getDefaultLocale\n         * @function\n         * @returns {string}    - Default locale\n         */ server . expose ( 'getDefaultLocale' , function getDefaultLocale ( ) { return internal . default ; } ) ; /**\n         * Returns requested language.\n         * @name getLocale\n         * @function\n         * @param {Object}      request - Hapi.js request object\n         * @returns {string}    Locale\n         */ server . expose ( 'getLocale' , function getLocale ( request ) { try { return lodash . get ( request , internal . options . getter ) ( ) ; } catch ( err ) { return null ; } } ) ; server . ext ( internal . options . onEvent , internal . processRequest , { bind : internal } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build a dependency tree from the flat mdeps list by recursing [CODESPLIT] function ( currDeps , loc ) { loc . deps = loc . deps || [ ] ; var covered = [ ] ; // only cover unique paths once to avoid stack overflow currDeps . forEach ( function ( obj ) { if ( covered . indexOf ( obj . path ) < 0 ) { covered . push ( obj . path ) ; // cover unique paths only once per level var key = obj . name , isRelative = ( [ '\\\\' , '/' , '.' ] . indexOf ( key [ 0 ] ) >= 0 ) , notCovered = notCoveredInArray ( loc . deps , key ) , isRecorded = ( ! isRelative || opts . showLocal ) && notCovered , res = isRecorded ? { name : key } : loc ; if ( isRecorded ) { // NB: !isRecorded => only inspect the file for recorded deps res . path = obj . path ; loc . deps . push ( res ) ; } // recurse (!isRecorded => keep adding to previous location) traverse ( lookup [ obj . path ] || [ ] , res ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "given a modules array with cycles - trim dependencies in each cycle [CODESPLIT] function ( ms , cycles ) { var removed = { } ; cycles . forEach ( function ( c ) { var last = c [ c . length - 1 ] ; // last id in cycle //console.log('will try to trim from', last, ms[last]); // need to find a dependency in the cycle var depsInCycle = ms [ last ] . filter ( function ( deps ) { return deps . path && c . indexOf ( deps . path ) >= 0 ; } ) ; if ( ! depsInCycle . length ) { throw new Error ( \"logic fail2\" ) ; // last thing in a cycle should have deps } var depToRemove = depsInCycle [ 0 ] . path ; //console.log('deps in cycle', depsInCycle); for ( var i = 0 ; i < ms [ last ] . length ; i += 1 ) { var dep = ms [ last ] [ i ] ; if ( dep . path && dep . path === depToRemove ) { //console.log('removing', depToRemove); removed [ last ] = dep . name ; ms [ last ] . splice ( i , 1 ) ; } } //console.log('after remove', ms[last]); } ) ; return removed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module @lobsangnet / lobsang - formatter - matrix / schema Library to get a schema for the given topic . [CODESPLIT] function schema ( topic ) { if ( topic === constants . LOBSANG_CONTENT_TOPIC ) { return wrapper . fetch ( constants . LOBSANG_CONTENT_SCHEMA_URL ) } return Promise . reject ( new Error ( 'Topic is not supported' ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a times series that you can report to . [CODESPLIT] function ( options ) { // Validate options assert ( options , \"options are required\" ) ; assert ( options . name , \"Series must be named\" ) ; options = _ . defaults ( { } , options , { columns : { } , additionalColumns : null } ) ; // Store options this . _options = options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "define the action [CODESPLIT] function whenRead ( args ) { let value = getValue ( args ) if ( value && typeof value . then === 'function' ) { value . then ( ( val ) => whenTest ( args , val ) ) . catch ( ( error ) => { console . error ( ` ${ action . displayName } ` , error ) } ) } else { whenTest ( args , value ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is value an * AsyncFunction * [CODESPLIT] function isAsyncFunction ( value ) { if ( ! value ) return false ; const afcText = value . toString ( ) . toLocaleLowerCase ( ) . replace ( / \\n / g , '' ) . replace ( /   / g , '' ) ; return _testConstructor ( 'AsyncFunction' , value ) || ( ( _testConstructor ( 'Function' , value ) && ( afcText . slice ( afcText . indexOf ( '{' ) ) . indexOf ( 'returnnewpromise(function($return,$error)' ) === 1 ) ) ) ; //fast-async monkey-support\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is value iterable ( * object * or * Array * with not zero length ) [CODESPLIT] function isIterable ( value ) { return ( isObject ( value ) ? ! ! Object . keys ( value ) . length : false ) || ( isArray ( value ) ? ! ! value . length : false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is value a JSON and can be decoded as * object * [CODESPLIT] function isJSON ( value ) { if ( ! isString ( value ) ) return false ; try { const obj = JSON . parse ( value ) ; return ! ! obj && typeof obj === 'object' ; } catch ( e ) { } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[[ include : TAnyArray - to - object . md ]] [CODESPLIT] function arrayToObject ( value , toKeys ) { return ( iterate ( value , ( row , idx , iter ) => { if ( toKeys ) { if ( isInteger ( row ) || isString ( row ) ) iter . key ( idx + 1 ) ; return row ; } else { iter . key ( row ) ; return idx + 1 ; } } , { } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[[ include : object - to - TAnyArray . md ]] [CODESPLIT] function objectToArray ( value , toKeys ) { return iterate ( value , ( val , key ) => toKeys ? key : val , [ ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[[ include : set - defaults . md ]] [CODESPLIT] function setDefaults ( obj , name , value ) { if ( isUndefined ( obj [ name ] ) ) { obj [ name ] = value ; } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[[ include : iterate . md ]] [CODESPLIT] function iterate ( value , callback , accumulate , assign ) { let breakFlag = false ; function newIteration ( index ) { let instance = { 'break' : ( ) => breakFlag = true , accKeyName : index , key : ( name ) => instance . accKeyName = name } ; return instance ; } let iterateInstanceAsync = async ( callback , val , index ) => { let iteration = newIteration ( index ) ; pushRet ( await callback ( val , index , iteration ) , iteration ) ; } ; let iterateInstance = ( callback , val , index ) => { let iteration = newIteration ( index ) ; pushRet ( callback ( val , index , iteration ) , iteration ) ; } ; let ret = isObject ( accumulate ) ? accumulate : isArray ( accumulate ) ? accumulate : accumulate === true ? false : value ; let pushRet = ( val , iteration ) => { if ( isUndefined ( val ) ) return ; if ( isObject ( accumulate ) ) { ret [ iteration . accKeyName ] = assign ? Object . assign ( ret [ iteration . accKeyName ] || { } , val ) : val ; } if ( isArray ( accumulate ) ) ret . push ( val ) ; if ( accumulate === true ) ret = ret || val ; } ; return isAsyncFunction ( callback ) ? new Promise ( async ( resolve ) => { if ( isArray ( value ) ) { for ( let index = 0 ; index < value . length ; ++ index ) { if ( breakFlag ) break ; await iterateInstanceAsync ( callback , value [ index ] , index ) ; } resolve ( ret ) ; } if ( isObject ( value ) ) { await iterate ( Object . keys ( value ) , async ( index , _ , iteration ) => { if ( breakFlag ) iteration . break ( ) ; await iterateInstanceAsync ( callback , value [ index ] , index ) ; } ) ; resolve ( ret ) ; } if ( isInteger ( value ) ) { for ( let index = 0 ; index < value ; ++ index ) { if ( breakFlag ) break ; await iterateInstanceAsync ( callback , index , index ) ; } resolve ( ret ) ; } resolve ( false ) ; } ) : ( ( ) => { if ( isArray ( value ) ) { for ( let index = 0 ; index < value . length ; ++ index ) { if ( breakFlag ) break ; iterateInstance ( callback , value [ index ] , index ) ; } return ret ; } if ( isObject ( value ) ) { iterate ( Object . keys ( value ) , ( index , _ , iteration ) => { if ( breakFlag ) iteration . break ( ) ; iterateInstance ( callback , value [ index ] , index ) ; } ) ; return ret ; } if ( isInteger ( value ) ) { for ( let index = 0 ; index < value ; ++ index ) { if ( breakFlag ) break ; iterateInstance ( callback , index , index ) ; } return ret ; } return false ; } ) ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[[ include : iterate - keys . md ]] [CODESPLIT] function iterateKeys ( value , callback , accumulate ) { return isAsyncFunction ( callback ) ? ( async ( ) => await iterate ( value , async ( row , key , iteration ) => await callback ( key , row , iteration ) , accumulate ) ) ( ) : iterate ( value , ( row , key , iteration ) => callback ( key , row , iteration ) , accumulate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[[ include : iterate - parallel . md ]] [CODESPLIT] async function iterateParallel ( value , callback ) { return Promise . all ( iterate ( value , ( val , key , iter ) => ( async ( ) => await callback ( val , key , iter ) ) ( ) , [ ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds and deletes first encounter of value in target [CODESPLIT] function findAndDelete ( target , value ) { if ( ! isIterable ( target ) ) return false ; if ( isArray ( target ) ) { for ( let i = 0 ; i < target . length ; i ++ ) { if ( deep_equal_1 . default ( target [ i ] , value ) ) { target . splice ( i , 1 ) ; return true ; } } } else if ( isObject ( target ) ) { const keys = Object . keys ( target ) ; for ( let i = 0 ; i < keys . length ; i ++ ) { if ( deep_equal_1 . default ( target [ keys [ i ] ] , value ) ) { delete target [ keys [ i ] ] ; return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds and deletes all encounters of value in target [CODESPLIT] function findAndDeleteAll ( target , value ) { let flag = false ; while ( findAndDelete ( target , value ) ) { flag = true ; } return flag ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "AppSrv Logic [CODESPLIT] function SignAgreement ( data ) { var d = { 'a_name' : data . a_name , 'a_dob' : data . a_dob } ; XForm . prototype . XExecutePost ( '../agreement/_sign' , d , function ( rslt ) { if ( '_success' in rslt ) { window . location . href = jsh . _BASEURL + 'agreement/welcome/' ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : remove [CODESPLIT] function start ( instance ) { console . log ( 'start called!' ) ; var chatClient = instance ( ) , // If messages are going to a specific user, store that here. activeBuddylistEntry , buddylist , input ; document . getElementById ( 'msg-input' ) . focus ( ) ; function clearLog ( ) { var log = document . getElementById ( 'messagelist' ) ; log . innerHTML = \"\" ; } function appendLog ( elt ) { var log = document . getElementById ( 'messagelist' ) , br ; //Trim old messages while ( log . childNodes . length > 36 ) { log . removeChild ( log . firstChild ) ; } log . appendChild ( elt ) ; br = document . createElement ( 'br' ) ; log . appendChild ( br ) ; br . scrollIntoView ( ) ; } function makeDisplayString ( buddylistEntry ) { return buddylistEntry . name && buddylistEntry . name !== buddylistEntry . clientId ? buddylistEntry . name + ' (' + buddylistEntry . clientId + ')' : buddylistEntry . clientId ; } function redrawBuddylist ( ) { var onClick = function ( buddylistEntry , child ) { console . log ( \"Messages will be sent to: \" + buddylistEntry . clientId ) ; activeBuddylistEntry = buddylistEntry ; redrawBuddylist ( ) ; document . getElementById ( 'msg-input' ) . focus ( ) ; } , buddylistDiv = document . getElementById ( 'buddylist' ) , clientId , child ; // Remove all elements in there now buddylistDiv . innerHTML = \"<b>Buddylist</b>\" ; // Create a new element for each buddy for ( clientId in buddylist ) { if ( buddylist . hasOwnProperty ( clientId ) ) { child = document . createElement ( 'div' ) ; if ( activeBuddylistEntry === buddylist [ clientId ] ) { child . innerHTML = \"[\" + makeDisplayString ( buddylist [ clientId ] ) + \"]\" ; } else { child . innerHTML = makeDisplayString ( buddylist [ clientId ] ) ; } // If the user clicks on a buddy, change our current destination for messages child . addEventListener ( 'click' , onClick . bind ( this , buddylist [ clientId ] , child ) , true ) ; buddylistDiv . appendChild ( child ) ; } } } // on changes to the buddylist, redraw entire buddylist chatClient . on ( 'recv-buddylist' , function ( val ) { buddylist = val ; theBuddylist = buddylist ; console . log ( 'got buddylist' , buddylist ) ; redrawBuddylist ( ) ; } ) ; // On new messages, append it to our message log chatClient . on ( 'recv-message' , function ( data ) { // Show the name instead of the clientId, if it's available. var clientId = data . from . clientId , displayName = buddylist [ clientId ] . name || clientId , message = displayName + \": \" + data . message ; appendLog ( document . createTextNode ( message ) ) ; } ) ; // On new messages, append it to our message log chatClient . on ( 'recv-err' , function ( data ) { document . getElementById ( 'uid' ) . textContent = \"Error: \" + data . message ; } ) ; // Display our own clientId when we get it chatClient . on ( 'recv-uid' , function ( data ) { document . getElementById ( 'uid' ) . textContent = \"Logged in as: \" + data ; } ) ; // Display the current status of our connection to the Social provider chatClient . on ( 'recv-status' , function ( msg ) { if ( msg && msg === 'online' ) { document . getElementById ( 'msg-input' ) . disabled = false ; } else { document . getElementById ( 'msg-input' ) . disabled = true ; } clearLog ( ) ; var elt = document . createElement ( 'b' ) ; elt . appendChild ( document . createTextNode ( 'Status: ' + msg ) ) ; appendLog ( elt ) ; } ) ; // Listen for the enter key and send messages on return input = document . getElementById ( 'msg-input' ) ; input . onkeydown = function ( evt ) { if ( evt . keyCode === 13 ) { var text = input . value ; input . value = \"\" ; appendLog ( document . createTextNode ( \"You: \" + text ) ) ; chatClient . send ( activeBuddylistEntry . clientId , text ) ; } } ; // Just call boot when login is clicked console . log ( 'connecting login!' ) ; var loginButton = document . getElementById ( 'uid' ) ; console . log ( 'loginButton: ' + loginButton ) ; loginButton . addEventListener ( 'click' , function ( ) { console . log ( 'login clicked' ) ; chatClient . login ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module @lobsangnet / lobsang - connect - matrix / connect Connects to a MatrixClient and resolves once connection was established . [CODESPLIT] function connect ( client ) { client . startClient ( ) return new Promise ( ( resolve , reject ) => { client . once ( 'sync' , ( state ) => { if ( wrapper . isSyncState ( state ) ) { return resolve ( client ) } else { return reject ( new Error ( 'Client could not sync' ) ) } } ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module @lobsangnet / lobsang - processor - hostname Library to process the hostname from an URL . [CODESPLIT] function lobsangProcessorHostname ( link ) { let parts try { parts = parseUrl ( link ) } catch ( error ) { return Promise . reject ( error ) } if ( parts . hostname === '' ) { return Promise . reject ( new Error ( 'Not an URL' ) ) } return Promise . resolve ( parts . hostname ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a frame around strings . [CODESPLIT] function frameOfMind ( string , options = { } ) { const { padding = 1 } = options const l = string . split ( '\\n' ) const w = l . reduce ( ( acc , { length } ) => length > acc ? length : acc , 0 ) const ww = w + padding * 2 const bt = ` '─ '.rep e at(ww) } ┐`    const bb = ` '─ '.rep e at(ww) } ┘`    const pp = ' ' . repeat ( padding ) const p = paddys ( string ) . split ( '\\n' ) . map ( line => ` pp }$ { li ne}$ { pp }│ `   . join ( '\\n' ) return ` ${ bt } \\n ${ p } \\n ${ bb } ` }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module @lobsangnet / lobsang - connect - matrix / sync Helper method to check the state against those indicating some sync state . [CODESPLIT] function isSyncState ( state ) { if ( state === CONSTANTS . MATRIX_STATE_PREPARED ) { return true } if ( state === CONSTANTS . MATRIX_STATE_SYNCING ) { return true } return false }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module @lobsangnet / lobsang - formatter - matrix Library to wrap a message into an object which complies to the given schema . [CODESPLIT] function lobsangFormatterSchema ( message , topic ) { if ( typeof message !== 'string' ) { return Promise . reject ( new Error ( 'Message is not a string' ) ) } return schema ( topic ) . then ( ( schemaObject ) => { const validator = validate ( schemaObject ) const schemaMessage = format ( message ) if ( validator ( schemaMessage ) ) { return Promise . resolve ( schemaMessage ) } return Promise . reject ( validator . errors ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************************************* [CODESPLIT] function _resolve ( path , options , mod ) { if ( path ) { var i = path . indexOf ( ':' ) if ( i === - 1 ) { return resolveModule ( path , options , mod ) } else { var namespace = path . substring ( 0 , i ) var p = path . substring ( i + 1 ) if ( namespace === \"env\" ) { return resolveEnv ( p , options , mod ) } else if ( namespace === \"http\" || namespace === \"https\" ) { return resolveHttp ( path , options , mod ) } else if ( namespace === \"file\" ) { return resolveFile ( p , options , mod ) } else { throw new Error ( \"Unable to resolve path: '\" + path + \"'. Unknown namespace: \" + namespace ) } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************************************* [CODESPLIT] function resolveEnv ( path , options , mod ) { var result = undefined if ( path ) { result = ( process [ PRIVATE_ENV ] && process [ PRIVATE_ENV ] [ path ] ) || process . env [ path ] } return result }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************************************* [CODESPLIT] function resolveModule ( path , options , mod ) { // XXX this is ineffecient. must cache var result = null var filepath = resolveFilename ( path , mod ) try { result = mod . require ( filepath ) } catch ( e ) { var error = undefined if ( e instanceof errors . ResolveModuleSyntaxError ) { error = e } else if ( e instanceof SyntaxError ) { error = new errors . ResolveModuleSyntaxError ( e , filepath ) } else { error = new Error ( \"Error loading module: \" + filepath + \" \" + e . stack ) } throw error } return result }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************************************* [CODESPLIT] function resolveFilename ( path , mod ) { var result = null ; if ( path ) { try { return Module . _resolveFilename ( path , mod ) // TODO: is this what we want? } catch ( e ) { // XXX really slows this down if ( path && path . length > 1 && path [ 0 ] != '/' ) { pathlist = path . split ( '/' ) if ( pathlist . length > 1 ) { if ( pathlist . indexOf ( \"lib\" ) == - 1 ) { pathlist . splice ( 1 , 0 , \"lib\" ) var newpath = pathlist . join ( '/' ) result = Module . _resolveFilename ( newpath , mod ) return result } } } throw ( e ) } } return result }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************************************* [CODESPLIT] function resolveFile ( path , options , mod ) { if ( path ) { var f = Object ( ) Object . defineProperties ( f , { readStream : { enumerable : true , configurable : false , writeable : false , get : function ( ) { return fs . createReadStream ( path ) } } , writeStream : { enumerable : true , configurable : false , writeable : false , get : function ( ) { return fs . createWriteStream ( path , { flags : \"a\" } ) } } , content : { enumerable : true , configurable : false , writeable : false , get : function ( ) { return fs . readFile . sync ( path ) . toString ( ) } } } ) f . toString = function ( ) { return this . content } /* open(flags[, mode][, callback])\n     */ f . open = function ( ) { if ( ! arguments || arguments . length < 1 ) { throw ( Error ( \"flags argument is required\" ) ) } var flags = arguments [ 0 ] var mode = null var cb = null if ( arguments . length > 2 ) { mode = arguments [ 1 ] cb = arguments [ 2 ] } else if ( arguments . length > 1 ) { if ( typeof arguments [ 1 ] === \"number\" ) { mode = arguments [ 1 ] } else { cb = arguments [ 1 ] } } if ( cb ) { fs . open ( path , flags , mode , cb ) } else { return fs . openSync ( path , flags , mode ) } } return f } else { throw ( Error ( \"File not found: \" + path ) ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************************************* [CODESPLIT] function _o ( mod ) { if ( ! ( mod instanceof Module ) ) { throw ( Error ( \"Must supply a module to _o: \" + mod ) ) } return function ( path , options ) { return _resolve ( path , options , mod ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module @lobsangnet / lobsang - formatter - matrix / validate Derives a validator from a schema . [CODESPLIT] function validate ( schema ) { const ajv = new Ajv ( ) try { const validator = ajv . compile ( schema ) return Promise . resolve ( validator ) } catch ( error ) { return Promise . reject ( error ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an Influx Database Connection [CODESPLIT] function ( options ) { assert ( options , \"options are required\" ) ; assert ( options . connectionString , \"options.connectionString is missing\" ) ; assert ( url . parse ( options . connectionString ) . protocol === 'https:' || options . allowHTTP , \"InfluxDB connectionString must use HTTPS!\" ) ; options = _ . defaults ( { } , options , { maxDelay : 60 * 5 , maxPendingPoints : 250 } ) ; this . _options = options ; this . _pendingPoints = { } ; this . _nbPendingPoints = 0 ; this . _flushTimeout = setTimeout ( this . flush . bind ( this , true ) , options . maxDelay * 1000 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a handler timer for AMQP messages received through taskcluster - client . Please note that this relies on that messages format . [CODESPLIT] function ( handler , options ) { assert ( handler instanceof Function , \"A handler must be provided\" ) ; assert ( options , \"options required\" ) ; assert ( options . drain , \"options.drain is required\" ) ; assert ( options . component , \"options.component is required\" ) ; // Create a reporter var reporter = series . HandlerReports . reporter ( options . drain ) ; // Wrap handler and let that be it return function ( message ) { // Create most of the point var point = { component : options . component , duration : undefined , exchange : message . exchange || '' , redelivered : ( message . redelivered ? 'true' : 'false' ) , error : 'false' } ; // Start timer var start = process . hrtime ( ) ; // Handle the message return Promise . resolve ( handler ( message ) ) . then ( function ( ) { // Get duration var d = process . hrtime ( start ) ; // Convert to milliseconds point . duration = d [ 0 ] * 1000 + ( d [ 1 ] / 1000000 ) ; // Send point to reporter reporter ( point ) ; } , function ( err ) { // Get duration var d = process . hrtime ( start ) ; // Convert to milliseconds point . duration = d [ 0 ] * 1000 + ( d [ 1 ] / 1000000 ) ; // Flag and error point . error = 'true' ; // Send point to reporter reporter ( point ) ; // Re-throw the error throw err ; } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Monitor CPU and memory for this instance . [CODESPLIT] function ( options ) { // Validate options assert ( options , \"Options are required\" ) ; assert ( options . drain , \"A drain for the measurements must be provided!\" ) ; assert ( options . component , \"A component must be specified\" ) ; assert ( options . process , \"A process name must be specified\" ) ; // Provide default options options = _ . defaults ( { } , options , { interval : 60 } ) ; // Clear reporting if already started if ( _processUsageReportingInterval ) { debug ( \"WARNING: startProcessUsageReporting() already started!\" ) ; clearInterval ( _processUsageReportingInterval ) ; _processUsageReportingInterval = null ; } // Lazy load the usage monitor module var usage = require ( 'usage' ) ; // Create reporter var reporter = series . UsageReports . reporter ( options . drain ) ; // Set interval to report usage at interval _processUsageReportingInterval = setInterval ( function ( ) { // Lookup usage for the current process usage . lookup ( process . pid , { keepHistory : true } , function ( err , result ) { // Check for error if ( err ) { debug ( \"Failed to get usage statistics, err: %s, %j\" , err , err , err . stack ) ; return ; } // Report usage reporter ( { component : options . component , process : options . process , cpu : result . cpu , memory : result . memory } ) ; } ) ; } , options . interval * 1000 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a stats handler for taskcluster - client clients which takes an option stats as function that will be call after an API call . [CODESPLIT] function ( options ) { options = _ . defaults ( { } , options || { } , { tags : { } , drain : undefined } ) ; assert ( options . drain , \"options.drain is required\" ) ; assert ( typeof options . tags === 'object' , \"options.tags is required\" ) ; assert ( _ . intersection ( _ . keys ( options . tags ) , series . APIClientCalls . columns ( ) ) . length === 0 , \"Can't used reserved tag names!\" ) ; // Create a reporter return series . APIClientCalls . reporter ( options . drain , options . tags ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module @lobsangnet / lobsang - connect - matrix / check Checks the message on type etc . [CODESPLIT] function check ( message ) { if ( ! message ) { return Promise . reject ( new Error ( 'Argument must not be falsy!' ) ) } if ( typeof message !== 'string' ) { return Promise . reject ( new Error ( 'Argument must be a string!' ) ) } return Promise . resolve ( message ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate help [CODESPLIT] function generateHelp ( params ) { var output = '' ; if ( params . usage ) { var usage = result ( params , 'usage' ) ; output += EOL ; output += format ( 'Usage: %s' , usage ) ; output += EOL ; } if ( params . desc ) { var desc = result ( params , 'desc' ) ; output += EOL ; output += desc ; output += EOL ; } if ( is . object ( params . options ) && objectLength ( params . options ) > 0 ) { var options = buildOptions ( params . options ) ; output += EOL ; output += 'Options:' ; output += EOL ; output += EOL ; output += indent ( options , ' ' , 2 ) ; output += EOL ; } if ( is . array ( params . commands ) && params . commands . length > 0 ) { var commands = buildCommands ( params . commands ) ; output += EOL ; output += 'Commands:' ; output += EOL ; output += EOL ; output += indent ( commands , ' ' , 2 ) ; output += EOL ; } output += EOL ; return indent ( output , ' ' , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helpers Output option list [CODESPLIT] function buildOptions ( options ) { var result = [ ] ; var keys = Object . keys ( options ) ; keys . forEach ( function ( key ) { var props = options [ key ] ; // convert short to long form if ( is . string ( props ) ) { props = { type : props } ; } // all names of an option // aliases come first // full name comes last var name = [ format ( '--%s' , dasherize ( key ) ) ] ; // accept both string and array var aliases = props . alias || props . aliases || [ ] ; if ( is . not . array ( aliases ) ) { aliases = [ aliases ] ; } // aliases are prefixed with \"-\" aliases . forEach ( function ( alias ) { alias = format ( '-%s' , alias ) ; name . unshift ( alias ) ; } ) ; result . push ( [ name . join ( ', ' ) , props . desc || '' ] ) ; } ) ; return table ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Output command list [CODESPLIT] function buildCommands ( commands ) { var result = [ ] ; commands . forEach ( function ( command ) { result . push ( [ command . name , command . desc || '' ] ) ; } ) ; return table ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "========================================================================== DEFAULT NOTIFICATIONS ========================================================================== [CODESPLIT] function initGrowlStatus ( ) { grunt . util . hooker . hook ( grunt . log , 'write' , function ( msg ) { if ( grunt . log . uncolor ( msg ) . match ( / Waiting... / ) ) { flushMessages ( 'ok' ) ; } } ) ; grunt . util . hooker . hook ( grunt . log , 'header' , function ( msg ) { msg = grunt . log . uncolor ( msg ) ; if ( ignoreWatch && msg . match ( / \"watch\" task / ) ) { return ; } if ( msg . match ( / \".+:.+\" / ) ) { return ; } if ( ! ignoreWatch && msg . match ( / \"watch\" task / ) ) { msg += ' for ' + path . basename ( process . cwd ( ) ) ; ignoreWatch = true ; } messages . push ( msg ) ; } ) ; grunt . util . hooker . hook ( grunt . log , 'ok' , function ( msg ) { if ( typeof msg === 'string' ) { messages . push ( grunt . log . uncolor ( msg ) ) ; } } ) ; grunt . util . hooker . hook ( grunt , 'warn' , function ( error ) { var warning = [ ] ; if ( typeof error !== 'undefined' ) { warning . push ( messages [ 0 ] ) ; warning . push ( messages [ messages . length - 1 ] ) ; warning . push ( String ( error . message || error ) ) ; messages = warning ; flushMessages ( 'error' ) ; } } ) ; grunt . util . hooker . hook ( grunt . log , 'error' , function ( msg ) { if ( typeof msg === 'string' ) { messages . push ( grunt . log . uncolor ( msg ) ) ; flushMessages ( 'error' ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module @lobsangnet / lobsang - formatter - matrix Library to wrap a message into an object which can be sent to matrix . [CODESPLIT] function lobsangFormatterMatrix ( message ) { if ( typeof message !== 'string' ) { return Promise . reject ( new Error ( 'Message is not a string' ) ) } const formattedMessage = { body : message , msgtype : CONSTANTS . MATRIX_NOTICE_TYPE } return Promise . resolve ( formattedMessage ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Module main constructor [CODESPLIT] function Router ( options ) { const logPrefix = topLogPrefix + 'Router() - ' ; const that = this ; let defaultRouteFound = false ; that . options = options || { } ; if ( ! that . options . paths ) { that . options . paths = { 'controller' : { 'path' : 'controllers' , 'exts' : 'js' } , 'static' : { 'path' : 'public' , 'exts' : false } , 'template' : { 'path' : 'public/templates' , 'exts' : [ 'tmpl' , 'tmp' , 'ejs' , 'pug' ] } } ; } if ( ! that . options . routes ) that . options . routes = [ ] ; if ( ! that . options . basePath ) that . options . basePath = process . cwd ( ) ; if ( ! that . options . log ) { const lUtils = new LUtils ( ) ; that . options . log = new lUtils . Log ( ) ; } for ( const key of Object . keys ( that . options . paths ) ) { if ( ! Array . isArray ( that . options . paths [ key ] . exts ) && that . options . paths [ key ] . exts !== false ) { that . options . paths [ key ] . exts = [ that . options . paths [ key ] . exts ] ; } } if ( ! that . options . lfs ) { that . options . lfs = new Lfs ( { 'basePath' : that . options . basePath , 'log' : that . options . log } ) ; } for ( let i = 0 ; that . options . routes [ i ] !== undefined ; i ++ ) { if ( that . options . routes [ i ] . regex === '^/$' ) { defaultRouteFound = true ; break ; } } // We should always have a default route, so if none exists, create one if ( defaultRouteFound === false ) { that . options . routes . push ( { 'regex' : '^/$' , 'controllerPath' : 'default.js' , 'templatePath' : 'default.tmpl' } ) ; } for ( const key of Object . keys ( that . options ) ) { that [ key ] = that . options [ key ] ; } that . log . debug ( logPrefix + 'Instantiated with options: ' + JSON . stringify ( that . options ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "jsdom window document navigator setup http : // airbnb . io / enzyme / docs / guides / jsdom . html [CODESPLIT] function copyProps ( src , target ) { const props = Object . getOwnPropertyNames ( src ) . filter ( prop => typeof target [ prop ] === 'undefined' ) . reduce ( ( result , prop ) => R . merge ( result , { [ prop ] : Object . getOwnPropertyDescriptor ( src , prop ) } ) , { } ) ; Object . defineProperties ( target , props ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module @lobsangnet / lobsang - processor - port Library to process the port from an URL . [CODESPLIT] function lobsangProcessorPort ( link ) { let parts try { parts = parseUrl ( link ) } catch ( error ) { return Promise . reject ( error ) } if ( parts . port === '' ) { return getDefaultPortByProtocol ( parts . protocol ) } // For some reasons, the Promise resolves always to a String (not Number). return Promise . resolve ( String ( parts . port ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to look up port by protocol . [CODESPLIT] function getDefaultPortByProtocol ( rawProtocol ) { // port-numbers expect no trailing colon const protocol = rawProtocol . endsWith ( ':' ) ? rawProtocol . slice ( 0 , - 1 ) : rawProtocol // e.g. mailto has no port associated // example return value: // { port: 80, protocol: 'tcp', description: 'World Wide Web HTTP' } const portByProtocol = portNumbers . getPort ( protocol ) return portByProtocol ? Promise . resolve ( String ( portByProtocol . port ) ) : Promise . reject ( new Error ( 'Has no port' ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace scripts with ... and prune empty scripts [CODESPLIT] function clearScripts ( node ) { var rslt = { } ; for ( var key in node ) { var val = node [ key ] ; if ( _ . isString ( val ) ) { if ( val . trim ( ) ) rslt [ key ] = \"...\" ; } else { var childScripts = clearScripts ( val ) ; if ( ! _ . isEmpty ( childScripts ) ) rslt [ key ] = childScripts ; } } return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "holds functions and error handlers [CODESPLIT] function ( obj , array ) { if ( ! Array . prototype . indexOf ) { for ( var i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] === obj ) { return i ; } } return - 1 ; } else { return array . indexOf ( obj ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module @lobsangnet / lobsang - formatter - matrix / schema Library to format a message into a schemaMessage [CODESPLIT] function format ( message , topic ) { const now = new Date ( ) const license = constants . LOBSANG_DEFAULT_LICENSE const id = 'toBeAdapted' const issuer = 'toBeAdapted' return { content : message , topic , license , contentType : null , created : now . toISOString ( ) , derivedFrom : null , id , issuer } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * jslint moz : true [CODESPLIT] function setupListeners ( chat , displayWorker ) { chat . on ( displayWorker . port . emit . bind ( displayWorker . port ) ) ; displayWorker . port . on ( 'login' , function ( ) { chat . login ( ) ; } ) ; displayWorker . port . on ( 'logout' , function ( ) { chat . logout ( ) ; } ) ; displayWorker . port . on ( 'send' , function ( data ) { chat . send ( data . to , data . msg ) ; } ) ; displayWorker . port . on ( 'test' , function ( data ) { console . log ( 'Test message: ' + data ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Functional map with sugar . [CODESPLIT] function factory ( fn , options ) { var settings = options || { } var key = settings . key var indices = settings . indices var gapless = settings . gapless if ( typeof settings === 'string' ) { key = settings } if ( indices == null ) { indices = true } return all function all ( values ) { var results = [ ] var parent = values var index = - 1 var length var result if ( key ) { if ( array ( values ) ) { parent = null } else { values = parent [ key ] } } length = values . length while ( ++ index < length ) { if ( indices ) { result = fn . call ( this , values [ index ] , index , parent ) } else { result = fn . call ( this , values [ index ] , parent ) } if ( ! gapless || result != null ) { results . push ( result ) } } return results } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the element values of a given node list . [CODESPLIT] function getElementValues ( nodeList , initialScope ) { const valueList = [ ] for ( let i = 0 ; i < nodeList . length ; ++ i ) { const elementNode = nodeList [ i ] if ( elementNode == null ) { valueList . length = i + 1 } else if ( elementNode . type === \"SpreadElement\" ) { const argument = getStaticValueR ( elementNode . argument , initialScope ) if ( argument == null ) { return null } valueList . push ( ... argument . value ) } else { const element = getStaticValueR ( elementNode , initialScope ) if ( element == null ) { return null } valueList . push ( element . value ) } } return valueList }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value of a given node if it s a static value . [CODESPLIT] function getStaticValueR ( node , initialScope ) { if ( node != null && Object . hasOwnProperty . call ( operations , node . type ) ) { return operations [ node . type ] ( node , initialScope ) } return null }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether a given variable is modified or not . [CODESPLIT] function isModifiedGlobal ( variable ) { return ( variable == null || variable . defs . length !== 0 || variable . references . some ( r => r . isWrite ( ) ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define the output configuration . [CODESPLIT] function config ( ext ) { return { input : \"src/index.js\" , output : { file : ` ${ ext } ` , format : ext === \".mjs\" ? \"es\" : \"cjs\" , sourcemap : true , sourcemapFile : ` ${ ext } ` , strict : true , banner : ` ` , } , plugins : [ sourcemaps ( ) ] , external : Object . keys ( require ( \"./package.json\" ) . dependencies ) , } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether a given character is escaped or not . [CODESPLIT] function isEscaped ( str , index ) { let escaped = false for ( let i = index - 1 ; i >= 0 && str . charCodeAt ( i ) === 0x5c ; -- i ) { escaped = ! escaped } return escaped }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace a given string by a given matcher . [CODESPLIT] function replaceS ( matcher , str , replacement ) { const chunks = [ ] let index = 0 /** @type {RegExpExecArray} */ let match = null /**\n     * @param {string} key The placeholder.\n     * @returns {string} The replaced string.\n     */ function replacer ( key ) { switch ( key ) { case \"$$\" : return \"$\" case \"$&\" : return match [ 0 ] case \"$`\" : return str . slice ( 0 , match . index ) case \"$'\" : return str . slice ( match . index + match [ 0 ] . length ) default : { const i = key . slice ( 1 ) if ( i in match ) { return match [ i ] } return key } } } for ( match of matcher . execAll ( str ) ) { chunks . push ( str . slice ( index , match . index ) ) chunks . push ( replacement . replace ( placeholder , replacer ) ) index = match . index + match [ 0 ] . length } chunks . push ( str . slice ( index ) ) return chunks . join ( \"\" ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eslint - disable - next - line valid - jsdoc Replace a given string by a given matcher . [CODESPLIT] function replaceF ( matcher , str , replace ) { const chunks = [ ] let index = 0 for ( const match of matcher . execAll ( str ) ) { chunks . push ( str . slice ( index , match . index ) ) chunks . push ( String ( replace ( ... match , match . index , match . input ) ) ) index = match . index + match [ 0 ] . length } chunks . push ( str . slice ( index ) ) return chunks . join ( \"\" ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the left parenthesis of the parent node syntax if it exists . E . g . if ( a ) {} then the ( . [CODESPLIT] function getParentSyntaxParen ( node , sourceCode ) { const parent = node . parent switch ( parent . type ) { case \"CallExpression\" : case \"NewExpression\" : if ( parent . arguments . length === 1 && parent . arguments [ 0 ] === node ) { return sourceCode . getTokenAfter ( parent . callee , isOpeningParenToken ) } return null case \"DoWhileStatement\" : if ( parent . test === node ) { return sourceCode . getTokenAfter ( parent . body , isOpeningParenToken ) } return null case \"IfStatement\" : case \"WhileStatement\" : if ( parent . test === node ) { return sourceCode . getFirstToken ( parent , 1 ) } return null case \"SwitchStatement\" : if ( parent . discriminant === node ) { return sourceCode . getFirstToken ( parent , 1 ) } return null case \"WithStatement\" : if ( parent . object === node ) { return sourceCode . getFirstToken ( parent , 1 ) } return null default : return null } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // dev . twitch . tv / docs / v5 / guides / PubSub / [CODESPLIT] function psOpen ( ) { _event ( 'dev' , 'pubsub - connected successfully' ) ; let frame = { type : 'LISTEN' , nonce : 'listenToTopics' , data : { topics : [ 'channel-bits-events-v1.' + state . channel_id , // 'channel-subscribe-events-v1.' + state.channel_id, 'chat_moderator_actions.' + state . id + '.' + state . channel_id , 'whispers.' + state . id , ] , auth_token : state . oauth , } , } ; send ( JSON . stringify ( frame ) ) ; ping ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this provides some preventative error handling because the pubsub edge seems to be unstable [CODESPLIT] function send ( msg ) { switch ( ps . readyState ) { case 0 : // CONNECTING setTimeout ( function ( ) { send ( msg ) ; } , 1000 ) ; break ; case 2 : // CLOSING case 3 : // CLOSED _event ( 'dev' , 'pubsub - reconnect: send() - closing/closed state' ) ; connect ( ) ; setTimeout ( function ( ) { send ( msg ) ; } , 2000 ) ; break ; case 1 : // OPEN try { ps . send ( msg ) ; } catch ( err ) { console . error ( err ) ; setTimeout ( function ( ) { send ( msg ) ; } , 1500 ) ; } break ; default : break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "data is message . data so it should have msg . topic and msg . message [CODESPLIT] function parseMessage ( data ) { switch ( data . topic ) { // https://dev.twitch.tv/docs/v5/guides/PubSub/ case 'channel-bits-events-v1.' + state . channel_id : bits ( ) ; break ; // https://discuss.dev.twitch.tv/t/in-line-broadcaster-chat-mod-logs/7281/12 case 'chat_moderator_actions.' + state . id + '.' + state . id : moderation ( ) ; break ; case 'whispers.' + state . id : whisper ( ) ; break ; // case 'channel-subscribe-events-v1.' + state.channel_id: //   sub(); //   break; default : break ; } function bits ( ) { let bits = JSON . parse ( data . message ) ; _event ( 'bits' , bits ) ; } function moderation ( ) { let moderation = JSON . parse ( data . message ) . data ; _event ( 'moderation' , moderation ) ; } function whisper ( ) { let message = JSON . parse ( data . message ) . data_object ; // TODO: figure out why some whispers are dropped... // _event('whisper', message); } // function sub() { //   // TODO: https://discuss.dev.twitch.tv/t/subscriptions-beta-changes/10023 // } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JWT - Class representing a JSON Web Token it s payload and it s status [CODESPLIT] function JWT ( secret , options ) { this . token = '' ; this . payload = { } ; this . secret = secret ; this . options = options ; this . valid = false ; this . expired = false ; this . stale = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sign - generate a new token from the payload [CODESPLIT] function ( payload ) { payload . stales = Date . now ( ) + this . options . stales ; this . payload = payload ; this . token = utils . sign ( this . payload , this . secret , this . options . signOptions ) ; this . valid = true ; this . expired = false ; this . stale = false ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "store - stores the JWT in the cookie [CODESPLIT] function ( res ) { if ( this . options . cookies ) { res . cookie ( this . options . cookie , this . token , this . options . cookieOptions ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "toJSON - this function is called when the jwt is passed through JSON . stringify we don t want the secret or options to be stringified [CODESPLIT] function ( ) { return { token : this . token , payload : this . payload , valid : this . valid , expired : this . expired , stale : this . stale } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "verify - verifies the JWT s token [CODESPLIT] function ( token ) { this . token = token || '' ; try { this . payload = utils . verify ( this . token , this . secret , this . options . verifyOptions ) ; this . valid = true ; } catch ( err ) { this . payload = utils . decode ( this . token ) || { } ; if ( err . name == 'TokenExpiredError' ) { this . expired = true ; } } if ( this . valid && ! this . options . verify ( this ) ) { this . valid = false ; } if ( this . payload . stales && Date . now ( ) <= this . payload . stales ) { this . stale = false ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * create - creates a JWT without storing it [CODESPLIT] function ( secret , payload ) { if ( ! secret ) { throw new ReferenceError ( 'secret must be defined' ) ; } if ( typeof secret == 'string' ) { var _secret = secret ; secret = function ( payload ) { return _secret } ; } var jwt = new JWT ( secret ( payload ) , this . options ) ; return jwt . sign ( payload ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "init - initialize jwt - express [CODESPLIT] function ( secret , options ) { if ( ! secret ) { throw new ReferenceError ( 'secret must be defined' ) ; } if ( typeof secret == 'string' ) { var _secret = secret ; secret = function ( req ) { return _secret } ; } options = options || { } ; var defaults = { cookie : 'jwt-express' , cookieOptions : { httpOnly : true } , cookies : true , refresh : true , reqProperty : 'jwt' , revoke : function ( jwt ) { } , signOptions : { } , stales : 900000 , verify : function ( jwt ) { return true } , verifyOptions : { } } ; for ( var key in defaults ) { this . options [ key ] = options [ key ] !== undefined ? options [ key ] : defaults [ key ] ; } return function ( req , res , next ) { var token ; if ( this . options . cookies ) { token = req . cookies [ this . options . cookie ] ; } else if ( req . headers . authorization ) { // Authorization: Bearer abc.abc.abc token = req . headers . authorization . split ( ' ' ) [ 1 ] ; } var jwt = new JWT ( secret ( req ) , this . options ) ; req [ this . options . reqProperty ] = jwt . verify ( token ) ; if ( jwt . valid && ! jwt . stale && jwt . options . refresh ) { jwt . resign ( ) . store ( res ) ; } /**\n             * jwt - Creates and signs a new JWT. If cookies are in use, it stores\n             *     the JWT in the cookie as well.\n             * @param object payload The payload of the JWT\n             * @return JWT\n             */ res . jwt = function ( payload ) { var jwt = new JWT ( secret ( req ) , this . options ) ; return jwt . sign ( payload ) . store ( res ) ; } . bind ( this ) ; this . clear = function ( ) { if ( this . options . cookies ) { res . clearCookie ( this . options . cookie ) ; } } . bind ( this ) ; next ( ) ; } . bind ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "require - requires that data in the JWT s payload meets certain requirements If only the key is passed it simply checks that payload [ key ] == true [CODESPLIT] function ( key , operator , value ) { if ( ! key ) { throw new ReferenceError ( 'key must be defined' ) ; } if ( operator && [ '==' , '===' , '!=' , '!==' , '<' , '<=' , '>' , '>=' ] . indexOf ( operator ) === - 1 ) { throw new JWTExpressError ( 'Invalid operator: ' + operator ) ; } return function ( req , res , next ) { var jwt = req [ this . options . reqProperty ] || { payload : { } } , data = jwt . payload [ key ] , ok ; if ( ! operator ) { ok = ! ! data ; } else if ( operator == '==' ) { ok = data == value ; } else if ( operator == '===' ) { ok = data === value ; } else if ( operator == '!=' ) { ok = data != value ; } else if ( operator == '!==' ) { ok = data !== value ; } else if ( operator == '<' ) { ok = data < value ; } else if ( operator == '<=' ) { ok = data <= value ; } else if ( operator == '>' ) { ok = data > value ; } else if ( operator == '>=' ) { ok = data >= value ; } if ( ! ok ) { var err = new JWTExpressError ( 'JWT is insufficient' ) ; err . key = key ; err . data = data ; err . operator = operator ; err . value = value ; next ( err ) ; } else { next ( ) ; } } . bind ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "valid - requires that a JWT is valid [CODESPLIT] function ( ) { return function ( req , res , next ) { var jwt = req [ this . options . reqProperty ] || { } ; if ( ! jwt . valid ) { next ( new JWTExpressError ( 'JWT is invalid' ) ) ; } else { next ( ) ; } } . bind ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setupComponent - Assumes it has been called in the context of a jasmine spec . - Creates a new HTML element and attaches to it an instance of this . Component - If a fixture is provided the fixture will serve as the component root . [CODESPLIT] function setupComponent ( fixture , options ) { // tear down any existing component instance if ( this . component ) { this . component . teardown ( ) ; this . $node . remove ( ) ; } if ( fixture instanceof jQuery || typeof fixture === 'string' ) { // use the fixture to create component root node this . $node = $ ( fixture ) . addClass ( 'component-root' ) ; } else { // create an empty component root node this . $node = $ ( '<div class=\"component-root\" />' ) ; options = fixture ; fixture = null ; } // append component root node to body $ ( 'body' ) . append ( this . $node ) ; // normalize options options = options === undefined ? { } : options ; // instantiate component on component root node this . component = ( new this . Component ( ) ) . initialize ( this . $node , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "describeComponentFactory loads the specified amd component / mixin before executing specDefinitions provides this . setupComponent Component instances created with this . setupComponent are torn down after each spec [CODESPLIT] function describeComponentFactory ( componentPath , specDefinitions , isMixin ) { return function ( ) { beforeEach ( function ( done ) { // reset member variables this . Component = this . component = this . $node = null ; // bind setupComponent to the current context this . setupComponent = setupComponent . bind ( this ) ; var requireCallback = function ( registry , defineComponent , Component ) { // reset the registry registry . reset ( ) ; if ( isMixin ) { // mix the mixin in to an anonymous, component this . Component = defineComponent ( function ( ) { } , Component ) ; } else { this . Component = Component ; } // let Jasmine know we're good to continue with the tests done ( ) ; } . bind ( this ) ; require ( [ 'flight/lib/registry' , 'flight/lib/component' , componentPath ] , requireCallback ) ; } ) ; afterEach ( function ( done ) { // remove the component root node if ( this . $node ) { this . $node . remove ( ) ; this . $node = null ; } var requireCallback = function ( defineComponent ) { // reset local member variables this . component = null ; this . Component = null ; // teardown all flight components defineComponent . teardownAll ( ) ; done ( ) ; } . bind ( this ) ; require ( [ 'flight/lib/component' ] , requireCallback ) ; } ) ; specDefinitions . apply ( this ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load amd module before executing specDefinitions [CODESPLIT] function describeModuleFactory ( modulePath , specDefinitions ) { return function ( ) { beforeEach ( function ( done ) { this . module = null ; var requireCallback = function ( module ) { this . module = module ; done ( ) ; } . bind ( this ) ; require ( [ modulePath ] , requireCallback ) ; } ) ; specDefinitions . apply ( this ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "apply a function to all values should only be used for side effects ( fn ) - > prom [CODESPLIT] function each ( fn ) { assert . equal ( typeof fn , 'function' ) return function ( arr ) { arr = Array . isArray ( arr ) ? arr : [ arr ] return arr . reduce ( function ( prev , curr , i ) { return prev . then ( function ( ) { return fn ( curr , i , arr . length ) } ) } , Promise . resolve ( ) ) . then ( function ( ) { return arr } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Middleware constructor function [CODESPLIT] function consul ( options , resilient ) { defineResilientOptions ( params , options ) return { // Incoming traffic middleware 'in' : function inHandler ( err , res , next ) { if ( err ) return next ( ) // resilient.js sometimes calls the middleware function more than once, with the output // of the previous invokation; checking here the type of the items in the response to // only call `mapServers` with service objects, not URLs (strings) if ( Array . isArray ( res . data ) && Object ( res . data [ 0 ] ) === res . data [ 0 ] ) { res . data = mapServers ( res . data ) } next ( ) } , // Outgoing traffic middleware 'out' : function outHandler ( options , next ) { options . params = options . params || { } if ( params . datacenter ) { options . params . dc = params . datacenter } if ( params . onlyHealthy ) { options . params . passing = true } if ( params . tag ) { options . params . tag = params . tag } next ( ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Incoming traffic middleware [CODESPLIT] function inHandler ( err , res , next ) { if ( err ) return next ( ) // resilient.js sometimes calls the middleware function more than once, with the output // of the previous invokation; checking here the type of the items in the response to // only call `mapServers` with service objects, not URLs (strings) if ( Array . isArray ( res . data ) && Object ( res . data [ 0 ] ) === res . data [ 0 ] ) { res . data = mapServers ( res . data ) } next ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Outgoing traffic middleware [CODESPLIT] function outHandler ( options , next ) { options . params = options . params || { } if ( params . datacenter ) { options . params . dc = params . datacenter } if ( params . onlyHealthy ) { options . params . passing = true } if ( params . tag ) { options . params . tag = params . tag } next ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "API [CODESPLIT] function parsePrice ( input ) { var str = String ( input ) var decimalPart = '00' var decimalSymbol = getDecimalSymbol ( str ) if ( decimalSymbol ) { decimalPart = str . split ( decimalSymbol ) [ 1 ] } var integerPart = str . split ( decimalSymbol ) [ 0 ] return Number ( filterNumbers ( integerPart ) + '.' + filterNumbers ( decimalPart ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Notice : It s a Scrollable best practice to use plain functions instead of React bound methods . Read more about why on the minimal example . [CODESPLIT] function handler ( x , y , self , items , scroller ) { var transitionPixels = 100 ; var ratio = 6 ; var headerPos = Math . max ( transitionPixels - y , 0 ) / ratio ; if ( y < 0 ) { headerPos = transitionPixels / ratio ; } switch ( self . props . name ) { case \"content\" : return { zIndex : 3 , y : - y + items . background . rect . height , } ; case \"white\" : return { // this rounding to 0.001 and 0.9999 should not be needed. // some browsers were causing re-paint. So I will leave this here // as documentation opacity : Math . max ( 0.001 , Math . min ( 1 / transitionPixels * y , 0.9999 ) ) , zIndex : 5 , y : headerPos , } ; case \"transparent\" : return { zIndex : 4 , y : headerPos , } ; case \"background\" : return { scale : Math . max ( 1 , 1 - ( y / 400 ) ) , zIndex : 2 , y : Math . min ( 0 , - y ) , } ; default : // during development, if I create a new <ScrollItem> this is handy // as it will sticky this element to the bottom of the <Scroller> return { zIndex : 10 , y : scroller . rect . height - self . rect . height , } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Notice : It s a Scrollable best practice to use plain functions instead of React bound methods . Read more about why on the minimal example . [CODESPLIT] function consumptionBars ( x , y , self , items , scroller ) { // All calculations are made for top handler, then inverted in the end // if this call refers to the bottom handler // If we are in the middle of the content and scrolled past the swipe origin // keeps reseting origin until user scrolls down. Effectively this means the // first time user scrolls down starts hiding the bars again. if ( y > 0 && y < scroller . origin && scroller . consuming ) { scroller . origin = y ; } // if we are near the top, force topBar to show if ( y <= self . rect . height && ! scroller . consuming ) { scroller . consuming = true ; scroller . origin = 0 ; } var pos ; if ( scroller . consuming ) { pos = Math . min ( scroller . origin - y , 0 ) ; } else { pos = - self . rect . height ; // offscreen } // As the top bar moves offscreen, it should be locked offscreen if ( pos <= - self . rect . height ) { scroller . consuming = false ; } // If this was called from botbar, make it work from bottom of the viewport. if ( self === items . botbar ) { pos = scroller . rect . height - self . rect . height - pos ; } return { y : pos , zIndex : 5 , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "constructor [CODESPLIT] function Pipe2Pam ( ) { if ( ! ( this instanceof Pipe2Pam ) ) { return new Pipe2Pam ( ) ; } //set readableObjectMode to true so that we can push objects out //set writableObjectMode to false since we only support receiving buffer Transform . call ( this , { writableObjectMode : false , readableObjectMode : true } ) ; //parsing first chunk should be looking for image header info this . _parseChunk = this . _findHeaders ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * cleanupStyles ------------- Used for removing all prefixed versions added by server - side rendering . There is a lot of edge - cases in browsers with vendor prefixes so the only strategy that works consistently is let React render all prefixed styles at all times then having this cleanup phase that removes all styles then adds back the styles that we should keep . [CODESPLIT] function cleanupStyles ( item ) { var prop ; var reactProps ; if ( item . props . style ) { reactProps = { } ; for ( prop in item . props . style ) { reactProps [ prop ] = item . _node . style [ prop ] ; } } item . _node . removeAttribute ( 'style' ) ; if ( reactProps ) { for ( prop in reactProps ) { item . _node . style [ prop ] = reactProps [ prop ] ; } } if ( item . _prevStyles ) { for ( prop in item . _prevStyles ) { item . _node . style [ prop ] = item . _prevStyles [ prop ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a list of image search results from Google @param ( String ) searchTerm @param ( Function ) callback ( function to call once results are processed ) @param ( Number ) - optional - start ( starting from what result ) @param ( Number ) - optional - num ( how many results to return 1 - 10 ) [CODESPLIT] function getImageSearchResults ( searchTerm , callback , start , num ) { start = start < 0 || start > 90 || typeof ( start ) === 'undefined' ? 0 : start ; num = num < 1 || num > 10 || typeof ( num ) === 'undefined' ? 10 : num ; if ( ! searchTerm ) { console . error ( 'No search term' ) ; } var parameters = '&q=' + encodeURIComponent ( searchTerm ) ; parameters += '&searchType=image' ; parameters += start ? '&start=' + start : '' ; parameters += '&num=' + num ; var options = { host : 'www.googleapis.com' , path : '/customsearch/v1?key=' + process . env . CSE_API_KEY + '&cx=' + process . env . CSE_ID + parameters } ; var result = '' ; https . get ( options , function ( response ) { response . setEncoding ( 'utf8' ) ; response . on ( 'data' , function ( data ) { result += data ; } ) ; response . on ( 'end' , function ( ) { var data = JSON . parse ( result ) ; var resultsArray = [ ] ; // check for usage limits (contributed by @ryanmete) // This handles the exception thrown when a user's Google CSE quota has been exceeded for the day. // Google CSE returns a JSON object with a field called \"error\" if quota is exceed. if ( data . error && data . error . errors ) { resultsArray . push ( data . error . errors [ 0 ] ) ; // returns the JSON formatted error message in the callback callback ( resultsArray ) ; } else if ( data . items ) { // search returned results data . items . forEach ( function ( item ) { resultsArray . push ( item ) ; } ) ; callback ( resultsArray ) ; } else { callback ( [ ] ) ; } } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When listing all categories and user taps on a given category [CODESPLIT] function ( categoryId , event ) { event . preventDefault ( ) ; this . refs . scroller . prepareAnimationSync ( ) ; this . setState ( { mode : 'single' , selected : categoryId , previousScrollPosition : this . refs . scroller . scrollTop , } , function ( ) { this . refs . scroller . animateAndResetScroll ( 0 , 0 ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When showing a single category and user taps the stack [CODESPLIT] function ( event ) { event . preventDefault ( ) ; this . setState ( { mode : 'all' , selected : null , } , function ( ) { this . refs . scroller . animateAndResetScroll ( 0 , this . state . previousScrollPosition ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ms [CODESPLIT] function handlePositionWhenShowingAllCategories ( x , y , self , items , scroller ) { var order = Data . categoryIds . indexOf ( self . props . categoryId ) ; var multiplier = Math . max ( 1 , 1 - ( y / friction ) ) ; // stretch effect var pos = Math . max ( 0 , order * multiplier * itemSizeDuringListMode - y ) ; return { height : scroller . rect . height - spaceAtBottom + 'px' , zIndex : 2 + order , y : pos , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Service represents a set of grouped values necessary to provide a logical function . For instance a Door Lock Mechanism service might contain two values one for the desired lock state and one for the current lock state . A particular Service is distinguished from others by its type which is a UUID . HomeKit provides a set of known Service UUIDs defined in HomeKitTypes . js along with a corresponding concrete subclass that you can instantiate directly to setup the necessary values . These natively - supported Services are expected to contain a particular set of Characteristics . [CODESPLIT] function Service ( displayName , UUID , subtype ) { if ( ! UUID ) throw new Error ( \"Services must be created with a valid UUID.\" ) ; this . displayName = displayName ; this . UUID = UUID ; this . subtype = subtype ; this . iid = null ; // assigned later by our containing Accessory this . characteristics = [ ] ; this . optionalCharacteristics = [ ] ; // every service has an optional Characteristic.Name property - we'll set it to our displayName // if one was given // if you don't provide a display name, some HomeKit apps may choose to hide the device. if ( displayName ) { // create the characteristic if necessary var nameCharacteristic = this . getCharacteristic ( Characteristic . Name ) || this . addCharacteristic ( Characteristic . Name ) ; nameCharacteristic . setValue ( displayName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Characteristic represents a particular typed variable that can be assigned to a Service . For instance a Hue Characteristic might store a float value of type arcdegrees . You could add the Hue Characteristic to a Service in order to store that value . A particular Characteristic is distinguished from others by its UUID . HomeKit provides a set of known Characteristic UUIDs defined in HomeKitTypes . js along with a corresponding concrete subclass . [CODESPLIT] function Characteristic ( displayName , UUID , props ) { this . displayName = displayName ; this . UUID = UUID ; this . iid = null ; // assigned by our containing Service this . value = null ; this . props = props || { format : null , unit : null , minValue : null , maxValue : null , minStep : null , perms : [ ] } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bridge is a special type of HomeKit Accessory that hosts other Accessories behind it . This way you can simply publish () the Bridge ( with a single HAPServer on a single port ) and all bridged Accessories will be hosted automatically instead of needed to publish () every single Accessory as a separate server . [CODESPLIT] function Bridge ( displayName , serialNumber ) { Accessory . call ( this , displayName , serialNumber ) ; this . _isBridge = true ; // true if we are a Bridge (creating a new instance of the Bridge subclass sets this to true) this . bridgedAccessories = [ ] ; // If we are a Bridge, these are the Accessories we are bridging }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the schema descriptors to upgrade the database schema to the greatest version specified . [CODESPLIT] function migrateDatabase ( nativeDatabase , nativeTransaction , schemaDescriptors , currentVersion ) { let descriptorsToProcess = schemaDescriptors . filter ( ( descriptor ) => { return descriptor . version > currentVersion } ) if ( ! descriptorsToProcess . length ) { return PromiseSync . resolve ( undefined ) } return migrateDatabaseVersion ( nativeDatabase , nativeTransaction , descriptorsToProcess [ 0 ] ) . then ( ( ) => { return migrateDatabase ( nativeDatabase , nativeTransaction , descriptorsToProcess , descriptorsToProcess [ 0 ] . version ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a single - version database migration to the schema described by the provided database schema descriptor . [CODESPLIT] function migrateDatabaseVersion ( nativeDatabase , nativeTransaction , descriptor ) { let fetchPromise if ( descriptor . fetchBefore && descriptor . fetchBefore . length ) { let fetcher = new RecordFetcher ( ) let objectStores = normalizeFetchBeforeObjectStores ( descriptor . fetchBefore ) fetchPromise = fetcher . fetchRecords ( nativeTransaction , objectStores ) } else { fetchPromise = PromiseSync . resolve ( { } ) } return fetchPromise . then ( ( recordsMap ) => { let versionMigrator = new DatabaseVersionMigrator ( nativeDatabase , nativeTransaction , descriptor . objectStores ) return versionMigrator . executeMigration ( descriptor . after || ( ( ) => { } ) , recordsMap ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalizes the provided array of object store fetch descriptors to process before upgrading the database schema . [CODESPLIT] function normalizeFetchBeforeObjectStores ( objectStores ) { return objectStores . map ( ( objectStore ) => { if ( typeof objectStore === \"string\" ) { return { objectStore , preprocessor : record => record } } else if ( ! objectStore . preprocessor ) { return { objectStore : objectStore . objectStore , preprocessor : record => record } } else { return objectStore } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the types of the provided schema descriptors . [CODESPLIT] function checkSchemaDescriptorTypes ( schemaDescriptors ) { let onlyPlainObjects = schemaDescriptors . every ( ( descriptor ) => { return descriptor . constructor === Object } ) if ( onlyPlainObjects ) { return } if ( ! ( schemaDescriptors [ 0 ] instanceof DatabaseSchema ) ) { throw new TypeError ( \"The schema descriptor of the lowest described \" + ` ${ schemaDescriptors [ 0 ] . version } ` + \"DatabaseSchema instance, or all schema descriptors must be plain \" + \"objects\" ) } schemaDescriptors . slice ( 1 ) . forEach ( ( descriptor ) => { if ( ! ( descriptor instanceof UpgradedDatabaseSchema ) ) { throw new TypeError ( \"The schema descriptors of the upgraded database \" + \"versions must be UpgradedDatabaseSchema instances, but the \" + ` ${ descriptor . version } ` + \"UpgradedDatabaseSchema instance, or all schema descriptors must \" + \"be plain objects\" ) } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a promise that resolves to a record list containing the first page of records matching the provided filter . [CODESPLIT] function list ( storage , keyRange , filter , direction , unique , pageSize , storageFactory ) { return new Promise ( ( resolve , reject ) => { let items = [ ] storage . createCursorFactory ( keyRange , direction ) ( ( cursor ) => { if ( ! filter || filter ( cursor . record , cursor . primaryKey , cursor . key ) ) { if ( items . length === pageSize ) { finalize ( true , cursor . key , cursor . primaryKey ) return } else { items . push ( cursor . record ) } } cursor . continue ( ) } ) . then ( ( ) => finalize ( false , null , null ) ) . catch ( error => reject ( error ) ) function finalize ( hasNextPage , nextKey , nextPrimaryKey ) { resolve ( new RecordList ( items , storageFactory , nextKey , nextPrimaryKey , direction , unique , filter , pageSize , hasNextPage ) ) } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalizes the provided compound key represented as an object into a compound key representation compatible with the Indexed DB . [CODESPLIT] function normalizeCompoundObjectKey ( keyPaths , key ) { let normalizedKey = [ ] keyPaths . forEach ( ( keyPath ) => { let keyValue = key keyPath . split ( \".\" ) . forEach ( ( fieldName ) => { if ( ! keyValue . hasOwnProperty ( fieldName ) ) { throw new Error ( ` ${ keyPath } ` + \"provided compound key\" ) } keyValue = keyValue [ fieldName ] } ) normalizedKey . push ( keyValue ) } ) return normalizedKey }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates the cursor to which the provided Indexed DB request resolves . The method will iterate the cursor over the records in this storage within the range specified when the cursor was opened until the provided callback does not request iterating to the next record or the last matching record is reached . [CODESPLIT] function iterateCursor ( request , cursorConstructor , recordCallback ) { return new PromiseSync ( ( resolve , reject ) => { let traversedRecords = 0 let canIterate = true request . onerror = ( ) => reject ( request . error ) request . onsuccess = ( ) => { if ( ! canIterate ) { console . warn ( \"Cursor iteration was requested asynchronously, \" + \"ignoring the new cursor position\" ) return } if ( ! request . result ) { resolve ( traversedRecords ) return } traversedRecords ++ let iterationRequested = handleCursorIteration ( request , cursorConstructor , recordCallback , reject ) if ( ! iterationRequested ) { canIterate = false resolve ( traversedRecords ) } } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles a single iteration of a Indexed DB cursor iterating the records in the storage . [CODESPLIT] function handleCursorIteration ( request , cursorConstructor , recordCallback , reject ) { let iterationRequested = false let cursor = new cursorConstructor ( request , ( ) => { iterationRequested = true } , ( subRequest ) => { return PromiseSync . resolve ( subRequest ) . catch ( ( error ) => { reject ( error ) throw error } ) } ) try { recordCallback ( cursor ) } catch ( error ) { iterationRequested = false reject ( error ) } return iterationRequested }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches all records from the specified object stores using the provided read - write transaction . [CODESPLIT] function fetchAllRecords ( transaction , objectStores ) { return PromiseSync . all ( objectStores . map ( ( descriptor ) => { return fetchRecords ( transaction . getObjectStore ( descriptor . objectStore ) , descriptor . preprocessor ) } ) ) . then ( ( fetchedRecords ) => { let recordsMap = { } for ( let i = 0 ; i < objectStores . length ; i ++ ) { recordsMap [ objectStores [ i ] . objectStore ] = fetchedRecords [ i ] } return recordsMap } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts all records from the provided object store and preprocess them using the provided preprocessor . [CODESPLIT] function fetchRecords ( objectStore , preprocessor ) { return new PromiseSync ( ( resolve , reject ) => { let records = [ ] objectStore . openCursor ( null , CursorDirection . NEXT , ( cursor ) => { let primaryKey = cursor . primaryKey if ( primaryKey instanceof Object ) { Object . freeze ( primaryKey ) } let preprocessedRecord = preprocessor ( cursor . record , primaryKey ) if ( preprocessedRecord === UpgradedDatabaseSchema . DELETE_RECORD ) { cursor . delete ( ) cursor . continue ( ) return } else if ( preprocessedRecord !== UpgradedDatabaseSchema . SKIP_RECORD ) { records . push ( { key : primaryKey , record : preprocessedRecord } ) } else { // SKIP_RECORD returned, do nothing } cursor . continue ( ) } ) . then ( ( ) => resolve ( records ) ) . catch ( error => reject ( error ) ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writeFileP Create the directory structure and then create the file . [CODESPLIT] function writeFileP ( outputPath , data , cb ) { outputPath = abs ( outputPath ) ; let dirname = path . dirname ( outputPath ) ; mkdirp ( dirname , err => { if ( err ) { return cb ( err ) ; } let str = data ; if ( typpy ( data , Array ) || typpy ( data , Object ) ) { str = JSON . stringify ( data , null , 2 ) ; } fs . writeFile ( outputPath , str , err => cb ( err , data ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs the provided transaction operations on the specified object stores obtained from the provided transaction . [CODESPLIT] function runTransaction ( transaction , objectStoreNames , transactionOperations ) { let callbackArguments = objectStoreNames . map ( ( objectStoreName ) => { return transaction . getObjectStore ( objectStoreName ) } ) callbackArguments . push ( ( ) => transaction . abort ( ) ) let resultPromise = transactionOperations ( ... callbackArguments ) return Promise . resolve ( resultPromise ) . then ( ( result ) => { return transaction . completionPromise . then ( ( ) => result ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the cursor direction to use with the native Indexed DB API . [CODESPLIT] function toNativeCursorDirection ( direction , unique ) { if ( typeof direction === \"string\" ) { if ( CURSOR_DIRECTIONS . indexOf ( direction . toUpperCase ( ) ) === - 1 ) { throw new Error ( \"When using a string as cursor direction, use NEXT \" + ` ${ direction } ` ) ; } } else { direction = direction . value } let cursorDirection = direction . toLowerCase ( ) . substring ( 0 , 4 ) if ( unique ) { cursorDirection += \"unique\" } return cursorDirection }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { @code true } if the index should be deleted from the object store whether because it is no longer present in the schema or its properties have been updated in the schema . [CODESPLIT] function shouldDeleteIndex ( objectStore , schema , indexName ) { let schemaIndexes = schema . indexes || [ ] let newIndexNames = schemaIndexes . map ( indexSchema => indexSchema . name ) if ( newIndexNames . indexOf ( indexName ) === - 1 ) { return true } let index = objectStore . index ( indexName ) let indexKeyPath = index . keyPath ; if ( indexKeyPath && ( typeof indexKeyPath !== \"string\" ) ) { indexKeyPath = Array . from ( indexKeyPath ) } let serializedIndexKeyPath = JSON . stringify ( indexKeyPath ) let indexSchema = schemaIndexes . filter ( ( indexSchema ) => { return indexSchema . name === index . name } ) [ 0 ] return ( index . unique !== indexSchema . unique ) || ( index . multiEntry !== indexSchema . multiEntry ) || ( serializedIndexKeyPath !== JSON . stringify ( indexSchema . keyPaths ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new index in the provided object store according to the provided index schema . [CODESPLIT] function createIndex ( objectStore , indexSchema ) { let indexNames = Array . from ( objectStore . indexNames ) if ( indexNames . indexOf ( indexSchema . name ) !== - 1 ) { return } objectStore . createIndex ( indexSchema . name , indexSchema . keyPath , { unique : indexSchema . unique , multiEntry : indexSchema . multiEntry } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches the next page of records in a new ready - only transaction and resolves into a record list containing the fetched records . [CODESPLIT] function fetchNextPage ( storageFactory , keyRange , cursorDirection , unique , firstPrimaryKey , filter , pageSize ) { let storage = storageFactory ( ) let nextItems = [ ] return new Promise ( ( resolve , reject ) => { let idb = idbProvider ( ) let cursorFactory = storage . createCursorFactory ( keyRange , cursorDirection , unique ) cursorFactory ( ( cursor ) => { if ( ! unique ) { let shouldSkip = ( ( cursorDirection === CursorDirection . NEXT ) && ( idb . cmp ( firstPrimaryKey , cursor . primaryKey ) > 0 ) ) || ( ( cursorDirection === CursorDirection . PREVIOUS ) && ( idb . cmp ( firstPrimaryKey , cursor . primaryKey ) < 0 ) ) if ( shouldSkip ) { cursor . continue ( ) return } } if ( ! filter || filter ( cursor . record , cursor . primaryKey , cursor . key ) ) { if ( nextItems . length === pageSize ) { finalize ( true , cursor . key , cursor . primaryKey ) return } else { nextItems . push ( cursor . record ) } } cursor . continue ( ) } ) . then ( ( ) => finalize ( false , null , null ) ) . catch ( error => reject ( error ) ) function finalize ( hasNextPage , nextKey , nextPrimaryKey ) { resolve ( new RecordList ( nextItems , storageFactory , nextKey , nextPrimaryKey , cursorDirection , unique , filter , pageSize , hasNextPage ) ) } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the provided event listeners with the provided parameters . Any errors thrown by the executed event listeners will be caught and logged to the console and then the remaining event listeners will be executed . [CODESPLIT] function executeEventListeners ( listeners , ... parameters ) { listeners . forEach ( ( listener ) => { try { listener . apply ( null , parameters ) } catch ( error ) { console . error ( \"An event listener threw an error\" , error ) } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves the provided promise to the specified state and result value . This function has no effect if the provided promise has already been resolved . [CODESPLIT] function resolve ( instance , newState , value ) { if ( instance [ FIELDS . state ] !== STATE . PENDING ) { return } instance [ FIELDS . state ] = newState instance [ FIELDS . value ] = value let listeners if ( newState === STATE . RESOLVED ) { listeners = instance [ FIELDS . fulfillListeners ] } else { listeners = instance [ FIELDS . errorListeners ] } for ( let listener of listeners ) { listener ( ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the specified query using the provided cursor factory . [CODESPLIT] function runQuery ( cursorFactory , filter , comparator , offset , limit , callback ) { let records = [ ] let recordIndex = - 1 return cursorFactory ( ( cursor ) => { if ( ! filter && offset && ( ( recordIndex + 1 ) < offset ) ) { recordIndex = offset - 1 cursor . advance ( offset ) return } let primaryKey = cursor . primaryKey if ( filter && ! filter ( cursor . record , primaryKey ) ) { cursor . continue ( ) return } if ( comparator ) { insertSorted ( records , cursor . record , primaryKey , comparator ) if ( offset || limit ) { if ( records . length > ( offset + limit ) ) { records . pop ( ) } } cursor . continue ( ) return } recordIndex ++ if ( recordIndex < offset ) { cursor . continue ( ) return } callback ( cursor . record , primaryKey ) if ( ! limit || ( ( recordIndex + 1 ) < ( offset + limit ) ) ) { cursor . continue ( ) } } ) . then ( ( ) => { if ( ! comparator ) { return } records = records . slice ( offset ) for ( let { record , primaryKey } of records ) { callback ( record , primaryKey ) } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the provided record into the sorted array of records and their primary keys keeping it sorted . [CODESPLIT] function insertSorted ( records , record , primaryKey , comparator ) { let index = findInsertIndex ( records , record , comparator ) records . splice ( index , 0 , { record , primaryKey } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the binary search algorithm to find the index at which the specified record should be inserted into the specified array of records to keep the array sorted according to the provided comparator . [CODESPLIT] function findInsertIndex ( records , record , comparator ) { if ( ! records . length ) { return 0 } if ( records . length === 1 ) { let comparison = comparator ( records [ 0 ] . record , record ) return ( comparison > 0 ) ? 0 : 1 } let comparison = comparator ( records [ 0 ] . record , record ) if ( comparison > 0 ) { return 0 } let bottom = 1 let top = records . length - 1 while ( bottom <= top ) { let pivotIndex = Math . floor ( ( bottom + top ) / 2 ) let comparison = comparator ( records [ pivotIndex ] . record , record ) if ( comparison > 0 ) { let previousElement = records [ pivotIndex - 1 ] . record if ( comparator ( previousElement , record ) <= 0 ) { return pivotIndex } top = pivotIndex - 1 } else { bottom = pivotIndex + 1 } } return records . length }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares the query that uses the specified filter and record order for execution on this storage . [CODESPLIT] function prepareQuery ( thisStorage , filter , order ) { order = normalizeKeyPath ( order ) let expectedSortingDirection = order [ 0 ] . charAt ( 0 ) === \"!\" let canSortingBeOptimized canSortingBeOptimized = canOptimizeSorting ( expectedSortingDirection , order ) let storages = new Map ( ) storages . set ( normalizeKeyPath ( thisStorage . keyPath ) , { storage : thisStorage , score : 1 // traversing storage is faster than fetching records by index } ) for ( let indexName of thisStorage . indexNames ) { let index = thisStorage . getIndex ( indexName ) if ( ! index . multiEntry ) { storages . set ( normalizeKeyPath ( index . keyPath ) , { storage : index , score : 0 } ) } } let simplifiedOrderFieldPaths = simplifyOrderingFieldPaths ( order ) if ( canSortingBeOptimized ) { prepareSortingOptimization ( storages , simplifiedOrderFieldPaths ) } prepareFilteringOptimization ( storages , filter ) return chooseStorageForQuery ( storages , order , simplifiedOrderFieldPaths , canSortingBeOptimized , expectedSortingDirection ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the best possible sorting optimization for the provided storages updating the provided map with sorting optimization scores for each storage . [CODESPLIT] function prepareSortingOptimization ( storages , simplifiedOrderFieldPaths ) { let idb = idbProvider ( ) for ( let [ keyPath , storageAndScore ] of storages ) { let keyPathSlice = keyPath . slice ( 0 , simplifiedOrderFieldPaths . length ) if ( idb . cmp ( keyPathSlice , simplifiedOrderFieldPaths ) === 0 ) { storageAndScore . score += 4 // optimizing the sorting is more important } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the best possible filtering optimizations for the provided storages updating the provided map with optimized filtering info and optimization score for each storage . [CODESPLIT] function prepareFilteringOptimization ( storages , filter ) { if ( filter instanceof Function ) { for ( let [ keyPath , storageAndScore ] of storages ) { storageAndScore . filter = filter } return } for ( let [ keyPath , storageAndScore ] of storages ) { let normalizedFilter = normalizeFilter ( filter , keyPath ) if ( normalizedFilter instanceof Function ) { let isOptimizableFilter = ( filter instanceof Object ) && ! ( filter instanceof Date ) && ! ( filter instanceof Array ) && ! ( filter instanceof IDBKeyRange ) if ( isOptimizableFilter ) { let partialOptimization = partiallyOptimizeFilter ( filter , keyPath ) storageAndScore . keyRange = partialOptimization . keyRange storageAndScore . filter = partialOptimization . filter if ( partialOptimization . score ) { storageAndScore . score += 1 + partialOptimization . score } } else { storageAndScore . filter = normalizedFilter } } else { storageAndScore . keyRange = normalizedFilter storageAndScore . score += 2 } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects the storage on which the execute a query that should lead to the best possible performance . The method returns all the data necessary to execute the query . [CODESPLIT] function chooseStorageForQuery ( storages , order , simplifiedOrderFieldPaths , canSortingBeOptimized , expectedSortingDirection ) { let sortedStorages = Array . from ( storages . values ( ) ) sortedStorages . sort ( ( storage1 , storage2 ) => { return storage2 . score - storage1 . score } ) let chosenStorageDetails = sortedStorages [ 0 ] let chosenStorage = chosenStorageDetails . storage let chosenStorageKeyPath = normalizeKeyPath ( chosenStorage . keyPath ) let storageKeyPathSlice = chosenStorageKeyPath . slice ( 0 , simplifiedOrderFieldPaths . length ) let optimizeSorting = canSortingBeOptimized && ( idbProvider ( ) . cmp ( storageKeyPathSlice , simplifiedOrderFieldPaths ) === 0 ) return { storage : chosenStorage , direction : optimizeSorting ? ( CursorDirection [ expectedSortingDirection ? \"PREVIOUS\" : \"NEXT\" ] ) : CursorDirection . NEXT , comparator : optimizeSorting ? null : compileOrderingFieldPaths ( order ) , keyRange : chosenStorageDetails . keyRange , filter : chosenStorageDetails . filter } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether the sorting of the query result can be done through an index ( provided such index exists ) or the natural order of the records in the object store . [CODESPLIT] function canOptimizeSorting ( expectedSortingDirection , order ) { for ( let orderingFieldPath of order ) { if ( ( orderingFieldPath . charAt ( 0 ) === \"!\" ) !== expectedSortingDirection ) { return false } } return true }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Preprocess the raw ordering specification into form that can be used in query optimization . [CODESPLIT] function prepareOrderingSpecificationForQuery ( order , keyPath ) { if ( order === null ) { order = CursorDirection . NEXT } let isCursorDirection = ( ( typeof order === \"string\" ) && ( CURSOR_DIRECTIONS . indexOf ( order . toUpperCase ( ) ) > - 1 ) ) || ( CURSOR_DIRECTIONS . indexOf ( order ) > - 1 ) if ( isCursorDirection && ( typeof order === \"string\" ) ) { order = CursorDirection [ order . toUpperCase ( ) ] || CursorDirection . PREVIOUS } if ( order instanceof CursorDirection ) { keyPath = normalizeKeyPath ( keyPath ) if ( order === CursorDirection . NEXT ) { return keyPath } else { return keyPath . map ( fieldPath => ` ${ fieldPath } ` ) } } return order }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles opening the connection to the database and wraps the whole process in a promise . [CODESPLIT] function openConnection ( databaseName , sortedSchemaDescriptors ) { let version = sortedSchemaDescriptors . slice ( ) . pop ( ) . version let request = NativeDBAccessor . indexedDB . open ( databaseName , version ) return new Promise ( ( resolve , reject ) => { let wasBlocked = false let upgradeTriggered = false let migrationPromiseResolver , migrationPromiseRejector let migrationPromise = new Promise ( ( resolve , reject ) => { migrationPromiseResolver = resolve migrationPromiseRejector = reject } ) // prevent leaking the same error to the console twice migrationPromise . catch ( ( ) => { } ) request . onsuccess = ( ) => { let database = new Database ( request . result ) resolve ( database ) migrationPromiseResolver ( ) } request . onupgradeneeded = ( event ) => { if ( ! wasBlocked ) { upgradeTriggered = true } let database = request . result let transaction = request . transaction if ( wasBlocked ) { transaction . abort ( ) return } upgradeDatabaseSchema ( databaseName , event , migrationPromise , database , transaction , sortedSchemaDescriptors , migrationPromiseResolver , migrationPromiseRejector ) . catch ( ( error ) => { transaction . abort ( ) } ) } request . onerror = ( event ) => { handleConnectionError ( event , request . error , wasBlocked , upgradeTriggered , reject , migrationPromiseRejector ) } request . onblocked = ( ) => { wasBlocked = true let error = new Error ( \"A database upgrade was needed, but could not \" + \"be performed, because the attempt was blocked by a connection \" + \"that remained opened after receiving the notification\" ) reject ( error ) migrationPromiseRejector ( error ) } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles a database error encountered during connection establishing . [CODESPLIT] function handleConnectionError ( event , error , wasBlocked , upgradeTriggered , reject , migrationPromiseRejector ) { if ( wasBlocked || upgradeTriggered ) { event . preventDefault ( ) return } reject ( request . error ) migrationPromiseRejector ( request . error ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the provided { @code upgradeneeded } event that occurred during opening a database that was not blocked . The function handles database schema upgrade . [CODESPLIT] function upgradeDatabaseSchema ( databaseName , event , migrationPromise , database , transaction , sortedSchemaDescriptors , migrationPromiseResolver , migrationPromiseRejector ) { executeMigrationListeners ( databaseName , event . oldVersion , event . newVersion , migrationPromise ) let migrator = new DatabaseMigrator ( database , transaction , sortedSchemaDescriptors , event . oldVersion ) return PromiseSync . resolve ( ) . then ( ( ) => { return migrator . executeMigration ( ) } ) . then ( ( ) => { migrationPromiseResolver ( ) } ) . catch ( ( error ) => { migrationPromiseRejector ( error ) throw error } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the currently registered database schema migration listeners with the provided arguments . [CODESPLIT] function executeMigrationListeners ( databaseName , oldVersion , newVersion , completionPromise ) { for ( let listener of migrationListeners ) { try { listener ( databaseName , oldVersion , newVersion , completionPromise ) } catch ( e ) { console . warn ( \"A schema migration event listener threw an error\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A sub - routine of the { @linkcode partiallyOptimizeFilter } used to generate optimization result if the storage key path matches the field paths in the filter object . [CODESPLIT] function partiallyOptimizeKeyPathMatchingFilter ( filter , keyPath ) { let keyRange = convertFieldMapToKeyRange ( filter , keyPath ) if ( ! keyRange ) { // at least one of the values is a IDBKeyRange instance return { keyRange : undefined , filter : compileFieldRangeFilter ( filter ) , score : 0 } } return { keyRange , filter : null , score : 1 } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits the provided filter object to two objects according the the provided storage key path . This is used to separate a complex filter object into an object optimizable into a key range and a simpler object that will be compiled into a filter predicate function . [CODESPLIT] function splitFilteringObject ( filter , filterFieldPaths , storageKeyPath ) { let fieldsToOptimize = { } let fieldsToCompile = { } filterFieldPaths . forEach ( ( fieldPath ) => { let value = getFieldValue ( filter , fieldPath ) if ( storageKeyPath . indexOf ( fieldPath ) > - 1 ) { setFieldValue ( fieldsToOptimize , fieldPath , value ) } else { setFieldValue ( fieldsToCompile , fieldPath , value ) } } ) return { fieldsToOptimize , fieldsToCompile } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles the provided field path to a function that retrieves the value of the field denoted by the field path from the object passed to the function or { @code undefined } if the field does not exist in the object . [CODESPLIT] function compileFieldGetter ( fieldPath ) { let fields = fieldPath . split ( \".\" ) return ( record ) => { let value = record for ( let field of fields ) { if ( ! ( value instanceof Object ) || ! value . hasOwnProperty ( field ) ) { return undefined } value = value [ field ] } return value } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to convert the provided filter to a single { @codelink IDBKeyRange } instance . [CODESPLIT] function convertFieldMapToKeyRange ( filter , keyPaths ) { let isOtherFormOfFilter = ! ( filter instanceof Object ) || ( filter instanceof Function ) || ( filter instanceof Array ) || ( filter instanceof Date ) || ( filter instanceof IDBKeyRange ) if ( isOtherFormOfFilter ) { return null } if ( ! ( keyPaths instanceof Array ) ) { keyPaths = [ keyPaths ] } let fieldPaths = getFieldPaths ( filter ) if ( ! fieldPaths ) { return null } let isKeyFilter = ( fieldPaths . length === keyPaths . length ) && fieldPaths . every ( path => keyPaths . indexOf ( path ) > - 1 ) if ( ! isKeyFilter ) { return null } if ( keyPaths . length === 1 ) { return IDBKeyRange . only ( getFieldValue ( filter , keyPaths [ 0 ] ) ) } return new IDBKeyRange . only ( keyPaths . map ( ( keyPath ) => { getFieldValue ( filter , keyPath ) } ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates an array containing all field paths in the provided object . [CODESPLIT] function getFieldPaths ( object , stopOnKeyRange = true ) { let fieldPaths = [ ] fieldPaths . containsKeyRange = false generateFieldPaths ( object , [ ] ) return fieldPaths function generateFieldPaths ( object , parts ) { Object . keys ( object ) . some ( ( fieldName ) => { let value = object [ fieldName ] if ( stopOnKeyRange && ( value instanceof IDBKeyRange ) ) { fieldPaths = null return true } let isTerminalValue = ! ( value instanceof Object ) || ( value instanceof Date ) || ( value instanceof Array ) || ( value instanceof IDBKeyRange ) let fieldPath = parts . slice ( ) fieldPath . push ( fieldName ) if ( isTerminalValue ) { fieldPaths . push ( fieldPath . join ( \".\" ) ) } else { generateFieldPaths ( value , fieldPath ) } } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified field denoted by the specified field path on the provided object to the provided value . [CODESPLIT] function setFieldValue ( object , fieldPath , value ) { let parts = fieldPath . split ( \".\" ) let done = [ ] let currentObject = object while ( parts . length ) { let field = parts . shift ( ) if ( ! parts . length ) { if ( currentObject . hasOwnProperty ( field ) ) { throw new Error ( ` ${ fieldPath } ` ) } currentObject [ field ] = value break } if ( ! currentObject . hasOwnProperty ( field ) ) { currentObject [ field ] = { } } if ( ! ( currentObject [ field ] instanceof Object ) ) { throw new Error ( ` ${ fieldPath } ` + ` ${ done . join ( \".\" ) } ` ) } currentObject = currentObject [ field ] done . push ( field ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the value from the provided object at the specified field path . [CODESPLIT] function getFieldValue ( object , fieldPath ) { if ( ! fieldPath ) { return object } let currentObject = object fieldPath . split ( \".\" ) . forEach ( ( fieldName ) => { if ( ! currentObject . hasOwnProperty ( fieldName ) ) { throw new Error ( ` ${ fieldPath } ` + \"provided object\" ) } currentObject = currentObject [ fieldName ] } ) return currentObject }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the schema of the provided Indexed DB database to the schema specified by the provided schema descriptors . [CODESPLIT] function upgradeSchema ( nativeDatabase , nativeTransaction , descriptors ) { let objectStoreNames = Array . from ( nativeDatabase . objectStoreNames ) let newObjectStoreNames = descriptors . map ( ( objectStore ) => { return objectStore . name } ) objectStoreNames . forEach ( ( objectStoreName ) => { if ( newObjectStoreNames . indexOf ( objectStoreName ) === - 1 ) { nativeDatabase . deleteObjectStore ( objectStoreName ) } } ) descriptors . forEach ( ( objectStoreDescriptor ) => { let objectStoreName = objectStoreDescriptor . name let nativeObjectStore = objectStoreNames . indexOf ( objectStoreName ) > - 1 ? nativeTransaction . objectStore ( objectStoreName ) : null let objectStoreMigrator = new ObjectStoreMigrator ( nativeDatabase , nativeObjectStore , objectStoreDescriptor ) objectStoreMigrator . executeMigration ( ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signal { x : Int y : Int } [CODESPLIT] function MousePosition ( ) { return signal ( function ( next ) { document . addEventListener ( \"mousemove\" , function ( event ) { next ( getXY ( event ) ) } ) } , new Point ( 0 , 0 ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Int - > Int - > { x : Number y : Number } - > Shape [CODESPLIT] function rect ( width , height , pos ) { return new Shape ( [ { x : 0 - width / 2 , y : 0 - height / 2 } , { x : 0 - width / 2 , y : height / 2 } , { x : width / 2 , y : height / 2 } , { x : width / 2 , y : 0 - height / 2 } ] , pos ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Int - > Int - > Position - > Element - > Element [CODESPLIT] function container ( width , height , position , elem ) { return new Element ( new ContainerElement ( position , elem ) , width , height ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Various template functions to render subsets of the UI [CODESPLIT] function mainSection ( state ) { var todos = state . todos var route = state . route return h ( \"section.main\" , { hidden : todos . length === 0 } , [ toggleAllPool . change ( h ( \"input#toggle-all.toggle-all\" , { type : \"checkbox\" , checked : todos . every ( function ( todo ) { return todo . completed } ) } ) ) , h ( \"label\" , { htmlFor : \"toggle-all\" } , \"Mark all as complete\" ) , h ( \"ul.todo-list\" , todos . filter ( function ( todo ) { return route === \"completed\" && todo . completed || route === \"active\" && ! todo . completed || route === \"all\" } ) . map ( todoItem ) ) ] ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a dreamscreen client [CODESPLIT] function Client ( ) { EventEmitter . call ( this ) ; this . debug = true ; //false this . socket = dgram . createSocket ( 'udp4' ) ; this . isSocketBound = false ; this . devices = { } ; this . port = constants . DREAMSCREEN_PORT ; this . discoveryTimer = null ; this . messageHandlers = [ ] ; this . messageHandlerTimeout = 5000 ; // 45000 45 sec this . broadcastIp = constants . DEFAULT_BROADCAST_IP ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "(( A - > void ) - > void ) - > A - > Signal A [CODESPLIT] function signal ( generator , defaultValue ) { var value = defaultValue var listeners = [ ] setTimeout ( function ( ) { generator ( set ) } , 0 ) return observable function observable ( listener ) { if ( isGet ( listener ) ) { return value } else if ( isSet ( listener ) ) { throw new Error ( \"read-only\" ) } else { listeners . push ( listener ) } } function set ( v ) { value = v for ( var i = 0 ; i < listeners . length ; i ++ ) { var listener = listeners [ i ] listener ( value ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Outbound Rate Limits [CODESPLIT] function getOutDom ( hmail ) { // outbound isn't internally consistent in the use of hmail.domain // vs hmail.todo.domain. // TODO: fix haraka/Haraka/outbound/HMailItem to be internally consistent. if ( hmail . todo && hmail . todo . domain ) return hmail . todo . domain ; return hmail . domain ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A representation of a light bulb DreamScreen HD DreamScreen 4K SideKick [CODESPLIT] function Light ( constr ) { this . client = constr . client ; this . ipAddress = constr . ipAddress ; this . serialNumber = constr . serialNumber ; this . productId = constr . productId ; //devicetype this . lastSeen = constr . lastSeen ; this . isReachable = constr . isReachable ; this . name = constr . name ; //devicename this . groupName = constr . groupName ; //groupname this . groupNumber = constr . groupNumber ; //groupnumber this . mode = constr . mode ; //mode this . brightness = constr . brightness ; //brightness this . ambientColor = constr . ambientColor ; //ambientr ambientg ambientb this . ambientShow = constr . ambientShow ; //ambientscene this . ambientModeType = constr . ambientModeType ; // this . hdmiInput = constr . hdmiInput ; //hdmiinput this . hdmiInputName1 = constr . hdmiInputName1 ; //hdminame1 this . hdmiInputName2 = constr . hdmiInputName2 ; //hdminame2 this . hdmiInputName3 = constr . hdmiInputName3 ; //hdminame3 }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signal { x : Number y : Number } [CODESPLIT] function KeyboardArrows ( ) { var validKeys = [ 37 , 38 , 39 , 40 ] return signal ( function ( next ) { var down = { } document . addEventListener ( \"keyup\" , function onup ( ev ) { if ( ev . which in KEYS ) { var key = KEYS [ ev . which ] down [ key ] = false next ( getState ( ) ) } } ) document . addEventListener ( \"keydown\" , function ondown ( ev ) { if ( ev . which in KEYS ) { var key = KEYS [ ev . which ] down [ key ] = true next ( getState ( ) ) } } ) function getState ( ) { var x = 0 , y = 0 if ( down . up ) { y = 1 } else if ( down . down ) { y = - 1 } if ( down . left ) { x = - 1 } else if ( down . right ) { x = 1 } return { x : x , y : y } } } , { x : 0 , y : 0 } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signal Number [CODESPLIT] function fps ( desiredFps ) { var msPerFrame = 1000 / desiredFps return signal ( function ( next ) { var prev = Date . now ( ) setTimeout ( tick , msPerFrame ) function tick ( ) { var curr = Date . now ( ) var diff = curr - prev prev = curr next ( diff ) setTimeout ( tick , msPerFrame ) } } , 0 ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * String - > { signal : Signal<Any > on : Element - > String - > ( EventTarget - > Any ) - > Element submit : Element - > ( valueof EventTarget - > Any ) - > Element change : Element - > ( valueof EventTarget - > Any ) - > Element } [CODESPLIT] function EventPool ( name ) { var storage = TransformStorage ( name ) var events = { } var _next var nextTick = function ( value , elem ) { process . nextTick ( function ( ) { _next ( value , elem ) } ) } return { signal : signal ( function ( next ) { handleSubmit ( next ) handleChange ( next ) Object . keys ( events ) . forEach ( function ( event ) { handleEvent ( event , next ) } ) _next = next } ) , submit : function ( elem , transform ) { return storage . set ( \"submit\" , elem , transform ) } , change : function ( elem , transform ) { return storage . set ( \"change\" , elem , transform ) } , on : function ( elem , event , transform ) { if ( ! events [ event ] ) { events [ event ] = true if ( _next ) { handleEvent ( event , _next ) } } return storage . set ( event , elem , transform ) } } function handleSubmit ( next ) { document . addEventListener ( \"keypress\" , function ( ev ) { var target = ev . target var fn = storage . get ( \"submit\" , target ) var validEvent = fn && target . type === \"text\" && ev . keyCode === ENTER && ! ev . shiftKey if ( ! validEvent ) { return } var item = fn ( target . value , target ) nextTick ( item ) } ) document . addEventListener ( \"click\" , function ( ev ) { var target = ev . target var fn = storage . get ( \"submit\" , target ) if ( ! fn || target . tagName !== \"BUTTON\" ) { return } nextTick ( fn ( ) , target ) } ) } function handleChange ( next ) { document . addEventListener ( \"keypress\" , function ( ev ) { var target = ev . target var fn = storage . get ( \"change\" , target ) if ( ! fn || target . type !== \"text\" ) { return } nextTick ( fn ( target . value ) , target ) } ) document . addEventListener ( \"change\" , function ( ev ) { var target = ev . target var fn = storage . get ( \"change\" , target ) if ( ! fn || target . type !== \"checkbox\" ) { return } nextTick ( fn ( target . checked ) , target ) } ) } function handleEvent ( event , next ) { document . addEventListener ( event , function ( ev ) { var target = ev . target var fn = storage . get ( event , target ) if ( fn ) { nextTick ( fn ( target . value , target ) ) } } , true ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "String - > Element [CODESPLIT] function plainText ( content ) { var textSize = getTextSize ( content ) return new Element ( new TextElement ( \"left\" , content ) , textSize . width , textSize . height ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signal { width : Number height : Number } [CODESPLIT] function WindowDimensions ( ) { return signal ( function ( next ) { window . addEventListener ( \"resize\" , function ( e ) { next ( { width : window . innerWidth , height : window . innerHeight } ) } ) } , { width : window . innerWidth , height : window . innerHeight } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a basic JSON datatype ( number string boolean null object array ) into an HTML fragment . [CODESPLIT] function ( value ) { var valueType = typeof value ; var output = \"\" ; if ( value === null || value === undefined ) { output += this . decorateWithSpan ( 'null' , 'null' ) ; } else if ( value && value . constructor === Array ) { output += this . arrayToHTML ( value ) ; } else if ( valueType === 'object' ) { output += this . objectToHTML ( value ) ; } else if ( valueType === 'number' ) { output += this . decorateWithSpan ( value , 'num' ) ; } else if ( valueType === 'string' ) { if ( / ^(http|https):\\/\\/[^\\s]+$ / . test ( value ) ) { output += '<a href=\"' + value + '\">' + this . htmlEncode ( value ) + '</a>' ; } else { output += this . decorateWithSpan ( '\"' + value + '\"' , 'string' ) ; } } else if ( valueType === 'boolean' ) { output += this . decorateWithSpan ( value , 'bool' ) ; } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an array into an HTML fragment [CODESPLIT] function ( json ) { var output = '[<ul class=\"array collapsible\">' ; var hasContents = false ; for ( var prop in json ) { hasContents = true ; output += '<li>' ; output += this . valueToHTML ( json [ prop ] ) ; output += '</li>' ; } output += '</ul>]' ; if ( ! hasContents ) { output = \"[ ]\" ; } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Produce an error document for when parsing fails . [CODESPLIT] function ( error , data , uri ) { // var output = '<div id=\"error\">' + //    this.stringbundle.GetStringFromName('errorParsing') + '</div>'; // output += '<h1>' + //    this.stringbundle.GetStringFromName('docContents') + ':</h1>'; var output = '<div id=\"error\">Error parsing JSON: ' + error . message + '</div>' output += '<h1>' + error . stack + ':</h1>' ; output += '<div id=\"jsonview\">' + this . htmlEncode ( data ) + '</div>' ; return this . toHTML ( output , uri + ' - Error' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO remember collapsal path [CODESPLIT] function collapse ( evt ) { var collapser = evt . target ; var target = collapser . parentNode . getElementsByClassName ( 'collapsible' ) ; if ( ! target . length ) { return } target = target [ 0 ] ; if ( target . style . display === 'none' ) { var ellipsis = target . parentNode . getElementsByClassName ( 'ellipsis' ) [ 0 ] target . parentNode . removeChild ( ellipsis ) ; target . style . display = '' ; collapser . innerHTML = '-' ; } else { target . style . display = 'none' ; var ellipsis = document . createElement ( 'span' ) ; ellipsis . className = 'ellipsis' ; ellipsis . innerHTML = ' &hellip; ' ; target . parentNode . insertBefore ( ellipsis , target ) ; collapser . innerHTML = '+' ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "String - > [ Element ] - > Element [CODESPLIT] function flow ( direction , elements ) { var widths = elements . map ( widthOf ) var heights = elements . map ( heightOf ) var width = direction === \"left\" ? sum ( widths ) : direction === \"right\" ? sum ( widths ) : maximum ( widths ) var height = direction === \"down\" ? sum ( heights ) : direction === \"right\" ? sum ( heights ) : maximum ( heights ) return new Element ( new FlowElement ( direction , elements ) , width , height ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Int - > Int - > [ Form ] - > Element [CODESPLIT] function collage ( width , height , forms ) { return new Element ( new CollageElement ( forms , width , height ) , width , height ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * a HtmlElement has a tagName a hash of special attributes and a hash of general attributes . [CODESPLIT] function HtmlElement ( tagName , special , general , children ) { this . tagName = tagName this . specialProperties = special this . generalProperties = general this . children = children this . cl = null // elem.classList this . ds = null // elem.dataset }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ <reference path = common . js / > [CODESPLIT] function createLexer ( g ) { function Token ( tag , text , index , subMatches , end , pos ) { this . tag = tag ; this . text = text ; this . index = index ; this . subMatches = subMatches ; this . end = end ; this . pos = pos ; } Token . prototype . toString = function ( ) { return this . text ; } ; function emptyFunc ( ) { } function tofn ( f ) { if ( typeof f == 'function' ) return f ; return function ( ) { return f ; } ; } function buildScanner ( a ) { var n = 1 ; var b = [ ] ; var matchIndexes = [ 1 ] ; var fa = [ ] ; for ( var i = 0 ; i < a . length ; ++ i ) { matchIndexes . push ( n += RegExp ( '|' + a [ i ] [ 0 ] . source ) . exec ( '' ) . length ) ; fa . push ( a [ i ] [ 1 ] ? tofn ( a [ i ] [ 1 ] ) : emptyFunc ) ; b . push ( '(' + a [ i ] [ 0 ] . source + ')' ) ; } var re = RegExp ( b . join ( '|' ) + '|' , 'g' ) ; return [ re , matchIndexes , fa ] ; } var endTag = g . $ || '$' ; var scanner = { } ; for ( var i in g ) { if ( i . charAt ( 0 ) != '$' ) scanner [ i ] = buildScanner ( g [ i ] ) ; } return Lexer ; function Lexer ( s ) { /// <param name=\"s\" type=\"String\"></param>\r var Length = s . length ; var i = 0 ; var stateStack = [ '' ] ; var obj = { text : '' , index : 0 , source : s , pushState : function ( s ) { stateStack . push ( s ) ; } , popState : function ( ) { stateStack . pop ( ) ; } , retract : function ( n ) { i -= n ; } } ; var currentPos = new Position ( 1 , 1 ) ; function scan ( ) { var st = stateStack [ stateStack . length - 1 ] ; var rule = scanner [ st ] ; var re = rule [ 0 ] ; re . lastIndex = i ; var t = re . exec ( s ) ; if ( t [ 0 ] == '' ) { if ( i < Length ) { throw Error ( 'lexer error: ' + currentPos + '\\n' + s . slice ( i , i + 50 ) ) ; } return new Token ( endTag , '' , i , null , i , currentPos ) ; } obj . index = i ; i = re . lastIndex ; var idx = rule [ 1 ] ; for ( var j = 0 ; j < idx . length ; ++ j ) if ( t [ idx [ j ] ] ) { var tag = rule [ 2 ] [ j ] . apply ( obj , t . slice ( idx [ j ] , idx [ j + 1 ] ) ) ; //if (tag == null) return null;\r return new Token ( tag , t [ 0 ] , obj . index , t . slice ( idx [ j ] + 1 , idx [ j + 1 ] ) , i , currentPos ) ; } } var re_newLine = / \\r\\n?|\\n / g ; var re_lastLine = / [^\\r\\n\\u2028\\u2029]*$ / ; return { scan : function ( ) { do { var t = scan ( ) ; var _row = currentPos . row ; var _col = currentPos . col ; var ms = t . text . match ( re_newLine ) ; var h = ms ? ms . length : 0 ; _row += h ; if ( h == 0 ) _col += t . text . length ; else _col = re_lastLine . exec ( t . text ) [ 0 ] . length + 1 ; currentPos = new Position ( _row , _col ) ; if ( t . tag != null ) { return t ; } } while ( true ) ; } , GetCurrentPosition : function ( ) { return currentPos ; } , getPos : function ( i ) { return getPos ( s , i ) ; } } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ <reference path = common . js / > / <reference path = codegen_common . js / > [CODESPLIT] function codegen_js_tran ( prog , encodeName , defaultEncode , ignoreWhitespace ) { /// <param name=\"prog\" type=\"Array\">AST</param>\r /// <param name=\"encodeName\" type=\"String\"></param>\r /// <param name=\"defaultEncode\" type=\"Boolean\"></param>\r /// <returns type=\"String\" />\r var i_tmake = 0 ; function TMake ( ) { return '_' + ( i_tmake ++ ) ; } function emit ( s ) { body . push ( s ) ; } function nodeWithPos ( node , pos ) { node . pos = pos ; return node ; } function stmtGen ( a ) { switch ( a [ 0 ] ) { case 'if' : emit ( 'if(' ) ; emit ( exprGen ( a [ 1 ] ) ) ; emit ( '){' ) ; stmtsGen ( a [ 2 ] ) ; emit ( '}' ) ; if ( a [ 3 ] ) { emit ( 'else{' ) ; stmtsGen ( a [ 3 ] ) ; emit ( '}' ) ; } break ; case 'each' : var keyName = a [ 3 ] ? encodeCommonName ( a [ 3 ] ) : TMake ( ) ; var tmpExpr = exprGen ( a [ 1 ] ) ; var tmpStr = joinCode ( tmpExpr ) ; if ( / ^\\w+$ / . test ( tmpStr ) ) { var listName = tmpStr ; } else { listName = TMake ( ) ; emit ( 'var ' + listName + ' = ' ) ; emit ( tmpExpr ) ; emit ( ';' ) ; } if ( a [ 5 ] ) { emit ( 'for(var ' + keyName + '=0;' + keyName + '<' ) ; //listName + '.length'\r emit ( exprGen ( [ '.' , nodeWithPos ( [ 't' , listName ] , a [ 1 ] . pos ) , 'length' ] ) ) ; emit ( ';' + keyName + '++){' ) ; } else emit ( 'for(var ' + keyName + ' in ' + listName + ') {' ) ; emit ( 'var ' + a [ 4 ] + ' = ' ) ; //listName + '[' + keyName + ']'\r emit ( exprGen ( [ '[]' , nodeWithPos ( [ 't' , listName ] , a [ 1 ] . pos ) , [ 't' , keyName ] ] ) ) ; emit ( ';' ) ; stmtsGen ( a [ 2 ] ) ; emit ( '}' ) ; break ; case 'set' : if ( typeof a [ 1 ] == 'string' ) emit ( 'var ' + encodeCommonName ( a [ 1 ] ) + '=' ) ; else { emit ( exprGen ( a [ 1 ] ) ) ; emit ( '=' ) ; } emit ( exprGen ( a [ 2 ] ) ) ; emit ( ';' ) ; break ; case 'eval' : var tmpExpr = exprGen ( a [ 1 ] ) ; var tmpStr = joinCode ( tmpExpr ) ; if ( / ^\\w+$ / . test ( tmpStr ) ) var tName = tmpStr ; else { tName = '_t' ; emit ( '_t = ' ) ; emit ( tmpExpr ) ; emit ( ';' ) ; } emit ( 'if(' + tName + ' !=null)_s += ' + ( ( defaultEncode ? ! a [ 2 ] : a [ 2 ] ) ? encodeName + '(' + tName + ')' : tName ) + ';' ) ; break ; case 'text' : if ( ignoreWhitespace ) { if ( / ^\\s+$ / . test ( a [ 1 ] ) ) break ; } emit ( '_s += ' + quote ( a [ 1 ] ) + ';' ) ; break ; case 'inc' : //stmtsGen(a[2][1]);\r break ; case 'script' : scripts . push ( a [ 1 ] ) ; break ; default : throw Error ( 'unknown stmt: ' + a [ 0 ] ) ; } } function stmtsGen ( a ) { for ( var i = 0 ; i < a . length ; ++ i ) stmtGen ( a [ i ] ) ; } function joinCode ( a ) { if ( typeof a == 'string' ) return a ; if ( a instanceof Array ) { var r = [ ] ; for ( var i = 0 ; i < a . length ; ++ i ) { r . push ( joinCode ( a [ i ] ) ) ; } return r . join ( '' ) ; } throw new Error ( \"unknown type\" ) ; } function exprToStr ( x , check ) { var t = exprGen ( x ) ; if ( check && ! check ( x [ 0 ] ) ) t = [ '(' , t , ')' ] ; return t ; } function exprGen ( x ) { return nodeWithPos ( exprGen_original ( x ) , x . pos ) ; } function exprGen_original ( x ) { switch ( x [ 0 ] ) { case 't' : return x [ 1 ] ; //临时变量直接返回\r case 'id' : return encodeCommonName ( x [ 1 ] ) ; case 'lit' : return ( typeof x [ 1 ] == 'string' ) ? quote ( x [ 1 ] ) : String ( x [ 1 ] ) ; case 'array' : var tmp = [ '[' ] ; for ( var i = 0 ; i < x [ 1 ] . length ; ++ i ) { if ( i > 0 ) tmp . push ( \",\" ) ; tmp . push ( exprGen ( x [ 1 ] [ i ] ) ) ; } tmp . push ( ']' ) ; return tmp ; case 'object' : var tmp = [ '{' ] ; for ( var i = 0 ; i < x [ 1 ] . length ; ++ i ) { if ( i > 0 ) tmp . push ( \",\" ) ; tmp . push ( quote ( x [ 1 ] [ i ] [ 1 ] ) ) ; tmp . push ( ':' ) ; tmp . push ( exprGen ( x [ 1 ] [ i ] [ 2 ] ) ) ; } tmp . push ( '}' ) ; return tmp ; case 'null' : return [ 'null' ] ; case '.' : return [ exprToStr ( x [ 1 ] , isMember ) , '.' , x [ 2 ] ] ; case '[]' : return [ exprToStr ( x [ 1 ] , isMember ) , '[' , exprGen ( x [ 2 ] ) , ']' ] ; case '()' : var a = [ exprToStr ( x [ 1 ] , isMember ) , '(' ] ; if ( x [ 2 ] ) { for ( var i = 0 ; i < x [ 2 ] . length ; ++ i ) { if ( i > 0 ) a . push ( ',' ) ; a . push ( exprGen ( x [ 2 ] [ i ] ) ) ; } } a . push ( ')' ) ; return a ; case '!' : return [ '!' , exprToStr ( x [ 1 ] , isUnary ) ] ; case 'u-' : return [ '- ' , exprToStr ( x [ 1 ] , isUnary ) ] ; case '*' : case '/' : case '%' : return [ exprToStr ( x [ 1 ] , isMul ) , x [ 0 ] , exprToStr ( x [ 2 ] , isUnary ) ] ; case '+' : case '-' : return [ exprToStr ( x [ 1 ] , isAdd ) , x [ 0 ] , ' ' , exprToStr ( x [ 2 ] , isMul ) ] ; case '<' : case '>' : case '<=' : case '>=' : return [ exprToStr ( x [ 1 ] , isRel ) , x [ 0 ] , exprToStr ( x [ 2 ] , isAdd ) ] ; case '==' : case '!=' : case '===' : case '!==' : return [ exprToStr ( x [ 1 ] , isEquality ) , x [ 0 ] , exprToStr ( x [ 2 ] , isRel ) ] ; case '&&' : return [ exprToStr ( x [ 1 ] , isLogicalAnd ) , '&&' , exprToStr ( x [ 2 ] , isEquality ) ] ; case '||' : return [ exprToStr ( x [ 1 ] , isLogicalOr ) , '||' , exprToStr ( x [ 2 ] , isLogicalAnd ) ] ; case 'cond' : return [ exprToStr ( x [ 1 ] , isLogicalOr ) , '?' , exprToStr ( x [ 2 ] , isCond ) , ':' , exprToStr ( x [ 3 ] , isCond ) ] ; default : throw Error ( \"unknown expr: \" + x [ 0 ] ) ; } } var body = [ ] ; var scripts = [ ] ; stmtsGen ( prog [ 1 ] ) ; var posLog = [ ] ; var jsStr = '' ; function joinJsStr ( a ) { if ( typeof a == 'string' ) jsStr += a ; if ( a instanceof Array ) { if ( a . pos ) { posLog . push ( [ jsStr . length , a . pos ] ) ; } for ( var i = 0 ; i < a . length ; ++ i ) { joinJsStr ( a [ i ] ) ; } } } joinJsStr ( body ) ; if ( scripts . length ) { jsStr += scripts . join ( ';' ) ; } //alert(posLog.join('\\n'));\r var strObj = new String ( jsStr ) ; strObj . posLog = posLog ; return strObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ <reference path = common . js / > / <reference path = codegen_common . js / > [CODESPLIT] function codegen_php_tran ( prog , defaultEncode ) { /// <param name=\"prog\" type=\"Array\">AST</param>\r /// <param name=\"defaultEncode\" type=\"Boolean\"></param>\r /// <returns type=\"String\" />\r //用户变量名 都奇数个下划线开头\r function encodeId ( s ) { return '$crox_' + encodeCommonName ( s ) ; } function emit ( t ) { s += t ; } function compileEval ( stmt ) { var t = walkExpr ( stmt [ 1 ] ) ; emit ( 'crox_echo(' + t + ', ' + ( defaultEncode ? ! stmt [ 2 ] : stmt [ 2 ] ) + ');' ) ; } function compileContent ( stmt ) { var t = stmt [ 1 ] ; if ( / <\\?(?:php)?|\\?> / . test ( t ) ) emit ( 'echo ' + phpQuote ( stmt [ 1 ] ) + ';' ) ; else { emit ( '?>' + t + '<?php ' ) ; } } function compileIf ( stmt ) { emit ( 'if(' + walkExpr ( stmt [ 1 ] ) + '){' ) ; compileStmts ( stmt [ 2 ] ) ; emit ( '}' ) ; if ( stmt [ 3 ] ) { emit ( 'else{' ) ; compileStmts ( stmt [ 3 ] ) ; emit ( '}' ) ; } } function compileEach ( stmt ) { emit ( 'foreach(' + walkExpr ( stmt [ 1 ] ) + ' as ' + ( stmt [ 3 ] ? encodeId ( stmt [ 3 ] ) + '=>' : '' ) + encodeId ( stmt [ 4 ] ) + ')' ) ; emit ( '{' ) ; compileStmts ( stmt [ 2 ] ) ; emit ( '}' ) ; } function compileSet ( stmt ) { emit ( encodeId ( stmt [ 1 ] ) + ' = ' + walkExpr ( stmt [ 2 ] ) + ';' ) ; } function compileStmt ( a ) { switch ( a [ 0 ] ) { case 'if' : compileIf ( a ) ; break ; case 'each' : compileEach ( a ) ; break ; case 'set' : compileSet ( a ) ; break ; case 'eval' : compileEval ( a ) ; break ; case 'text' : compileContent ( a ) ; break ; case 'inc' : emit ( \"include '\" + changeExt ( a [ 1 ] , 'php' ) + \"';\" ) ; break ; default : throw Error ( 'unknown stmt: ' + a [ 0 ] ) ; } } function compileStmts ( a ) { for ( var i = 0 ; i < a . length ; ++ i ) compileStmt ( a [ i ] ) ; } function exprToStr ( x , check ) { var t = walkExpr ( x ) ; if ( check && ! check ( x [ 0 ] ) ) t = '(' + t + ')' ; return t ; } function walkExpr ( x ) { switch ( x [ 0 ] ) { case 'id' : return encodeId ( x [ 1 ] ) ; case 'lit' : if ( typeof x [ 1 ] == 'string' ) return phpQuote ( x [ 1 ] ) ; return String ( x [ 1 ] ) ; case '.' : return exprToStr ( x [ 1 ] , isMember ) + \"->\" + x [ 2 ] ; case '[]' : return exprToStr ( x [ 1 ] , isMember ) + '[' + walkExpr ( x [ 2 ] ) + ']' ; case '!' : return '!crox_ToBoolean(' + exprToStr ( x [ 1 ] , isUnary ) + ')' ; case 'u-' : return '- ' + exprToStr ( x [ 1 ] , isUnary ) ; case '*' : case '/' : case '%' : return exprToStr ( x [ 1 ] , isMul ) + x [ 0 ] + exprToStr ( x [ 2 ] , isUnary ) ; case '+' : return 'crox_plus(' + exprToStr ( x [ 1 ] , null ) + ', ' + exprToStr ( x [ 2 ] , null ) + ')' ; case '-' : return exprToStr ( x [ 1 ] , isAdd ) + '- ' + exprToStr ( x [ 2 ] , isMul ) ; case '<' : case '>' : case '<=' : case '>=' : return exprToStr ( x [ 1 ] , isRel ) + x [ 0 ] + exprToStr ( x [ 2 ] , isAdd ) ; case '==' : case '!=' : case '===' : case '!==' : return exprToStr ( x [ 1 ] , isEquality ) + x [ 0 ] + exprToStr ( x [ 2 ] , isRel ) ; case '&&' : return 'crox_logical_and(' + exprToStr ( x [ 1 ] , null ) + ', ' + exprToStr ( x [ 2 ] , null ) + ')' ; case '||' : return 'crox_logical_or(' + exprToStr ( x [ 1 ] , null ) + ', ' + exprToStr ( x [ 2 ] , null ) + ')' ; default : throw Error ( \"unknown expr: \" + x [ 0 ] ) ; } } var s = \"\" ; compileStmts ( prog [ 1 ] ) ; if ( s . slice ( 0 , 2 ) == '?>' ) s = s . slice ( 2 ) ; else s = '<?php ' + s ; if ( s . slice ( - 6 ) == '<?php ' ) s = s . slice ( 0 , - 6 ) ; else s += '?>' ; return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ <reference path = common . js / > / <reference path = codegen_common . js / > [CODESPLIT] function codegen_vm_tran ( prog ) { /// <param name=\"prog\" type=\"Array\">AST</param>\r /// <returns type=\"String\" />\r //用户变量名 都奇数个下划线开头，临时变量都不下划线开头\r function encodeId ( s ) { return '$crox_' + encodeCommonName ( s ) ; } function isName ( s ) { return / ^$\\w+$ / . test ( s ) ; } function emit ( s ) { body += s ; } var i_each = 0 ; function stmtGen ( a ) { switch ( a [ 0 ] ) { case 'if' : emit ( '#if(' + exprGen ( a [ 1 ] ) + ')' ) ; stmtsGen ( a [ 2 ] ) ; if ( a [ 3 ] ) { emit ( '#{else}' ) ; stmtsGen ( a [ 3 ] ) ; } emit ( '#{end}' ) ; break ; case 'each' : ++ i_each ; var sExpr = exprGen ( a [ 1 ] ) ; if ( isName ( sExpr ) ) var listName = sExpr ; else { listName = '$list' + ( i_each == 1 ? '' : i_each ) ; emit ( '#set (' + listName + ' = ' + sExpr + ')' ) ; } if ( a [ 5 ] ) { //array\r emit ( '#foreach(' + encodeId ( a [ 4 ] ) + ' in ' + listName + ')' ) ; if ( a [ 3 ] ) { emit ( '#set(' + encodeId ( a [ 3 ] ) + ' = $velocityCount - 1)' ) ; } } else { //object\r if ( a [ 3 ] ) { emit ( '#foreach(' + encodeId ( a [ 3 ] ) + ' in ' + listName + '.keySet())' ) ; emit ( '#set(' + encodeId ( a [ 4 ] ) + ' =' + listName + '.get(' + encodeId ( a [ 3 ] ) + '))' ) ; } else { emit ( '#foreach(' + encodeId ( a [ 4 ] ) + ' in ' + listName + ')' ) ; } } stmtsGen ( a [ 2 ] ) ; emit ( '#{end}' ) ; -- i_each ; break ; case 'set' : emit ( '#set (' + encodeId ( a [ 1 ] ) + '=' + exprGen ( a [ 2 ] ) + ')' ) ; break ; case 'eval' : var s = exprGen ( a [ 1 ] ) ; if ( isName ( s ) ) emit ( '$!{' + s . slice ( 1 ) + '}' ) ; else { emit ( '#set($t = ' + s + ')$!{t}' ) ; } break ; case 'text' : emit ( a [ 1 ] . replace ( / \\$ / g , '$${dollar}' ) . replace ( / # / g , '$${sharp}' ) ) ; break ; case 'inc' : emit ( \"#parse('\" + changeExt ( a [ 1 ] , 'vm' ) + \"')\" ) ; break ; default : throw Error ( 'unknown stmt: ' + a [ 0 ] ) ; } } function stmtsGen ( a ) { for ( var i = 0 ; i < a . length ; ++ i ) stmtGen ( a [ i ] ) ; } function exprToStr ( x , check ) { var t = exprGen ( x ) ; if ( check && ! check ( x [ 0 ] ) ) t = '(' + t + ')' ; return t ; } function exprGen ( x ) { switch ( x [ 0 ] ) { case 'id' : return encodeId ( x [ 1 ] ) ; case 'lit' : if ( typeof x [ 1 ] == 'string' ) return vmQuote ( x [ 1 ] ) ; return String ( x [ 1 ] ) ; case '.' : return exprToStr ( x [ 1 ] , isMember ) + '.' + x [ 2 ] ; case '[]' : return exprToStr ( x [ 1 ] , isMember ) + '[' + exprGen ( x [ 2 ] ) + ']' ; case '!' : return '!' + exprToStr ( x [ 1 ] , isUnary ) ; case 'u-' : if ( x [ 1 ] [ 0 ] == 'u-' ) throw Error ( \"禁止两个负号连用\");\r   return '-' + exprToStr ( x [ 1 ] , isUnary ) ; case '*' : case '/' : case '%' : return exprToStr ( x [ 1 ] , isMul ) + x [ 0 ] + exprToStr ( x [ 2 ] , isUnary ) ; case '+' : case '-' : return exprToStr ( x [ 1 ] , isAdd ) + x [ 0 ] + ' ' + exprToStr ( x [ 2 ] , isMul ) ; case '<' : case '>' : case '<=' : case '>=' : return exprToStr ( x [ 1 ] , isRel ) + x [ 0 ] + exprToStr ( x [ 2 ] , isAdd ) ; case '==' : case '!=' : case '===' : case '!==' : return exprToStr ( x [ 1 ] , isEquality ) + x [ 0 ] . slice ( 0 , 2 ) + exprToStr ( x [ 2 ] , isRel ) ; case '&&' : return exprToStr ( x [ 1 ] , isLogicalAnd ) + '&&' + exprToStr ( x [ 2 ] , isEquality ) ; case '||' : return exprToStr ( x [ 1 ] , isLogicalOr ) + '||' + exprToStr ( x [ 2 ] , isLogicalAnd ) ; default : throw Error ( \"unknown expr: \" + x [ 0 ] ) ; } } function vmQuote ( s ) { /// <param name=\"s\" type=\"String\"></param>\r if ( s . indexOf ( \"'\" ) == - 1 ) return \"'\" + s + \"'\" ; var a = s . split ( \"'\" ) ; return \"('\" + a . join ( \"'+\\\"'\\\"+'\" ) + \"')\" ; } var body = \"#set($dollar='$')#set($sharp='#')\" ; stmtsGen ( prog [ 1 ] ) ; return body ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a chunk into memory . [CODESPLIT] function write ( chunk , encoding , callback ) { if ( typeof encoding === 'function' ) { callback = encoding encoding = null } if ( ended ) { throw new Error ( 'Did not expect `write` after `end`' ) } chunks . push ( ( chunk || '' ) . toString ( encoding || 'utf8' ) ) if ( callback ) { callback ( ) } // Signal succesful write. return true }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "End the writing . Passes all arguments to a final write . Starts the process which will trigger error with a fatal error if any ; data with the generated document in string form if succesful . If messages are triggered during the process those are triggerd as warning s . [CODESPLIT] function end ( ) { write . apply ( null , arguments ) ended = true processor . process ( chunks . join ( '' ) , done ) return true function done ( err , file ) { var messages = file ? file . messages : [ ] var length = messages . length var index = - 1 chunks = null // Trigger messages as warnings, except for fatal error. while ( ++ index < length ) { /* istanbul ignore else - shouldn’t happen. */ if ( messages [ index ] !== err ) { emitter . emit ( 'warning' , messages [ index ] ) } } if ( err ) { // Don’t enter an infinite error throwing loop. global . setTimeout ( function ( ) { emitter . emit ( 'error' , err ) } , 4 ) } else { emitter . emit ( 'data' , file . contents ) emitter . emit ( 'end' ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pipe the processor into a writable stream . Basically Stream#pipe but inlined and simplified to keep the bundled size down . See <https : // github . com / nodejs / node / blob / master / lib / stream . js#L26 > . [CODESPLIT] function pipe ( dest , options ) { var settings = options || { } var onend = once ( onended ) emitter . on ( 'data' , ondata ) emitter . on ( 'error' , onerror ) emitter . on ( 'end' , cleanup ) emitter . on ( 'close' , cleanup ) // If the `end` option is not supplied, `dest.end()` will be called when the // `end` or `close` events are received.  Only `dest.end()` once. if ( ! dest . _isStdio && settings . end !== false ) { emitter . on ( 'end' , onend ) } dest . on ( 'error' , onerror ) dest . on ( 'close' , cleanup ) dest . emit ( 'pipe' , emitter ) return dest // End destination. function onended ( ) { if ( dest . end ) { dest . end ( ) } } // Handle data. function ondata ( chunk ) { if ( dest . writable ) { dest . write ( chunk ) } } // Clean listeners. function cleanup ( ) { emitter . removeListener ( 'data' , ondata ) emitter . removeListener ( 'end' , onend ) emitter . removeListener ( 'error' , onerror ) emitter . removeListener ( 'end' , cleanup ) emitter . removeListener ( 'close' , cleanup ) dest . removeListener ( 'error' , onerror ) dest . removeListener ( 'close' , cleanup ) } // Close dangling pipes and handle unheard errors. function onerror ( err ) { var handlers = emitter . _events . error cleanup ( ) // Cannot use `listenerCount` in node <= 0.12. if ( ! handlers || handlers . length === 0 || handlers === onerror ) { throw err // Unhandled stream error in pipe. } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clean listeners . [CODESPLIT] function cleanup ( ) { emitter . removeListener ( 'data' , ondata ) emitter . removeListener ( 'end' , onend ) emitter . removeListener ( 'error' , onerror ) emitter . removeListener ( 'end' , cleanup ) emitter . removeListener ( 'close' , cleanup ) dest . removeListener ( 'error' , onerror ) dest . removeListener ( 'close' , cleanup ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close dangling pipes and handle unheard errors . [CODESPLIT] function onerror ( err ) { var handlers = emitter . _events . error cleanup ( ) // Cannot use `listenerCount` in node <= 0.12. if ( ! handlers || handlers . length === 0 || handlers === onerror ) { throw err // Unhandled stream error in pipe. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "snap rm <names ... > delete one or more boilerplates [CODESPLIT] function rm ( names ) { console . log ( ) ; for ( const name of names ) { const bplate = path . join ( os . homedir ( ) , '.snap' , name ) ; if ( fs . pathExistsSync ( bplate ) ) { fs . removeSync ( bplate ) ; console . log ( ` ${ chalk . green ( 'Success:' ) } ${ chalk . redBright ( name ) } ` ) ; } else { console . error ( ` ${ chalk . red ( 'Error:' ) } ${ chalk . yellow ( name ) } ` ) ; } } console . log ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "snap save <name > [ source ] save a directory or repository provided by [ source ] to . snap / <name > [CODESPLIT] function save ( name , src = path . resolve ( ) , options ) { // ensure that the vault exists const vault = path . join ( os . homedir ( ) , '.snap' ) ; if ( ! fs . pathExistsSync ( vault ) ) shell . exec ( ` ${ path . join ( __dirname , 'init.js' ) } ` ) ; const root = path . join ( vault , name ) ; // check if the name is already taken if ( fs . pathExistsSync ( root ) && ! options . overwrite ) { console . error ( ` \\n ${ chalk . red ( chalk . underline ( name ) , 'already exists' ) } \\n ` ) ; return ; } // check if the source provided resolves to a valid path const sourcePath = path . resolve ( src ) ; if ( fs . pathExistsSync ( sourcePath ) ) { // if --overwrite is passed, remove the existing save first if ( options . overwrite ) fs . removeSync ( root ) ; // copy the source provided to the new boilerplate in the vault fs . copySync ( src , root , { overwrite : false , // don't want to modify existing boilerplates, -o will remove the old one first errorOnExist : true , // shouldn't happen, either the boilerplate is new or has been removed with -o filter : pathToCopy => { const match = pathToCopy . match ( / node_modules$|.git$ / ) ; if ( match ) { console . log ( ` ${ chalk . dim . redBright ( match [ 0 ] ) } ${ chalk . yellow ( name ) } ` ) ; } return ! match ; } } ) ; logSuccess ( name ) ; clean ( root , name ) ; return ; } // check if the source provided is a valid git url const gitUrl = / ((git|ssh|http(s)?)|(git@[\\w.]+))(:(\\/\\/)?)([\\w.@:/\\-~]+)(\\.git)(\\/)? / ; if ( gitUrl . test ( src ) ) { shell . exec ( ` ${ src } ${ root } ` , { silent : true } , exitCode => { if ( exitCode !== 0 ) { console . error ( ` \\n ${ chalk . red ( 'Save failed :(' ) } ${ chalk . cyan ( src ) } \\n ` ) ; } else { logSuccess ( name ) ; clean ( root , name ) ; } } ) ; return ; } // log if the source was invalid console . error ( chalk . red ( '\\nInvalid [source]' ) ) ; console . log ( ` ${ chalk . yellow ( 'snap save -h' ) } \\n ` ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "clean out blacklisted content [CODESPLIT] function clean ( root , name ) { const blacklist = [ '.git' , 'node_modules' ] ; for ( const item of blacklist ) { const pathToItem = path . join ( root , item ) ; if ( fs . pathExistsSync ( pathToItem ) ) { fs . removeSync ( pathToItem ) ; console . log ( ` ${ chalk . dim . redBright ( item ) } ${ chalk . yellow ( name ) } ` ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "snap ls list saved boilerplates [CODESPLIT] function ls ( ) { const vault = path . join ( os . homedir ( ) , '.snap' ) ; const list = shell . ls ( vault ) ; if ( ! list . length ) { console . log ( \"\\nIt seems you don't have anything saved...\" ) ; console . log ( ` ${ chalk . yellow ( 'snap save' ) } ` ) ; console . log ( ` ${ chalk . yellow ( 'snap save -h' ) } \\n ` ) ; return ; } console . log ( '\\nThe following boilerplates have been saved...' ) ; console . log ( ` ${ chalk . yellow ( 'snap <boilerplate-name> <project-directory>' ) } ` ) ; for ( const bplate of list ) { console . log ( ` bp late}` ) ;   } console . log ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "snap <boilerplate - name > <project - directory > [ - i ] create a new project with a boilerplate [CODESPLIT] function snap ( bplateName , projectDir , options ) { // find the boilerplate const bplate = path . join ( os . homedir ( ) , '.snap' , bplateName ) ; if ( ! fs . pathExistsSync ( bplate ) ) { console . log ( ` \\n ${ chalk . red ( 'Error:' ) } ${ chalk . yellow ( bplateName ) } \\n ` ) ; return ; } const projectPath = path . resolve ( projectDir ) ; // check if the project directory is already taken if ( fs . pathExistsSync ( projectPath ) ) { console . log ( ` \\n ${ chalk . red ( 'Error:' ) } ${ chalk . cyan ( projectPath ) } \\n ` ) ; return ; } // copy the boilerplate console . log ( '\\nCopying...' ) ; fs . copySync ( bplate , projectPath ) ; if ( options . install ) { console . log ( ` ${ chalk . yellow ( 'npm install' ) } ` ) ; shell . exec ( ` ${ projectDir } ` ) ; } console . log ( chalk . green ( '\\nSuccess! ＼(＾O＾)／'));    console . log ( ` ${ chalk . yellow ( ` ${ projectDir } ` ) } \\n ` ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "snap show <name > display the file structure of a boilerplate [CODESPLIT] function show ( name ) { const root = path . join ( os . homedir ( ) , '.snap' , name ) ; if ( ! fs . pathExistsSync ( root ) ) { console . log ( ` \\n ${ chalk . red ( 'Error:' ) } ${ chalk . yellow ( name ) } \\n ` ) ; return ; } const tree = walk ( root , 0 ) ; console . log ( ) ; printTree ( tree ) ; console . log ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从右边弹出 左边退出 [CODESPLIT] function AnimationScaleInRight ( init ) { let buildStyleInterpolator = init ; return Object . assign ( { } , { ... NavigatorSceneConfigs . PushFromRight , animationInterpolators : { into : buildStyleInterpolator ( { ... CenterScaleRightIn } ) , out : buildStyleInterpolator ( { ... CenterScaleLeftOut } ) } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "const AnimationScaleInRight = Object . assign ( {} { ... NavigatorSceneConfigs . PushFromRight animationInterpolators : { into : buildStyleInterpolator ( { ... CenterScaleRightIn } ) out : buildStyleInterpolator ( { ... CenterScaleLeftOut } ) } } ) ; 从右下角弹出 左下角退出 [CODESPLIT] function AnimationScaleInRightDown ( init ) { let buildStyleInterpolator = init ; return Object . assign ( { } , { ... NavigatorSceneConfigs . PushFromRight , animationInterpolators : { into : buildStyleInterpolator ( { ... DownScaleIn } ) , out : buildStyleInterpolator ( { ... DownScaleOut } ) } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "const AnimationScaleInRightDown = Object . assign ( {} { ... NavigatorSceneConfigs . PushFromRight animationInterpolators : { into : buildStyleInterpolator ( { ... DownScaleIn } ) out : buildStyleInterpolator ( { ... DownScaleOut } ) } } ) ; 从右上角弹出 左上角退出 [CODESPLIT] function AnimationScaleInRightUp ( init ) { let buildStyleInterpolator = init ; return Object . assign ( { } , { ... NavigatorSceneConfigs . PushFromRight , animationInterpolators : { into : buildStyleInterpolator ( { ... UpScaleIn } ) , out : buildStyleInterpolator ( { ... UpScaleOut } ) } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "const AnimationScaleInRightUp = Object . assign ( {} { ... NavigatorSceneConfigs . PushFromRight animationInterpolators : { into : buildStyleInterpolator ( { ... UpScaleIn } ) out : buildStyleInterpolator ( { ... UpScaleOut } ) } } ) ; 右边旋转进入 左边旋转退出 [CODESPLIT] function AnimationRotateInLeft ( init ) { let buildStyleInterpolator = init ; return Object . assign ( { } , { ... NavigatorSceneConfigs . FadeAndroid , animationInterpolators : { into : buildStyleInterpolator ( { ... RightRotateInDown } ) , out : buildStyleInterpolator ( { ... LeftRotateOutDown } ) } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "定制动画 ( 是上 / 下 是左 / 右 是进 / 出 是否支持手势 ) 第一个参数必须是定义的进入动画 第二个必须是退出的动画 [CODESPLIT] function CustomAnimation ( init ) { let buildStyleInterpolator = init ; return ( LeftRightIn , UpDowmOut , Gestures , Base = { springFriction : 26 , springTension : 200 , defaultTransitionVelocity : 1.5 } ) => { return Object . assign ( { } , NavigatorSceneConfigs . FadeAndroid , { animationInterpolators : { into : buildStyleInterpolator ( { ... CheckParams ( LeftRightIn ) } ) , out : buildStyleInterpolator ( { ... CheckParams ( UpDowmOut ) } ) } , gestures : Gestures ? Gestures : { pop : { ... BaseLeftToRightGesture , direction : \"left-to-right\" , fullDistance : Width } } , ... Base // springFriction:Base.springFriction, // springTension:Base.springTension, // defaultTransitionVelocity:Base.defaultTransitionVelocity, } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "===================== [CODESPLIT] function socketConnection ( socket ) { const cookies = getCookies ( socket . handshake . headers . cookie ) ; socket . session_start = Date . now ( ) ; socket . blurred = 0 ; socket . blurring = Date . now ( ) ; socket . req_id = cookies . na_req ; socket . session_id = cookies . na_session ; // Get session if ( socket . session_id ) { Session . findById ( socket . session_id , function ( err , session ) { if ( err ) return log . error ( 'Session find error :: id[socket]' , this . session_id , err ) ; if ( ! session ) return log . error ( 'Session not found :: id[socket]' , this . session_id ) ; const socket = this ; // set regional session and request socket . session = session ; if ( socket . req_id ) { for ( let i = session . reqs . length - 1 ; i >= 0 ; i -- ) { if ( session . reqs [ i ] . _id . toString ( ) == socket . req_id ) { socket . req = session . reqs [ i ] ; break ; } } } // log and initiate socket sensitivity if ( ! socket . req ) log . error ( 'socket connected; request not found' ) ; else if ( opts . log_all ) log . session ( session , 'socket connected; request:' , socket . req . _id ) ; socketResponse ( socket ) ; } . bind ( socket ) ) ; } // ============= function socketResponse ( socket ) { // session updates from the client // Trivial not-bot check: socket connects; //   Could / should be improved to having done action on page if ( socket . session . is_bot ) Update . session ( socket . session , { $set : { is_bot : false } } ) ; if ( ! socket . session . resolution ) socket . on ( 'resolution' , _socket . resolution . bind ( socket ) ) ; // request updates socket . on ( 'click' , _socket . click . bind ( socket ) ) ; socket . on ( 'reach' , _socket . reach . bind ( socket ) ) ; socket . on ( 'pause' , _socket . pause . bind ( socket ) ) ; // session timer socket . on ( 'blur' , _socket . blur . bind ( socket ) ) ; socket . on ( 'focus' , _socket . focus . bind ( socket ) ) ; // Disconnection socket . on ( 'disconnect' , _socket . disconnect . bind ( socket ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "============= [CODESPLIT] function socketResponse ( socket ) { // session updates from the client // Trivial not-bot check: socket connects; //   Could / should be improved to having done action on page if ( socket . session . is_bot ) Update . session ( socket . session , { $set : { is_bot : false } } ) ; if ( ! socket . session . resolution ) socket . on ( 'resolution' , _socket . resolution . bind ( socket ) ) ; // request updates socket . on ( 'click' , _socket . click . bind ( socket ) ) ; socket . on ( 'reach' , _socket . reach . bind ( socket ) ) ; socket . on ( 'pause' , _socket . pause . bind ( socket ) ) ; // session timer socket . on ( 'blur' , _socket . blur . bind ( socket ) ) ; socket . on ( 'focus' , _socket . focus . bind ( socket ) ) ; // Disconnection socket . on ( 'disconnect' , _socket . disconnect . bind ( socket ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "===================== populate var session ; returns boolean on whether newly formed [CODESPLIT] function getSession ( req , res , cb ) { const now = new Date ( ) ; const cookies = getCookies ( req . headers . cookie ) ; // cookies.na_session  :: session._id // cookies.na_user     :: session.user // Establish session: new/old session? new/old user? if ( cookies . na_session ) { if ( opts . log_all ) log ( 'Session cookie found:' , cookies . na_session ) ; Session . findById ( cookies . na_session , session_fields ) . lean ( ) . exec ( function ( err , session ) { if ( err ) { log . error ( 'getSession error' , err ) ; return cb ( err ) ; } if ( ! session ) { log . error ( 'Session not found :: id[cookie]:' , this . cookies . na_session ) ; // send to check if user instead if ( cookies . na_user ) userSession ( ) ; else newSession ( ) ; } else { Update . session ( session , { $set : { last : Date . now ( ) } } , ( err , session ) => { if ( err ) { log . error ( 'establish session / update error' ) ; return cb ( true ) ; } session . continued = true ; cb ( err , this . req , this . res , session ) } ) ; } } . bind ( { cookies : cookies , req : req , res : res } ) ) } else if ( cookies . na_user ) userSession ( ) ; else newSession ( ) ; // ==================== function userSession ( ) { // OLD USER, NEW SESSION cb ( null , req , res , new Session ( { user : cookies . na_user , new_session : true } ) . toObject ( { virtuals : true } ) ) ; if ( opts . log_all ) log . timer ( 'getSession 1' , now ) ; } function newSession ( ) { // NEW USER, NEW SESSION // Initiate session to get _id let session = new Session ( ) ; session . user = session . _id . toString ( ) ; session . new_user = true ; session = session . toObject ( { virtuals : true } ) ; cb ( null , req , res , session ) ; if ( opts . log_all ) log . timer ( 'getSession 2' , now ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "==================== [CODESPLIT] function userSession ( ) { // OLD USER, NEW SESSION cb ( null , req , res , new Session ( { user : cookies . na_user , new_session : true } ) . toObject ( { virtuals : true } ) ) ; if ( opts . log_all ) log . timer ( 'getSession 1' , now ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set cookies [CODESPLIT] function setCookies ( req , res , session , cb ) { const now = new Date ( ) ; // Set cookies res . cookie ( 'na_session' , AES . encrypt ( session . _id . toString ( ) ) , { maxAge : 1000 * 60 * 15 , // 15 mins httpOnly : true , secure : opts . secure } ) ; res . cookie ( 'na_user' , AES . encrypt ( session . user ) , { maxAge : 1000 * 60 * 60 * 24 * 365 , // 1 year httpOnly : true , secure : opts . secure } ) ; cb ( null , req , res , session ) ; if ( opts . log_all ) log . timer ( 'setCookies' , now ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "append session data [CODESPLIT] function sessionData ( req , res , session , cb ) { const now = new Date ( ) ; if ( session . continued ) return cb ( null , req , res , session ) ; async . parallelLimit ( [ getIp , getLocation , getSystem ] , 2 , function ( err ) { cb ( err , this . req , this . res , this . session ) ; if ( opts . log_all ) log . timer ( 'sessionData' , now ) ; } . bind ( { req : req , res : res , session : session } ) ) ; // ====================== // .ip function getIp ( cb ) { session . ip = get_ip ( req ) . clientIp ; cb ( null ) } // .geo :: .city, .state, .country function getLocation ( cb ) { if ( ! geo_lookup ) return cb ( null ) ; const loc = geo_lookup . get ( session . ip ) ; if ( ! session . geo ) session . geo = { } ; if ( loc ) { try { if ( loc . city ) session . geo . city = loc . city . names . en ; if ( loc . subdivisions ) session . geo . state = loc . subdivisions [ 0 ] . iso_code ; if ( loc . country ) session . geo . country = loc . country . iso_code ; if ( loc . continent ) session . geo . continent = loc . continent . code ; if ( loc . location ) session . geo . time_zone = loc . location . time_zone ; } catch ( e ) { log . error ( 'geoIP error:' , e ) ; } } cb ( null ) } // .system :: .os{, .broswer{ .name, .version function getSystem ( cb ) { var agent = useragent . parse ( req . headers [ 'user-agent' ] ) ; var os = agent . os ; if ( ! session . system ) session . system = { } ; if ( ! session . system . browser ) session . system . browser = { } ; if ( ! session . system . os ) session . system . os = { } ; session . system . browser . name = agent . family ; session . system . browser . version = agent . major + '.' + agent . minor + '.' + agent . patch ; session . system . os . name = os . family ; session . system . os . version = os . major + '.' + os . minor + '.' + os . patch ; cb ( null ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": ". geo :: . city . state . country [CODESPLIT] function getLocation ( cb ) { if ( ! geo_lookup ) return cb ( null ) ; const loc = geo_lookup . get ( session . ip ) ; if ( ! session . geo ) session . geo = { } ; if ( loc ) { try { if ( loc . city ) session . geo . city = loc . city . names . en ; if ( loc . subdivisions ) session . geo . state = loc . subdivisions [ 0 ] . iso_code ; if ( loc . country ) session . geo . country = loc . country . iso_code ; if ( loc . continent ) session . geo . continent = loc . continent . code ; if ( loc . location ) session . geo . time_zone = loc . location . time_zone ; } catch ( e ) { log . error ( 'geoIP error:' , e ) ; } } cb ( null ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": ". system :: . os { . broswer { . name . version [CODESPLIT] function getSystem ( cb ) { var agent = useragent . parse ( req . headers [ 'user-agent' ] ) ; var os = agent . os ; if ( ! session . system ) session . system = { } ; if ( ! session . system . browser ) session . system . browser = { } ; if ( ! session . system . os ) session . system . os = { } ; session . system . browser . name = agent . family ; session . system . browser . version = agent . major + '.' + agent . minor + '.' + agent . patch ; session . system . os . name = os . family ; session . system . os . version = os . major + '.' + os . minor + '.' + os . patch ; cb ( null ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return new request document create req cookie [CODESPLIT] function newRequest ( req , res , session , cb ) { const now = new Date ( ) ; const request = { _id : ` ${ crypto . randomBytes ( 16 ) . toString ( 'hex' ) } ${ Date . now ( ) } ` , host : req . hostname , url : req . url , method : req . method , referrer : req . get ( 'Referrer' ) || req . get ( 'Referer' ) } ; // populate request query for ( let field in req . query ) { if ( field === 'ref' ) request . ref = req . query [ field ] ; else { if ( ! request . query ) request . query = [ ] ; request . query . push ( { field : field , value : req . query [ field ] } ) } } // add request cookie for communication/association with socket res . cookie ( 'na_req' , AES . encrypt ( request . _id ) , { maxAge : 1000 * 60 * 15 , // 15 mins httpOnly : true , secure : opts . secure } ) ; // return request object: will be added at sessionSave(); cb ( null , req , res , session , request ) ; if ( opts . log_all ) log . timer ( 'newRequest' , now ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "log request [CODESPLIT] function logRequest ( req , res , session , request , cb ) { const now = new Date ( ) ; if ( opts . log ) { onHeaders ( res , log_start . bind ( res ) ) ; onFinished ( res , req_log . bind ( { req : request , ses : session } ) ) ; } cb ( null , session , request ) ; if ( opts . log_all ) log . timer ( 'logRequest' , now ) ; /// ============== function log_start ( ) { this . _log_start = process . hrtime ( ) ; } function req_log ( ) { const request = this . req ; const session = this . ses ; // Status colour const sc = res . statusCode < 400 ? 'green' : 'red' ; // Res time const ms = nano_time ( res . _log_start ) ; // Referrer let ref = request . referrer ; if ( ref ) { ref = ref . replace ( 'http://' , '' ) ; ref = ref . replace ( 'https://' , '' ) ; } // Args const args = [ session , '|' , chalk . magenta ( request . url ) , '|' , request . method , chalk [ sc ] ( res . statusCode ) , ` ${ ms } ` ] ; if ( session && session . system ) { args . push ( '|' ) ; if ( session . system . browser ) { args . push ( chalk . grey ( session . system . browser . name ) ) ; args . push ( chalk . grey ( session . system . browser . version ) ) ; } if ( session . system . os ) { args . push ( chalk . grey ( session . system . os . name ) ) ; args . push ( chalk . grey ( session . system . os . version ) ) ; } } if ( ref ) args . push ( '|' , chalk . grey ( ` ${ ref } ` ) ) ; // Apply log . session . apply ( log , args ) ; // === function nano_time ( start ) { let t = conv ( process . hrtime ( ) ) - conv ( start ) ; // ns t = Math . round ( t / 1000 ) ; // µs return t / 1000 ; // ms [3 dec] // ==== function conv ( t ) { if ( ! t || typeof t [ 0 ] === 'undefined' ) return 0 ; return t [ 0 ] * 1e9 + t [ 1 ] ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "=== [CODESPLIT] function nano_time ( start ) { let t = conv ( process . hrtime ( ) ) - conv ( start ) ; // ns t = Math . round ( t / 1000 ) ; // µs return t / 1000 ; // ms [3 dec] // ==== function conv ( t ) { if ( ! t || typeof t [ 0 ] === 'undefined' ) return 0 ; return t [ 0 ] * 1e9 + t [ 1 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "save / update session to DB & proceed to socket [CODESPLIT] function sessionSave ( session , request , cb ) { const now = new Date ( ) ; if ( ! session . continued ) { session . reqs = [ request ] ; Update . session ( session , { $set : session } , ( err , session ) => { if ( err ) return cb ( 'db session save error' ) ; if ( opts . log_all ) log . session ( session , 'session active [ new ]' ) ; cb ( null , session ) ; if ( opts . log_all ) log . timer ( 'sessionSave 1' , now ) ; } ) } else { // an old session: all that needs be updated is request Update . session ( session , { $push : { reqs : request } } , ( err , session ) => { if ( err ) { log . error ( 'db session update error' ) ; return cb ( true ) ; } if ( opts . log_all ) log . session ( session , 'session active [ updated ]' ) ; cb ( null , session ) ; if ( opts . log_all ) log . timer ( 'sessionSave 2' , now ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "===================== [CODESPLIT] function Identify ( name ) { Update . session ( this , { $set : { name : name } } , ( err ) => { if ( err ) log . error ( 'session.associate: name save error' , err ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "===================== [CODESPLIT] function getCookies ( src ) { let cookies = cookie . parse ( src || '' ) ; for ( let k in cookies ) { if ( k . indexOf ( 'na_' ) === 0 ) { try { cookies [ k ] = AES . decrypt ( cookies [ k ] ) ; } catch ( err ) { log . error ( 'getCookies error' , err ) ; delete cookies [ k ] ; } } } return cookies ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "===================== [CODESPLIT] function sessions ( options , cb ) { if ( ! cb ) { cb = options ; options = { is_bot : false } ; } var n = 32 ; Session . find ( options ) . sort ( { date : 'desc' } ) . limit ( n ) . exec ( function ( err , results ) { if ( err ) log . error ( 'Sessions query error:' , err ) ; cb ( err , results ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor for the message class [CODESPLIT] function ( packet ) { this . updatePayload = function ( packet ) { this . p_previous = this . p ; this . p = packet . payload ; this . changed = this . p_previous != this . p ; this . retained = packet . retain ; this . lastChange = this . currentChange ; this . currentChange = new Date ( ) ; } ; this . changedFromTo = function ( from , to ) { return this . changed && this . p_previous == from && this . p == to ; } ; this . changedTo = function ( to ) { return this . changed && this . p == to ; } ; this . changedFrom = function ( from ) { return this . changed && this . p_previous == from ; } ; this . t = packet . topic ; this . updatePayload ( packet ) ; this . currentChange = new Date ( ) ; this . lastChange = undefined ; //aliases this . payload = this . p ; this . topic = this . t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor for the clock class [CODESPLIT] function ( ) { this . date = new Date ( ) ; this . getHours = function ( ) { return this . date . getHours ( ) ; } ; this . getMinutes = function ( ) { return this . date . getMinutes ( ) ; } ; this . hoursIsBetween = function ( a , b ) { if ( a <= b ) return this . date . getHours ( ) >= a && this . date . getHours ( ) <= b ; else return this . date . getHours ( ) >= a || this . date . getHours ( ) <= b ; } ; this . step = function ( ) { this . date = new Date ( ) ; this . isMorning = this . hoursIsBetween ( 6 , 11 ) ; this . isNoon = this . hoursIsBetween ( 12 , 14 ) ; this . isAfternoon = this . hoursIsBetween ( 15 , 17 ) ; this . isEvening = this . hoursIsBetween ( 18 , 23 ) ; this . isNight = this . hoursIsBetween ( 0 , 5 ) ; return this ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////// NoolsFire : Output node of a nools flow // ////////////////////////////////////////////////////////////////////////////// [CODESPLIT] function NoolsFire ( n ) { RED . nodes . createNode ( this , n ) ; var node = this ; node . name = n . name ; node . topic = n . topic ; node . session = RED . nodes . getNode ( n . session ) . session ; node . messages = RED . nodes . getNode ( n . session ) . messages ; RED . nodes . getNode ( n . session ) . on ( \"publish\" , function ( msg ) { if ( ! node . topic || node . topic === msg . topic ) { node . send ( msg ) ; } } ) ; node . session . on ( \"fire\" , function ( name , rule ) { node . send ( [ null , { topic : node . topic , payload : name , facts : node . session . getFacts ( ) , name : name } ] ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////// NoolsFlowNode : Configuration node containing the flow and session // ////////////////////////////////////////////////////////////////////////////// [CODESPLIT] function NoolsFlowNode ( n ) { RED . nodes . createNode ( this , n ) ; var node = this ; // node.messages contains all messages received by any assert node node . messages = { } ; node . clock = new Clock ( ) ; var publish = function ( msg ) { node . emit ( \"publish\" , msg ) ; } ; node . flow = nools . compile ( n . flow , { name : n . id , define : { Message : Message , Clock : Clock , publish : publish } } ) ; node . session = node . flow . getSession ( ) ; node . session . assert ( node . clock ) ; //Run once for init node . session . match ( ) ; node . on ( \"close\" , function ( ) { node . session . dispose ( ) ; nools . deleteFlow ( n . id ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the spherical arclength of the icosahedron s edges . Returns the arc length between two positions . [CODESPLIT] function distance ( f1_φ,   1_λ,  f _φ, f 2 λ) {   return 2 * asin ( sqrt ( pow ( sin ( ( f1_φ    2_φ)  / 2 ,   2   +  cos ( f1_φ)     os( f 2_φ)  * p w(s i n(( f 1 _λ -  2 λ) /  2 , 2 )    ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the course between two positions . [CODESPLIT] function course ( pos1 , pos2 ) { var f1_φ    os1[ 0 ] ,  f1_λ    os1[ 1 ] ,  f2_φ    os2[ 0 ] ,  f2_λ    os2[ 1 ] ;  var d = distance ( f1_φ,   1_λ,  f _φ, f 2 λ), a ,   o u se = { ;    if ( sin ( f2_λ    1_λ)  < 0   {  a = acos ( ( sin ( f2_φ)     in( f 1_φ)  * c s(d ) )   / ( i n(d )   * c s(f 1 _φ))) ;    } else { a = 2 * π    cos( ( s in( f 2_φ)  - s n(f 1 _φ) *   o (d) )   /   s n (d)   *   o (f1 _ φ)));     } course . d = d ; course . a = a ; return course ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the position halfway between two positions . Chiefly used to test interpolate . [CODESPLIT] function midpoint ( pos1 , pos2 ) { var Bx = Math . cos ( pos2 . φ)     ath. c os( p os2. λ  - p s1.λ ) ;   var By = Math . cos ( pos2 . φ)     ath. s in( p os2. λ  - p s1.λ ) ;   return { φ:   tan2( s in( p os1. φ )  + s n(p o s2.φ ) ,   sqrt ( ( cos ( pos1 . φ)     x)     c os( p os1. φ )  + B )  + B  * B )) ,   λ:   os1. λ  + a an2(B y ,  c s(p o s1.φ )  +   x   } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates buffer buf with d - 1 evenly - spaced positions between two points . [CODESPLIT] function interpolate ( f1_φ,   1_λ,  f _φ, f 2 λ, d,   u f  {   for ( var i = 1 ; i < d ; i += 1 ) { let f = i / d , Δ    istance( f 1_φ,  f _λ, f 2 φ, f2 _ );   let A = sin ( ( 1 - f ) * Δ)     in( Δ ),   B = sin ( f * Δ)     in( Δ );   let x = A * cos ( f1_φ)     os( f 1_λ)  + B * c s(f 2 _φ) *   o (f2 _ λ),   z = A * cos ( f1_φ)     in( f 1_λ)  + B * c s(f 2 _φ) *   i (f2 _ λ),   y = A * sin ( f1_φ)         in( f 2_φ);   let φ    tan2( y ,   qrt( p ow( x ,   )     ow( z ,   ) ) ) ,  λ    tan2( z ,   ) ;  buf [ 2 * ( i - 1 ) + 0 ] = φ;  buf [ 2 * ( i - 1 ) + 1 ] = λ;  } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates buffer buf from offset b with the center point of positions provided [CODESPLIT] function centroid ( buf , b , ... p ) { var n = p . length / 2 ; var sum_x = 0 , sum_z = 0 , sum_y = 0 ; for ( let i = 0 ; i < n ; i += 1 ) { let i_φ    [ 2         ] ,  i_λ    [ 2         ] ;  sum_x += cos ( i_φ)     os( i _λ);   sum_z += cos ( i_φ)     in( i _λ);   sum_y += sin ( i_φ) ;  } var x = sum_x / n , z = sum_z / n , y = sum_y / n ; var r = sqrt ( x * x + z * z + y * y ) ; var φ    sin( y     ) ,  λ    tan2( z ,   ) ;  buf [ b + 0 ] = φ;  buf [ b + 1 ] = λ;  }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the barycenter position of every field on a Sphere . [CODESPLIT] function populate ( ) { var d = this . _divisions , max_x = 2 * d - 1 , buf = new Float64Array ( ( d - 1 ) * 2 ) ; this . _positions = new Float64Array ( ( 5 * 2 * d * d + 2 ) * 2 ) ; // Determine position for polar and tropical fields using only arithmetic. this . _Fields [ 0 ] . _setPosition ( π    ,   ) ;  this . _Fields [ 1 ] . _setPosition ( π    2 ,   ) ;  for ( let s = 0 ; s < PEELS ; s += 1 ) { let λNorth                ,  λSouth                 + π /  ;   this . get ( s , d - 1 , 0 ) . _setPosition ( π        ,   North);   this . get ( s , max_x , 0 ) . _setPosition ( π    2     ,   South);   } // Determine positions for the fields along the edges using arc interpolation. if ( ( d - 1 ) > 0 ) { // d must be at least 2 for there to be fields between vertices. for ( let s = 0 ; s < PEELS ; s += 1 ) { let p = ( s + 4 ) % PEELS ; let snP = 0 , ssP = 1 , cnT = this . get ( s , d - 1 , 0 ) . _i , pnT = this . get ( p , d - 1 , 0 ) . _i , csT = this . get ( s , max_x , 0 ) . _i , psT = this . get ( p , max_x , 0 ) . _i ; // north pole to current north tropical pentagon interpolate ( this . _positions [ 2 * snP + 0 ] , this . _positions [ 2 * snP + 1 ] , this . _positions [ 2 * cnT + 0 ] , this . _positions [ 2 * cnT + 1 ] , d , buf ) ; for ( let i = 1 ; i < d ; i += 1 ) this . get ( s , i - 1 , 0 ) . _setPosition ( buf [ 2 * ( i - 1 ) + 0 ] , buf [ 2 * ( i - 1 ) + 1 ] ) ; // current north tropical pentagon to previous north tropical pentagon interpolate ( this . _positions [ 2 * cnT + 0 ] , this . _positions [ 2 * cnT + 1 ] , this . _positions [ 2 * pnT + 0 ] , this . _positions [ 2 * pnT + 1 ] , d , buf ) ; for ( let i = 1 ; i < d ; i += 1 ) this . get ( s , d - 1 - i , i ) . _setPosition ( buf [ 2 * ( i - 1 ) + 0 ] , buf [ 2 * ( i - 1 ) + 1 ] ) ; // current north tropical pentagon to previous south tropical pentagon interpolate ( this . _positions [ 2 * cnT + 0 ] , this . _positions [ 2 * cnT + 1 ] , this . _positions [ 2 * psT + 0 ] , this . _positions [ 2 * psT + 1 ] , d , buf ) ; for ( let i = 1 ; i < d ; i += 1 ) this . get ( s , d - 1 , i ) . _setPosition ( buf [ 2 * ( i - 1 ) + 0 ] , buf [ 2 * ( i - 1 ) + 1 ] ) ; // current north tropical pentagon to current south tropical pentagon interpolate ( this . _positions [ 2 * cnT + 0 ] , this . _positions [ 2 * cnT + 1 ] , this . _positions [ 2 * csT + 0 ] , this . _positions [ 2 * csT + 1 ] , d , buf ) ; for ( let i = 1 ; i < d ; i += 1 ) this . get ( s , d - 1 + i , 0 ) . _setPosition ( buf [ 2 * ( i - 1 ) + 0 ] , buf [ 2 * ( i - 1 ) + 1 ] ) ; // current south tropical pentagon to previous south tropical pentagon interpolate ( this . _positions [ 2 * csT + 0 ] , this . _positions [ 2 * csT + 1 ] , this . _positions [ 2 * psT + 0 ] , this . _positions [ 2 * psT + 1 ] , d , buf ) ; for ( let i = 1 ; i < d ; i += 1 ) this . get ( s , max_x - i , i ) . _setPosition ( buf [ 2 * ( i - 1 ) + 0 ] , buf [ 2 * ( i - 1 ) + 1 ] ) ; // current south tropical pentagon to south pole interpolate ( this . _positions [ 2 * csT + 0 ] , this . _positions [ 2 * csT + 1 ] , this . _positions [ 2 * ssP + 0 ] , this . _positions [ 2 * ssP + 1 ] , d , buf ) ; for ( let i = 1 ; i < d ; i += 1 ) this . get ( s , max_x , i ) . _setPosition ( buf [ 2 * ( i - 1 ) + 0 ] , buf [ 2 * ( i - 1 ) + 1 ] ) ; } } // Determine positions for fields between edges using interpolation. if ( ( d - 2 ) > 0 ) { // d must be at least 3 for there to be fields not along edges. for ( let s = 0 ; s < PEELS ; s += 1 ) { for ( let x = 0 ; x < d * 2 ; x += 1 ) { // for each column, fill in values for fields between edge fields, // whose positions were defined in the previous block. if ( ( x + 1 ) % d > 0 ) { // ignore the columns that are edges. let j = d - ( ( x + 1 ) % d ) , // the y index of the field in this column that is along a diagonal edge n1 = j - 1 , // the number of unpositioned fields before j n2 = d - 1 - j , // the number of unpositioned fields after j f1 = this . get ( s , x , 0 ) . _i , // the field along the early edge f2 = this . get ( s , x , j ) . _i , // the field along the diagonal edge f3 = this . get ( s , x , d - 1 ) . _adjacentFields [ 2 ] . _i ; // the field along the later edge, // which will necessarily belong to // another section. interpolate ( this . _positions [ 2 * f1 + 0 ] , this . _positions [ 2 * f1 + 1 ] , this . _positions [ 2 * f2 + 0 ] , this . _positions [ 2 * f2 + 1 ] , n1 + 1 , buf ) ; for ( let i = 1 ; i < j ; i += 1 ) this . get ( s , x , i ) . _setPosition ( buf [ 2 * ( i - 1 ) + 0 ] , buf [ 2 * ( i - 1 ) + 1 ] ) ; interpolate ( this . _positions [ 2 * f2 + 0 ] , this . _positions [ 2 * f2 + 1 ] , this . _positions [ 2 * f3 + 0 ] , this . _positions [ 2 * f3 + 1 ] , n2 + 1 , buf ) ; for ( let i = j + 1 ; i < d ; i += 1 ) this . get ( s , x , i ) . _setPosition ( buf [ 2 * ( i - j - 1 ) + 0 ] , buf [ 2 * ( i - j - 1 ) + 1 ] ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override request process so it first fetches the data needed for a page transition . [CODESPLIT] function ( req , cb ) { req = request . normalizeRequest ( req ) ; var page ; try { page = this . createPageForRequest ( req ) ; } catch ( err ) { if ( cb ) return cb ( err ) else throw err ; } var needData = typeof page . fetchData === 'function' && ! this . state . request . data ; if ( request . isEqual ( this . state . request , req ) && ! needData ) return ; fetchDataForRequest ( this , page , req , function ( err , req ) { if ( err ) { if ( cb ) return cb ( err ) else throw err ; } this . setState ( { request : req , page : page } ) ; } . bind ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a set of OGR Parameters for an export [CODESPLIT] function create ( format , options ) { const ogrFormat = ogrFormats [ format ] // shapefiles cannot be streamed out of ogr2ogr const output = format === 'zip' ? ` ${ options . path || '.' } ${ options . name } ` : '/vsistdout/' const input = options . input || 'layer.vrt' let cmd = [ '--config' , 'SHAPE_ENCODING' , 'UTF-8' , '-f' , ogrFormat , output , input ] options . geometry = options . geometry && options . geometry . toUpperCase ( ) || 'NONE' if ( format === 'csv' ) cmd = csvParams ( cmd , options ) if ( format === 'zip' ) cmd = shapefileParams ( cmd , options ) if ( format === 'georss' ) cmd = georssParams ( cmd , options ) return finishOgrParams ( cmd ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add parameters specific to a csv export [CODESPLIT] function csvParams ( cmd , options ) { cmd . push ( '-lco' , 'WRITE_BOM=YES' ) const hasPointGeom = options . geometry === 'POINT' const fields = options . fields . join ( '|' ) . toLowerCase ( ) . split ( '|' ) const hasXY = fields . indexOf ( 'x' ) > - 1 && fields . indexOf ( 'y' ) > - 1 if ( hasPointGeom && ! hasXY ) cmd = cmd . concat ( [ '-lco' , 'GEOMETRY=AS_XY' ] ) return cmd }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add parameters specific to a shapefile export [CODESPLIT] function shapefileParams ( cmd , options ) { // make sure geometries are still written even if the first is null if ( options . geometry !== 'NONE' ) cmd . push ( '-nlt' , options . geometry . toUpperCase ( ) ) cmd . push ( '-fieldmap' , 'identity' ) if ( ! options . ignoreShpLimit ) cmd . push ( '-lco' , '2GB_LIMIT=yes' ) if ( options . srs ) cmd . push ( '-t_srs' , options . srs ) return cmd }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates edges ** between field barycenters ** and returns an array of vertices and a corresponding array of faces to use in three . js . Bear in mind this is not necessarily the most accurate representation of the model . [CODESPLIT] function barycenterVerticesAndFaces ( sphere , options , done ) { var n = sphere . _Fields . length , positions = new Float32Array ( n * 3 ) , indices = sphere . _interfieldTriangles , colors = new Float32Array ( indices . length * 3 ) ; for ( let f = 0 ; f < sphere . _Fields . length ; f += 1 ) { let field = sphere . _Fields [ f ] , f_φ    phere. _ positions[ 2         ] ,  f_λ    phere. _ positions[ 2         ] ,  color = options . colorFn . call ( field ) ; positions [ f * 3 + 0 ] = cos ( f_φ)     os( f _λ);   /  x positions [ f * 3 + 2 ] = cos ( f_φ)     in( f _λ);   /  z positions [ f * 3 + 1 ] = sin ( f_φ) ;   / y colors [ f * 3 + 0 ] = color . r ; colors [ f * 3 + 1 ] = color . g ; colors [ f * 3 + 2 ] = color . b ; } // normals are exactly positions, as long as radius is 1 var normals = positions . slice ( 0 ) ; if ( done ) done . call ( null , null , { positions , normals , indices , colors } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates edges between actual fields and returns an array of vertices and a corresponding array of faces to use in three . js . This representation of the model is popularly depicted in the reference materials . [CODESPLIT] function fieldVerticesAndFaces ( sphere , options , done ) { // counter-clockwise face-vertex orders const PENT_FACES = [ 0 , 2 , 1 , /**/ 0 , 4 , 2 , /**/ 4 , 3 , 2 ] , HEX_FACES = [ 0 , 2 , 1 , /**/ 0 , 3 , 2 , /**/ 0 , 5 , 3 , /**/ 5 , 4 , 3 ] , PENT_FACES_CW = [ 1 , 2 , 0 , /**/ 2 , 4 , 0 , /**/ 2 , 3 , 4 ] ; var interfieldTriangles = sphere . _interfieldTriangles , nPolyEdgeVerts = interfieldTriangles . length / 3 , nPolys = sphere . _Fields . length ; var nDistinctVertices = nPolys * 6 - 12 , // 6 vertices for each poly (-12 vertices for the 12 pentagons) nTriangles = nPolys * 4 - 12 ; // 4 triangles to each hexagon, 3 to each pentagon of which there are 12. // support maps var fieldPosMap = intArr ( nDistinctVertices , nPolys ) , indexedPositions = new Float32Array ( nPolyEdgeVerts * 3 ) ; // maps for the GPU var indices = intArr ( nDistinctVertices , nTriangles * 3 ) , positions = new Float32Array ( nDistinctVertices * 3 ) , normals = new Float32Array ( nDistinctVertices * 3 ) , colors = new Float32Array ( nDistinctVertices * 3 ) ; // populate the cartesian coordinates of positions for ( let v = 0 ; v < nPolyEdgeVerts ; v += 1 ) { let c_φ    phere. _ interfieldCentroids[ 2         ] ,  c_λ    phere. _ interfieldCentroids[ 2         ] ;  indexedPositions [ 3 * v + 0 ] = cos ( c_φ)     os( c _λ);   /  x indexedPositions [ 3 * v + 2 ] = cos ( c_φ)     in( c _λ);   /  z indexedPositions [ 3 * v + 1 ] = sin ( c_φ) ;   / y } var c = 0 , t = 0 ; for ( let f = 0 ; f < nPolys ; f += 1 ) { let field = sphere . _Fields [ f ] , sides = field . _adjacentFields . length , color = options . colorFn . call ( field ) , f_φ    phere. _ positions[ 2         ] ,  f_λ    phere. _ positions[ 2         ] ,  polyPosIndices = [ ] ; fieldPosMap [ f ] = c ; for ( let s = 0 ; s < sides ; s += 1 ) { let cc = ( c + s ) , fi = sphere . _interfieldIndices [ 6 * f + s ] ; polyPosIndices . push ( fi ) ; positions [ cc * 3 + 0 ] = indexedPositions [ fi * 3 + 0 ] ; positions [ cc * 3 + 1 ] = indexedPositions [ fi * 3 + 1 ] ; positions [ cc * 3 + 2 ] = indexedPositions [ fi * 3 + 2 ] ; colors [ cc * 3 + 0 ] = color . r ; colors [ cc * 3 + 1 ] = color . g ; colors [ cc * 3 + 2 ] = color . b ; normals [ cc * 3 + 0 ] = cos ( f_φ)     os( f _λ);   normals [ cc * 3 + 2 ] = cos ( f_φ)     in( f _λ);   normals [ cc * 3 + 1 ] = sin ( f_φ) ;  } let faces ; if ( f === 1 ) { faces = PENT_FACES_CW ; } else { faces = sides === 5 ? PENT_FACES : HEX_FACES ; } for ( let v = 0 ; v < faces . length ; v += 1 ) { let tt = ( t + v ) ; indices [ tt ] = c + faces [ v ] ; } c += sides ; t += faces . length ; } done . call ( null , null , { positions , indices , normals , colors } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a field s edge vertices and its bounds . Latitudinal coordinates may be greater than π if the field straddles the meridian across from 0 . [CODESPLIT] function _fieldGeometry ( ) { const ifi = this . _parent . _interfieldIndices , ifc = this . _parent . _interfieldCentroids , i = this . _i ; var max_φ    I nfinity,  min_φ    nfinity,  max_λ    I nfinity,  min_λ    nfinity,  mid_λ    his. _ parent. _ positions[ 2         ] ,  vertices = [ ] ; for ( let v = 0 ; v < this . _adjacentFields . length ; v += 1 ) { let φ    fc[ 2     fi[ 6         ]     ] ,  λ    fc[ 2     fi[ 6         ]     ] ;  max_φ    ax( m ax_φ,  φ ;   min_φ    in( m in_φ,  φ ;   max_λ    ax( m ax_λ,  λ ;   min_λ    in( m in_λ,  λ ;   vertices . push ( [ λ,   ]) ;   } if ( i === 0 ) { max_φ     / 2   } if ( i === 1 ) { min_φ     / - ;   } if ( i < 2 ) { min_λ    π ;  max_λ    ;  vertices = [ [ min_λ,   ax_φ],   [ max_λ,   ax_φ],   [ max_λ,   in_φ],   [ min_λ,   in_φ]  ] ; } else if ( max_λ      &  in_λ < 0 &  ( i d_λ <     -   |   id λ > π    )) {     // this spans the meridian, so shift negative λ values past π and recalculate latitudinal bounds max_λ    I nfinity;  min_λ    nfinity;  for ( let v = 0 ; v < vertices . length ; v += 1 ) { if ( vertices [ v ] [ 0 ] < 0 ) vertices [ v ] [ 0 ] += τ;  max_λ    ax( m ax_λ,  v rtices[v ] [ 0 ] ) ;   min_λ    in( m in_λ,  v rtices[v ] [ 0 ] ) ;   } } return { min_φ,  max_φ,  min_λ,  max_λ,  vertices } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes booleans indicating which pixel corners lay inside a field s edges to a bitmap . Returns the bounds within which writing took place . [CODESPLIT] function _populateSelectionGrid ( bmp , geo , w , h ) { var w_rect = τ    ,  h_rect = π    ;  var min_x = floor ( geo . min_λ    _rect        ) ,  max_x = ceil ( geo . max_λ    _rect        ) ,  min_y = floor ( geo . min_φ    _rect        ) ,  max_y = ceil ( geo . max_φ    _rect        ) ;  for ( let x = min_x ; x <= max_x ; x += 1 ) { for ( let y = min_y ; y <= max_y ; y += 1 ) { bmp . write ( x % w , y , inside ( [ x * w_rect - π,       _rect     / 2 ,   geo . vertices ) ) ; } } return { min_x , max_x , min_y , max_y } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A function that sets field data based on raster data . A flat array of numbers data is supplied representing height rows of width identical rectangles each rectangle comprising depth points of data . A plate carrée projection is assumed . [CODESPLIT] function fromRaster ( data , width , height , depth , map , done ) { var sphere = this ; populateInterfieldData . call ( sphere ) ; var bmp = new Bitmap ( width , height ) ; sphere . _Fields . forEach ( function ( field ) { var geo = _fieldGeometry . call ( field ) , selection = _populateSelectionGrid ( bmp , geo , width , height ) ; var valSums = [ ] , weightSum = 0 ; for ( let z = 0 ; z < depth ; z += 1 ) { valSums [ z ] = 0 ; } for ( let x = selection . min_x ; x < selection . max_x ; x += 1 ) { for ( let y = selection . min_y ; y < selection . max_y ; y += 1 ) { let w = _testPoints ( bmp , x , y ) / 4 ; for ( let z = 0 ; z < depth ; z += 1 ) { valSums [ z ] += data [ ( height - y - 1 ) * width * depth + ( width - x - 1 ) * depth + z ] * w ; } weightSum += w ; } } if ( weightSum <= 0 ) debugger ; // weight sum should never be non-positive map . apply ( field , valSums . map ( ( val ) => { return val / weightSum } ) ) ; bmp . clear ( selection . max_x - selection . min_x , selection . max_y - selection . min_y , selection . min_x , selection . min_y ) ; } ) ; done ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "查找节点，返回一个可操作的节点数组 [CODESPLIT] function tethys ( selector , context ) { var nodes = [ ] ; // 把参数转换为包含Node的数组 if ( selector . each && selector . on ) { // tethys 对象 return selector ; } else if ( typeof selector === 'string' ) { // html代码或选择器 if ( selector . match ( / ^[^\\b\\B]*\\< / ) ) { // html代码 nodes = tethys . parseHtml ( selector ) ; } else { // 选择器 nodes = ( context || document ) . querySelectorAll ( selector ) ; } ; } else if ( Array . isArray ( selector ) || selector . constructor === NodeList ) { // 包含节点的数组或NodeList nodes = selector ; } else { // 节点 nodes = [ selector ] ; } ; // 当Node被appendChild方法添加到其它元素中后，该Node会被从它所在的NodeList中移除 // 为了避免这种情况，我们要把NodeList转换成包含Node的数组 nodes = Array . prototype . map . call ( nodes , function ( n ) { return n ; } ) ; // 给数组添加dom操作方法 tethys . extend ( nodes , tethys . fn ) ; return nodes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "绑定事件 [CODESPLIT] function ( events , fn ) { events = events . split ( / \\s*\\,\\s* / ) ; return this . each ( function ( el ) { fn = fn . bind ( el ) ; events . forEach ( function ( event ) { el . addEventListener ( event , fn ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置css css ( color red ) css ( { color : red } ) [CODESPLIT] function ( key , value ) { var format = function ( key ) { return key . replace ( / (-([a-z])) / g , function ( s , s1 , s2 ) { return s2 . toUpperCase ( ) ; } ) ; } ; return keyValue . call ( this , arguments , function ( el ) { return el . style [ format ( key ) ] ; } , function ( el , key , attrs ) { el . style [ format ( key ) ] = attrs [ key ] + '' ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置或者返回属性 [CODESPLIT] function ( key , value ) { return keyValue . call ( this , arguments , function ( el ) { return el . getAttribute ( key ) ; } , function ( el , key , attrs ) { el . setAttribute ( key , attrs [ key ] + '' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "检查是否有class [CODESPLIT] function ( cls ) { var has = false , reg = new RegExp ( '\\\\b' + cls + '\\\\b' ) ; this . each ( function ( el ) { has = has || ! ! el . className . match ( reg ) ; } ) ; return has ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "显示 [CODESPLIT] function ( ) { return this . each ( function ( el ) { if ( el . style . display === 'none' ) { el . style . display = el . getAttribute ( 'o-d' ) || '' ; } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "隐藏 [CODESPLIT] function ( ) { return this . each ( function ( el ) { if ( el . style . display !== 'none' ) { el . setAttribute ( 'o-d' , el . style . display ) ; el . style . display = 'none' ; } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "切换显示隐藏 [CODESPLIT] function ( ) { return this . each ( function ( el ) { var e = $ ( el ) ; e . css ( \"display\" ) == \"none\" ? e . show ( ) : e . hide ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "追加节点 [CODESPLIT] function ( child ) { var children = tethys ( child ) ; return this . each ( function ( el ) { children . each ( function ( child , i ) { el . appendChild ( child ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "查找 [CODESPLIT] function ( selector ) { var nodes = [ ] ; this . each ( function ( el ) { tethys ( selector , el ) . each ( function ( node ) { nodes . push ( node ) ; } ) ; } ) ; return tethys ( nodes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "file changes watcher [CODESPLIT] function watcherFn ( schemaFilepath , watchInterval , reinitBabelRelayPlugin , prevMtime ) { try { let stats ; try { stats = fs . statSync ( schemaFilepath ) ; } catch ( e ) { // no problem } if ( stats ) { if ( ! prevMtime ) prevMtime = stats . mtime ; if ( stats . mtime . getTime ( ) !== prevMtime . getTime ( ) ) { prevMtime = stats . mtime ; reinitBabelRelayPlugin ( ) ; } } setTimeout ( ( ) => { watcherFn ( schemaFilepath , watchInterval , reinitBabelRelayPlugin , prevMtime ) ; } , watchInterval ) . unref ( ) ; // fs.watch blocks babel from exit, so using `setTimeout` with `unref` } catch ( e ) { log ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "babelRelayPlugin initializer [CODESPLIT] function initBabelRelayPlugin ( pluginOptions , babel , ref ) { const verbose = ! ! pluginOptions . verbose ; const schemaFilepath = pluginOptions . schema || '' ; let schema ; try { schema = fs . readFileSync ( schemaFilepath , 'utf8' ) ; } catch ( e ) { schema = null ; log ( 'Cannot load GraphQL Schema from file \\'' + schemaFilepath + '\\': ' + e ) ; } if ( schema ) { if ( verbose ) { log ( 'GraphQL Schema loaded successfully from \\'' + schemaFilepath + '\\'' ) ; } ref . babelRelayPlugin = require ( 'babel-plugin-relay' ) ( babel ) ; } else { // empty Plugin log ( 'Relay.QL will not be transformed, cause `schema.data` is empty.' ) ; ref . babelRelayPlugin = { visitor : { Program : function ( ) { } , TaggedTemplateExpression : function ( ) { } , } , } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! tap . js Copyright ( c ) 2015 Alex Gibson https : // github . com / alexgibson / tap . js / Released under MIT license [CODESPLIT] function Tap ( el ) { this . el = typeof el === 'object' ? el : document . getElementById ( el ) ; this . moved = false ; //flags if the finger has moved this . startX = 0 ; //starting x coordinate this . startY = 0 ; //starting y coordinate this . hasTouchEventOccured = false ; //flag touch event this . el . addEventListener ( 'touchstart' , this , false ) ; this . el . addEventListener ( 'mousedown' , this , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "初始化渲染 [CODESPLIT] function ( ) { var doc = document . documentElement ; this . el = $ ( tpl ) ; this . el . hide ( ) . css ( { width : doc . clientWidth + 'px' , height : doc . clientHeight + 'px' } ) ; bindTapEvent ( this . el . find ( '.as-cover' ) [ 0 ] , this . hide . bind ( this ) ) ; $ ( 'body' ) . append ( this . el ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "更新按钮 [CODESPLIT] function ( buttons ) { var buttonContainer = this . el . find ( '.as-buttons' ) ; // 清空按钮容器 buttonContainer . html ( '' ) ; // 添加取消按钮 buttons [ '取消'] =  t i .hid e .bin d (thi s );   // 遍历创建按钮 Object . keys ( buttons ) . forEach ( function ( key ) { var n = buttons [ key ] , btn = $ ( $ . tpl ( buttonTpl , { text : key } ) ) ; // 绑定tap事件 bindTapEvent ( btn [ 0 ] , function ( e ) { e . stopPropagation ( ) ; e . preventDefault ( ) ; // 如果参数是函数则调用 // 如果是字符串则认为是url直接跳转 if ( typeof this . action === 'function' ) { this . action . call ( this . context , e ) ; } else if ( typeof this . action === 'string' ) { location . href = this . action ; } ; } . bind ( { action : n , context : this } ) ) ; // 触摸反馈 btn . on ( 'touchstart' , function ( e ) { $ ( e . target ) . addClass ( 'as-active' ) ; } ) . on ( 'touchend' , function ( e ) { $ ( e . target ) . removeClass ( 'as-active' ) ; } ) ; // 添加到按钮容器 buttonContainer . append ( btn ) ; } . bind ( this ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A writable stream to act as a sink for the binary OpenPixelControl - protocol . For protocol - details see http : // openpixelcontrol . org / [CODESPLIT] function OpcParseStream ( options ) { WritableStream . call ( this ) ; options = options || { } ; this . _pushback = null ; /**\n     * @type {OpcParseStream.DataFormat}\n     */ this . dataFormat = options . dataFormat || OpcParseStream . DataFormat . BUFFER ; /**\n     * @type {number}\n     */ this . channel = ~ ~ options . channel || 0 ; /**\n     * @type {number}\n     */ this . systemId = ~ ~ options . systemId || 0xffff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cornerstone function that sends a purge request to Akamai s CCU REST API It will return a promise . options is optional . [CODESPLIT] function AkamaiPurge ( username , password , objects , options ) { var auth = { } , requestBody = { } , requestOptions ; // Ensure options exist and are the right type if ( options === undefined || ! lodash . isPlainObject ( options ) ) { options = { } ; } // Prepare authentication auth . username = username ; auth . password = password ; // Validate the given type if ( - 1 !== constants . VALID_TYPES . indexOf ( options . type ) ) { requestBody . type = options . type ; } else if ( options . hasOwnProperty ( 'type' ) ) { warn ( 'Invalid purge request type. Valid types: [' + constants . VALID_TYPES . join ( ', ' ) + ']. Given: ' + options . type ) ; } // Validate the given domain if ( - 1 !== constants . VALID_DOMAINS . indexOf ( options . domain ) ) { requestBody . domain = options . domain ; } else if ( options . hasOwnProperty ( 'domain' ) ) { warn ( 'Invalid purge request domain. Valid domains: [' + constants . VALID_DOMAINS . join ( ', ' ) + ']. Given: ' + options . domain ) ; } // Validate the given action if ( - 1 !== constants . VALID_ACTIONS . indexOf ( options . action ) ) { requestBody . action = options . action ; } else if ( options . hasOwnProperty ( 'action' ) ) { warn ( 'Invalid purge request action. Valid actions: [' + constants . VALID_ACTIONS . join ( ', ' ) + ']. Given: ' + options . action ) ; } // Append objects to the request body requestBody . objects = objects ; // Prepare request's options requestOptions = { uri : constants . AKAMAI_API_QUEUE , method : 'POST' , json : requestBody , auth : auth } ; // Reset all modifiers applyModifiers ( AkamaiPurge ) ; // Create request and return the promise return AkamaiRequest ( requestOptions ) . then ( function ( response ) { // Do some post-processing on the response response . requestBody = requestBody ; // Add a status function that pre-configured to call this purge's `progressUri` response . status = function ( ) { // If this purge doesn't have a `progressUri`, return a rejection if ( ! response . hasOwnProperty ( 'progressUri' ) ) { return when . reject ( new Error ( 'Missing progressUri from response' ) ) ; } // Otherwise, call `AkamaiStatus` return AkamaiStatus ( username , password , response . progressUri ) ; } ; return response ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new function pre - configured with the options that exist up to this point [CODESPLIT] function ( ) { // Apply the modifier to the current `options` options = lodash . assign ( options , modifier ) ; // Create new wrapper function. var AkamaiPurgeChain = function AkamaiPurgeChain ( username , password , objects ) { return AkamaiPurge ( username , password , objects , options ) ; } ; // Apply new modifiers to given wrapper function applyModifiers ( AkamaiPurgeChain , options ) ; // Expose current `options` AkamaiPurgeChain . options = options ; return AkamaiPurgeChain ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Akamai Queue Length ------------------- Request your accounts current object queue status / length . Returns an AkamaiRequest . [CODESPLIT] function AkamaiQueueLength ( username , password ) { var requestOptions , auth = { } ; auth . username = username ; auth . password = password ; requestOptions = { uri : constants . AKAMAI_API_QUEUE , method : 'GET' , auth : auth , json : true } ; return AkamaiRequest ( requestOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a Mock instance . [CODESPLIT] function Mock ( mount , options ) { // convert to absolute path this . mount = mount ; this . options = options || { } ; this . options . params = this . options . params === undefined ? true : this . options . params ; this . locator = new Locator ( mount ) ; debug ( 'mount at %s' , this . mount ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Akamai Status ------------- Request the status of a purge request . Returns an AkamaiRequest . [CODESPLIT] function AkamaiStatus ( username , password , progressUri ) { var requestOptions , auth = { } ; auth . username = username ; auth . password = password ; requestOptions = { uri : constants . AKAMAI_API_BASE + progressUri , method : 'GET' , auth : auth , json : true } ; return AkamaiRequest ( requestOptions ) . then ( function ( response ) { // Create a function to allow for easy recall of this status call response . status = function ( ) { return AkamaiStatus ( username , password , progressUri ) ; } ; return response ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Akamai Request -------------- This function will execute a web request and return a promise . [CODESPLIT] function AkamaiRequest ( requestOptions ) { // Create said promise return when . promise ( function ( resolve , reject ) { // Initiate request request ( requestOptions , function ( err , res , response ) { if ( err ) { // Reject the promise return reject ( err ) ; } // Check the status code is a 2xx code else if ( res . statusCode < 200 || res . statusCode > 299 ) { err = new Error ( 'Unexpected status code: ' + res . statusCode ) ; err . res = res ; // If the response has a `describeBy` property, we will create a helper function to // request that url to retrieve Akamai's description of this error. Obviously // the added `describe` function may not always exist. Please make sure it exists // before using. Will return a promise. if ( response && response . hasOwnProperty ( 'describedBy' ) ) { response . describe = function ( ) { return AkamaiRequest ( { method : 'GET' , uri : response . describedBy } ) ; } ; } // Expose the response err . body = response || null ; // Reject the promise return reject ( err ) ; } // Resolve the promise with the response return resolve ( response ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "written by Dean Edwards 2005 with input from Tino Zijdel Matthias Miller Diego Perini http : // dean . edwards . name / weblog / 2005 / 10 / add - event / [CODESPLIT] function dean_addEvent ( element , type , handler ) { if ( element . addEventListener ) { element . addEventListener ( type , handler , false ) ; } else { // assign each event handler a unique ID if ( ! handler . $$guid ) handler . $$guid = dean_addEvent . guid ++ ; // create a hash table of event types for the element if ( ! element . events ) element . events = { } ; // create a hash table of event handlers for each element/event pair var handlers = element . events [ type ] ; if ( ! handlers ) { handlers = element . events [ type ] = { } ; // store the existing event handler (if there is one) if ( element [ \"on\" + type ] ) { handlers [ 0 ] = element [ \"on\" + type ] ; } } // store the event handler in the hash table handlers [ handler . $$guid ] = handler ; // assign a global event handler to do all the work element [ \"on\" + type ] = handleEvent ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "globally resolve forEach enumeration [CODESPLIT] function forEach ( object , block , context ) { if ( object ) { let resolve = Object ; // default if ( object instanceof Function ) { // functions have a \"length\" property resolve = Function ; } else if ( object . forEach instanceof Function ) { // the object implements a custom forEach method so use that object . forEach ( block , context ) ; return ; } else if ( typeof object === \"string\" ) { // the object is a string resolve = String ; } else if ( typeof object . length === \"number\" ) { // the object is array-like resolve = Array ; } resolve . forEach ( object , block , context ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "merge in any properties to target that are excelusively only in source [CODESPLIT] function ( target , source ) { var skeys = _ . keys ( source ) ; _ . each ( skeys , function ( skey ) { if ( ! target [ skey ] ) { target [ skey ] = source [ skey ] ; } } ) ; return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deploy a plan See https : // github . com / nearform / nscale - planner for a plan example . [CODESPLIT] function ( origin , target , plan , mode , out , completeCb ) { var c ; var container ; var containerDef ; out . initProgress ( plan . length , '--> deploying plan...' ) ; var currProgress = 0 ; var prnt ; function tick ( command , c ) { currProgress += 1 ; out . progress ( command + ' ' + c . id + ' ' + ( c . type || '' ) ) ; } logger . info ( 'deploying plan' ) ; async . eachSeries ( plan , function ( step , cb ) { c = target . topology . containers [ step . id ] || origin . topology . containers [ step . id ] ; container = _ . cloneDeep ( c ) ; prnt = target . topology . containers [ step . parent ] || origin . topology . containers [ step . parent ] ; containerDef = _ . find ( target . containerDefinitions , function ( cdef ) { return cdef . id === container . containerDefinitionId ; } ) ; if ( ! containerDef ) { containerDef = _ . find ( origin . containerDefinitions , function ( cdef ) { return cdef . id === container . containerDefinitionId ; } ) ; } if ( container . specific && origin . topology . containers [ step . id ] && origin . topology . containers [ step . id ] . specific ) { container . specific = merge ( container . specific , origin . topology . containers [ step . id ] . specific ) ; } logger . info ( 'calling: ' + step . cmd ) ; // matchup containers to type and apply matching function remove executor var err = 'no matching container available for type' ; if ( containerDef && containerDef . type ) { _containers . getHandler ( target , containerDef . type , function ( err , impl ) { if ( err ) { return cb ( err ) ; } if ( ! impl ) { logger . error ( err ) ; return cb ( new Error ( err ) ) ; } tick ( step . cmd , container ) ; impl [ step . cmd ] ( mode , prnt . specific , target , containerDef , container , out , function ( err , newTarget , replace ) { if ( newTarget ) { target = newTarget ; if ( replace ) { _ . each ( replace , function ( repl ) { plan = sd . replaceId ( repl . oldId , repl . newId , plan ) ; } ) ; } } cb ( err ) ; } ) ; } ) ; } else { cb ( ) ; } } , function ( err ) { completeCb ( err , target ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an object for the prototype [CODESPLIT] function createObject ( proto , args ) { var instance = Object . create ( proto ) ; if ( instance . $meta . constructors ) { instance . $meta . constructors . forEach ( function ( constructor ) { constructor . apply ( instance , args ) ; } ) ; } return instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge source object into destination @see mergerProperty [CODESPLIT] function merge ( destination , source ) { for ( var property in source ) { if ( source . hasOwnProperty ( property ) ) { mergeProperty ( destination , source , property ) ; } } return destination ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge a single property [CODESPLIT] function mergeProperty ( destination , source , property ) { if ( source [ property ] instanceof Array ) { mergeAsArray ( destination , source , property ) ; } else if ( isPrimitive ( source [ property ] ) || ! isLiteral ( source [ property ] ) ) { overrideIfNotExists ( destination , source , property ) ; } else { mergeAsObject ( destination , source , property ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges arrays by concatenating them [CODESPLIT] function mergeAsArray ( destination , source , property ) { destination [ property ] = source [ property ] . concat ( destination [ property ] || [ ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges object recursively using merge function [CODESPLIT] function mergeAsObject ( destination , source , property ) { destination [ property ] = destination [ property ] || { } ; merge ( destination [ property ] , source [ property ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mixes mixin source properties into destination object unless the property starts with __ [CODESPLIT] function mix ( destination , source ) { for ( var property in source ) { if ( property . substr ( 0 , 2 ) !== \"__\" && ! ( property in destination ) ) { destination [ property ] = source [ property ] ; } } return destination ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mixes all mixins into the instance [CODESPLIT] function mixin ( instance , mixins ) { mixins . forEach ( function ( Mixin ) { mix ( instance , Mixin ) ; } ) ; return instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Coined [CODESPLIT] function Coined ( options ) { var self = this , dbType , dbDir , dbPath ; if ( ! ( this instanceof Coined ) ) { return new Coined ( options ) ; } EventEmitter . call ( this ) ; options = options || { } ; options . db = options . db || { } ; dbType = options . db . type || 'tiny' ; dbDir = dbType === 'level' ? '.coined.level' : '.coined' ; dbPath = dbType === 'level' ? path . resolve ( process . env . HOME , dbDir ) : path . resolve ( process . env . HOME , dbDir , 'db' ) ; options . db . type = options . db . type || dbType ; options . db . path = options . db . path || dbPath ; if ( options . db . clear ) { cleanup ( options . db . path ) ; } if ( options . db . type === 'level' ) { mkdirp ( options . db . path ) ; this . db = require ( 'levelup' ) ( options . db . path , { db : require ( 'leveldown' ) , valueEncoding : 'json' } ) ; } else if ( options . db . type === 'tiny' ) { mkdirp ( path . resolve ( options . db . path , '..' ) ) ; this . db = require ( 'tiny' ) . json ( { file : options . db . path , saveIndex : false , initialCache : false } ) ; } else { throw new Error ( 'Invalid DB type.' ) ; } this . options = options ; this . socketIndex = 0 ; this . crypto = options . crypto ; this . compressed = options . compressed != null ? options . compressed : true ; this . walletPath = options . walletPath || options . wallet || process . env . HOME + '/.coined/wallet.json' ; this . addr = null ; this . dust = 5460 ; this . fee = 10000 ; mkdirp ( path . dirname ( this . walletPath ) ) ; this . account = null ; this . accounts = [ ] ; this . aaccounts = { } ; this . laccounts = { } ; this . recipients = { } ; if ( options . noPreload ) { this . _clearPreload ( ) ; } this . pool = options . pool || bcoin . pool ( { size : options . size , createConnection : function ( ) { if ( self . socketIndex >= seeds . length ) { self . socketIndex = 0 ; } if ( seeds . length > 3000 ) { seeds = seeds . slice ( 0 , 1500 ) ; self . socketIndex = 0 ; } var addr = seeds [ self . socketIndex ++ ] , parts = addr . split ( ':' ) , host = parts [ 0 ] , port = + parts [ 1 ] || network . port , socket ; socket = net . connect ( port , host ) ; socket . on ( 'connect' , function ( ) { var peers = [ ] . concat ( self . pool . peers . pending , self . pool . peers . block , self . pool . peers . load ) . filter ( Boolean ) ; for ( var i = 0 ; i < peers . length ; i ++ ) { var peer = peers [ i ] ; if ( peer . socket !== socket ) { continue ; } if ( peer . version ) { return self . emit ( 'peer' , peer , socket ) ; } return peer . parser . on ( 'packet' , function callee ( payload ) { if ( payload . cmd !== 'version' ) return ; peer . removeListener ( 'packet' , callee ) ; return setImmediate ( function ( ) { self . emit ( 'peer' , peer , socket ) ; } ) ; } ) ; } self . _log ( 'Connected to %s:%d' , host , port ) ; } ) ; return socket ; } , storage : this . db , startHeight : options . startHeight , fullNode : options . fullNode // relay: options.relay } ) ; this . blockHeight = 0 ; this . on ( 'peer' , function ( peer ) { if ( ! peer . version || ! peer . socket ) { return ; } if ( peer . version . height > self . blockHeight ) { self . blockHeight = peer . version . height ; } self . _log ( 'Connected to %s:%d (%s v%s) height=%d relay=%d' , peer . socket . remoteAddress , peer . socket . remotePort , peer . version . agent , peer . version . v , peer . version . height , peer . version . relay ) ; } ) ; if ( options . noPreload ) { network . preload = network . _preload ; } this . pool . on ( 'error' , function ( err ) { self . _error ( err ) ; } ) ; this . salt = 'coined:' ; this . pending = { } ; this . loadWallet ( null , this . passphrase ) ; if ( ! this . account ) { this . createAccount ( options ) ; } // Keep track of version, handle upgrades. this . version = Coined . version ; this . previousVersion = '0.0.0' ; this . db . get ( 'meta/version' , function ( err , data ) { if ( data ) { self . previousVersion = data . version ; } return self . db . put ( 'meta/version' , { version : self . version } , function ( err ) { if ( err ) return self . _error ( err ) ; self . _log ( 'Version written: %s, previous: %s' , self . version , self . previousVersion ) ; } ) ; } ) ; // Listeners to remove on .destroy(); this . pool . _poolOnTX = null ; this . pool . _poolOnReject = null ; this . pool . _poolOnceFull = null ; this . closed = false ; this . init ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copyright 2010 James Halliday ( mail [CODESPLIT] function mkdirp ( dir , made ) { var mode = 0777 & ( ~ process . umask ( ) ) ; if ( ! made ) made = null ; dir = path . resolve ( dir ) ; try { fs . mkdirSync ( dir , mode ) ; made = made || dir ; } catch ( err0 ) { switch ( err0 . code ) { case 'ENOENT' : made = mkdirp ( path . dirname ( dir ) , made ) ; mkdirp ( dir , made ) ; break ; default : var stat ; try { stat = fs . statSync ( dir ) ; } catch ( err1 ) { throw err0 ; } if ( ! stat . isDirectory ( ) ) throw err0 ; break ; } } return made ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walker function to iterate though the collection / array / object tree [CODESPLIT] function ( obj ) { if ( _ . isArray ( obj ) ) { for ( var i = 0 ; i < obj . length ; i ++ ) { obj [ i ] = walker ( obj [ i ] ) ; } } else if ( _ . isPlainObject ( obj ) ) { var newObj = { } ; for ( var k in obj ) { if ( ! obj . hasOwnProperty ( k ) ) continue ; var include = true ; if ( options . renameFields [ k ] ) { newObj [ options . renameFields [ k ] ] = obj [ k ] ; include = false ; } for ( var rf in options . removeFields ) { if ( _ . isRegExp ( options . removeFields [ rf ] ) ) { if ( options . removeFields [ rf ] . test ( k ) ) include = false ; } else { // Assume its a function if ( options . removeFields [ rf ] . test ( obj [ k ] , k ) ) include = false ; } if ( ! include ) break ; } if ( include ) newObj [ k ] = walker ( obj [ k ] ) ; } obj = newObj ; } else if ( _ . isObject ( obj ) ) { return obj . toString ( ) ; } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回文件名字 + 后缀 [CODESPLIT] function fileext ( type , path ) { if ( ! path ) path = type , type = false ; var file_arr = path . match ( / ([^:\\\\/]*?)(?:\\.([^ :\\\\/.]*))$ / ) var fileext = file_arr [ 2 ] ; var name = file_arr [ 1 ] ; var new_name = '' switch ( type ) { case \"min\" : new_name = name + '.min.' + fileext ; break ; case \"map\" : new_name = name + '.min.map' ; break ; case \"gz\" : new_name = name + '.min.gz' ; break ; default : new_name = file_arr [ 0 ] ; } return new_name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "换算 [CODESPLIT] function format_number ( size , precision ) { var decimal , factor ; if ( precision == null ) precision = 1 ; factor = Math . pow ( 10 , precision ) ; decimal = Math . round ( size * factor ) % factor ; return parseInt ( size ) + \".\" + decimal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "输出大小 [CODESPLIT] function report_size ( file ) { return echo ( \" › \" + c c.x t erm(1 6 1)( f i le)    \"  \" + ( o rmat_number(f s ize(f i le)  / 1 24))   + \" KiB\");   }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the full head system definition ( latest revision ) [CODESPLIT] function ( identifier , target , cb ) { logger . info ( 'get head system: ' + identifier ) ; var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } _sr . getHead ( systemId , target , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the full deployed system definition [CODESPLIT] function ( identifier , target , cb ) { var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } fetchTarget ( systemId , target , function ( err , target ) { if ( err ) { return cb ( err ) ; } logger . info ( { systemId : systemId , target : target } , 'get deployed system' ) ; _sr . getDeployedRevision ( systemId , target , cb ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a new blank system [CODESPLIT] function ( user , name , namespace , cwd , cb ) { logger . info ( 'create system name: ' + name + ', namespace: ' + namespace + ', cwd: ' + cwd ) ; _sr . createSystem ( user , namespace , name , cwd , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "link a system from local fs [CODESPLIT] function ( user , path , cwd , cb ) { logger . info ( 'link system: ' + path + ', ' + cwd ) ; _sr . linkSystem ( user , path , cwd , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * unlink a system from local fs [CODESPLIT] function ( user , identifier , cb ) { var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { return cb ( new Error ( ERR_NOSYSID ) ) ; } logger . info ( 'unlink system: ' + systemId ) ; _sr . unlinkSystem ( user , systemId , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "list all of the available containers in a system [CODESPLIT] function ( identifier , revisionId , out , cb ) { logger . info ( 'list containers: ' + identifier ) ; var systemId = _sr . findSystem ( identifier ) ; var containers = { } ; if ( ! systemId ) { return cb ( new Error ( ERR_NOSYSID ) ) ; } _builder . loadTargets ( systemId , revisionId , function ( err , targets ) { if ( err ) { return cb ( err ) ; } _ . each ( targets , function ( target ) { _ . each ( target . containerDefinitions , function ( cdef ) { containers [ cdef . id ] = cdef ; } ) ; } ) ; cb ( null , _ . values ( containers ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build a container [CODESPLIT] function ( user , identifier , containerIdentifier , revision , target , out , cb ) { var containerDef ; var systemId ; systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } var systemRoot = _sr . repoPath ( systemId ) ; out . initProgress ( 9 , '--> finding container' ) ; fetchTarget ( systemId , target , revision , function ( err , target ) { if ( err ) { return cb ( err ) ; } _builder . loadMatchingTargets ( systemId , revision , target , function ( err , targets ) { if ( err ) { return cb ( err ) ; } _builder . findContainer ( systemId , revision , targets , containerIdentifier , function ( err , containerDefId , targets ) { if ( err ) { out . stdout ( err ) ; logger . error ( err ) ; return cb ( err ) ; } if ( ! containerDefId ) { out . stdout ( ERR_NOCDEF ) ; logger . error ( ERR_NOCDEF ) ; return cb ( ERR_NOCDEF ) ; } async . eachSeries ( _ . values ( targets ) , function ( json , cb ) { var root = buildSys ( json ) ; containerDef = root . containerDefByDefId ( containerDefId ) ; json . repoPath = systemRoot ; if ( ! containerDef . specific || ! containerDef . specific . repositoryUrl ) { return _builder . build ( user , systemId , targets , json , containerDef , target , out , cb ) ; } _synchrotron . synch ( json , containerDef , out , function ( err ) { if ( err ) { out . stdout ( err ) ; logger . error ( err ) ; return cb ( err ) ; } _builder . build ( user , systemId , targets , json , containerDef , target , out , cb ) ; } ) ; } , cb ) ; } ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build all containers belonging to a system in series [CODESPLIT] function ( user , systemName , revision , target , out , cb ) { var systemId = _sr . findSystem ( systemName ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } logger . info ( { systemId : systemId , revision : revision } , 'building all containers' ) ; fetchTarget ( systemId , target , revision , function ( err , target ) { if ( err ) { return cb ( err ) ; } _builder . loadMatchingTargets ( systemId , revision , target , function ( err , targets ) { if ( err ) { return cb ( err ) ; } out . stdout ( '--> building all containers for ' + targets [ Object . keys ( targets ) [ 0 ] ] . name + ' revision ' + revision + ' target ' + target ) ; var containers = _ . chain ( targets ) . filter ( function ( value , key ) { return target === 'alltargets' || key === target ; } ) . map ( function ( target ) { return _ . map ( target . containerDefinitions , function ( cdef ) { return { id : cdef . id , target : target . topology . name , type : cdef . type } ; } ) ; } ) . flatten ( ) . reduce ( function ( acc , cont ) { var notPresent = ! _ . find ( acc , function ( found ) { return found . id === cont . id && found . type === cont . type ; } ) ; if ( notPresent ) { acc . push ( cont ) ; } return acc ; } , [ ] ) . value ( ) ; async . eachSeries ( containers , function ( cont , next ) { buildContainer ( user , systemId , cont . id , revision , cont . target , out , function ( err ) { if ( err ) { out . stderr ( err ) ; } // so that buildall fails if one build fail next ( err ) ; } ) ; } , cb ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Supports target abbreviation [CODESPLIT] function ( systemId , target , revision , cb ) { if ( target === 'alltargets' ) { cb ( null , target ) ; } else { _sr . getDeployedRevisionId ( systemId , target , function ( err , deployedRevId ) { if ( typeof revision === 'function' ) { cb = revision ; if ( ! err ) { revision = deployedRevId ; } else { revision = 'latest' ; } } _builder . loadTargets ( systemId , revision , function ( err , targets ) { if ( err ) { return cb ( err ) ; } var candidates = Object . keys ( targets ) . filter ( function ( candidate ) { return candidate . indexOf ( target ) >= 0 ; } ) ; if ( candidates . length === 0 || candidates . length > 1 ) { logger . error ( ERR_NOTARGET ) ; return cb ( new Error ( ERR_NOTARGET ) ) ; } else { target = candidates [ 0 ] ; } cb ( null , target ) ; } ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "deploy the specified revision to the nominated target handle if file is missing [CODESPLIT] function ( user , identifier , revisionIdentifier , target , mode , out , cb ) { var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } fetchTarget ( systemId , target , revisionIdentifier , function ( err , target ) { if ( err ) { return cb ( err ) ; } _sr . findRevision ( systemId , revisionIdentifier , function ( err , revisionId ) { if ( err ) { out . stdout ( ERR_NOREV ) ; logger . error ( ERR_NOREV ) ; return cb ( ERR_NOREV ) ; } logger . info ( { systemId : systemId , revisionId : revisionId , environment : target } , 'deploy revision' ) ; if ( ! mode ) { mode = 'live' ; } if ( ! revisionId ) { return cb ( new Error ( 'revisionId is needed to deploy' ) ) ; } return createAnalyzeAndDeployTask ( user , systemId , revisionId , target , mode , out , cb ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "preview a system deploy [CODESPLIT] function ( user , identifier , revisionIdentifier , target , out , cb ) { logger . info ( 'preview revision: ' + identifier + ', ' + revisionIdentifier + ' ' + target ) ; deployRevision ( user , identifier , revisionIdentifier , target , 'preview' , out , function ( err ) { cb ( err , { plan : out . getPlan ( ) , ops : out . operations ( ) } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the revision history for a system [CODESPLIT] function ( identifier , cb ) { logger . info ( 'list revisions: ' + identifier ) ; if ( ! identifier ) { return cb ( new Error ( 'no identifier' ) ) ; } var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { return cb ( new Error ( 'system not found' ) ) ; } _sr . listRevisions ( systemId , function ( err , revisions ) { cb ( err , _ . first ( revisions , 20 ) ) ; //cb(err, revisions); } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get a specific revision [CODESPLIT] function ( identifier , revisionIdentifier , target , cb ) { logger . info ( 'get revision: ' + identifier + ', ' + revisionIdentifier ) ; var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } fetchTarget ( systemId , target , revisionIdentifier , function ( err , target ) { if ( err ) { return cb ( err ) ; } _sr . findRevision ( systemId , revisionIdentifier , function ( err , revisionId ) { if ( err ) { return cb ( err ) ; } _sr . getRevision ( systemId , revisionId , target , cb ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get timeline [CODESPLIT] function ( identifier , cb ) { var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } _sr . getTimeline ( systemId , function ( err , timeline ) { cb ( err , { entries : timeline } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compile the system into the various targets and commit them to the repository [CODESPLIT] function ( user , identifier , comment , out , cb ) { logger . info ( 'compile system: ' + identifier ) ; var systemId = _sr . findSystem ( identifier ) ; var system ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } var repoPath = _sr . repoPath ( systemId ) ; _compiler . compile ( systemId , repoPath , out , function ( err , systems ) { if ( err ) { return cb ( err ) ; } async . eachSeries ( _ . keys ( systems ) , function ( key , next ) { system = systems [ key ] ; _sr . writeFile ( system . id , key + '.json' , JSON . stringify ( system , null , 2 ) , next ) ; } , function ( err ) { cb ( err ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "commit the system [CODESPLIT] function ( user , identifier , comment , out , cb ) { logger . info ( 'commit system: ' + identifier ) ; var systemId = _sr . findSystem ( identifier ) ; _sr . commitRevision ( user , systemId , comment , function ( err , revisionId ) { _sr . getDeployedTargets ( systemId , function ( err , targets ) { if ( targets ) { async . eachSeries ( targets , function ( target , next ) { if ( target . commit === 'edits' ) { _sr . markDeployedRevision ( user , systemId , revisionId , target . env , function ( ) { next ( ) ; } ) ; } else { next ( ) ; } } , function ( ) { cb ( err , revisionId ) ; } ) ; } else { cb ( err , revisionId ) ; } } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "asynchronous task [CODESPLIT] function ( src , destination ) { grunt . verbose . writeln ( \"Adding entries to be coffeeified/browserified: \" + src ) ; var browserifyInstance = browserify ( src ) ; return { dest : destination , instance : browserifyInstance } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finalize the task . [CODESPLIT] function finalizeBuild ( sourceReport ) { // Something went wrong. Fail the build. if ( errorCount > 0 ) { grunt . fail . warn ( \"Coffeeification failed.\" ) ; // The build succeeded. Call done to  // finish the grunt task. } else { done ( \"Coffeified \" + sourceReport . count + \": \" + sourceReport . locations ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inject necessary code into the file app . js [CODESPLIT] function injectCode ( ) { var fullpath = path . join ( rootpath , \"app.js\" ) ; var source = fs . readFileSync ( fullpath , 'utf8' ) ; var test = / \\/\\/ALLOY-RESOLVER / . test ( source ) ; logger . trace ( \"CODE INJECTED ALREADY: \" + test ) ; if ( ! test ) { source = source . replace ( / (var\\s+Alloy[^;]+;) / g , \"$1\\n//ALLOY-RESOLVER\\nvar process=require('/process');\\nAlloy.resolve=new (require('/resolver'))().resolve;\\n\" ) ; fs . writeFileSync ( fullpath , source ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fix module resolution in all found javascript files [CODESPLIT] function fixFiles ( ) { logger . trace ( \"inside fixFiles()\" ) ; _ . each ( registry . files , function ( file ) { var fullpath = path . join ( rootpath , file ) ; var basepath = path . posix . dirname ( file ) ; var basefile = path . posix . resolve ( file ) ; var source = fs . readFileSync ( fullpath , 'utf8' ) ; logger . trace ( \"fixing file: \" + fullpath ) ; var requireRegex = / (require)\\s*\\(((?:[^)(]+|\\((?:[^)(]+|\\([^)(]*\\))*\\))*)\\) / g ; var staticRequireRegex = / (require)(?:\\(\\s*['\"])([^'\"]+)(?:['\"]\\s*\\)) / g ; source = source . replace ( requireRegex , function ( $1 , $2 , $3 ) { var requestedModule = $2 ; if ( staticRequireRegex . test ( $1 ) ) { var staticRequireSource = $1 ; staticRequireSource = staticRequireSource . replace ( staticRequireRegex , function ( $1 , $2 , $3 ) { var resolved_path = resolver . resolve ( $3 , basepath ) ; return 'require(\"' + resolved_path + '\")' ; } ) ; return staticRequireSource ; } else { return 'require(Alloy.resolve(' + $3 + ', \"' + basepath + '\"))' ; } } ) ; fs . writeFileSync ( fullpath , source , { mode : 0o755 } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace backslashes for cross - platform usage Adapted from https : // github . com / sindresorhus / slash [CODESPLIT] function replaceBackSlashes ( input ) { var isExtendedLengthPath = / ^\\\\\\\\\\?\\\\ / . test ( input ) ; var hasNonAscii = / [^\\x00-\\x80]+ / . test ( input ) ; if ( isExtendedLengthPath || hasNonAscii ) { return input ; } return input . replace ( / \\\\ / g , '/' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find all files that match extension criteria [CODESPLIT] function findFiles ( rootpath , patterns ) { logger . trace ( \"inside findFiles()\" ) ; var patterns = patterns || [ '**' ] ; if ( _ . isString ( patterns ) ) { patterns = [ patterns ] ; } var files = _ . map ( wrench . readdirSyncRecursive ( rootpath ) , function ( filename ) { return path . posix . sep + replaceBackSlashes ( filename ) ; } ) ; var matchedFiles = match ( files , patterns , { nocase : true , matchBase : true , dot : true , } ) ; return _ . filter ( matchedFiles , function ( file ) { return ! fs . statSync ( path . join ( rootpath , file ) ) . isDirectory ( ) ; } ) || [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find items in array that match a set of patterns Adapted from https : // github . com / sindresorhus / multimatch [CODESPLIT] function match ( list , patterns , options ) { list = list || [ ] ; patterns = patterns || [ ] ; if ( _ . isString ( patterns ) ) { patterns = [ patterns ] ; } if ( list . length === 0 || patterns . length === 0 ) { return [ ] ; } options = options || { } ; return patterns . reduce ( function ( ret , pattern ) { var process = _ . union if ( pattern [ 0 ] === '!' ) { pattern = pattern . slice ( 1 ) ; process = _ . difference ; } return process ( ret , minimatch . match ( list , pattern , options ) ) ; } , [ ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find and process all files [CODESPLIT] function loadFiles ( ) { logger . trace ( \"inside loadFiles()\" ) ; var allfiles = findFiles ( rootpath , includes ) ; var filepaths = _ . filter ( allfiles , function ( filepath ) { return ! / .+(package\\.json) / . test ( filepath ) ; } ) ; _ . forEach ( filepaths , function ( filepath ) { registry . files . push ( filepath ) ; } ) ; var packagepaths = _ . filter ( allfiles , function ( filepath ) { return ( / .+(package\\.json) / . test ( filepath ) ) ; } ) ; _ . forEach ( packagepaths , function ( filepath ) { var content = fs . readFileSync ( path . posix . join ( rootpath , filepath ) , 'utf8' ) ; var json = JSON . parse ( content ) ; if ( json . main ) { registry . directories . push ( { id : path . posix . dirname ( filepath ) , path : path . posix . resolve ( path . posix . join ( path . posix . dirname ( filepath ) , json . main ) ) } ) ; } } ) ; var indexpaths = _ . filter ( allfiles , function ( filepath ) { return ( / .+(index\\.js) / . test ( filepath ) ) ; } ) ; _ . forEach ( indexpaths , function ( filepath ) { var existingdir = _ . find ( registry . directories , function ( dir ) { return dir . id === path . posix . dirname ( filepath ) ; } ) ; if ( ! existingdir ) { registry . directories . push ( { id : path . posix . dirname ( filepath ) , path : filepath } ) ; } } ) ; return registry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write registry file to resolver . js [CODESPLIT] function writeRegistry ( ) { logger . trace ( \"inside writeRegistry()\" ) ; var filepath = path . join ( rootpath , \"resolver.js\" ) ; var content = fs . readFileSync ( filepath , 'utf8' ) ; var regex = / (var\\s+registry\\s+=\\s+)[^;]*(;) / g ; var modified = content . replace ( regex , \"$1\" + JSON . stringify ( registry ) + \"$2\" ) ; fs . writeFileSync ( filepath , modified ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------------------------- Public -------------------------------------------------------------------------- Returns the first letter of a string regardless of whitespace [CODESPLIT] function getFirstLetter ( text ) { var matches = text . match ( firstLetterRegex ) ; if ( null === matches ) { return '' ; } // Ignore JSDoc blocks if ( '@' === matches [ 1 ] ) { return '' ; } return matches [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "actions [CODESPLIT] function setTheme ( theme ) { const navigationOptions = getNavigationOptions ( theme ) const contentOffset = theme . defaultValues . colors . headerOpacity < 1 ? ( theme . systemValues . isIOS ? theme . systemValues . statusBarHeight : 0 ) + theme . systemValues . navigationBarHeight : 0 return { type : CONSTANTS . theme . setTheme , theme , navigationOptions , // childNavigationOptions, contentOffset , } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reducer [CODESPLIT] function themeReducer ( state = initialState , action ) { switch ( action . type ) { case CONSTANTS . theme . setTheme : return { ... state , theme : action . theme , navigationOptions : action . navigationOptions , contentOffset : action . contentOffset , } default : return state } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "URI // FUNCTION : uri ( value ) Validates if a value is a URI . [CODESPLIT] function uri ( val ) { var parts , scheme , authority , path ; if ( ! isString ( val ) ) { return false ; } // [1] Check for illegal characters: if ( ILLEGALS . test ( val ) ) { return false ; } // [2] Check for incomplete HEX escapes: if ( HEX1 . test ( val ) || HEX2 . test ( val ) ) { return false ; } // [3] Split the string into various URI components: parts = val . match ( URI ) ; scheme = parts [ 1 ] ; authority = parts [ 2 ] ; path = parts [ 3 ] ; // [4] Scheme is required and must be valid: if ( ! scheme || ! scheme . length || ! SCHEME . test ( scheme . toLowerCase ( ) ) ) { return false ; } // [5] If authority is not present, path must not begin with a '//': if ( ! authority && PATH . test ( path ) ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the container and update all instantiations of the container with the new speicific block and replace identifiers for new uuids [CODESPLIT] function build ( mode , system , cdef , out , cb ) { _containers . getHandler ( system , cdef . type , function ( err , container ) { if ( err ) { return cb ( err ) ; } if ( ! container ) { err = new Error ( 'no matching container available for type: ' + cdef . type ) ; logger . error ( err . message ) ; return cb ( err ) ; } if ( container . build ) { out . progress ( '--> executing container specific build for ' + cdef . id ) ; logger . info ( { containerDefinition : cdef . id } , 'executing container specific build' ) ; container . build ( mode , system , cdef , out , function ( err , specific ) { if ( err ) { logger . error ( err ) ; out . stdout ( err ) ; return cb ( err ) ; } out . progress ( '--> ' + cdef . id + ' built' ) ; logger . info ( { containerDefinition : cdef . id } , 'built' ) ; cb ( err ) ; } ) ; } else { out . progress ( '--> no need to build ' + cdef . id ) ; cb ( null , { } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find the container in the supplied target files return the container with the highest buildHead number [CODESPLIT] function findContainer ( systemId , revision , targets , containerIdentifier , cb ) { var cdefId ; var types = [ ] ; async . filter ( _ . keys ( targets ) , function ( key , next ) { _sr . findContainer ( systemId , revision , containerIdentifier , key , function ( err , containerDefId , cdef ) { var def ; if ( ! err && containerDefId ) { cdefId = containerDefId ; def = _ . find ( targets [ key ] . containerDefinitions , function ( def ) { return def . id === cdefId ; } ) ; if ( types . indexOf ( def . type ) < 0 ) { types . push ( def . type ) ; return next ( true ) ; } } next ( false ) ; } ) ; } , function ( keys ) { var result = keys . reduce ( function ( acc , key ) { acc [ key ] = targets [ key ] ; return acc ; } , { } ) ; cb ( null , cdefId , result ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Merge emoji and github - emoji ( punctuation marks symbols and words ) into an EmoticonNode . [CODESPLIT] function mergeEmoji ( child , index , parent ) { var siblings = parent . children var value = toString ( child ) var siblingIndex var node var nodes var subvalue var left var right var leftMatch var rightMatch var start var pos var end var replace var startIndex var nextSibling var nextNextSibling var possibleEmoji var maxSiblingIndex var loopIndex var lastSibling var lastSiblingIndex if ( child . type === 'WordNode' ) { /* 1️⃣ — sometimes a unicode emoji is marked as a word. Mark it as\n     * an `EmoticonNode`. */ if ( own . call ( unicodes , value ) ) { node = { type : EMOTICON_NODE , value : value } if ( child . position ) { node . position = child . position } siblings [ index ] = node } else { /* ❤️ — Sometimes a unicode emoji is split in two.  Remove the last\n       * and add its value to the first. */ node = siblings [ index - 1 ] if ( node && own . call ( unicodes , toString ( node ) + value ) ) { node . type = EMOTICON_NODE node . value = toString ( node ) + value if ( child . position && node . position ) { node . position . end = child . position . end } siblings . splice ( index , 1 ) return index } } } else if ( own . call ( unicodes , value ) ) { child . type = EMOTICON_NODE startIndex = index + 1 nextSibling = siblings [ startIndex ] if ( ! nextSibling ) { return } if ( nextSibling . type === 'WordNode' ) { /* 🏌 — Normal emoji. */ if ( ! isVarianceSelector ( nextSibling ) ) { return } possibleEmoji = value + toString ( nextSibling ) maxSiblingIndex = siblings . length loopIndex = startIndex + 1 while ( loopIndex < maxSiblingIndex && loopIndex - startIndex < 5 && siblings [ loopIndex ] . type !== 'WordNode' ) { possibleEmoji += toString ( siblings [ loopIndex ] ) loopIndex ++ } lastSibling = siblings [ loopIndex ] if ( lastSibling && lastSibling . type === 'WordNode' ) { possibleEmoji += toString ( lastSibling ) } /* 🏌️‍♀️ — Emoji with variance selector. */ if ( own . call ( unicodes , possibleEmoji ) ) { child . value = possibleEmoji if ( child . position && lastSibling . position ) { child . position . end = lastSibling . position . end } siblings . splice ( index + 1 , loopIndex - index ) return index + 1 } /* 👨‍❤️‍💋‍👨 — combined emoji. */ } else if ( nextSibling . type === 'SymbolNode' ) { possibleEmoji = value + toString ( nextSibling ) maxSiblingIndex = siblings . length loopIndex = startIndex + 1 while ( loopIndex < maxSiblingIndex && loopIndex - startIndex < 5 && ( siblings [ loopIndex ] . type === 'SymbolNode' || ( siblings [ loopIndex ] . type === 'WordNode' && isVarianceSelector ( siblings [ loopIndex ] ) ) ) ) { possibleEmoji += toString ( siblings [ loopIndex ] ) loopIndex ++ } if ( own . call ( unicodes , possibleEmoji ) ) { child . value = possibleEmoji lastSiblingIndex = loopIndex - 1 lastSibling = siblings [ lastSiblingIndex ] if ( child . position && lastSibling . position ) { child . position . end = lastSibling . position . end } siblings . splice ( index + 1 , lastSiblingIndex - index ) return index + 1 } } /* 🤽‍♀ — Combined emoji starting in a symbol. */ } else if ( child . type === 'SymbolNode' ) { nextSibling = siblings [ index + 1 ] nextNextSibling = siblings [ index + 2 ] if ( ! nextSibling || ! nextNextSibling ) { return } if ( ( nextSibling . type === 'SymbolNode' || nextSibling . type === 'WordNode' ) && nextNextSibling && nextNextSibling . type === 'SymbolNode' ) { possibleEmoji = value + toString ( nextSibling ) + toString ( nextNextSibling ) if ( own . call ( unicodes , possibleEmoji ) ) { child . type = EMOTICON_NODE child . value = possibleEmoji if ( child . position && nextNextSibling . position ) { child . position . end = nextNextSibling . position . end } siblings . splice ( index + 1 , 2 ) return index + 1 } } /* :+1: — Gemoji shortcodes. */ } else if ( value . charAt ( 0 ) === ':' ) { nodes = [ ] siblingIndex = index subvalue = value left = null right = null leftMatch = null rightMatch = null if ( subvalue . length === 1 ) { rightMatch = child } else { end = child . position && child . position . end start = end && child . position . start pos = end && { line : start . line , column : start . column + 1 , offset : start . offset + 1 } rightMatch = { type : 'PunctuationNode' , value : ':' } right = { type : 'PunctuationNode' , value : subvalue . slice ( 1 ) } if ( end ) { rightMatch . position = { start : start , end : pos } right . position = { start : pos , end : end } } } while ( siblingIndex -- ) { if ( index - siblingIndex > MAX_GEMOJI_PART_COUNT ) { return } node = siblings [ siblingIndex ] subvalue = toString ( node ) if ( subvalue . charAt ( subvalue . length - 1 ) === ':' ) { leftMatch = node break } if ( node . children ) { nodes = nodes . concat ( node . children . concat ( ) . reverse ( ) ) } else { nodes . push ( node ) } if ( siblingIndex === 0 ) { return } } if ( ! leftMatch ) { return } subvalue = toString ( leftMatch ) if ( subvalue . length !== 1 ) { end = leftMatch . position && leftMatch . position . end start = end && leftMatch . position . start pos = end && { line : end . line , column : end . column - 1 , offset : end . offset - 1 } left = { type : 'PunctuationNode' , value : subvalue . slice ( 0 , - 1 ) } leftMatch = { type : 'PunctuationNode' , value : ':' } if ( end ) { left . position = { start : start , end : pos } leftMatch . position = { start : pos , end : end } } } nodes . push ( leftMatch ) nodes . reverse ( ) . push ( rightMatch ) value = toString ( nodes ) if ( shortcodes . indexOf ( value ) === - 1 ) { return } replace = [ siblingIndex , index - siblingIndex + 1 ] if ( left ) { replace . push ( left ) } child . type = EMOTICON_NODE child . value = value if ( child . position && leftMatch . position ) { child . position . start = leftMatch . position . start } if ( child . position && rightMatch . position ) { child . position . end = rightMatch . position . end } replace . push ( child ) if ( right ) { replace . push ( right ) } ; [ ] . splice . apply ( siblings , replace ) return siblingIndex + 3 } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ==================================================== - returns starting row for Filter fn for a given table id ===================================================== [CODESPLIT] function getStartRow ( id ) { let r ; for ( let j in TblId ) { if ( TblId [ j ] === id ) r = StartRow [ j ] ; } return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ==================================================== - checks passed node is a ELEMENT_NODE nodeType = 1 - removes TEXT_NODE nodeType = 3 ===================================================== [CODESPLIT] function getChildElms ( n ) { if ( n . nodeType == 1 ) { let enfants = n . childNodes ; for ( let i = 0 ; i < enfants . length ; i ++ ) { let child = enfants [ i ] ; if ( child . nodeType == 3 ) n . removeChild ( child ) ; } return n ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ==================================================== - filter ( input ) ids are stored in this . SearchFlt array ===================================================== [CODESPLIT] function getFilters ( id ) { SearchFlt = [ ] ; let t = document . getElementById ( id ) ; let tr = t . getElementsByTagName ( \"tr\" ) [ 0 ] ; let inp = tr . getElementsByTagName ( \"input\" ) ; for ( let i = 0 ; i < inp . length ; i ++ ) SearchFlt . push ( inp [ i ] . getAttribute ( \"id\" ) ) ; return SearchFlt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ==================================================== - returns number of cells in a row - if nrow param is passed returns number of cells of that specific row ===================================================== [CODESPLIT] function getCellsNb ( id , nrow ) { let t = document . getElementById ( id ) ; let tr ; if ( nrow == undefined ) tr = t . getElementsByTagName ( \"tr\" ) [ 0 ] ; else tr = t . getElementsByTagName ( \"tr\" ) [ nrow ] ; let n = getChildElms ( tr ) ; return n . childNodes . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a Rollcall 2 . 0 client [CODESPLIT] function ( url , db ) { this . server = new Drowsy . Server ( url ) ; this . db = this . server . database ( db ) ; // User model this . User = this . db . Document ( 'users' ) . extend ( { addTag : function ( tag ) { var tags = _ . clone ( this . get ( 'tags' ) ) ; // if no classes array exists add it if ( ! tags ) { tags = [ ] ; } tags . push ( tag ) ; this . set ( 'tags' , _ . uniq ( tags ) ) ; } , removeTag : function ( tag ) { var tags = this . get ( 'tags' ) ; this . set ( 'tags' , _ . without ( tags , tag ) ) ; } , addCohort : function ( c ) { var classes = _ . clone ( this . get ( 'cohorts' ) ) ; // if no cohorts array exists add it if ( ! cohorts ) { cohorts = [ ] ; } cohorts . push ( c ) ; this . set ( 'cohorts' , _ . uniq ( cohorts ) ) ; } , removeCohort : function ( c ) { var cohorts = this . get ( 'cohorts' ) ; this . set ( 'cohorts' , _ . without ( cohorts , c ) ) ; } , isTeacher : function ( ) { if ( this . get ( 'user_role' ) === 'teacher' ) { return true ; } else { return false ; } } } ) ; this . Users = this . db . Collection ( 'users' ) . extend ( { model : this . User } ) ; /*\n     *   Group model\n     */ this . Group = this . db . Document ( 'groups' ) . extend ( { addGroup : function ( group ) { var groups = _ . clone ( this . get ( 'groups' ) ) ; groups . push ( group ) ; this . set ( 'groups' , _ . uniq ( group ) ) ; } } ) ; this . Groups = this . db . Collection ( 'groups' ) . extend ( { model : this . Group } ) ; // Run model this . Run = this . db . Document ( 'runs' ) . extend ( { } ) ; this . Runs = this . db . Collection ( 'runs' ) . extend ( { model : this . Run } ) ; /*\n     *   Model for Cohorts\n     */ this . Cohort = this . db . Document ( 'cohorts' ) . extend ( { addDiscussion : function ( discussionId ) { var discussions = _ . clone ( this . get ( 'discussions' ) ) ; // if no discussions array exists add it if ( ! discussions ) { discussions = [ ] ; } discussions . push ( discussionId ) ; this . set ( 'discussions' , _ . uniq ( discussions ) ) ; } , removeDiscussion : function ( discussionId ) { var discussions = this . get ( 'discussions' ) ; this . set ( 'discussions' , _ . without ( discussions , discussionId ) ) ; } } ) ; this . Cohorts = this . db . Collection ( 'cohorts' ) . extend ( { model : this . Cohort } ) ; /*\n     *   Model for Discussions\n     */ this . Discussion = this . db . Document ( 'discussions' ) . extend ( { } ) ; this . Discussions = this . db . Collection ( 'discussions' ) . extend ( { model : this . Discussion } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves . and .. elements in a path with directory names [CODESPLIT] function normalizeStringPosix ( path , allowAboveRoot ) { var res = '' ; var lastSlash = - 1 ; var dots = 0 ; var code ; for ( var i = 0 ; i <= path . length ; ++ i ) { if ( i < path . length ) code = path . charCodeAt ( i ) ; else if ( code === 47 /*/*/ ) break ; else code = 47 /*/*/ ; if ( code === 47 /*/*/ ) { if ( lastSlash === i - 1 || dots === 1 ) { // NOOP } else if ( lastSlash !== i - 1 && dots === 2 ) { if ( res . length < 2 || res . charCodeAt ( res . length - 1 ) !== 46 /*.*/ || res . charCodeAt ( res . length - 2 ) !== 46 /*.*/ ) { if ( res . length > 2 ) { var start = res . length - 1 ; var j = start ; for ( ; j >= 0 ; -- j ) { if ( res . charCodeAt ( j ) === 47 /*/*/ ) break ; } if ( j !== start ) { if ( j === - 1 ) res = '' ; else res = res . slice ( 0 , j ) ; lastSlash = i ; dots = 0 ; continue ; } } else if ( res . length === 2 || res . length === 1 ) { res = '' ; lastSlash = i ; dots = 0 ; continue ; } } if ( allowAboveRoot ) { if ( res . length > 0 ) res += '/..' ; else res = '..' ; } } else { if ( res . length > 0 ) res += '/' + path . slice ( lastSlash + 1 , i ) ; else res = path . slice ( lastSlash + 1 , i ) ; } lastSlash = i ; dots = 0 ; } else if ( code === 46 /*.*/ && dots !== - 1 ) { ++ dots ; } else { dots = - 1 ; } } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "path . resolve ( [ from ... ] to ) [CODESPLIT] function resolve ( ) { var resolvedDevice = '' ; var resolvedTail = '' ; var resolvedAbsolute = false ; for ( var i = arguments . length - 1 ; i >= - 1 ; i -- ) { var path ; if ( i >= 0 ) { path = arguments [ i ] ; } else if ( ! resolvedDevice ) { path = process . cwd ( ) ; } else { // Windows has the concept of drive-specific current working // directories. If we've resolved a drive letter but not yet an // absolute path, get cwd for that drive. We're sure the device is not // a UNC path at this points, because UNC paths are always absolute. path = process . env [ '=' + resolvedDevice ] ; // Verify that a drive-local cwd was found and that it actually points // to our drive. If not, default to the drive's root. if ( path === undefined || path . slice ( 0 , 3 ) . toLowerCase ( ) !== resolvedDevice . toLowerCase ( ) + '\\\\' ) { path = resolvedDevice + '\\\\' ; } } assertPath ( path ) ; // Skip empty entries if ( path . length === 0 ) { continue ; } var len = path . length ; var rootEnd = 0 ; var code = path . charCodeAt ( 0 ) ; var device = '' ; var isAbsolute = false ; // Try to match a root if ( len > 1 ) { if ( code === 47 /*/*/ || code === 92 /*\\*/ ) { // Possible UNC root // If we started with a separator, we know we at least have an // absolute path of some kind (UNC or otherwise) isAbsolute = true ; code = path . charCodeAt ( 1 ) ; if ( code === 47 /*/*/ || code === 92 /*\\*/ ) { // Matched double path separator at beginning var j = 2 ; var last = j ; // Match 1 or more non-path separators for ( ; j < len ; ++ j ) { code = path . charCodeAt ( j ) ; if ( code === 47 /*/*/ || code === 92 /*\\*/ ) break ; } if ( j < len && j !== last ) { var firstPart = path . slice ( last , j ) ; // Matched! last = j ; // Match 1 or more path separators for ( ; j < len ; ++ j ) { code = path . charCodeAt ( j ) ; if ( code !== 47 /*/*/ && code !== 92 /*\\*/ ) break ; } if ( j < len && j !== last ) { // Matched! last = j ; // Match 1 or more non-path separators for ( ; j < len ; ++ j ) { code = path . charCodeAt ( j ) ; if ( code === 47 /*/*/ || code === 92 /*\\*/ ) break ; } if ( j === len ) { // We matched a UNC root only device = '\\\\\\\\' + firstPart + '\\\\' + path . slice ( last ) ; rootEnd = j ; } else if ( j !== last ) { // We matched a UNC root with leftovers device = '\\\\\\\\' + firstPart + '\\\\' + path . slice ( last , j ) ; rootEnd = j ; } } } } else { rootEnd = 1 ; } } else if ( code >= 65 /*A*/ && code <= 90 /*Z*/ || code >= 97 /*a*/ && code <= 122 /*z*/ ) { // Possible device root code = path . charCodeAt ( 1 ) ; if ( path . charCodeAt ( 1 ) === 58 /*:*/ ) { device = path . slice ( 0 , 2 ) ; rootEnd = 2 ; if ( len > 2 ) { code = path . charCodeAt ( 2 ) ; if ( code === 47 /*/*/ || code === 92 /*\\*/ ) { // Treat separator following drive name as an absolute path // indicator isAbsolute = true ; rootEnd = 3 ; } } } } } else if ( code === 47 /*/*/ || code === 92 /*\\*/ ) { // `path` contains just a path separator rootEnd = 1 ; isAbsolute = true ; } if ( device . length > 0 && resolvedDevice . length > 0 && device . toLowerCase ( ) !== resolvedDevice . toLowerCase ( ) ) { // This path points to another device so it is not applicable continue ; } if ( resolvedDevice . length === 0 && device . length > 0 ) { resolvedDevice = device ; } if ( ! resolvedAbsolute ) { resolvedTail = path . slice ( rootEnd ) + '\\\\' + resolvedTail ; resolvedAbsolute = isAbsolute ; } if ( resolvedDevice . length > 0 && resolvedAbsolute ) { break ; } } // At this point the path should be resolved to a full absolute path, // but handle relative paths to be safe (might happen when process.cwd() // fails) // Normalize the tail path resolvedTail = normalizeStringWin32 ( resolvedTail , ! resolvedAbsolute ) ; return resolvedDevice + ( resolvedAbsolute ? '\\\\' : '' ) + resolvedTail || '.' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It will solve the relative path from from to to for instance : from = C : \\\\ orandea \\\\ test \\\\ aaa to = C : \\\\ orandea \\\\ impl \\\\ bbb The output of the function should be : .. \\\\ .. \\\\ impl \\\\ bbb [CODESPLIT] function relative ( from , to ) { assertPath ( from ) ; assertPath ( to ) ; if ( from === to ) return '' ; var fromOrig = win32 . resolve ( from ) ; var toOrig = win32 . resolve ( to ) ; if ( fromOrig === toOrig ) return '' ; from = fromOrig . toLowerCase ( ) ; to = toOrig . toLowerCase ( ) ; if ( from === to ) return '' ; // Trim any leading backslashes var fromStart = 0 ; for ( ; fromStart < from . length ; ++ fromStart ) { if ( from . charCodeAt ( fromStart ) !== 92 /*\\*/ ) break ; } // Trim trailing backslashes (applicable to UNC paths only) var fromEnd = from . length ; for ( ; fromEnd - 1 > fromStart ; -- fromEnd ) { if ( from . charCodeAt ( fromEnd - 1 ) !== 92 /*\\*/ ) break ; } var fromLen = fromEnd - fromStart ; // Trim any leading backslashes var toStart = 0 ; for ( ; toStart < to . length ; ++ toStart ) { if ( to . charCodeAt ( toStart ) !== 92 /*\\*/ ) break ; } // Trim trailing backslashes (applicable to UNC paths only) var toEnd = to . length ; for ( ; toEnd - 1 > toStart ; -- toEnd ) { if ( to . charCodeAt ( toEnd - 1 ) !== 92 /*\\*/ ) break ; } var toLen = toEnd - toStart ; // Compare paths to find the longest common path from root var length = fromLen < toLen ? fromLen : toLen ; var lastCommonSep = - 1 ; var i = 0 ; for ( ; i <= length ; ++ i ) { if ( i === length ) { if ( toLen > length ) { if ( to . charCodeAt ( toStart + i ) === 92 /*\\*/ ) { // We get here if `from` is the exact base path for `to`. // For example: from='C:\\\\foo\\\\bar'; to='C:\\\\foo\\\\bar\\\\baz' return toOrig . slice ( toStart + i + 1 ) ; } else if ( i === 2 ) { // We get here if `from` is the device root. // For example: from='C:\\\\'; to='C:\\\\foo' return toOrig . slice ( toStart + i ) ; } } if ( fromLen > length ) { if ( from . charCodeAt ( fromStart + i ) === 92 /*\\*/ ) { // We get here if `to` is the exact base path for `from`. // For example: from='C:\\\\foo\\\\bar'; to='C:\\\\foo' lastCommonSep = i ; } else if ( i === 2 ) { // We get here if `to` is the device root. // For example: from='C:\\\\foo\\\\bar'; to='C:\\\\' lastCommonSep = 3 ; } } break ; } var fromCode = from . charCodeAt ( fromStart + i ) ; var toCode = to . charCodeAt ( toStart + i ) ; if ( fromCode !== toCode ) break ; else if ( fromCode === 92 /*\\*/ ) lastCommonSep = i ; } // We found a mismatch before the first common path separator was seen, so // return the original `to`. // TODO: do this just for device roots (and not UNC paths)? if ( i !== length && lastCommonSep === - 1 ) { if ( toStart > 0 ) return toOrig . slice ( toStart ) ; else return toOrig ; } var out = '' ; if ( lastCommonSep === - 1 ) lastCommonSep = 0 ; // Generate the relative path based on the path difference between `to` and // `from` for ( i = fromStart + lastCommonSep + 1 ; i <= fromEnd ; ++ i ) { if ( i === fromEnd || from . charCodeAt ( i ) === 92 /*\\*/ ) { if ( out . length === 0 ) out += '..' ; else out += '\\\\..' ; } } // Lastly, append the rest of the destination (`to`) path that comes after // the common path parts if ( out . length > 0 ) return out + toOrig . slice ( toStart + lastCommonSep , toEnd ) ; else { toStart += lastCommonSep ; if ( toOrig . charCodeAt ( toStart ) === 92 /*\\*/ ) ++ toStart ; return toOrig . slice ( toStart , toEnd ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "path . resolve ( [ from ... ] to ) [CODESPLIT] function resolve ( ) { var resolvedPath = '' ; var resolvedAbsolute = false ; var cwd ; for ( var i = arguments . length - 1 ; i >= - 1 && ! resolvedAbsolute ; i -- ) { var path ; if ( i >= 0 ) path = arguments [ i ] ; else { if ( cwd === undefined ) cwd = process . cwd ( ) ; path = cwd ; } assertPath ( path ) ; // Skip empty entries if ( path . length === 0 ) { continue ; } resolvedPath = path + '/' + resolvedPath ; resolvedAbsolute = path . charCodeAt ( 0 ) === 47 /*/*/ ; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeStringPosix ( resolvedPath , ! resolvedAbsolute ) ; if ( resolvedAbsolute ) { if ( resolvedPath . length > 0 ) return '/' + resolvedPath ; else return '/' ; } else if ( resolvedPath . length > 0 ) { return resolvedPath ; } else { return '.' ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Gets default options and merges with user options if any . [CODESPLIT] function ( options ) { var defaults = { 'method' : 'get' , 'data' : null , 'needleRetry' : null , 'rule' : { 'second' : 1 } } ; if ( ! options ) { return defaults ; } return R . merge ( defaults , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ==================================================== - adds a filter ( input ) for each column ( td ) - adds button on last column ===================================================== [CODESPLIT] function AddRow ( id , n ) { var t = document . getElementById ( id ) ; var fltrow = t . insertRow ( 0 ) ; var inpclass = \"flt\" ; for ( var i = 0 ; i < n ; i ++ ) { var fltcell = fltrow . insertCell ( i ) ; var inp = document . createElement ( \"input\" ) ; inp . setAttribute ( \"id\" , \"flt\" + i + \"_\" + id ) ; inp . setAttribute ( \"type\" , \"text\" ) ; inp . setAttribute ( \"class\" , i == n - 1 ? \"flt_s\" : \"flt\" ) ; inp . setAttribute ( 'placeholder' , 'Filter' ) ; inp . addEventListener ( 'keyup' , Filter ) ; fltcell . appendChild ( inp ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ==================================================== - returns text + text of child nodes of a cell ===================================================== [CODESPLIT] function getCellText ( n ) { var s = \"\" ; var enfants = n . childNodes ; for ( var i = 0 ; i < enfants . length ; i ++ ) { var child = enfants [ i ] ; if ( child . nodeType == 3 ) s += child . data ; else s += getCellText ( child ) ; } return s . toLowerCase ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ==================================================== - Checks if id exists and is a table - Calls fn that adds inputs and button ===================================================== [CODESPLIT] function setFilterGrid ( id , ref_row ) { if ( typeof window === 'undefined' || typeof document === 'undefined' ) return ; var tbl = document . getElementById ( id ) ; if ( tbl && tbl . nodeName . toLowerCase ( ) === \"table\" ) { TblId . push ( id ) ; ref_row = ref_row === undefined ? StartRow . push ( 2 ) : StartRow . push ( ref_row + 2 ) ; //let ncells = getCellsNb(id, ref_row); // AddRow(id, ncells); } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ==================================================== - gets search strings from this . SearchFlt array - retrieves data from each td in every single tr and compares to search string for current column - tr is hidden if all search strings are not found ===================================================== [CODESPLIT] function Filter ( e ) { if ( typeof document === 'undefined' ) return ; var id = e . target . getAttribute ( \"id\" ) . split ( \"_\" ) [ 1 ] ; var SearchFlt = getFilters ( id ) ; var t = document . getElementById ( id ) ; var SearchArgs = [ ] ; var ncells = getCellsNb ( id ) ; for ( var i in SearchFlt ) { SearchArgs . push ( document . getElementById ( SearchFlt [ i ] ) . value . toLowerCase ( ) ) ; } var start_row = getStartRow ( id ) ; var row = t . getElementsByTagName ( \"tr\" ) ; for ( var k = start_row ; k < row . length ; k ++ ) { /*** if table already filtered some rows are not visible ***/ if ( row [ k ] . style . display === \"none\" ) row [ k ] . style . display = \"\" ; var cell = getChildElms ( row [ k ] ) . childNodes ; var nchilds = cell . length ; var isRowValid = true ; if ( nchilds === ncells ) { // checks if row has exact cell # var cell_value = [ ] ; var occurence = [ ] ; for ( var j = 0 ; j < nchilds ; j ++ ) // this loop retrieves cell data { var cell_data = getCellText ( cell [ j ] ) ; cell_value . push ( cell_data ) ; if ( SearchArgs [ j ] !== \"\" ) { occurence [ j ] = cell_data . split ( SearchArgs [ j ] ) . length ; } } //for j for ( var _t = 0 ; _t < ncells ; _t ++ ) { if ( SearchArgs [ _t ] !== \"\" && occurence [ _t ] < 2 ) { isRowValid = false ; } } //for t } //if if ( isRowValid === false ) row [ k ] . style . display = \"none\" ; else row [ k ] . style . display = \"\" ; } // for k }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set global variables on worker & main threads else node [CODESPLIT] function setAppConsts ( ) { var mergedConstants = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : ( 0 , _seamlessImmutable2 . default ) ( appConsts ) ; // set node app consts if ( typeof self === 'undefined' && typeof global !== 'undefined' ) { global . appConsts = global . appConsts ? _seamlessImmutable2 . default . merge ( global . appConsts , mergedConstants ) : mergedConstants ; return global . appConsts ; } else if ( typeof self !== 'undefined' ) { // set main & worker threads self . appConsts = self . appConsts ? _seamlessImmutable2 . default . merge ( self . appConsts , mergedConstants ) : mergedConstants ; return self . appConsts ; } return { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split a string to an array . [CODESPLIT] function splitTo ( ) { let to = arguments . length <= 0 || arguments [ 0 ] === undefined ? '' : arguments [ 0 ] ; if ( / # / . test ( to ) ) { return to . split ( '#' ) ; } return [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the arguments and return an special array . [CODESPLIT] function parseArgs ( ) { for ( var _len = arguments . length , args = Array ( _len ) , _key = 0 ; _key < _len ; _key ++ ) { args [ _key ] = arguments [ _key ] ; } const l = args . length ; const last = args [ l - 1 ] ; let cb , opts , paths ; if ( _lodash2 . default . isFunction ( last ) ) { cb = last ; args . pop ( ) ; // don't remove this semicolon var _parseArgs = parseArgs ( ... args ) ; var _parseArgs2 = _slicedToArray ( _parseArgs , 2 ) ; paths = _parseArgs2 [ 0 ] ; opts = _parseArgs2 [ 1 ] ; } else if ( _lodash2 . default . isObject ( last ) && ! Array . isArray ( last ) ) { opts = last ; args . pop ( ) ; paths = args ; } else if ( ! last && l > 0 ) { args . pop ( ) ; return parseArgs ( ... args ) ; } else { paths = args ; } return [ _lodash2 . default . compact ( _lodash2 . default . flatten ( paths , true ) ) , opts || { } , cb ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ensures that the system repository is in place creates it if doesn t exist [CODESPLIT] function ( cb ) { fse . readFile ( systemsJsonPath , 'utf8' , function ( err , data ) { if ( err ) { if ( err . code !== 'ENOENT' ) { return cb ( err ) ; } fse . mkdirpSync ( sysRepoPath ) ; fse . writeFileSync ( systemsJsonPath , JSON . stringify ( blank , null , 2 ) , 'utf8' ) ; return git . createRepository ( sysRepoPath , 'system' , 'system@nfd.com' , function ( err_ ) { _systems = blank ; cb ( err_ ) ; } ) ; } _systems = JSON . parse ( data ) ; cb ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "register a system [CODESPLIT] function ( user , namespace , name , repoName , repoPath , systemId , cb ) { if ( ! _systems [ systemId ] ) { _systems [ systemId ] = { name : name , namespace : namespace , repoName : repoName , repoPath : repoPath } ; fse . writeFileSync ( systemsJsonPath , JSON . stringify ( _systems , null , 2 ) , 'utf8' ) ; git . commit ( sysRepoPath , 'registered system: ' + repoPath , user . name , user . email , cb ) ; } else { cb ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unregister a system [CODESPLIT] function ( user , systemId , cb ) { if ( ! _systems [ systemId ] ) { return cb ( ) ; } var newSystems = _ . clone ( _systems ) ; delete newSystems [ systemId ] ; fse . writeFileSync ( systemsJsonPath , JSON . stringify ( newSystems , null , 2 ) , 'utf8' ) ; _systems = newSystems ; git . commit ( sysRepoPath , 'unregistered system: ' + systemId , user . name , user . email , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert identifier into full system guid using : 1 ) exact match on key 2 ) partial match on key 3 ) partial match on name [CODESPLIT] function ( identifier ) { identifier = identifier . replace ( / [.+] / g , function ( match ) { return '\\\\' + match ; } ) ; var re = new RegExp ( '^' + identifier + '.*' , [ 'i' ] ) ; var systemId ; systemId = _ . find ( _ . keys ( _systems ) , function ( system ) { return system === identifier ; } ) ; if ( ! systemId ) { systemId = _ . find ( _ . keys ( _systems ) , function ( system ) { return re . test ( system ) ; } ) ; } if ( ! systemId ) { systemId = _ . find ( _ . keys ( _systems ) , function ( system ) { return re . test ( _systems [ system ] . name ) ; } ) ; } return systemId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Init the object construct and process DOM [CODESPLIT] function ( ) { var domWrapper ; this . _children = [ ] ; this . _createRootHtml ( ) ; domWrapper = utils . html . parseHTML ( this . html ) ; if ( domWrapper . childNodes . length > 1 ) { throw new Error ( \"Component should have only one root element\" ) ; } this . root = domWrapper . firstChild ; this . processInstance ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process DOM using defined DOM processors [CODESPLIT] function ( ) { var i , elements , element , value ; if ( this . _root ) { ( this . $meta . domProcessors || [ ] ) . forEach ( function ( processor ) { elements = this . _root . querySelectorAll ( \"[\" + processor . attribute + \"]\" ) ; for ( i = 0 ; i < elements . length ; i ++ ) { element = elements [ i ] ; value = element . getAttribute ( processor . attribute ) ; processor . process ( this , element , value ) ; } } , this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a child component [CODESPLIT] function ( child ) { this . _validateChild ( child ) ; if ( child . parent ) { child . parent . remove ( child ) ; } child . parent = this ; this . _children . push ( child ) ; this . root . appendChild ( child . root ) ; if ( this . __fastinject__ ) { this . __fastinject__ ( child ) ; } // otherwise it will be injected when __fastinject__ is set }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove child component [CODESPLIT] function ( child ) { var index = this . _children . indexOf ( child ) ; if ( index !== - 1 ) { this . _children . splice ( index , 1 ) ; child . root . parentNode . removeChild ( child . root ) ; child . destroy ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attaches a component by replacing the provided element . Element must be an element inside the parent component . [CODESPLIT] function ( child , element , root ) { this . _children . push ( child ) ; ( root || this . root ) . insertBefore ( child . root , element ) ; ( root || this . root ) . removeChild ( element ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ensures that system has all required files [CODESPLIT] function ( repoPath , doc , done ) { generify ( path . join ( __dirname , 'template' ) , repoPath , { name : doc . name , namespace : doc . namespace , id : doc . id } , done ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checks if a directory is a system ( has all the required files and correct system . json and system . js [CODESPLIT] function ( repoPath ) { var sys ; if ( fse . existsSync ( path . join ( repoPath , 'system.js' ) ) ) { // TODO extract in its own module sys = require ( repoPath + '/system.js' ) ; delete require . cache [ repoPath + '/system.js' ] ; } if ( ! sys ) { return new Error ( 'missing system.js, is this an nscale repository?' ) ; } if ( ! sys . name ) { return new Error ( 'missing name in system.js, correct and try again' ) ; } if ( ! sys . namespace ) { return new Error ( 'missing namespace in system.js, correct and try again' ) ; } if ( ! sys . id ) { return new Error ( 'missing id in system.js, correct and try again' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "timeline format [ { user : user ts : new Date () type : entryType details : details } ... custom values can be provided through the details object TODO change the format to include all the details in the main object [CODESPLIT] function ( user , systemId , entryType , details , cb ) { var file = path . join ( options . timelinesRoot , findSystem ( systemId ) ) ; if ( typeof details === 'function' ) { cb = details ; details = { } ; } else if ( ! details ) { details = { } ; } var entry = { v : 0 , user : user , ts : new Date ( ) , type : entryType , details : details } ; fs . writeFile ( file , JSON . stringify ( entry ) + '\\n' , { flag : 'a' } , function ( ) { // error is swallowed, as this file does not really matter cb ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "make a commit to local git repository TODO : implement seperate push functionality TODO : replace with git hub id [CODESPLIT] function ( user , systemId , message , cb ) { logger . info ( 'committing revision: ' + systemId + ', ' + message ) ; var repoPath = _meta . repoPath ( systemId ) ; git . commit ( repoPath , message , user . name , user . email , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a new system repository [CODESPLIT] function ( user , namespace , name , cwd , cb ) { var repoName = name ; var doc = _ . extend ( { } , blank ) ; var repoPath = path . join ( cwd , repoName ) ; doc . name = name ; doc . namespace = namespace ; doc . id = uuid . v4 ( ) ; if ( ! fse . existsSync ( repoPath ) ) { fse . mkdirpSync ( repoPath ) ; initNscaleFiles ( repoPath , doc , function ( ) { git . createRepository ( repoPath , user . name , user . email , function ( err ) { if ( err ) { return cb ( err ) ; } _meta . register ( user , namespace , name , repoName , cwd + '/' + repoName , doc . id , function ( err ) { writeTimeline ( user , doc . id , 'create' , 'system created' , function ( ) { // swallow any errors here cb ( err , { id : doc . id , err : err } ) ; } ) ; } ) ; } ) ; } ) ; } else { cb ( null , { id : _meta . repoId ( repoName ) , err : null } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a new system by linking from local file system [CODESPLIT] function ( user , path_ , cwd , cb ) { var repoPath = path . resolve ( cwd , path_ ) ; var sys ; var validationError = validateSystem ( repoPath ) ; if ( validationError ) { return cb ( validationError ) ; } sys = require ( repoPath + '/system.js' ) ; delete require . cache [ repoPath + '/system.js' ] ; _meta . register ( user , sys . namespace , sys . name , path . basename ( repoPath ) , repoPath , sys . id , function ( err ) { writeTimeline ( user , sys . id , 'link' , 'system linked' , function ( ) { cb ( err , { id : sys . id , err : err } ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unlink system from the daemon [CODESPLIT] function ( user , systemId , cb ) { writeTimeline ( user , systemId , 'system unlinked' , function ( ) { // swallow any errors here _meta . unregister ( user , systemId , function ( err ) { cb ( err ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "commit a new version of the system the head of the commit log may be ahead of the actual deployed version of the system [CODESPLIT] function ( systemId , fileName , contents , cb ) { var repoPath = _meta . repoPath ( systemId ) ; fse . writeFile ( path . join ( repoPath , fileName ) , contents , 'utf8' , cb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the head revision for a system [CODESPLIT] function ( systemId , target , cb ) { listRevisions ( systemId , function ( err , revs ) { if ( err ) { return cb ( err ) ; } getRevision ( systemId , revs [ 0 ] . id , target , cb ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the head revision id for a system [CODESPLIT] function ( systemId , cb ) { listRevisions ( systemId , function ( err , revs ) { cb ( err , revs && revs [ 0 ] && revs [ 0 ] . id ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the head revision id for a system [CODESPLIT] function ( systemId , cb ) { listRevisions ( systemId , function ( err , revs ) { if ( revs [ 0 ] . id === EDITS ) { cb ( err , revs && revs [ 1 ] && revs [ 1 ] . id ) ; } else { cb ( err , revs && revs [ 0 ] && revs [ 0 ] . id ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get a revision from the history with a specific version number [CODESPLIT] function ( systemId , revisionId , target , cb ) { var repoPath = _meta . repoPath ( systemId ) ; git . getFileRevision ( repoPath , revisionId , target + '.json' , function ( err , rev ) { if ( err ) { return cb ( err ) ; } var s ; try { s = JSON . parse ( rev ) ; } catch ( e ) { return cb ( new Error ( 'invalid system definition: ' + e . message ) , null ) ; } cb ( err , s ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get a revision from the history with abbreviation support [CODESPLIT] function ( systemId , revisionId , target , cb ) { if ( revisionId === EDITS ) { _getOnDiskVersion ( systemId , revisionId , target , cb ) ; } else { findRevision ( systemId , revisionId , function ( err , rev ) { if ( err ) { return cb ( err ) ; } if ( rev === EDITS ) { _getOnDiskVersion ( systemId , revisionId , target , cb ) ; } else { _getRevision ( systemId , rev , target , cb ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * tesnt this to fuck and PR and release move onto proxy - must be testing it tomorrow night app dynamics only - load to AJ set the currently deployed revision there will only ever be one deployed revision clear the currently deployed flag and set the deployed flag against the specified revision [CODESPLIT] function ( user , systemId , revisionId , env , cb ) { var repoPath = _meta . repoPath ( systemId ) ; var removeTag ; var addTag ; var revId ; getComittedHeadRevisionId ( systemId , function ( err , comittedHeadId ) { if ( revisionId === EDITS ) { removeTag = baseTag + env ; addTag = editsTag + env ; revId = comittedHeadId ; } else { addTag = baseTag + env ; removeTag = editsTag + env ; revId = revisionId ; } ngit . Repository . open ( repoPath , function ( err , repo ) { if ( err ) { return cb ( err ) ; } ngit . Reference . remove ( repo , removeTag ) ; repo . getCommit ( revId , function ( err , commit ) { if ( err ) { return cb ( err ) ; } var now = Math . round ( Date . now ( ) / 1000 ) ; var author = ngit . Signature . create ( user . name , user . email , now , 0 ) ; ngit . Reference . create ( repo , addTag , commit , 1 , author , 'Tagged ' + addTag ) . then ( function ( ) { writeTimeline ( user , systemId , 'deployed revision' , revisionId , function ( ) { cb ( ) ; } ) ; } ) . catch ( cb ) ; } ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the currently deployed revision [CODESPLIT] function ( systemId , env , cb ) { var repoPath = _meta . repoPath ( systemId ) ; var tagName = baseTag + env ; var editsTagName = editsTag + env ; ngit . Repository . open ( repoPath , function ( err , repo ) { if ( err ) { return cb ( err ) ; } ngit . Reference . nameToId ( repo , tagName , function ( err , head ) { if ( err && ( ! err . message || err . message . indexOf ( 'not found' ) === - 1 ) ) { return cb ( err ) ; } if ( head ) { cb ( null , head . toString ( ) ) ; } else { ngit . Reference . nameToId ( repo , editsTagName , function ( err ) { if ( err ) { return cb ( err ) ; } cb ( null , EDITS ) ; } ) ; } } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "list all of the available revisions in the system [CODESPLIT] function ( systemId , cb ) { var repoPath = _meta . repoPath ( systemId ) ; getDeployedTargets ( systemId , function ( err , targets ) { if ( err ) { return cb ( err ) ; } git . listRevisions ( repoPath , function ( err , revisions ) { revisions . forEach ( function ( revision ) { var deployedTo = _ . find ( targets , function ( target ) { return target . commit === revision . id ; } ) ; if ( deployedTo ) { revision . deployedTo = deployedTo . env ; } } ) ; cb ( err , revisions ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find revision id by parital or full identifier [CODESPLIT] function ( systemId , identifier , cb ) { var re = new RegExp ( '^' + identifier + '.*' , [ 'i' ] ) ; var revision ; if ( identifier !== 'head' && identifier !== 'latest' ) { listRevisions ( systemId , function ( err , revisions ) { revision = _ . find ( revisions , function ( revision ) { return re . test ( revision . id ) ; } ) ; if ( revision ) { cb ( err , revision . id ) ; } else { cb ( new Error ( 'revision not found' ) ) ; } } ) ; } else { getHeadRevisionId ( systemId , cb ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Import javascript depending on the * mode * . We currently support sprite and data - uri modes ( NO basic image mode ) . [CODESPLIT] function ( app , parentAddon ) { this . _super . included ( app ) ; var target = ( parentAddon || app ) ; target . import ( target . bowerDirectory + '/emojify/dist/js/emojify.js' ) ; if ( _emojiConfig . mode === 'sprites' ) { var destSpriteDir = 'images/sprites' ; var spritePath = '/emojify/dist/images/sprites/' ; target . import ( target . bowerDirectory + spritePath + 'emojify.png' , { destDir : destSpriteDir } ) ; target . import ( target . bowerDirectory + spritePath + 'emojify@2x.png' , { destDir : destSpriteDir } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows custom configuration from environment [CODESPLIT] function ( environment , baseConfig ) { if ( 'emoji' in baseConfig ) { if ( ! baseConfig . emoji ) { _emojiConfig = false ; } else { Object . keys ( _defaultEmojiConfig ) . forEach ( function ( key ) { _emojiConfig [ key ] = baseConfig . emoji . hasOwnProperty ( key ) ? baseConfig . emoji [ key ] : _defaultEmojiConfig [ key ] ; } ) ; } } else { _emojiConfig = _defaultEmojiConfig ; } if ( environment === 'development' ) { return { emoji : _emojiConfig , contentSecurityPolicy : { 'script-src' : \"'self' 'unsafe-eval' 'unsafe-inline'\" } } ; } return { emoji : _emojiConfig } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Import style depending on the * mode * . We currently support sprite and data - uri modes ( NO basic image mode ) . [CODESPLIT] function ( ) { var emojiDataURIPath = path . join ( this . app . bowerDirectory , 'emojify/dist/css/data-uri/emojify.css' ) , emojiSpritesPath = path . join ( this . app . bowerDirectory , 'emojify/dist/css/sprites/emojify.css' ) ; if ( _emojiConfig . mode === 'data-uri' ) { this . app . import ( emojiDataURIPath ) ; } else { this . app . import ( emojiSpritesPath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the target containers - machine containers that have a proxy on them . [CODESPLIT] function ( analyzed ) { var containers = analyzed . topology . containers ; var targets = [ ] ; _ . each ( containers , function ( c ) { if ( c . containerDefinitionId . indexOf ( '__proxy' ) === 0 ) { var cdef = _ . find ( analyzed . containerDefinitions , function ( cdef ) { return cdef . id === c . containerDefinitionId ; } ) ; targets . push ( { containerDef : cdef , container : c } ) ; } } ) ; return targets ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Function : getCollection Looks for a collection object attached to the current class . If one is not found it traverses the ancestor tree looking for the closest class that has a collection object associated with it and returns that collection . [CODESPLIT] function ( cls ) { if ( this . collection ) { return this . collection ; } cls = ( cls ) ? this . superclass ( cls ) : this ; while ( cls ) { if ( cls . collection ) { this . collection = cls . collection ; return cls . collection ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Relation . [CODESPLIT] function ( model , relation , options ) { var type = ! _ . isString ( relation . type ) ? relation . type : Backbone [ relation . type ] || this . getObjectByName ( relation . type ) ; if ( type && type . prototype instanceof Backbone . Relation ) { new type ( model , relation , options ) ; // Also pushes the new Relation into `model._relations` } else { Backbone . Relational . showWarnings && typeof console !== 'undefined' && console . warn ( 'Relation=%o; missing or invalid relation type!' , relation ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given modelType is registered as another model s subModel . If so add it to the super model s _subModels and set the modelType s _superModel _subModelTypeName and _subModelTypeAttribute . [CODESPLIT] function ( modelType ) { _ . find ( this . _subModels , function ( subModelDef ) { return _ . find ( subModelDef . subModels || [ ] , function ( subModelTypeName , typeValue ) { var subModelType = this . getObjectByName ( subModelTypeName ) ; if ( modelType === subModelType ) { // Set 'modelType' as a child of the found superModel subModelDef . superModelType . _subModels [ typeValue ] = modelType ; // Set '_superModel', '_subModelTypeValue', and '_subModelTypeAttribute' on 'modelType'. modelType . _superModel = subModelDef . superModelType ; modelType . _subModelTypeValue = typeValue ; modelType . _subModelTypeAttribute = subModelDef . superModelType . prototype . subModelTypeAttribute ; return true ; } } , this ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a reverse relation . Is added to the relations property on model s prototype and to existing instances of model in the store as well . [CODESPLIT] function ( relation ) { var exists = _ . any ( this . _reverseRelations , function ( rel ) { return _ . all ( relation || [ ] , function ( val , key ) { return val === rel [ key ] ; } ) ; } ) ; if ( ! exists && relation . model && relation . type ) { this . _reverseRelations . push ( relation ) ; this . _addRelation ( relation . model , relation ) ; this . retroFitRelation ( relation ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deposit a relation for which the relatedModel can t be resolved at the moment . [CODESPLIT] function ( relation ) { var exists = _ . any ( this . _orphanRelations , function ( rel ) { return _ . all ( relation || [ ] , function ( val , key ) { return val === rel [ key ] ; } ) ; } ) ; if ( ! exists && relation . model && relation . type ) { this . _orphanRelations . push ( relation ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to initialize any _orphanRelation s [CODESPLIT] function ( ) { // Make sure to operate on a copy since we're removing while iterating _ . each ( this . _orphanRelations . slice ( 0 ) , function ( rel ) { var relatedModel = Backbone . Relational . store . getObjectByName ( rel . relatedModel ) ; if ( relatedModel ) { this . initializeRelation ( null , rel ) ; this . _orphanRelations = _ . without ( this . _orphanRelations , rel ) ; } } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a relation to all existing instances of relation . model in the store [CODESPLIT] function ( relation ) { var coll = this . getCollection ( relation . model , false ) ; coll && coll . each ( function ( model ) { if ( ! ( model instanceof relation . model ) ) { return ; } new relation . type ( model , relation ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the Store s collection for a certain type of model . [CODESPLIT] function ( type , create ) { if ( type instanceof Backbone . RelationalModel ) { type = type . constructor ; } var rootModel = type ; while ( rootModel . _superModel ) { rootModel = rootModel . _superModel ; } var coll = _ . find ( this . _collections , function ( item ) { return item . model === rootModel ; } ) ; if ( ! coll && create !== false ) { coll = this . _createCollection ( rootModel ) ; } return coll ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a model type on one of the modelScopes by name . Names are split on dots . [CODESPLIT] function ( name ) { var parts = name . split ( '.' ) , type = null ; _ . find ( this . _modelScopes , function ( scope ) { type = _ . reduce ( parts || [ ] , function ( memo , val ) { return memo ? memo [ val ] : undefined ; } , scope ) ; if ( type && type !== scope ) { return true ; } } , this ) ; return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the attribute that is to be used as the id on a given object [CODESPLIT] function ( type , item ) { var id = _ . isString ( item ) || _ . isNumber ( item ) ? item : null ; if ( id === null ) { if ( item instanceof Backbone . RelationalModel ) { id = item . id ; } else if ( _ . isObject ( item ) ) { id = item [ type . prototype . idAttribute ] ; } } // Make all falsy values `null` (except for 0, which could be an id.. see '/issues/179') if ( ! id && id !== 0 ) { id = null ; } return id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a specific model of a certain type in the store [CODESPLIT] function ( type , item ) { var id = this . resolveIdForItem ( type , item ) ; var coll = this . getCollection ( type ) ; // Because the found object could be of any of the type's superModel // types, only return it if it's actually of the type asked for. if ( coll ) { var obj = coll . get ( id ) ; if ( obj instanceof type ) { return obj ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a model to its appropriate collection . Retain the original contents of model . collection . [CODESPLIT] function ( model ) { var coll = this . getCollection ( model ) ; if ( coll ) { var modelColl = model . collection ; coll . add ( model ) ; this . listenTo ( model , 'destroy' , this . unregister , this ) ; this . listenTo ( model , 'relational:unregister' , this . unregister , this ) ; model . collection = modelColl ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given model may use the given id [CODESPLIT] function ( model , id ) { var coll = this . getCollection ( model ) , duplicate = coll && coll . get ( id ) ; if ( duplicate && model !== duplicate ) { if ( Backbone . Relational . showWarnings && typeof console !== 'undefined' ) { console . warn ( 'Duplicate id! Old RelationalModel=%o, new RelationalModel=%o' , duplicate , model ) ; } throw new Error ( \"Cannot instantiate more than one Backbone.RelationalModel with the same id per type!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a model from the store . [CODESPLIT] function ( model , collection , options ) { this . stopListening ( model ) ; var coll = this . getCollection ( model ) ; coll && coll . remove ( model , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check several pre - conditions . [CODESPLIT] function ( ) { var i = this . instance , k = this . key , m = this . model , rm = this . relatedModel , warn = Backbone . Relational . showWarnings && typeof console !== 'undefined' ; if ( ! m || ! k || ! rm ) { warn && console . warn ( 'Relation=%o: missing model, key or relatedModel (%o, %o, %o).' , this , m , k , rm ) ; return false ; } // Check if the type in 'model' inherits from Backbone.RelationalModel if ( ! ( m . prototype instanceof Backbone . RelationalModel ) ) { warn && console . warn ( 'Relation=%o: model does not inherit from Backbone.RelationalModel (%o).' , this , i ) ; return false ; } // Check if the type in 'relatedModel' inherits from Backbone.RelationalModel if ( ! ( rm . prototype instanceof Backbone . RelationalModel ) ) { warn && console . warn ( 'Relation=%o: relatedModel does not inherit from Backbone.RelationalModel (%o).' , this , rm ) ; return false ; } // Check if this is not a HasMany, and the reverse relation is HasMany as well if ( this instanceof Backbone . HasMany && this . reverseRelation . type === Backbone . HasMany ) { warn && console . warn ( 'Relation=%o: relation is a HasMany, and the reverseRelation is HasMany as well.' , this ) ; return false ; } // Check if we're not attempting to create a relationship on a `key` that's already used. if ( i && _ . keys ( i . _relations ) . length ) { var existing = _ . find ( i . _relations , function ( rel ) { return rel . key === k ; } , this ) ; if ( existing ) { warn && console . warn ( 'Cannot create relation=%o on %o for model=%o: already taken by relation=%o.' , this , k , i , existing ) ; return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the related model ( s ) for this relation [CODESPLIT] function ( related ) { this . related = related ; this . instance . acquire ( ) ; this . instance . attributes [ this . key ] = related ; this . instance . release ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if a relation ( on a different RelationalModel ) is the reverse relation of the current one . [CODESPLIT] function ( relation ) { return relation . instance instanceof this . relatedModel && this . reverseRelation . key === relation . key && this . key === relation . reverseRelation . key ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the reverse relations ( pointing back to this . key on this . instance ) for the currently related model ( s ) . [CODESPLIT] function ( model ) { var reverseRelations = [ ] ; // Iterate over 'model', 'this.related.models' (if this.related is a Backbone.Collection), or wrap 'this.related' in an array. var models = ! _ . isUndefined ( model ) ? [ model ] : this . related && ( this . related . models || [ this . related ] ) ; _ . each ( models || [ ] , function ( related ) { _ . each ( related . getRelations ( ) || [ ] , function ( relation ) { if ( this . _isReverseRelation ( relation ) ) { reverseRelations . push ( relation ) ; } } , this ) ; } , this ) ; return reverseRelations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When this . instance is destroyed cleanup our relations . Get reverse relation call removeRelated on each . [CODESPLIT] function ( ) { this . stopListening ( ) ; if ( this instanceof Backbone . HasOne ) { this . setRelated ( null ) ; } else if ( this instanceof Backbone . HasMany ) { this . setRelated ( this . _prepareCollection ( ) ) ; } _ . each ( this . getReverseRelations ( ) , function ( relation ) { relation . removeRelated ( this . instance ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find related Models . [CODESPLIT] function ( options ) { var related = null ; options = _ . defaults ( { parse : this . options . parse } , options ) ; if ( this . keyContents instanceof this . relatedModel ) { related = this . keyContents ; } else if ( this . keyContents || this . keyContents === 0 ) { // since 0 can be a valid `id` as well var opts = _ . defaults ( { create : this . options . createModels } , options ) ; related = this . relatedModel . findOrCreate ( this . keyContents , opts ) ; } // Nullify `keyId` if we have a related model; in case it was already part of the relation if ( this . related ) { this . keyId = null ; } return related ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize and reduce keyContents to an id for easier comparison [CODESPLIT] function ( keyContents ) { this . keyContents = keyContents ; this . keyId = Backbone . Relational . store . resolveIdForItem ( this . relatedModel , this . keyContents ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for change : <key > . If the key is changed notify old & new reverse relations and initialize the new relation . [CODESPLIT] function ( model , attr , options ) { // Don't accept recursive calls to onChange (like onChange->findRelated->findOrCreate->initializeRelations->addRelated->onChange) if ( this . isLocked ( ) ) { return ; } this . acquire ( ) ; options = options ? _ . clone ( options ) : { } ; // 'options.__related' is set by 'addRelated'/'removeRelated'. If it is set, the change // is the result of a call from a relation. If it's not, the change is the result of // a 'set' call on this.instance. var changed = _ . isUndefined ( options . __related ) , oldRelated = changed ? this . related : options . __related ; if ( changed ) { this . setKeyContents ( attr ) ; var related = this . findRelated ( options ) ; this . setRelated ( related ) ; } // Notify old 'related' object of the terminated relation if ( oldRelated && this . related !== oldRelated ) { _ . each ( this . getReverseRelations ( oldRelated ) , function ( relation ) { relation . removeRelated ( this . instance , null , options ) ; } , this ) ; } // Notify new 'related' object of the new relation. Note we do re-apply even if this.related is oldRelated; // that can be necessary for bi-directional relations if 'this.instance' was created after 'this.related'. // In that case, 'this.instance' will already know 'this.related', but the reverse might not exist yet. _ . each ( this . getReverseRelations ( ) , function ( relation ) { relation . addRelated ( this . instance , options ) ; } , this ) ; // Fire the 'change:<key>' event if 'related' was updated if ( ! options . silent && this . related !== oldRelated ) { var dit = this ; this . changed = true ; Backbone . Relational . eventQueue . add ( function ( ) { dit . instance . trigger ( 'change:' + dit . key , dit . instance , dit . related , options , true ) ; dit . changed = false ; } ) ; } this . release ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a new this . relatedModel appears in the store try to match it to the last set keyContents [CODESPLIT] function ( model , coll , options ) { if ( ( this . keyId || this . keyId === 0 ) && model . id === this . keyId ) { // since 0 can be a valid `id` as well this . addRelated ( model , options ) ; this . keyId = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind events and setup collectionKeys for a collection that is to be used as the backing store for a HasMany . If no collection is supplied a new collection will be created of the specified collectionType option . [CODESPLIT] function ( collection ) { if ( this . related ) { this . stopListening ( this . related ) ; } if ( ! collection || ! ( collection instanceof Backbone . Collection ) ) { var options = _ . isFunction ( this . options . collectionOptions ) ? this . options . collectionOptions ( this . instance ) : this . options . collectionOptions ; collection = new this . collectionType ( null , options ) ; } collection . model = this . relatedModel ; if ( this . options . collectionKey ) { var key = this . options . collectionKey === true ? this . options . reverseRelation . key : this . options . collectionKey ; if ( collection [ key ] && collection [ key ] !== this . instance ) { if ( Backbone . Relational . showWarnings && typeof console !== 'undefined' ) { console . warn ( 'Relation=%o; collectionKey=%s already exists on collection=%o' , this , key , this . options . collectionKey ) ; } } else if ( key ) { collection [ key ] = this . instance ; } } this . listenTo ( collection , 'relational:add' , this . handleAddition ) . listenTo ( collection , 'relational:remove' , this . handleRemoval ) . listenTo ( collection , 'relational:reset' , this . handleReset ) ; return collection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find related Models . [CODESPLIT] function ( options ) { var related = null ; options = _ . defaults ( { parse : this . options . parse } , options ) ; // Replace 'this.related' by 'this.keyContents' if it is a Backbone.Collection if ( this . keyContents instanceof Backbone . Collection ) { this . _prepareCollection ( this . keyContents ) ; related = this . keyContents ; } // Otherwise, 'this.keyContents' should be an array of related object ids. // Re-use the current 'this.related' if it is a Backbone.Collection; otherwise, create a new collection. else { var toAdd = [ ] ; _ . each ( this . keyContents , function ( attributes ) { if ( attributes instanceof this . relatedModel ) { var model = attributes ; } else { // If `merge` is true, update models here, instead of during update. model = this . relatedModel . findOrCreate ( attributes , _ . extend ( { merge : true } , options , { create : this . options . createModels } ) ) ; } model && toAdd . push ( model ) ; } , this ) ; if ( this . related instanceof Backbone . Collection ) { related = this . related ; } else { related = this . _prepareCollection ( ) ; } // By now, both `merge` and `parse` will already have been executed for models if they were specified. // Disable them to prevent additional calls. related . set ( toAdd , _ . defaults ( { merge : false , parse : false } , options ) ) ; } // Remove entries from `keyIds` that were already part of the relation (and are thus 'unchanged') this . keyIds = _ . difference ( this . keyIds , _ . pluck ( related . models , 'id' ) ) ; return related ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize and reduce keyContents to a list of ids for easier comparison [CODESPLIT] function ( keyContents ) { this . keyContents = keyContents instanceof Backbone . Collection ? keyContents : null ; this . keyIds = [ ] ; if ( ! this . keyContents && ( keyContents || keyContents === 0 ) ) { // since 0 can be a valid `id` as well // Handle cases the an API/user supplies just an Object/id instead of an Array this . keyContents = _ . isArray ( keyContents ) ? keyContents : [ keyContents ] ; _ . each ( this . keyContents , function ( item ) { var itemId = Backbone . Relational . store . resolveIdForItem ( this . relatedModel , item ) ; if ( itemId || itemId === 0 ) { this . keyIds . push ( itemId ) ; } } , this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event handler for change : <key > . If the contents of the key are changed notify old & new reverse relations and initialize the new relation . [CODESPLIT] function ( model , attr , options ) { options = options ? _ . clone ( options ) : { } ; this . setKeyContents ( attr ) ; this . changed = false ; var related = this . findRelated ( options ) ; this . setRelated ( related ) ; if ( ! options . silent ) { var dit = this ; Backbone . Relational . eventQueue . add ( function ( ) { // The `changed` flag can be set in `handleAddition` or `handleRemoval` if ( dit . changed ) { dit . instance . trigger ( 'change:' + dit . key , dit . instance , dit . related , options , true ) ; dit . changed = false ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When a model is removed from a HasMany trigger remove on this . instance and notify reverse relations . ( should be HasOne which should be nullified ) [CODESPLIT] function ( model , coll , options ) { //console.debug('handleRemoval called; args=%o', arguments); options = options ? _ . clone ( options ) : { } ; this . changed = true ; _ . each ( this . getReverseRelations ( model ) , function ( relation ) { relation . removeRelated ( this . instance , null , options ) ; } , this ) ; var dit = this ; ! options . silent && Backbone . Relational . eventQueue . add ( function ( ) { dit . instance . trigger ( 'remove:' + dit . key , model , dit . related , options ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override trigger to queue change and change : * events [CODESPLIT] function ( eventName ) { if ( eventName . length > 5 && eventName . indexOf ( 'change' ) === 0 ) { var dit = this , args = arguments ; Backbone . Relational . eventQueue . add ( function ( ) { if ( ! dit . _isInitialized ) { return ; } // Determine if the `change` event is still valid, now that all relations are populated var changed = true ; if ( eventName === 'change' ) { // `hasChanged` may have gotten reset by nested calls to `set`. changed = dit . hasChanged ( ) || dit . _attributeChangeFired ; dit . _attributeChangeFired = false ; } else { var attr = eventName . slice ( 7 ) , rel = dit . getRelation ( attr ) ; if ( rel ) { // If `attr` is a relation, `change:attr` get triggered from `Relation.onChange`. // These take precedence over `change:attr` events triggered by `Model.set`. // The relation sets a fourth attribute to `true`. If this attribute is present, // continue triggering this event; otherwise, it's from `Model.set` and should be stopped. changed = ( args [ 4 ] === true ) ; // If this event was triggered by a relation, set the right value in `this.changed` // (a Collection or Model instead of raw data). if ( changed ) { dit . changed [ attr ] = args [ 2 ] ; } // Otherwise, this event is from `Model.set`. If the relation doesn't report a change, // remove attr from `dit.changed` so `hasChanged` doesn't take it into account. else if ( ! rel . changed ) { delete dit . changed [ attr ] ; } } else if ( changed ) { dit . _attributeChangeFired = true ; } } changed && Backbone . Model . prototype . trigger . apply ( dit , args ) ; } ) ; } else { Backbone . Model . prototype . trigger . apply ( this , arguments ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize Relations present in this . relations ; determine the type ( HasOne / HasMany ) then creates a new instance . Invoked in the first call so set ( which is made from the Backbone . Model constructor ) . [CODESPLIT] function ( options ) { this . acquire ( ) ; // Setting up relations often also involve calls to 'set', and we only want to enter this function once this . _relations = { } ; _ . each ( _ . result ( this , 'relations' ) || [ ] , function ( rel ) { Backbone . Relational . store . initializeRelation ( this , rel , options ) ; } , this ) ; this . _isInitialized = true ; this . release ( ) ; this . processQueue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When new values are set notify this model s relations ( also if options . silent is set ) . ( Relation . setRelated locks this model before calling set on it to prevent loops ) [CODESPLIT] function ( options ) { if ( this . _isInitialized && ! this . isLocked ( ) ) { _ . each ( this . _relations , function ( rel ) { // Update from data in `rel.keySource` if data got set in there, or `rel.key` otherwise var val = this . attributes [ rel . keySource ] || this . attributes [ rel . key ] ; if ( rel . related !== val ) { this . trigger ( 'relational:change:' + rel . key , this , val , options || { } ) ; } // Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'. if ( rel . keySource !== rel . key ) { delete rel . instance . attributes [ rel . keySource ] ; } } , this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve related objects . [CODESPLIT] function ( key , options , refresh ) { // Set default `options` for fetch options = _ . extend ( { update : true , remove : false } , options ) ; var setUrl , requests = [ ] , rel = this . getRelation ( key ) , idsToFetch = rel && ( ( rel . keyIds && rel . keyIds . slice ( 0 ) ) || ( ( rel . keyId || rel . keyId === 0 ) ? [ rel . keyId ] : [ ] ) ) ; // On `refresh`, add the ids for current models in the relation to `idsToFetch` if ( refresh ) { var models = rel . related instanceof Backbone . Collection ? rel . related . models : [ rel . related ] ; _ . each ( models , function ( model ) { if ( model . id || model . id === 0 ) { idsToFetch . push ( model . id ) ; } } ) ; } if ( idsToFetch && idsToFetch . length ) { // Find (or create) a model for each one that is to be fetched var created = [ ] , models = _ . map ( idsToFetch , function ( id ) { var model = Backbone . Relational . store . find ( rel . relatedModel , id ) ; if ( ! model ) { var attrs = { } ; attrs [ rel . relatedModel . prototype . idAttribute ] = id ; model = rel . relatedModel . findOrCreate ( attrs , options ) ; created . push ( model ) ; } return model ; } , this ) ; // Try if the 'collection' can provide a url to fetch a set of models in one request. if ( rel . related instanceof Backbone . Collection && _ . isFunction ( rel . related . url ) ) { setUrl = rel . related . url ( models ) ; } // An assumption is that when 'Backbone.Collection.url' is a function, it can handle building of set urls. // To make sure it can, test if the url we got by supplying a list of models to fetch is different from // the one supplied for the default fetch action (without args to 'url'). if ( setUrl && setUrl !== rel . related . url ( ) ) { var opts = _ . defaults ( { error : function ( ) { var args = arguments ; _ . each ( created , function ( model ) { model . trigger ( 'destroy' , model , model . collection , options ) ; options . error && options . error . apply ( model , args ) ; } ) ; } , url : setUrl } , options ) ; requests = [ rel . related . fetch ( opts ) ] ; } else { requests = _ . map ( models , function ( model ) { var opts = _ . defaults ( { error : function ( ) { if ( _ . contains ( created , model ) ) { model . trigger ( 'destroy' , model , model . collection , options ) ; options . error && options . error . apply ( model , arguments ) ; } } } , options ) ; return model . fetch ( opts ) ; } , this ) ; } } return requests ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert relations to JSON omits them when required [CODESPLIT] function ( options ) { // If this Model has already been fully serialized in this branch once, return to avoid loops if ( this . isLocked ( ) ) { return this . id ; } this . acquire ( ) ; var json = Backbone . Model . prototype . toJSON . call ( this , options ) ; if ( this . constructor . _superModel && ! ( this . constructor . _subModelTypeAttribute in json ) ) { json [ this . constructor . _subModelTypeAttribute ] = this . constructor . _subModelTypeValue ; } _ . each ( this . _relations , function ( rel ) { var related = json [ rel . key ] , includeInJSON = rel . options . includeInJSON , value = null ; if ( includeInJSON === true ) { if ( related && _ . isFunction ( related . toJSON ) ) { value = related . toJSON ( options ) ; } } else if ( _ . isString ( includeInJSON ) ) { if ( related instanceof Backbone . Collection ) { value = related . pluck ( includeInJSON ) ; } else if ( related instanceof Backbone . Model ) { value = related . get ( includeInJSON ) ; } // Add ids for 'unfound' models if includeInJSON is equal to (only) the relatedModel's `idAttribute` if ( includeInJSON === rel . relatedModel . prototype . idAttribute ) { if ( rel instanceof Backbone . HasMany ) { value = value . concat ( rel . keyIds ) ; } else if ( rel instanceof Backbone . HasOne ) { value = value || rel . keyId ; } } } else if ( _ . isArray ( includeInJSON ) ) { if ( related instanceof Backbone . Collection ) { value = [ ] ; related . each ( function ( model ) { var curJson = { } ; _ . each ( includeInJSON , function ( key ) { curJson [ key ] = model . get ( key ) ; } ) ; value . push ( curJson ) ; } ) ; } else if ( related instanceof Backbone . Model ) { value = { } ; _ . each ( includeInJSON , function ( key ) { value [ key ] = related . get ( key ) ; } ) ; } } else { delete json [ rel . key ] ; } if ( includeInJSON ) { json [ rel . keyDestination ] = value ; } if ( rel . keyDestination !== rel . key ) { delete json [ rel . key ] ; } } ) ; this . release ( ) ; return json ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines what type of ( sub ) model should be built if applicable . Looks up the proper subModelType in this . _subModels recursing into types until a match is found . Returns the applicable Backbone . Model or null if no match is found . [CODESPLIT] function ( type , attributes ) { if ( type . _subModels && type . prototype . subModelTypeAttribute in attributes ) { var subModelTypeAttribute = attributes [ type . prototype . subModelTypeAttribute ] ; var subModelType = type . _subModels [ subModelTypeAttribute ] ; if ( subModelType ) { return subModelType ; } else { // Recurse into subModelTypes to find a match for ( subModelTypeAttribute in type . _subModels ) { subModelType = this . _findSubModelType ( type . _subModels [ subModelTypeAttribute ] , attributes ) ; if ( subModelType ) { return subModelType ; } } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find an instance of this type in Backbone . Relational . store . - If attributes is a string or a number findOrCreate will just query the store and return a model if found . - If attributes is an object and is found in the store the model will be updated with attributes unless options . update is false . Otherwise a new model is created with attributes ( unless options . create is explicitly set to false ) . [CODESPLIT] function ( attributes , options ) { options || ( options = { } ) ; var parsedAttributes = ( _ . isObject ( attributes ) && options . parse && this . prototype . parse ) ? this . prototype . parse ( _ . clone ( attributes ) ) : attributes ; // Try to find an instance of 'this' model type in the store var model = Backbone . Relational . store . find ( this , parsedAttributes ) ; // If we found an instance, update it with the data in 'item' (unless 'options.merge' is false). // If not, create an instance (unless 'options.create' is false). if ( _ . isObject ( attributes ) ) { if ( model && options . merge !== false ) { // Make sure `options.collection` and `options.url` doesn't cascade to nested models delete options . collection ; delete options . url ; model . set ( parsedAttributes , options ) ; } else if ( ! model && options . create !== false ) { model = this . build ( attributes , options ) ; } } return model ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find an instance of this type in Backbone . Relational . store . - If attributes is a string or a number find will just query the store and return a model if found . - If attributes is an object and is found in the store the model will be updated with attributes unless options . update is false . [CODESPLIT] function ( attributes , options ) { options || ( options = { } ) ; options . create = false ; return this . findOrCreate ( attributes , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Base class for many xtal - components [CODESPLIT] function XtallatX ( superClass ) { return class extends superClass { constructor ( ) { super ( ... arguments ) ; this . _evCount = { } ; } static get observedAttributes ( ) { return [ disabled ] ; } /**\n         * Any component that emits events should not do so if it is disabled.\n         * Note that this is not enforced, but the disabled property is made available.\n         * Users of this mix-in should ensure not to call \"de\" if this property is set to true.\n         */ get disabled ( ) { return this . _disabled ; } set disabled ( val ) { this . attr ( disabled , val , '' ) ; } /**\n         * Set attribute value.\n         * @param name\n         * @param val\n         * @param trueVal String to set attribute if true.\n         */ attr ( name , val , trueVal ) { const v = val ? 'set' : 'remove' ; //verb this [ v + 'Attribute' ] ( name , trueVal || val ) ; } /**\n         * Turn number into string with even and odd values easy to query via css.\n         * @param n\n         */ to$ ( n ) { const mod = n % 2 ; return ( n - mod ) / 2 + '-' + mod ; } /**\n         * Increment event count\n         * @param name\n         */ incAttr ( name ) { const ec = this . _evCount ; if ( name in ec ) { ec [ name ] ++ ; } else { ec [ name ] = 0 ; } this . attr ( 'data-' + name , this . to$ ( ec [ name ] ) ) ; } attributeChangedCallback ( name , oldVal , newVal ) { switch ( name ) { case disabled : this . _disabled = newVal !== null ; break ; } } /**\n         * Dispatch Custom Event\n         * @param name Name of event to dispatch (\"-changed\" will be appended if asIs is false)\n         * @param detail Information to be passed with the event\n         * @param asIs If true, don't append event name with '-changed'\n         */ de ( name , detail , asIs = false ) { const eventName = name + ( asIs ? '' : '-changed' ) ; const newEvent = new CustomEvent ( eventName , { detail : detail , bubbles : true , composed : false , } ) ; this . dispatchEvent ( newEvent ) ; this . incAttr ( eventName ) ; return newEvent ; } /**\n         * Needed for asynchronous loading\n         * @param props Array of property names to \"upgrade\", without losing value set while element was Unknown\n         */ _upgradeProperties ( props ) { props . forEach ( prop => { if ( this . hasOwnProperty ( prop ) ) { let value = this [ prop ] ; delete this [ prop ] ; this [ prop ] = value ; } } ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( C ) Andrea Giammarchi - [CODESPLIT] function ( re ) { var arr = [ ] , tag ; for ( tag in register ) { if ( re . test ( tag ) ) arr . push ( tag ) ; } return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( C ) Andrea Giammarchi - [CODESPLIT] function ( Class , tag ) { tag = tag . toLowerCase ( ) ; if ( ! ( tag in register ) ) { register [ Class ] = ( register [ Class ] || [ ] ) . concat ( tag ) ; register [ tag ] = ( register [ tag . toUpperCase ( ) ] = Class ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize Path [CODESPLIT] function normalizePath ( path ) { path = '/' + path path = resolve ( normalize ( path ) ) path = path . replace ( / (%[a-f0-9]{2}) / g , $1 => $1 . toUpperCase ( ) ) if ( path === '' ) path = '/' return path }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the arguments and return an special array . [CODESPLIT] function parseArgs ( ... args ) { const l = args . length const last = args [ l - 1 ] let cb , opts , paths if ( _ . isFunction ( last ) ) { cb = last args . pop ( ) ; // don't remove this semicolon [ paths , opts ] = parseArgs ( ... args ) } else if ( _ . isObject ( last ) && ! Array . isArray ( last ) ) { opts = last args . pop ( ) paths = args } else if ( ! last && l > 0 ) { args . pop ( ) return parseArgs ( ... args ) } else { paths = args } return [ _ . compact ( _ . flatten ( paths , true ) ) , opts || { } , cb ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * sort functions each sort function takes two parameters a and b you are comparing a [ 0 ] and b [ 0 ] [CODESPLIT] function sort_numeric ( a , b ) { var aa = void 0 , bb = void 0 ; aa = parseFloat ( a [ 0 ] . replace ( / [^0-9.-] / g , '' ) ) ; if ( isNaN ( aa ) ) aa = 0 ; bb = parseFloat ( b [ 0 ] . replace ( / [^0-9.-] / g , '' ) ) ; if ( isNaN ( bb ) ) bb = 0 ; return aa - bb ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A Bitmap represents an Image Canvas or Video in the display list . A Bitmap can be instantiated using an existing HTML element or a string . [CODESPLIT] function Bitmap ( imageOrUri ) { this . DisplayObject_constructor ( ) ; // public properties: /**\n\t\t * The source image to display. This can be a CanvasImageSource\n\t\t * (image, video, canvas), an object with a `getImage` method that returns a CanvasImageSource, or a string URL to an image.\n\t\t * If the latter, a new Image instance with the URL as its src will be used.\n\t\t * @property image\n\t\t * @type CanvasImageSource | Object\n\t\t **/ if ( typeof imageOrUri == \"string\" ) { this . image = document . createElement ( \"img\" ) ; this . image . src = imageOrUri ; } else { this . image = imageOrUri ; } /**\n\t\t * Specifies an area of the source image to draw. If omitted, the whole image will be drawn.\n\t\t * Note that video sources must have a width / height set to work correctly with `sourceRect`.\n\t\t * @property sourceRect\n\t\t * @type Rectangle\n\t\t * @default null\n\t\t */ this . sourceRect = null ; // private properties: /**\n\t\t * Docced in superclass.\n\t\t */ this . _webGLRenderStyle = createjs . DisplayObject . _StageGL_BITMAP ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "constructor : Applies a box blur to DisplayObjects . Note that this filter is fairly CPU intensive particularly if the quality is set higher than 1 . [CODESPLIT] function BlurFilter ( blurX , blurY , quality ) { this . Filter_constructor ( ) ; // public properties: /**\n\t\t * Horizontal blur radius in pixels\n\t\t * @property blurX\n\t\t * @default 0\n\t\t * @type Number\n\t\t **/ this . _blurX = blurX ; this . _blurXTable = [ ] ; /**\n\t\t * Vertical blur radius in pixels\n\t\t * @property blurY\n\t\t * @default 0\n\t\t * @type Number\n\t\t **/ this . _blurY = blurY ; this . _blurYTable = [ ] ; /**\n\t\t * Number of blur iterations. For example, a value of 1 will produce a rough blur. A value of 2 will produce a\n\t\t * smoother blur, but take twice as long to run.\n\t\t * @property quality\n\t\t * @default 1\n\t\t * @type Number\n\t\t **/ this . _quality ; /**\n\t\t * This is a template to generate the shader for {{#crossLink FRAG_SHADER_BODY}}{{/crossLink}}\n\t\t */ this . FRAG_SHADER_TEMPLATE = ( \"uniform float xWeight[{{blurX}}];\" + \"uniform float yWeight[{{blurY}}];\" + \"uniform vec2 textureOffset;\" + \"void main(void) {\" + \"vec4 color = vec4(0.0);\" + \"float xAdj = ({{blurX}}.0-1.0)/2.0;\" + \"float yAdj = ({{blurY}}.0-1.0)/2.0;\" + \"vec2 sampleOffset;\" + \"for(int i=0; i<{{blurX}}; i++) {\" + \"for(int j=0; j<{{blurY}}; j++) {\" + \"sampleOffset = vRenderCoord + (textureOffset * vec2(float(i)-xAdj, float(j)-yAdj));\" + \"color += texture2D(uSampler, sampleOffset) * (xWeight[i] * yWeight[j]);\" + \"}\" + \"}\" + \"gl_FragColor = color.rgba;\" + \"}\" ) ; // update the filter using the setters if ( isNaN ( quality ) || quality < 1 ) { quality = 1 ; } this . setQuality ( quality | 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NODE_MODULES_PATHS ( START ) 1 . let PARTS = path split ( START ) 2 . let I = count of PARTS - 1 3 . let DIRS = [] 4 . while I > = 0 a . if PARTS [ I ] = node_modules CONTINUE c . DIR = path join ( PARTS [ 0 .. I ] + node_modules ) b . DIRS = DIRS + DIR c . let I = I - 1 5 . return DIRS Alloy doesn t like it when you include the file extension ... [CODESPLIT] function convert_to_alloy_path ( resolved_path ) { var parsed_path = path . posix . parse ( resolved_path ) ; return path . posix . join ( parsed_path . dir , parsed_path . name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOAD_AS_FILE ( X ) 1 . If X is a file load X as JavaScript text . STOP 2 . If X . js is a file load X . js as JavaScript text . STOP 3 . If X . json is a file parse X . json to a JavaScript Object . STOP 4 . If X . node is a file load X . node as binary addon . STOP [CODESPLIT] function load_as_file ( request , startpath ) { var module_path ; var resolved_path = path . posix . resolve ( startpath , request ) ; _ . includes ( registry . files , resolved_path ) && ( module_path = resolved_path ) ; if ( module_path ) { // logger.trace(\"file found: \" + module_path); return module_path ; } var extension = path . extname ( request ) ; if ( ! extension ) { var exts = [ \".js\" , \".json\" ] ; _ . forEach ( exts , function ( ext ) { resolved_path = path . posix . resolve ( startpath , request + ext ) ; _ . includes ( registry . files , resolved_path ) && ( module_path = resolved_path ) ; if ( ! module_path ) { return ! module_path ; } } ) ; } return module_path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOAD_AS_DIRECTORY ( X ) 1 . If X / package . json is a file a . Parse X / package . json and look for main field . b . let M = X + ( json main field ) c . LOAD_AS_FILE ( M ) 2 . If X / index . js is a file load X / index . js as JavaScript text . STOP 3 . If X / index . json is a file parse X / index . json to a JavaScript object . STOP 4 . If X / index . node is a file load X / index . node as binary addon . STOP [CODESPLIT] function load_as_directory ( request , startpath ) { var resolved_path = path . posix . resolve ( startpath , request ) ; var module_path = _ . find ( registry . directories , function ( item ) { return item . id === resolved_path ; } ) ; if ( module_path ) { return module_path . path ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOAD_NODE_MODULES ( X START ) 1 . let DIRS = NODE_MODULES_PATHS ( START ) 2 . for each DIR in DIRS : a . LOAD_AS_FILE ( DIR / X ) b . LOAD_AS_DIRECTORY ( DIR / X ) [CODESPLIT] function load_node_modules ( request , startpath ) { var resolved_path ; var nodepaths = node_modules_paths ( startpath ) ; _ . forEach ( nodepaths , function ( nodepath ) { resolved_path = load_as_file ( request , nodepath ) ; return ! resolved_path ; } ) ; if ( resolved_path ) { return resolved_path ; } _ . forEach ( nodepaths , function ( nodepath ) { resolved_path = load_as_directory ( request , nodepath ) ; return ! resolved_path ; } ) ; return resolved_path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a new Thing that has the keys in sorted order . Recursive . [CODESPLIT] function canonicalize ( value , stack ) { var canonicalizedObj ; /* eslint-disable no-unused-vars */ var prop ; /* eslint-enable no-unused-vars */ var type = getType ( value ) ; function withStack ( value , fn ) { stack . push ( value ) ; fn ( ) ; stack . pop ( ) ; } stack = stack || [ ] ; if ( stack . indexOf ( value ) !== - 1 ) { return '[Circular]' ; } switch ( type ) { case 'undefined' : case 'buffer' : case 'null' : canonicalizedObj = value ; break ; case 'array' : withStack ( value , function ( ) { canonicalizedObj = value . map ( function ( item ) { return canonicalize ( item , stack ) ; } ) ; } ) ; break ; case 'function' : /* eslint-disable guard-for-in */ for ( prop in value ) { canonicalizedObj = { } ; break ; } /* eslint-enable guard-for-in */ if ( ! canonicalizedObj ) { canonicalizedObj = emptyRepresentation ( value , type ) ; break ; } /* falls through */ case 'object' : canonicalizedObj = canonicalizedObj || { } ; withStack ( value , function ( ) { Object . keys ( value ) . sort ( ) . forEach ( function ( key ) { canonicalizedObj [ key ] = canonicalize ( value [ key ] , stack ) ; } ) ; } ) ; break ; case 'date' : case 'number' : case 'regexp' : case 'boolean' : canonicalizedObj = value ; break ; default : canonicalizedObj = value . toString ( ) ; } return canonicalizedObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a value could have properties and has none this function is called which returns a string representation of the empty value . [CODESPLIT] function emptyRepresentation ( value , type ) { type = type || getType ( value ) ; switch ( type ) { case 'function' : return '[Function]' ; case 'object' : return '{}' ; case 'array' : return '[]' ; default : return value . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used with spread to transform ( data metadata ) pairs from dynode into just data [CODESPLIT] function createDynodeOptions ( dynamoAsPromisedOptions , key , extraDynodeOptions ) { var dynodeOptions = _ . clone ( extraDynodeOptions || { } ) ; // If given an `onlyIfExists` option, assemble the `Expected` Dynode option value by looking at the key and values. // Example: //     var key = { hash: \"H\", range: 5 }; //     var dapOptions = { onlyIfExists: { hash: \"h\", range: \"r\" } }; //     createDynodeOptions(dapOptions, key) === { //         Expected: { h: { Value: { S: \"H\" }, r: { Value: { N: 5 } } } //     }; if ( typeof dynamoAsPromisedOptions === \"object\" && dynamoAsPromisedOptions . onlyIfExists ) { dynodeOptions . Expected = { } ; var keyValues = typeof key === \"string\" ? { hash : key } : key ; var keysThatMustExist = typeof dynamoAsPromisedOptions . onlyIfExists === \"string\" ? { hash : dynamoAsPromisedOptions . onlyIfExists } : dynamoAsPromisedOptions . onlyIfExists ; Object . keys ( keysThatMustExist ) . forEach ( function ( keyType ) { var keyName = keysThatMustExist [ keyType ] ; var beforeTypeAnnotations = { } ; beforeTypeAnnotations [ keyName ] = keyValues [ keyType ] ; var withTypeAnnotations = addDynamoTypeAnnotations ( beforeTypeAnnotations ) ; dynodeOptions . Expected [ keyName ] = { Value : withTypeAnnotations [ keyName ] } ; } ) ; } return dynodeOptions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "increment anchor count [CODESPLIT] function ( doc , first , last ) { var f = doc . WordPos [ first ] ; var l ; if ( last == doc . WordPos . length - 1 ) // l = doc . DocLength ; else l = doc . WordPos [ last + 1 ] ; return l - f ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given js currently supporting : [CODESPLIT] function parseConditionals ( js ) { var lines = js . split ( '\\n' ) , len = lines . length , buffer = true , browser = false , buf = [ ] , line , cond ; for ( var i = 0 ; i < len ; ++ i ) { line = lines [ i ] ; if ( / ^ *\\/\\/ *if *(node|browser) / gm . exec ( line ) ) { cond = RegExp . $1 ; buffer = browser = 'browser' == cond ; } else if ( / ^ *\\/\\/ *end / . test ( line ) ) { buffer = true ; browser = false ; } else if ( browser ) { buf . push ( line . replace ( / ^( *)\\/\\/ / , '$1' ) ) ; } else if ( buffer ) { buf . push ( line ) ; } } return buf . join ( '\\n' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile the files . [CODESPLIT] function compile ( ) { var buf = '' ; buf += '(function() {\\n' ; buf += '\\n// CommonJS require()\\n\\n' ; buf += browser . require + '\\n\\n' ; buf += 'require.modules = {};\\n\\n' ; buf += 'require.resolve = ' + browser . resolve + ';\\n\\n' ; buf += 'require.register = ' + browser . register + ';\\n\\n' ; buf += 'require.relative = ' + browser . relative + ';\\n\\n' ; args . forEach ( function ( file ) { var js = files [ file ] ; file = file . replace ( 'lib/' , '' ) ; buf += '\\nrequire.register(\"' + file + '\", function(module, exports, require){\\n' ; buf += js ; buf += '\\n}); // module: ' + file + '\\n' ; } ) ; buf += '\\nwindow.kiwi = require(\"kiwi\");\\n' ; buf += '})();\\n' ; fs . writeFile ( 'kiwi.js' , buf , function ( err ) { if ( err ) throw err ; console . log ( '  \\033[90m create : \\033[0m\\033[36m%s\\033[0m' , 'kiwi.js' ) ; console . log ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ a . b . c d ] - > [ a b c d ] [CODESPLIT] function splitDots ( list ) { var result = [ ] ; list . forEach ( function ( x ) { if ( typeof x === 'string' ) { x . split ( '.' ) . forEach ( function ( part ) { result . push ( part ) ; } ) ; } else { result . push ( x ) ; } } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an optimistic chain no checks before calling a function or accessing a property or calling a method [CODESPLIT] function fp ( ) { var args = Array . prototype . slice . call ( arguments , 0 ) ; if ( args . length ) { if ( ! args . every ( isStringOrFunction ) ) { var signature = args . map ( humanizeArgument ) . join ( '\\n\\t' ) ; throw new Error ( 'Invalid arguments to functional pipeline - not a string or function\\n\\t' + signature ) ; } var fns = splitDots ( args ) ; return function ( d ) { var originalObject = d ; fns . forEach ( function ( fn ) { if ( typeof fn === 'string' ) { if ( typeof d [ fn ] === 'function' ) { d = d [ fn ] . call ( d , d ) ; } else if ( typeof d [ fn ] !== 'undefined' ) { d = d [ fn ] ; } else { var signature = args . map ( humanizeArgument ) . join ( '\\n\\t' ) ; throw new Error ( 'Cannot use property ' + fn + ' from object ' + JSON . stringify ( d , null , 2 ) + '\\npipeline\\n\\t' + signature + '\\noriginal object\\n' + JSON . stringify ( originalObject , null , 2 ) ) ; } } else if ( typeof fn === 'function' ) { d = fn ( d ) ; } else { throw new Error ( 'Cannot apply ' + JSON . stringify ( fn , null , 2 ) + ' to value ' + d + ' not a property name or a function' ) ; } } ) ; return d ; } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "VATPeriod [CODESPLIT] function VATPeriod ( effectiveFrom , superReduced , reduced , standard , parking ) { this . _effectiveFrom = effectiveFrom ; this . _superReduced = superReduced ; this . _reduced = reduced ; this . _standard = standard ; this . _parking = parking ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Read tags from tags directory [CODESPLIT] function loadFilters ( loadedFiles ) { loadedFiles = loadedFiles || frame . files . requireDir ( __dirname + '/filters/' ) ; for ( var file in loadedFiles ) { var fileFilters = loadedFiles [ file ] ; for ( var filter in fileFilters ) { filters [ filter ] = fileFilters [ filter ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a new Rieussec stopwatch [CODESPLIT] function ( tickRate ) { events . EventEmitter . call ( this ) ; // Initialize private properties this . _milliseconds = 0 ; this . _setState ( 'stopped' ) ; this . _timer = new NanoTimer ( ) ; tickRate = tickRate || 100 ; Object . defineProperty ( this , 'tickRate' , { enumerable : true , configurable : false , writable : false , value : tickRate } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback for utils . applyAll [CODESPLIT] function onProcessed ( err , processed ) { if ( err ) return callback ( err ) ; _this . _tokenize ( processed , onTokenized ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback for Compiler#_tokenize [CODESPLIT] function onTokenized ( err , tokenized ) { if ( err ) return callback ( err ) ; tokenized . compile ( _this , onCompiled ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback for Compiler#_compileTokens [CODESPLIT] function onCompiled ( err , compiled ) { if ( err ) return callback ( err ) ; var func ; try { func = new Function ( \"$template\" , \"$tools\" , \"_\" , \"$data\" , \"$helpers\" , \"$callback\" , compiled ) ; } catch ( err ) { return callback ( err ) ; } func . $helpers = _this . helpers ; callback ( null , func ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Base token / * Initializes BaseToken with parent and root . [CODESPLIT] function BaseToken ( root , parent , options ) { this . parent = parent ; this . children = [ ] ; this . tag = null ; this . tagType = null ; this . options = options ; this . root = root ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Literal token / * Initialize LiteralToken with parent root and literal [CODESPLIT] function LiteralToken ( literal , root , parent , options ) { LiteralToken . _superclass . call ( this , root , parent , options ) ; this . literal = literal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Block token / * Initialize BlockToken for tag of tagType with parent and children [CODESPLIT] function BlockToken ( tag , tagType , root , parent , children , options ) { BlockToken . _superclass . call ( this , root , parent , options ) ; this . tag = tag ; this . tagType = tagType ; if ( ! children ) children = [ ] ; this . children = children ; this . intermediate = [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Initialize IntermediateToken for tag of tagType with parent and children [CODESPLIT] function IntermediateToken ( tag , tagType , root , parent , children , options ) { IntermediateToken . _superclass . call ( this , tag , tagType , root , parent , children , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Global functions Outputs if clause based on condition . If not strict actual test will be wrapped in a try…catch statement to catch ReferenceErrors silently [CODESPLIT] function createIfCondition ( condition , strict ) { var compiled ; if ( strict ) { compiled = 'if(' + condition + ')' ; } else { compiled = 'try {' + '__tmp = ' + condition + '} catch(__err) {' + 'if(__err instanceof ReferenceError) {' + '__tmp = false;' + '} else {' + 'throw __err;' + '}' + '}' + 'if(__tmp)' ; } return compiled ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "VATCountry [CODESPLIT] function VATCountry ( name , code , countryCode , periods , date ) { this . _name = name ; this . _code = code ; this . _countryCode = countryCode ; this . _periods = periods ; this . setDate ( date ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously compiles tokens and invoke callback ( err compiled ) with compiled as an array . [CODESPLIT] function compileTokenArray ( tokens , compiler , callback ) { var acc = [ ] ; var index = 0 ; function compileOne ( token , next ) { token . compile ( compiler , function onCompiled ( err , compiled ) { if ( err ) return next ( err ) ; acc . push ( compiled ) ; next ( null , compiled ) ; } ) ; index ++ ; } function done ( err ) { if ( err ) return callback ( err ) ; callback ( null , acc ) ; } asyncForEach ( tokens , compileOne , done ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes Template with optionnally the given str and options . [CODESPLIT] function Template ( str , options ) { // Handle the case where the only argument passed is the `options` object if ( _ . isObject ( str ) && ! options ) { options = str ; str = null ; } // Create options if not provided options = options ? _ . clone ( options ) : { } ; // Set default cache behavior // if node if ( ! _ . isBoolean ( options . cache ) ) { options . cache = process . env . NODE_ENV === 'production' ; } // end // Merges given `options` with `DEFAULTS` options = _ . defaults ( options , DEFAULTS ) ; options . cacheContext = options . cacheContext || Template ; // Sets instance variables this . template = str ; this . options = options ; this . _compiled = null ; // Creates the cache if not already done if ( options . cache && ! ( this . _getCache ( ) instanceof options . cacheHandler ) ) { var cacheOptions = [ options . cacheHandler ] . concat ( options . cacheOptions ) ; options . cacheContext [ options . _cacheProp ] = typeof window !== 'undefined' ? new options . cacheHandler ( ) : construct . apply ( this , cacheOptions ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "used to fix fs . watch on windows triggering cascading events the function fn can only be called once per rate [CODESPLIT] function ( fn , rate ) { var allowed = true ; return function ( ) { if ( allowed ) { allowed = false ; fn . apply ( null , [ ] . slice . call ( arguments , 0 ) ) ; setTimeout ( function ( ) { allowed = true ; } , rate ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get optional data from command line as json or file containing json or javascript [CODESPLIT] function get_data ( callback ) { var data ; try { data = program . data ? JSON . parse ( program . data ) : { } ; callback ( data ) ; } catch ( err ) { fs . readFile ( program . data , function ( err , str ) { str = '' + str ; if ( ! err ) { try { data = JSON . parse ( str ) ; callback ( data ) ; } catch ( err ) { data = eval ( str ) ; callback ( data ) ; } } } ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "function ispunct ( ch ) { return / [ ! #$%& () * + - . \\ / : ; < = > ? [CODESPLIT] function ispunct ( ch ) { ch = ch . charCodeAt ( 0 ) ; return ( ch >= 0x21 && ch <= 0x2F ) || ( ch >= 0x3a && ch <= 0x40 ) || ( ch >= 0x5B && ch <= 0x60 ) || ( ch >= 0x7F ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * hash : function ( s ) { using Java s hash method ( except on empty string ) var hash = 0 i l char ; if ( s . length == 0 ) return 1 ; for ( i = 0 l = s . length ; i < l ; i ++ ) { char = s . charCodeAt ( i ) ; hash = (( hash << 5 ) - hash ) + char ; hash | = 0 ; // Convert to 32bit integer } return hash ; [CODESPLIT] function ( str ) { var inhash = 0 ; var charcount = 0 ; var char ; if ( str . length == 0 ) return 1 ; // if word is null, return 1 as hash value else for ( var i = 0 ; i < str . length ; i ++ ) { char = str . charCodeAt ( i ) ; inhash = ( ( inhash << 7 ) | ( inhash >>> 25 ) ) ^ char ; // xor into the rotateleft(7) of inhash inhash >>>= 0 ; // Convert to 32bit unsigned integer } return inhash ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds the webhook authentication middleware module to the webserver [CODESPLIT] function secureWebhookEndpoints ( ) { var authenticationMiddleware = require ( __dirname + '/middleware/slack_authentication.js' ) ; // convert a variable argument list to an array, drop the webserver argument var tokens = Array . prototype . slice . call ( arguments ) ; var webserver = tokens . shift ( ) ; slack_botkit . logger . info ( '** Requiring token authentication for webhook endpoints for Slash commands ' + 'and outgoing webhooks; configured ' + tokens . length + ' token(s)' ) ; webserver . use ( authenticationMiddleware ( tokens ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a POST request as a form to the given url with the options as data [CODESPLIT] function postForm ( url , formData , cb , multipart ) { cb = cb || noop ; bot . logger . info ( '** API CALL: ' + url ) ; var params = { url : url , headers : { 'User-Agent' : bot . userAgent ( ) , } } ; if ( multipart === true ) { params . formData = formData ; } else { params . form = formData ; } request . post ( params , function ( error , response , body ) { bot . logger . debug ( 'Got response' , error , body ) ; if ( error ) { return cb ( error ) ; } if ( response . statusCode == 200 ) { var json ; try { json = JSON . parse ( body ) ; } catch ( parseError ) { return cb ( parseError ) ; } return cb ( ( json . ok ? null : json . error ) , json ) ; } else if ( response . statusCode == 429 ) { return cb ( new Error ( 'Rate limit exceeded' ) ) ; } else { return cb ( new Error ( 'Invalid response' ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "var PKG_VERSION = require ( .. / package . json ) . version ; var express = require ( express ) ; var bodyParser = require ( body - parser ) ; [CODESPLIT] function Botkit ( configuration ) { var botkit = { events : { } , // this will hold event handlers config : { } , // this will hold the configuration tasks : [ ] , taskCount : 0 , convoCount : 0 , my_version : null , my_user_agent : null , memory_store : { users : { } , channels : { } , teams : { } , } } ; /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ // TODO: externalize this into some sort of utterances.json file botkit . utterances = { yes : new RegExp ( / ^(yes|yea|yup|yep|ya|sure|ok|y|yeah|yah) / i ) , no : new RegExp ( / ^(no|nah|nope|n) / i ) , quit : new RegExp ( / ^(quit|cancel|end|stop|done|exit|nevermind|never mind) / i ) } ; /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ // define some middleware points where custom functions // can plug into key points of botkits process botkit . middleware = { spawn : ware ( ) , ingest : ware ( ) , normalize : ware ( ) , categorize : ware ( ) , receive : ware ( ) , heard : ware ( ) , // best place for heavy i/o because fewer messages triggered : ware ( ) , // like heard, but for other events capture : ware ( ) , format : ware ( ) , send : ware ( ) , } ; botkit . ingest = function ( bot , payload , source ) { // keep an unmodified copy of the message payload . raw_message = clone ( payload ) ; payload . _pipeline = { stage : 'ingest' , } ; botkit . middleware . ingest . run ( bot , payload , source , function ( err , bot , payload , source ) { if ( err ) { console . error ( 'An error occured in the ingest middleware: ' , err ) ; return ; } botkit . normalize ( bot , payload ) ; } ) ; } ; botkit . normalize = function ( bot , payload ) { payload . _pipeline . stage = 'normalize' ; botkit . middleware . normalize . run ( bot , payload , function ( err , bot , message ) { if ( err ) { console . error ( 'An error occured in the normalize middleware: ' , err ) ; return ; } if ( ! message . type ) { message . type = 'message_received' ; } botkit . categorize ( bot , message ) ; } ) ; } ; botkit . categorize = function ( bot , message ) { message . _pipeline . stage = 'categorize' ; botkit . middleware . categorize . run ( bot , message , function ( err , bot , message ) { if ( err ) { console . error ( 'An error occured in the categorize middleware: ' , err ) ; return ; } botkit . receiveMessage ( bot , message ) ; } ) ; } ; botkit . receiveMessage = function ( bot , message ) { message . _pipeline . stage = 'receive' ; botkit . middleware . receive . run ( bot , message , function ( err , bot , message ) { if ( err ) { console . error ( 'An error occured in the receive middleware: ' , err ) ; return ; } else { botkit . logger . debug ( 'RECEIVED MESSAGE' ) ; bot . findConversation ( message , function ( convo ) { if ( convo ) { convo . handle ( message ) ; } else { botkit . trigger ( message . type , [ bot , message ] ) ; } } ) ; } } ) ; } ; /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ function Conversation ( task , message ) { this . messages = [ ] ; this . sent = [ ] ; this . transcript = [ ] ; this . context = { user : message . user , channel : message . channel , bot : task . bot , } ; this . events = { } ; this . vars = { } ; this . threads = { } ; this . thread = null ; this . status = 'new' ; this . task = task ; this . source_message = message ; this . handler = null ; this . responses = { } ; this . capture_options = { } ; this . startTime = new Date ( ) ; this . lastActive = new Date ( ) ; /** will be pointing to a callback which will be called after timeout,\n     * conversation will be not be ended and should be taken care by callback\n     */ this . timeOutHandler = null ; this . collectResponse = function ( key , value ) { this . responses [ key ] = value ; } ; this . capture = function ( response , cb ) { var that = this ; var capture_key = this . sent [ this . sent . length - 1 ] . text ; botkit . middleware . capture . run ( that . task . bot , response , that , function ( err , bot , response , convo ) { if ( response . text ) { response . text = response . text . trim ( ) ; } else { response . text = '' ; } if ( that . capture_options . key != undefined ) { capture_key = that . capture_options . key ; } // capture the question that was asked // if text is an array, get 1st if ( typeof ( that . sent [ that . sent . length - 1 ] . text ) == 'string' ) { response . question = that . sent [ that . sent . length - 1 ] . text ; } else if ( Array . isArray ( that . sent [ that . sent . length - 1 ] . text ) ) { response . question = that . sent [ that . sent . length - 1 ] . text [ 0 ] ; } else { response . question = '' ; } if ( that . capture_options . multiple ) { if ( ! that . responses [ capture_key ] ) { that . responses [ capture_key ] = [ ] ; } that . responses [ capture_key ] . push ( response ) ; } else { that . responses [ capture_key ] = response ; } if ( cb ) cb ( response ) ; } ) ; } ; this . handle = function ( message ) { var that = this ; this . lastActive = new Date ( ) ; this . transcript . push ( message ) ; botkit . logger . debug ( 'HANDLING MESSAGE IN CONVO' , message ) ; // do other stuff like call custom callbacks if ( this . handler ) { this . capture ( message , function ( message ) { // if the handler is a normal function, just execute it! // NOTE: anyone who passes in their own handler has to call // convo.next() to continue after completing whatever it is they want to do. if ( typeof ( that . handler ) == 'function' ) { that . handler ( message , that ) ; } else { // handle might be a mapping of keyword to callback. // lets see if the message matches any of the keywords let match , patterns = that . handler ; for ( let p = 0 ; p < patterns . length ; p ++ ) { if ( patterns [ p ] . pattern && botkit . hears_test ( [ patterns [ p ] . pattern ] , message ) ) { botkit . middleware . heard . run ( that . task . bot , message , function ( err , bot , message ) { patterns [ p ] . callback ( message , that ) ; } ) ; return ; } } // none of the messages matched! What do we do? // if a default exists, fire it! for ( let p = 0 ; p < patterns . length ; p ++ ) { if ( patterns [ p ] . default ) { botkit . middleware . heard . run ( that . task . bot , message , function ( err , bot , message ) { patterns [ p ] . callback ( message , that ) ; } ) ; return ; } } } } ) ; } else { // do nothing } } ; this . setVar = function ( field , value ) { if ( ! this . vars ) { this . vars = { } ; } this . vars [ field ] = value ; } ; this . activate = function ( ) { this . task . trigger ( 'conversationStarted' , [ this ] ) ; this . task . botkit . trigger ( 'conversationStarted' , [ this . task . bot , this ] ) ; this . status = 'active' ; } ; /**\n     * active includes both ACTIVE and ENDING\n     * in order to allow the timeout end scripts to play out\n     **/ this . isActive = function ( ) { return ( this . status == 'active' || this . status == 'ending' ) ; } ; this . deactivate = function ( ) { this . status = 'inactive' ; } ; this . say = function ( message ) { this . addMessage ( message ) ; } ; this . sayFirst = function ( message ) { if ( typeof ( message ) == 'string' ) { message = { text : message , channel : this . source_message . channel , } ; } else { message . channel = this . source_message . channel ; } this . messages . unshift ( message ) ; } ; this . on = function ( event , cb ) { botkit . logger . debug ( 'Setting up a handler for' , event ) ; var events = event . split ( / \\, / g ) ; for ( var e in events ) { if ( ! this . events [ events [ e ] ] ) { this . events [ events [ e ] ] = [ ] ; } this . events [ events [ e ] ] . push ( cb ) ; } return this ; } ; this . trigger = function ( event , data ) { if ( this . events [ event ] ) { for ( var e = 0 ; e < this . events [ event ] . length ; e ++ ) { var res = this . events [ event ] [ e ] . apply ( this , data ) ; if ( res === false ) { return ; } } } else { } } ; // proceed to the next message after waiting for an answer this . next = function ( ) { this . handler = null ; } ; this . repeat = function ( ) { if ( this . sent . length ) { this . messages . push ( this . sent [ this . sent . length - 1 ] ) ; } else { // console.log('TRIED TO REPEAT, NOTHING TO SAY'); } } ; this . silentRepeat = function ( ) { return ; } ; this . addQuestion = function ( message , cb , capture_options , thread ) { if ( typeof ( message ) == 'string' ) { message = { text : message , channel : this . source_message . channel } ; } else { message . channel = this . source_message . channel ; } if ( capture_options ) { message . capture_options = capture_options ; } message . handler = cb ; this . addMessage ( message , thread ) ; } ; this . ask = function ( message , cb , capture_options ) { this . addQuestion ( message , cb , capture_options , this . thread || 'default' ) ; } ; this . addMessage = function ( message , thread ) { if ( ! thread ) { thread = this . thread ; } if ( typeof ( message ) == 'string' ) { message = { text : message , channel : this . source_message . channel , } ; } else { message . channel = this . source_message . channel ; } if ( ! this . threads [ thread ] ) { this . threads [ thread ] = [ ] ; } this . threads [ thread ] . push ( message ) ; // this is the current topic, so add it here as well if ( this . thread == thread ) { this . messages . push ( message ) ; } } ; // how long should the bot wait while a user answers? this . setTimeout = function ( timeout ) { this . task . timeLimit = timeout ; } ; // For backwards compatibility, wrap gotoThread in its previous name this . changeTopic = function ( topic ) { this . gotoThread ( topic ) ; } ; this . hasThread = function ( thread ) { return ( this . threads [ thread ] != undefined ) ; } ; this . transitionTo = function ( thread , message ) { // add a new transition thread // add this new message to it // set that message action to execute the actual transition // then change threads to transition thread var num = 1 ; while ( this . hasThread ( 'transition_' + num ) ) { num ++ ; } var threadname = 'transition_' + num ; if ( typeof ( message ) == 'string' ) { message = { text : message , action : thread } ; } else { message . action = thread ; } this . addMessage ( message , threadname ) ; this . gotoThread ( threadname ) ; } ; this . beforeThread = function ( thread , callback ) { if ( ! this . before_hooks ) { this . before_hooks = { } ; } if ( ! this . before_hooks [ thread ] ) { this . before_hooks [ thread ] = [ ] ; } this . before_hooks [ thread ] . push ( callback ) ; } ; this . gotoThread = function ( thread ) { var that = this ; that . next_thread = thread ; that . processing = true ; var makeChange = function ( ) { if ( ! that . hasThread ( that . next_thread ) ) { if ( that . next_thread == 'default' ) { that . threads [ that . next_thread ] = [ ] ; } else { botkit . logger . debug ( 'WARN: gotoThread() to an invalid thread!' , thread ) ; that . stop ( 'unknown_thread' ) ; return ; } } that . thread = that . next_thread ; that . messages = that . threads [ that . next_thread ] . slice ( ) ; that . handler = null ; that . processing = false ; } ; if ( that . before_hooks && that . before_hooks [ that . next_thread ] ) { // call any beforeThread hooks in sequence async . eachSeries ( this . before_hooks [ that . next_thread ] , function ( before_hook , next ) { before_hook ( that , next ) ; } , function ( err ) { if ( ! err ) { makeChange ( ) ; } } ) ; } else { makeChange ( ) ; } } ; this . combineMessages = function ( messages ) { if ( ! messages ) { return '' ; } if ( Array . isArray ( messages ) && ! messages . length ) { return '' ; } if ( messages . length > 1 ) { var txt = [ ] ; var last_user = null ; var multi_users = false ; last_user = messages [ 0 ] . user ; for ( let x = 0 ; x < messages . length ; x ++ ) { if ( messages [ x ] . user != last_user ) { multi_users = true ; } } last_user = '' ; for ( let x = 0 ; x < messages . length ; x ++ ) { if ( multi_users && messages [ x ] . user != last_user ) { last_user = messages [ x ] . user ; if ( txt . length ) { txt . push ( '' ) ; } txt . push ( '<@' + messages [ x ] . user + '>:' ) ; } txt . push ( messages [ x ] . text ) ; } return txt . join ( '\\n' ) ; } else { if ( messages . length ) { return messages [ 0 ] . text ; } else { return messages . text ; } } } ; this . getResponses = function ( ) { var res = { } ; for ( var key in this . responses ) { res [ key ] = { question : this . responses [ key ] . length ? this . responses [ key ] [ 0 ] . question : this . responses [ key ] . question , key : key , answer : this . extractResponse ( key ) , } ; } return res ; } ; this . getResponsesAsArray = function ( ) { var res = [ ] ; for ( var key in this . responses ) { res . push ( { question : this . responses [ key ] . length ? this . responses [ key ] [ 0 ] . question : this . responses [ key ] . question , key : key , answer : this . extractResponse ( key ) , } ) ; } return res ; } ; this . extractResponses = function ( ) { var res = { } ; for ( var key in this . responses ) { res [ key ] = this . extractResponse ( key ) ; } return res ; } ; this . extractResponse = function ( key ) { return this . combineMessages ( this . responses [ key ] ) ; } ; this . replaceAttachmentTokens = function ( attachments ) { if ( attachments && attachments . length ) { for ( let a = 0 ; a < attachments . length ; a ++ ) { for ( let key in attachments [ a ] ) { if ( typeof ( attachments [ a ] [ key ] ) == 'string' ) { attachments [ a ] [ key ] = this . replaceTokens ( attachments [ a ] [ key ] ) ; } else { attachments [ a ] [ key ] = this . replaceAttachmentTokens ( attachments [ a ] [ key ] ) ; } } } } else { for ( let a in attachments ) { if ( typeof ( attachments [ a ] ) == 'string' ) { attachments [ a ] = this . replaceTokens ( attachments [ a ] ) ; } else { attachments [ a ] = this . replaceAttachmentTokens ( attachments [ a ] ) ; } } } return attachments ; } ; this . replaceTokens = function ( text ) { var vars = { identity : this . task . bot . identity , responses : this . extractResponses ( ) , origin : this . task . source_message , vars : this . vars , } ; var rendered = '' ; try { rendered = mustache . render ( text , vars ) ; } catch ( err ) { botkit . logger . error ( 'Error in message template. Mustache failed with error: ' , err ) ; rendered = text ; } return rendered ; } ; this . stop = function ( status ) { this . handler = null ; this . messages = [ ] ; this . status = status || 'stopped' ; botkit . logger . debug ( 'Conversation is over with status ' + this . status ) ; this . task . conversationEnded ( this ) ; } ; // was this conversation successful? // return true if it was completed // otherwise, return false // false could indicate a variety of failed states: // manually stopped, timed out, etc this . successful = function ( ) { // if the conversation is still going, it can't be successful yet if ( this . isActive ( ) ) { return false ; } if ( this . status == 'completed' ) { return true ; } else { return false ; } } ; this . cloneMessage = function ( message ) { // clone this object so as not to modify source var outbound = clone ( message ) ; if ( typeof ( message . text ) == 'string' ) { outbound . text = this . replaceTokens ( message . text ) ; } else if ( message . text ) { outbound . text = this . replaceTokens ( message . text [ Math . floor ( Math . random ( ) * message . text . length ) ] ) ; } if ( outbound . attachments ) { outbound . attachments = this . replaceAttachmentTokens ( outbound . attachments ) ; } if ( outbound . attachment ) { // pick one variation of the message text at random if ( outbound . attachment . payload . text && typeof ( outbound . attachment . payload . text ) != 'string' ) { outbound . attachment . payload . text = this . replaceTokens ( outbound . attachment . payload . text [ Math . floor ( Math . random ( ) * outbound . attachment . payload . text . length ) ] ) ; } outbound . attachment = this . replaceAttachmentTokens ( [ outbound . attachment ] ) [ 0 ] ; } if ( this . messages . length && ! message . handler ) { outbound . continue_typing = true ; } if ( typeof ( message . attachments ) == 'function' ) { outbound . attachments = message . attachments ( this ) ; } return outbound ; } ; this . onTimeout = function ( handler ) { if ( typeof ( handler ) == 'function' ) { this . timeOutHandler = handler ; } else { botkit . logger . debug ( 'Invalid timeout function passed to onTimeout' ) ; } } ; this . tick = function ( ) { var now = new Date ( ) ; if ( this . isActive ( ) ) { if ( this . processing ) { // do nothing. The bot is waiting for async process to complete. } else if ( this . handler ) { // check timeout! // how long since task started? var duration = ( now . getTime ( ) - this . task . startTime . getTime ( ) ) ; // how long since last active? var lastActive = ( now . getTime ( ) - this . lastActive . getTime ( ) ) ; if ( this . task . timeLimit && // has a timelimit ( duration > this . task . timeLimit ) && // timelimit is up ( lastActive > this . task . timeLimit ) // nobody has typed for 60 seconds at least ) { // if timeoutHandler is set then call it, otherwise follow the normal flow // this will not break others code, after the update if ( this . timeOutHandler ) { this . timeOutHandler ( this ) ; } else if ( this . hasThread ( 'on_timeout' ) ) { this . status = 'ending' ; this . gotoThread ( 'on_timeout' ) ; } else { this . stop ( 'timeout' ) ; } } // otherwise do nothing } else { if ( this . messages . length ) { if ( this . sent . length && ! this . sent [ this . sent . length - 1 ] . sent ) { return ; } if ( this . task . bot . botkit . config . require_delivery && this . sent . length && ! this . sent [ this . sent . length - 1 ] . delivered ) { return ; } if ( typeof ( this . messages [ 0 ] . timestamp ) == 'undefined' || this . messages [ 0 ] . timestamp <= now . getTime ( ) ) { var message = this . messages . shift ( ) ; //console.log('HANDLING NEW MESSAGE',message); // make sure next message is delayed appropriately if ( this . messages . length && this . messages [ 0 ] . delay ) { this . messages [ 0 ] . timestamp = now . getTime ( ) + this . messages [ 0 ] . delay ; } if ( message . handler ) { //console.log(\">>>>>> SET HANDLER IN TICK\"); this . handler = message . handler ; } else { this . handler = null ; //console.log(\">>>>>>> CLEARING HANDLER BECAUSE NO HANDLER NEEDED\"); } if ( message . capture_options ) { this . capture_options = message . capture_options ; } else { this . capture_options = { } ; } this . lastActive = new Date ( ) ; // is there any text? // or an attachment? (facebook) // or multiple attachments (slack) // if (message.text || message.attachments || message.attachment) { if ( message ) { var outbound = this . cloneMessage ( message ) ; var that = this ; outbound . sent_timestamp = new Date ( ) . getTime ( ) ; that . sent . push ( outbound ) ; that . transcript . push ( outbound ) ; this . task . bot . reply ( this . source_message , outbound , function ( err , sent_message ) { if ( err ) { botkit . logger . error ( 'An error occurred while sending a message: ' , err ) ; // even though an error occured, set sent to true // this will allow the conversation to keep going even if one message fails // TODO: make a message that fails to send _resend_ at least once that . sent [ that . sent . length - 1 ] . sent = true ; that . sent [ that . sent . length - 1 ] . api_response = err ; } else { that . sent [ that . sent . length - 1 ] . sent = true ; that . sent [ that . sent . length - 1 ] . api_response = sent_message ; // if sending via slack's web api, there is no further confirmation // so we can mark the message delivered if ( that . task . bot . type == 'slack' && sent_message && sent_message . ts ) { that . sent [ that . sent . length - 1 ] . delivered = true ; } that . trigger ( 'sent' , [ sent_message ] ) ; } } ) ; } if ( message . action ) { if ( typeof ( message . action ) == 'function' ) { message . action ( this ) ; } else if ( message . action == 'repeat' ) { this . repeat ( ) ; } else if ( message . action == 'wait' ) { this . silentRepeat ( ) ; } else if ( message . action == 'stop' ) { this . stop ( ) ; } else if ( message . action == 'timeout' ) { this . stop ( 'timeout' ) ; } else if ( this . threads [ message . action ] ) { this . gotoThread ( message . action ) ; } } } else { //console.log('Waiting to send next message...'); } // end immediately instad of waiting til next tick. // if it hasn't already been ended by a message action! if ( this . isActive ( ) && ! this . messages . length && ! this . handler && ! this . processing ) { this . stop ( 'completed' ) ; } } else if ( this . sent . length ) { // sent at least 1 message this . stop ( 'completed' ) ; } } } } ; botkit . logger . debug ( 'CREATED A CONVO FOR' , this . source_message . user , this . source_message . channel ) ; this . gotoThread ( 'default' ) ; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ function Task ( bot , message , botkit ) { this . convos = [ ] ; this . botkit = botkit ; this . bot = bot ; this . events = { } ; this . source_message = message ; this . status = 'active' ; this . startTime = new Date ( ) ; this . isActive = function ( ) { return this . status == 'active' ; } ; this . createConversation = function ( message ) { var convo = new Conversation ( this , message ) ; convo . id = botkit . convoCount ++ ; this . convos . push ( convo ) ; return convo ; } ; this . startConversation = function ( message ) { var convo = this . createConversation ( message ) ; botkit . logger . debug ( '>   [Start] ' , convo . id , ' Conversation with ' , message . user , 'in' , message . channel ) ; convo . activate ( ) ; return convo ; } ; this . conversationEnded = function ( convo ) { botkit . logger . debug ( '>   [End] ' , convo . id , ' Conversation with ' , convo . source_message . user , 'in' , convo . source_message . channel ) ; this . trigger ( 'conversationEnded' , [ convo ] ) ; this . botkit . trigger ( 'conversationEnded' , [ bot , convo ] ) ; convo . trigger ( 'end' , [ convo ] ) ; var actives = 0 ; for ( var c = 0 ; c < this . convos . length ; c ++ ) { if ( this . convos [ c ] . isActive ( ) ) { actives ++ ; } } if ( actives == 0 ) { this . taskEnded ( ) ; } } ; this . endImmediately = function ( reason ) { for ( var c = 0 ; c < this . convos . length ; c ++ ) { if ( this . convos [ c ] . isActive ( ) ) { this . convos [ c ] . stop ( reason || 'stopped' ) ; } } } ; this . taskEnded = function ( ) { botkit . logger . debug ( '[End] ' , this . id , ' Task for ' , this . source_message . user , 'in' , this . source_message . channel ) ; this . status = 'completed' ; this . trigger ( 'end' , [ this ] ) ; } ; this . on = function ( event , cb ) { botkit . logger . debug ( 'Setting up a handler for' , event ) ; var events = event . split ( / \\, / g ) ; for ( var e in events ) { if ( ! this . events [ events [ e ] ] ) { this . events [ events [ e ] ] = [ ] ; } this . events [ events [ e ] ] . push ( cb ) ; } return this ; } ; this . trigger = function ( event , data ) { if ( this . events [ event ] ) { for ( var e = 0 ; e < this . events [ event ] . length ; e ++ ) { var res = this . events [ event ] [ e ] . apply ( this , data ) ; if ( res === false ) { return ; } } } } ; this . getResponsesByUser = function ( ) { var users = { } ; // go through all conversations // extract normalized answers for ( var c = 0 ; c < this . convos . length ; c ++ ) { var user = this . convos [ c ] . source_message . user ; users [ this . convos [ c ] . source_message . user ] = { } ; var convo = this . convos [ c ] ; users [ user ] = convo . extractResponses ( ) ; } return users ; } ; this . getResponsesBySubject = function ( ) { var answers = { } ; // go through all conversations // extract normalized answers for ( var c = 0 ; c < this . convos . length ; c ++ ) { var convo = this . convos [ c ] ; for ( var key in convo . responses ) { if ( ! answers [ key ] ) { answers [ key ] = { } ; } answers [ key ] [ convo . source_message . user ] = convo . extractResponse ( key ) ; } } return answers ; } ; this . tick = function ( ) { for ( var c = 0 ; c < this . convos . length ; c ++ ) { if ( this . convos [ c ] . isActive ( ) ) { this . convos [ c ] . tick ( ) ; } } } ; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ botkit . storage = { teams : { get : function ( team_id , cb ) { cb ( null , botkit . memory_store . teams [ team_id ] ) ; } , save : function ( team , cb ) { botkit . logger . warn ( 'Warning: using temporary storage. Data will be lost when process restarts.' ) ; if ( team . id ) { botkit . memory_store . teams [ team . id ] = team ; cb ( null , team . id ) ; } else { cb ( 'No ID specified' ) ; } } , all : function ( cb ) { cb ( null , botkit . memory_store . teams ) ; } } , users : { get : function ( user_id , cb ) { cb ( null , botkit . memory_store . users [ user_id ] ) ; } , save : function ( user , cb ) { botkit . logger . warn ( 'Warning: using temporary storage. Data will be lost when process restarts.' ) ; if ( user . id ) { botkit . memory_store . users [ user . id ] = user ; cb ( null , user . id ) ; } else { cb ( 'No ID specified' ) ; } } , all : function ( cb ) { cb ( null , botkit . memory_store . users ) ; } } , channels : { get : function ( channel_id , cb ) { cb ( null , botkit . memory_store . channels [ channel_id ] ) ; } , save : function ( channel , cb ) { botkit . logger . warn ( 'Warning: using temporary storage. Data will be lost when process restarts.' ) ; if ( channel . id ) { botkit . memory_store . channels [ channel . id ] = channel ; cb ( null , channel . id ) ; } else { cb ( 'No ID specified' ) ; } } , all : function ( cb ) { cb ( null , botkit . memory_store . channels ) ; } } } ; /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /**\n   * hears_regexp - default string matcher uses regular expressions\n   *\n   * @param  {array}  tests    patterns to match\n   * @param  {object} message message object with various fields\n   * @return {boolean}        whether or not a pattern was matched\n   */ botkit . hears_regexp = function ( tests , message ) { for ( var t = 0 ; t < tests . length ; t ++ ) { if ( message . text ) { // the pattern might be a string to match (including regular expression syntax) // or it might be a prebuilt regular expression var test = null ; if ( typeof ( tests [ t ] ) == 'string' ) { try { test = new RegExp ( tests [ t ] , 'i' ) ; } catch ( err ) { botkit . logger . error ( 'Error in regular expression: ' + tests [ t ] + ': ' + err ) ; return false ; } if ( ! test ) { return false ; } } else { test = tests [ t ] ; } let match = message . text . match ( test ) ; if ( match ) { message . match = match ; return true ; } } } return false ; } ; /**\n   * changeEars - change the default matching function\n   *\n   * @param  {function} new_test a function that accepts (tests, message) and returns a boolean\n   */ botkit . changeEars = function ( new_test ) { botkit . hears_test = new_test ; } ; botkit . hears = function ( keywords , events , middleware_or_cb , cb ) { // the third parameter is EITHER a callback handler // or a middleware function that redefines how the hear works var test_function = botkit . hears_test ; if ( cb ) { test_function = middleware_or_cb ; } else { cb = middleware_or_cb ; } if ( typeof ( keywords ) == 'string' ) { keywords = [ keywords ] ; } if ( keywords instanceof RegExp ) { keywords = [ keywords ] ; } if ( typeof ( events ) == 'string' ) { events = events . split ( / \\, / g ) . map ( function ( str ) { return str . trim ( ) ; } ) ; } for ( var e = 0 ; e < events . length ; e ++ ) { ( function ( keywords , test_function ) { botkit . on ( events [ e ] , function ( bot , message ) { if ( test_function && test_function ( keywords , message ) ) { botkit . logger . debug ( 'I HEARD' , keywords ) ; botkit . middleware . heard . run ( bot , message , function ( err , bot , message ) { cb . apply ( this , [ bot , message ] ) ; botkit . trigger ( 'heard_trigger' , [ bot , keywords , message ] ) ; } ) ; return false ; } } , true ) ; } ) ( keywords , test_function ) ; } return this ; } ; botkit . on = function ( event , cb , is_hearing ) { botkit . logger . debug ( 'Setting up a handler for' , event ) ; var events = ( typeof ( event ) == 'string' ) ? event . split ( / \\, / g ) : event ; for ( var e in events ) { if ( ! this . events [ events [ e ] ] ) { this . events [ events [ e ] ] = [ ] ; } this . events [ events [ e ] ] . push ( { callback : cb , type : is_hearing ? 'hearing' : 'event' } ) ; } return this ; } ; botkit . trigger = function ( event , data ) { if ( this . events [ event ] ) { var hearing = this . events [ event ] . filter ( function ( e ) { return ( e . type == 'hearing' ) ; } ) ; var handlers = this . events [ event ] . filter ( function ( e ) { return ( e . type != 'hearing' ) ; } ) ; // first, look for hearing type events // these are always handled before normal event handlers for ( var e = 0 ; e < hearing . length ; e ++ ) { var res = hearing [ e ] . callback . apply ( this , data ) ; if ( res === false ) { return ; } } // now, if we haven't already heard something, // fire the remaining event handlers if ( handlers . length ) { botkit . middleware . triggered . run ( data [ 0 ] , data [ 1 ] , function ( err , bot , message ) { for ( var e = 0 ; e < handlers . length ; e ++ ) { var res = handlers [ e ] . callback . apply ( this , data ) ; if ( res === false ) { return ; } } } ) ; } } } ; botkit . startConversation = function ( bot , message , cb ) { botkit . startTask ( bot , message , function ( task , convo ) { cb ( null , convo ) ; } ) ; } ; botkit . createConversation = function ( bot , message , cb ) { var task = new Task ( bot , message , this ) ; task . id = botkit . taskCount ++ ; var convo = task . createConversation ( message ) ; this . tasks . push ( task ) ; cb ( null , convo ) ; } ; botkit . defineBot = function ( unit ) { if ( typeof ( unit ) != 'function' ) { throw new Error ( 'Bot definition must be a constructor function' ) ; } this . worker = unit ; } ; botkit . spawn = function ( config , cb ) { var worker = new this . worker ( this , config ) ; // mutate the worker so that we can call middleware worker . say = function ( message , cb ) { var platform_message = { } ; botkit . middleware . send . run ( worker , message , function ( err , worker , message ) { if ( err ) { botkit . logger . error ( 'An error occured in the send middleware:: ' + err ) ; } else { botkit . middleware . format . run ( worker , message , platform_message , function ( err , worker , message , platform_message ) { if ( err ) { botkit . logger . error ( 'An error occured in the format middleware: ' + err ) ; } else { worker . send ( platform_message , cb ) ; } } ) ; } } ) ; } ; // add platform independent convenience methods worker . startConversation = function ( message , cb ) { botkit . startConversation ( worker , message , cb ) ; } ; worker . createConversation = function ( message , cb ) { botkit . createConversation ( worker , message , cb ) ; } ; botkit . middleware . spawn . run ( worker , function ( err , worker ) { if ( err ) { botkit . logger . error ( 'Error in middlware.spawn.run: ' + err ) ; } else { botkit . trigger ( 'spawned' , [ worker ] ) ; if ( cb ) { cb ( worker ) ; } } } ) ; return worker ; } ; botkit . startTicking = function ( ) { if ( ! botkit . tickInterval ) { // set up a once a second tick to process messages botkit . tickInterval = setInterval ( function ( ) { botkit . tick ( ) ; } , 1500 ) ; } } ; botkit . shutdown = function ( ) { if ( botkit . tickInterval ) { clearInterval ( botkit . tickInterval ) ; } } ; botkit . startTask = function ( bot , message , cb ) { var task = new Task ( bot , message , this ) ; task . id = botkit . taskCount ++ ; botkit . logger . debug ( '[Start] ' , task . id , ' Task for ' , message . user , 'in' , message . channel ) ; var convo = task . startConversation ( message ) ; this . tasks . push ( task ) ; if ( cb ) { cb ( task , convo ) ; } else { return task ; } } ; botkit . tick = function ( ) { for ( let t = 0 ; t < botkit . tasks . length ; t ++ ) { botkit . tasks [ t ] . tick ( ) ; } for ( let t = botkit . tasks . length - 1 ; t >= 0 ; t -- ) { if ( ! botkit . tasks [ t ] . isActive ( ) ) { botkit . tasks . splice ( t , 1 ) ; } } this . trigger ( 'tick' , [ ] ) ; } ; // Provide a fairly simple Express-based webserver botkit . setupWebserver = function ( port , cb ) { if ( ! port ) { throw new Error ( 'Cannot start webserver without a port' ) ; } var static_dir = process . cwd ( ) + '/public' ; if ( botkit . config && botkit . config . webserver && botkit . config . webserver . static_dir ) static_dir = botkit . config . webserver . static_dir ; botkit . config . port = port ; var express = require ( 'express' ) ; var bodyParser = require ( 'body-parser' ) ; botkit . webserver = express ( ) ; botkit . webserver . use ( bodyParser . json ( ) ) ; botkit . webserver . use ( bodyParser . urlencoded ( { extended : true } ) ) ; botkit . webserver . use ( express . static ( static_dir ) ) ; var server = botkit . webserver . listen ( botkit . config . port , botkit . config . hostname , function ( ) { botkit . logger . info ( '** Starting webserver on port ' + botkit . config . port ) ; if ( cb ) { cb ( null , botkit . webserver ) ; } botkit . trigger ( 'webserver_up' , [ botkit . webserver ] ) ; } ) ; return botkit ; } ; /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /**\n   * Define a default worker bot. This function should be customized outside\n   * of Botkit and passed in as a parameter by the developer\n   **/ botkit . worker = function ( botkit , config ) { this . botkit = botkit ; this . config = config ; this . say = function ( message , cb ) { botkit . logger . debug ( 'SAY:' , message ) ; } ; this . replyWithQuestion = function ( message , question , cb ) { botkit . startConversation ( message , function ( convo ) { convo . ask ( question , cb ) ; } ) ; } ; this . reply = function ( src , resp ) { botkit . logger . debug ( 'REPLY:' , resp ) ; } ; this . findConversation = function ( message , cb ) { botkit . logger . debug ( 'DEFAULT FIND CONVO' ) ; cb ( null ) ; } ; } ; /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ botkit . userAgent = function ( ) { if ( ! botkit . my_user_agent ) { // set user agent to Botkit var ua = 'Botkit/' + botkit . version ( ) ; // add OS info ua = ua + ' ' + os . platform ( ) + '/' + os . release ( ) ; // add Node info ua = ua + ' ' + 'node/' + process . version . replace ( 'v' , '' ) ; botkit . my_user_agent = ua ; } return botkit . my_user_agent ; } ; botkit . version = function ( ) { if ( ! botkit . my_version ) { botkit . my_version = '0.0.0' ; } return botkit . my_version ; } ; botkit . config = configuration ; /** Default the application to listen to the 0.0.0.0, the default\n   * for node's http module. Developers can specify a hostname or IP\n   * address to override this.\n   **/ if ( ! botkit . config . hostname ) { botkit . config . hostname = '0.0.0.0' ; } if ( ! configuration . logLevel ) { if ( configuration . debug ) { configuration . logLevel = 'debug' ; } else if ( configuration . log === false ) { configuration . logLevel = 'error' ; } else { configuration . logLevel = 'info' ; } } if ( configuration . logger ) { botkit . logger = configuration . logger ; } else { botkit . logger = logging ( 'abbott-framework:botkit:CoreBot' ) ; } // botkit.log = function () { //   botkit.logger.info.apply(botkit.log, arguments); // }; // Object.keys(LogLevels).forEach(function (level) { //   botkit.log[level] = botkit.logger.log.bind(botkit.logger, level); // }); // botkit.debug = botkit.logger.debug; // if (!botkit.config.disable_startup_messages) { //   console.log('Initializing Botkit v' + botkit.version()); // } if ( configuration . storage ) { if ( configuration . storage . teams && configuration . storage . teams . get && configuration . storage . teams . save && configuration . storage . users && configuration . storage . users . get && configuration . storage . users . save && configuration . storage . channels && configuration . storage . channels . get && configuration . storage . channels . save ) { botkit . logger . debug ( '** Using custom storage system.' ) ; botkit . storage = configuration . storage ; } else { throw new Error ( 'Storage object does not have all required methods!' ) ; } // } else if (configuration.json_file_store) { //   botkit.logger.debug('** Using simple storage. Saving data to ' + configuration.json_file_store); //   botkit.storage = simple_storage({ //     path: configuration.json_file_store //   }); } else { botkit . logger . debug ( '** No persistent storage method specified! Data may be lost when process shuts down.' ) ; } // set the default set of ears to use the regular expression matching botkit . changeEars ( botkit . hears_regexp ) ; //enable Botkit Studio // studio(botkit); return botkit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [CODESPLIT] function Conversation ( task , message ) { this . messages = [ ] ; this . sent = [ ] ; this . transcript = [ ] ; this . context = { user : message . user , channel : message . channel , bot : task . bot , } ; this . events = { } ; this . vars = { } ; this . threads = { } ; this . thread = null ; this . status = 'new' ; this . task = task ; this . source_message = message ; this . handler = null ; this . responses = { } ; this . capture_options = { } ; this . startTime = new Date ( ) ; this . lastActive = new Date ( ) ; /** will be pointing to a callback which will be called after timeout,\n     * conversation will be not be ended and should be taken care by callback\n     */ this . timeOutHandler = null ; this . collectResponse = function ( key , value ) { this . responses [ key ] = value ; } ; this . capture = function ( response , cb ) { var that = this ; var capture_key = this . sent [ this . sent . length - 1 ] . text ; botkit . middleware . capture . run ( that . task . bot , response , that , function ( err , bot , response , convo ) { if ( response . text ) { response . text = response . text . trim ( ) ; } else { response . text = '' ; } if ( that . capture_options . key != undefined ) { capture_key = that . capture_options . key ; } // capture the question that was asked // if text is an array, get 1st if ( typeof ( that . sent [ that . sent . length - 1 ] . text ) == 'string' ) { response . question = that . sent [ that . sent . length - 1 ] . text ; } else if ( Array . isArray ( that . sent [ that . sent . length - 1 ] . text ) ) { response . question = that . sent [ that . sent . length - 1 ] . text [ 0 ] ; } else { response . question = '' ; } if ( that . capture_options . multiple ) { if ( ! that . responses [ capture_key ] ) { that . responses [ capture_key ] = [ ] ; } that . responses [ capture_key ] . push ( response ) ; } else { that . responses [ capture_key ] = response ; } if ( cb ) cb ( response ) ; } ) ; } ; this . handle = function ( message ) { var that = this ; this . lastActive = new Date ( ) ; this . transcript . push ( message ) ; botkit . logger . debug ( 'HANDLING MESSAGE IN CONVO' , message ) ; // do other stuff like call custom callbacks if ( this . handler ) { this . capture ( message , function ( message ) { // if the handler is a normal function, just execute it! // NOTE: anyone who passes in their own handler has to call // convo.next() to continue after completing whatever it is they want to do. if ( typeof ( that . handler ) == 'function' ) { that . handler ( message , that ) ; } else { // handle might be a mapping of keyword to callback. // lets see if the message matches any of the keywords let match , patterns = that . handler ; for ( let p = 0 ; p < patterns . length ; p ++ ) { if ( patterns [ p ] . pattern && botkit . hears_test ( [ patterns [ p ] . pattern ] , message ) ) { botkit . middleware . heard . run ( that . task . bot , message , function ( err , bot , message ) { patterns [ p ] . callback ( message , that ) ; } ) ; return ; } } // none of the messages matched! What do we do? // if a default exists, fire it! for ( let p = 0 ; p < patterns . length ; p ++ ) { if ( patterns [ p ] . default ) { botkit . middleware . heard . run ( that . task . bot , message , function ( err , bot , message ) { patterns [ p ] . callback ( message , that ) ; } ) ; return ; } } } } ) ; } else { // do nothing } } ; this . setVar = function ( field , value ) { if ( ! this . vars ) { this . vars = { } ; } this . vars [ field ] = value ; } ; this . activate = function ( ) { this . task . trigger ( 'conversationStarted' , [ this ] ) ; this . task . botkit . trigger ( 'conversationStarted' , [ this . task . bot , this ] ) ; this . status = 'active' ; } ; /**\n     * active includes both ACTIVE and ENDING\n     * in order to allow the timeout end scripts to play out\n     **/ this . isActive = function ( ) { return ( this . status == 'active' || this . status == 'ending' ) ; } ; this . deactivate = function ( ) { this . status = 'inactive' ; } ; this . say = function ( message ) { this . addMessage ( message ) ; } ; this . sayFirst = function ( message ) { if ( typeof ( message ) == 'string' ) { message = { text : message , channel : this . source_message . channel , } ; } else { message . channel = this . source_message . channel ; } this . messages . unshift ( message ) ; } ; this . on = function ( event , cb ) { botkit . logger . debug ( 'Setting up a handler for' , event ) ; var events = event . split ( / \\, / g ) ; for ( var e in events ) { if ( ! this . events [ events [ e ] ] ) { this . events [ events [ e ] ] = [ ] ; } this . events [ events [ e ] ] . push ( cb ) ; } return this ; } ; this . trigger = function ( event , data ) { if ( this . events [ event ] ) { for ( var e = 0 ; e < this . events [ event ] . length ; e ++ ) { var res = this . events [ event ] [ e ] . apply ( this , data ) ; if ( res === false ) { return ; } } } else { } } ; // proceed to the next message after waiting for an answer this . next = function ( ) { this . handler = null ; } ; this . repeat = function ( ) { if ( this . sent . length ) { this . messages . push ( this . sent [ this . sent . length - 1 ] ) ; } else { // console.log('TRIED TO REPEAT, NOTHING TO SAY'); } } ; this . silentRepeat = function ( ) { return ; } ; this . addQuestion = function ( message , cb , capture_options , thread ) { if ( typeof ( message ) == 'string' ) { message = { text : message , channel : this . source_message . channel } ; } else { message . channel = this . source_message . channel ; } if ( capture_options ) { message . capture_options = capture_options ; } message . handler = cb ; this . addMessage ( message , thread ) ; } ; this . ask = function ( message , cb , capture_options ) { this . addQuestion ( message , cb , capture_options , this . thread || 'default' ) ; } ; this . addMessage = function ( message , thread ) { if ( ! thread ) { thread = this . thread ; } if ( typeof ( message ) == 'string' ) { message = { text : message , channel : this . source_message . channel , } ; } else { message . channel = this . source_message . channel ; } if ( ! this . threads [ thread ] ) { this . threads [ thread ] = [ ] ; } this . threads [ thread ] . push ( message ) ; // this is the current topic, so add it here as well if ( this . thread == thread ) { this . messages . push ( message ) ; } } ; // how long should the bot wait while a user answers? this . setTimeout = function ( timeout ) { this . task . timeLimit = timeout ; } ; // For backwards compatibility, wrap gotoThread in its previous name this . changeTopic = function ( topic ) { this . gotoThread ( topic ) ; } ; this . hasThread = function ( thread ) { return ( this . threads [ thread ] != undefined ) ; } ; this . transitionTo = function ( thread , message ) { // add a new transition thread // add this new message to it // set that message action to execute the actual transition // then change threads to transition thread var num = 1 ; while ( this . hasThread ( 'transition_' + num ) ) { num ++ ; } var threadname = 'transition_' + num ; if ( typeof ( message ) == 'string' ) { message = { text : message , action : thread } ; } else { message . action = thread ; } this . addMessage ( message , threadname ) ; this . gotoThread ( threadname ) ; } ; this . beforeThread = function ( thread , callback ) { if ( ! this . before_hooks ) { this . before_hooks = { } ; } if ( ! this . before_hooks [ thread ] ) { this . before_hooks [ thread ] = [ ] ; } this . before_hooks [ thread ] . push ( callback ) ; } ; this . gotoThread = function ( thread ) { var that = this ; that . next_thread = thread ; that . processing = true ; var makeChange = function ( ) { if ( ! that . hasThread ( that . next_thread ) ) { if ( that . next_thread == 'default' ) { that . threads [ that . next_thread ] = [ ] ; } else { botkit . logger . debug ( 'WARN: gotoThread() to an invalid thread!' , thread ) ; that . stop ( 'unknown_thread' ) ; return ; } } that . thread = that . next_thread ; that . messages = that . threads [ that . next_thread ] . slice ( ) ; that . handler = null ; that . processing = false ; } ; if ( that . before_hooks && that . before_hooks [ that . next_thread ] ) { // call any beforeThread hooks in sequence async . eachSeries ( this . before_hooks [ that . next_thread ] , function ( before_hook , next ) { before_hook ( that , next ) ; } , function ( err ) { if ( ! err ) { makeChange ( ) ; } } ) ; } else { makeChange ( ) ; } } ; this . combineMessages = function ( messages ) { if ( ! messages ) { return '' ; } if ( Array . isArray ( messages ) && ! messages . length ) { return '' ; } if ( messages . length > 1 ) { var txt = [ ] ; var last_user = null ; var multi_users = false ; last_user = messages [ 0 ] . user ; for ( let x = 0 ; x < messages . length ; x ++ ) { if ( messages [ x ] . user != last_user ) { multi_users = true ; } } last_user = '' ; for ( let x = 0 ; x < messages . length ; x ++ ) { if ( multi_users && messages [ x ] . user != last_user ) { last_user = messages [ x ] . user ; if ( txt . length ) { txt . push ( '' ) ; } txt . push ( '<@' + messages [ x ] . user + '>:' ) ; } txt . push ( messages [ x ] . text ) ; } return txt . join ( '\\n' ) ; } else { if ( messages . length ) { return messages [ 0 ] . text ; } else { return messages . text ; } } } ; this . getResponses = function ( ) { var res = { } ; for ( var key in this . responses ) { res [ key ] = { question : this . responses [ key ] . length ? this . responses [ key ] [ 0 ] . question : this . responses [ key ] . question , key : key , answer : this . extractResponse ( key ) , } ; } return res ; } ; this . getResponsesAsArray = function ( ) { var res = [ ] ; for ( var key in this . responses ) { res . push ( { question : this . responses [ key ] . length ? this . responses [ key ] [ 0 ] . question : this . responses [ key ] . question , key : key , answer : this . extractResponse ( key ) , } ) ; } return res ; } ; this . extractResponses = function ( ) { var res = { } ; for ( var key in this . responses ) { res [ key ] = this . extractResponse ( key ) ; } return res ; } ; this . extractResponse = function ( key ) { return this . combineMessages ( this . responses [ key ] ) ; } ; this . replaceAttachmentTokens = function ( attachments ) { if ( attachments && attachments . length ) { for ( let a = 0 ; a < attachments . length ; a ++ ) { for ( let key in attachments [ a ] ) { if ( typeof ( attachments [ a ] [ key ] ) == 'string' ) { attachments [ a ] [ key ] = this . replaceTokens ( attachments [ a ] [ key ] ) ; } else { attachments [ a ] [ key ] = this . replaceAttachmentTokens ( attachments [ a ] [ key ] ) ; } } } } else { for ( let a in attachments ) { if ( typeof ( attachments [ a ] ) == 'string' ) { attachments [ a ] = this . replaceTokens ( attachments [ a ] ) ; } else { attachments [ a ] = this . replaceAttachmentTokens ( attachments [ a ] ) ; } } } return attachments ; } ; this . replaceTokens = function ( text ) { var vars = { identity : this . task . bot . identity , responses : this . extractResponses ( ) , origin : this . task . source_message , vars : this . vars , } ; var rendered = '' ; try { rendered = mustache . render ( text , vars ) ; } catch ( err ) { botkit . logger . error ( 'Error in message template. Mustache failed with error: ' , err ) ; rendered = text ; } return rendered ; } ; this . stop = function ( status ) { this . handler = null ; this . messages = [ ] ; this . status = status || 'stopped' ; botkit . logger . debug ( 'Conversation is over with status ' + this . status ) ; this . task . conversationEnded ( this ) ; } ; // was this conversation successful? // return true if it was completed // otherwise, return false // false could indicate a variety of failed states: // manually stopped, timed out, etc this . successful = function ( ) { // if the conversation is still going, it can't be successful yet if ( this . isActive ( ) ) { return false ; } if ( this . status == 'completed' ) { return true ; } else { return false ; } } ; this . cloneMessage = function ( message ) { // clone this object so as not to modify source var outbound = clone ( message ) ; if ( typeof ( message . text ) == 'string' ) { outbound . text = this . replaceTokens ( message . text ) ; } else if ( message . text ) { outbound . text = this . replaceTokens ( message . text [ Math . floor ( Math . random ( ) * message . text . length ) ] ) ; } if ( outbound . attachments ) { outbound . attachments = this . replaceAttachmentTokens ( outbound . attachments ) ; } if ( outbound . attachment ) { // pick one variation of the message text at random if ( outbound . attachment . payload . text && typeof ( outbound . attachment . payload . text ) != 'string' ) { outbound . attachment . payload . text = this . replaceTokens ( outbound . attachment . payload . text [ Math . floor ( Math . random ( ) * outbound . attachment . payload . text . length ) ] ) ; } outbound . attachment = this . replaceAttachmentTokens ( [ outbound . attachment ] ) [ 0 ] ; } if ( this . messages . length && ! message . handler ) { outbound . continue_typing = true ; } if ( typeof ( message . attachments ) == 'function' ) { outbound . attachments = message . attachments ( this ) ; } return outbound ; } ; this . onTimeout = function ( handler ) { if ( typeof ( handler ) == 'function' ) { this . timeOutHandler = handler ; } else { botkit . logger . debug ( 'Invalid timeout function passed to onTimeout' ) ; } } ; this . tick = function ( ) { var now = new Date ( ) ; if ( this . isActive ( ) ) { if ( this . processing ) { // do nothing. The bot is waiting for async process to complete. } else if ( this . handler ) { // check timeout! // how long since task started? var duration = ( now . getTime ( ) - this . task . startTime . getTime ( ) ) ; // how long since last active? var lastActive = ( now . getTime ( ) - this . lastActive . getTime ( ) ) ; if ( this . task . timeLimit && // has a timelimit ( duration > this . task . timeLimit ) && // timelimit is up ( lastActive > this . task . timeLimit ) // nobody has typed for 60 seconds at least ) { // if timeoutHandler is set then call it, otherwise follow the normal flow // this will not break others code, after the update if ( this . timeOutHandler ) { this . timeOutHandler ( this ) ; } else if ( this . hasThread ( 'on_timeout' ) ) { this . status = 'ending' ; this . gotoThread ( 'on_timeout' ) ; } else { this . stop ( 'timeout' ) ; } } // otherwise do nothing } else { if ( this . messages . length ) { if ( this . sent . length && ! this . sent [ this . sent . length - 1 ] . sent ) { return ; } if ( this . task . bot . botkit . config . require_delivery && this . sent . length && ! this . sent [ this . sent . length - 1 ] . delivered ) { return ; } if ( typeof ( this . messages [ 0 ] . timestamp ) == 'undefined' || this . messages [ 0 ] . timestamp <= now . getTime ( ) ) { var message = this . messages . shift ( ) ; //console.log('HANDLING NEW MESSAGE',message); // make sure next message is delayed appropriately if ( this . messages . length && this . messages [ 0 ] . delay ) { this . messages [ 0 ] . timestamp = now . getTime ( ) + this . messages [ 0 ] . delay ; } if ( message . handler ) { //console.log(\">>>>>> SET HANDLER IN TICK\"); this . handler = message . handler ; } else { this . handler = null ; //console.log(\">>>>>>> CLEARING HANDLER BECAUSE NO HANDLER NEEDED\"); } if ( message . capture_options ) { this . capture_options = message . capture_options ; } else { this . capture_options = { } ; } this . lastActive = new Date ( ) ; // is there any text? // or an attachment? (facebook) // or multiple attachments (slack) // if (message.text || message.attachments || message.attachment) { if ( message ) { var outbound = this . cloneMessage ( message ) ; var that = this ; outbound . sent_timestamp = new Date ( ) . getTime ( ) ; that . sent . push ( outbound ) ; that . transcript . push ( outbound ) ; this . task . bot . reply ( this . source_message , outbound , function ( err , sent_message ) { if ( err ) { botkit . logger . error ( 'An error occurred while sending a message: ' , err ) ; // even though an error occured, set sent to true // this will allow the conversation to keep going even if one message fails // TODO: make a message that fails to send _resend_ at least once that . sent [ that . sent . length - 1 ] . sent = true ; that . sent [ that . sent . length - 1 ] . api_response = err ; } else { that . sent [ that . sent . length - 1 ] . sent = true ; that . sent [ that . sent . length - 1 ] . api_response = sent_message ; // if sending via slack's web api, there is no further confirmation // so we can mark the message delivered if ( that . task . bot . type == 'slack' && sent_message && sent_message . ts ) { that . sent [ that . sent . length - 1 ] . delivered = true ; } that . trigger ( 'sent' , [ sent_message ] ) ; } } ) ; } if ( message . action ) { if ( typeof ( message . action ) == 'function' ) { message . action ( this ) ; } else if ( message . action == 'repeat' ) { this . repeat ( ) ; } else if ( message . action == 'wait' ) { this . silentRepeat ( ) ; } else if ( message . action == 'stop' ) { this . stop ( ) ; } else if ( message . action == 'timeout' ) { this . stop ( 'timeout' ) ; } else if ( this . threads [ message . action ] ) { this . gotoThread ( message . action ) ; } } } else { //console.log('Waiting to send next message...'); } // end immediately instad of waiting til next tick. // if it hasn't already been ended by a message action! if ( this . isActive ( ) && ! this . messages . length && ! this . handler && ! this . processing ) { this . stop ( 'completed' ) ; } } else if ( this . sent . length ) { // sent at least 1 message this . stop ( 'completed' ) ; } } } } ; botkit . logger . debug ( 'CREATED A CONVO FOR' , this . source_message . user , this . source_message . channel ) ; this . gotoThread ( 'default' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [CODESPLIT] function Task ( bot , message , botkit ) { this . convos = [ ] ; this . botkit = botkit ; this . bot = bot ; this . events = { } ; this . source_message = message ; this . status = 'active' ; this . startTime = new Date ( ) ; this . isActive = function ( ) { return this . status == 'active' ; } ; this . createConversation = function ( message ) { var convo = new Conversation ( this , message ) ; convo . id = botkit . convoCount ++ ; this . convos . push ( convo ) ; return convo ; } ; this . startConversation = function ( message ) { var convo = this . createConversation ( message ) ; botkit . logger . debug ( '>   [Start] ' , convo . id , ' Conversation with ' , message . user , 'in' , message . channel ) ; convo . activate ( ) ; return convo ; } ; this . conversationEnded = function ( convo ) { botkit . logger . debug ( '>   [End] ' , convo . id , ' Conversation with ' , convo . source_message . user , 'in' , convo . source_message . channel ) ; this . trigger ( 'conversationEnded' , [ convo ] ) ; this . botkit . trigger ( 'conversationEnded' , [ bot , convo ] ) ; convo . trigger ( 'end' , [ convo ] ) ; var actives = 0 ; for ( var c = 0 ; c < this . convos . length ; c ++ ) { if ( this . convos [ c ] . isActive ( ) ) { actives ++ ; } } if ( actives == 0 ) { this . taskEnded ( ) ; } } ; this . endImmediately = function ( reason ) { for ( var c = 0 ; c < this . convos . length ; c ++ ) { if ( this . convos [ c ] . isActive ( ) ) { this . convos [ c ] . stop ( reason || 'stopped' ) ; } } } ; this . taskEnded = function ( ) { botkit . logger . debug ( '[End] ' , this . id , ' Task for ' , this . source_message . user , 'in' , this . source_message . channel ) ; this . status = 'completed' ; this . trigger ( 'end' , [ this ] ) ; } ; this . on = function ( event , cb ) { botkit . logger . debug ( 'Setting up a handler for' , event ) ; var events = event . split ( / \\, / g ) ; for ( var e in events ) { if ( ! this . events [ events [ e ] ] ) { this . events [ events [ e ] ] = [ ] ; } this . events [ events [ e ] ] . push ( cb ) ; } return this ; } ; this . trigger = function ( event , data ) { if ( this . events [ event ] ) { for ( var e = 0 ; e < this . events [ event ] . length ; e ++ ) { var res = this . events [ event ] [ e ] . apply ( this , data ) ; if ( res === false ) { return ; } } } } ; this . getResponsesByUser = function ( ) { var users = { } ; // go through all conversations // extract normalized answers for ( var c = 0 ; c < this . convos . length ; c ++ ) { var user = this . convos [ c ] . source_message . user ; users [ this . convos [ c ] . source_message . user ] = { } ; var convo = this . convos [ c ] ; users [ user ] = convo . extractResponses ( ) ; } return users ; } ; this . getResponsesBySubject = function ( ) { var answers = { } ; // go through all conversations // extract normalized answers for ( var c = 0 ; c < this . convos . length ; c ++ ) { var convo = this . convos [ c ] ; for ( var key in convo . responses ) { if ( ! answers [ key ] ) { answers [ key ] = { } ; } answers [ key ] [ convo . source_message . user ] = convo . extractResponse ( key ) ; } } return answers ; } ; this . tick = function ( ) { for ( var c = 0 ; c < this . convos . length ; c ++ ) { if ( this . convos [ c ] . isActive ( ) ) { this . convos [ c ] . tick ( ) ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies the SHA1 signature of the raw request payload before bodyParser parses it Will abort parsing if signature is invalid and pass a generic error to response [CODESPLIT] function verifyRequest ( req , res , buf , encoding ) { var expected = req . headers [ 'x-hub-signature' ] ; var calculated = getSignature ( buf ) ; if ( expected !== calculated ) { throw new Error ( 'Invalid signature on incoming request' ) ; } else { // facebook_botkit.logger.debug('** X-Hub Verification successful!') } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Route [CODESPLIT] function Route ( pattern , Handler , observe , router ) { this . pattern = pattern ; this . map = parsePattern ( pattern ) ; this . regExp = patternToRegExp ( pattern ) ; this . strictRegExp = patternToStrictRegExp ( pattern ) ; this . isComponent = ! ! Handler . extend ; this . Handler = Handler ; this . observe = assign ( { qs : [ ] , hash : [ ] , state : [ ] } , observe ) ; this . allObserved = this . observe . qs . concat ( this . observe . hash , this . observe . state ) ; this . router = router || { } ; this . view = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取某个cookie [CODESPLIT] function getCookie ( cookies , name ) { var match = String ( cookies ) . match ( new RegExp ( name + '=([^;]+)' ) ) ; if ( match ) { return match [ 1 ] ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append each option from the given <code > fromOptions< / code > to the given <code > options< / code > array flattening them to pass them later as parameters to a sub call process . [CODESPLIT] function appendOptions ( options , fromOptions ) { function pushOption ( optionName , optionValue ) { var valueDefined = optionValue !== null && optionValue !== undefined ; if ( optionName . length === 1 ) { // simple letter option options . push ( '-' + optionName ) ; if ( valueDefined ) { options . push ( optionValue ) ; } } else { // full option name options . push ( '--' + optionName + ( valueDefined ? '=' + optionValue : '' ) ) ; } } for ( var optionName in fromOptions ) { if ( fromOptions . hasOwnProperty ( optionName ) && optionName !== '_' ) { var optionValue = fromOptions [ optionName ] ; if ( Array . isArray ( optionValue ) ) { // we have multiple values for the same option, let's iterate on each optionValue . forEach ( function ( iOptionValue ) { pushOption ( optionName , iOptionValue ) ; } ) ; } else { pushOption ( optionName , optionValue ) ; } } } // now append the \"_\" which are not \"options\" but args if ( fromOptions && fromOptions . _ ) { [ ] . concat ( fromOptions . _ ) . forEach ( function ( arg ) { options . push ( arg ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "**************************************************************************** Performs the given request on the KISSmetrics tracker host . [CODESPLIT] function request_kissmetrics_client ( pathname , query_params , callback ) { var query_string = [ '_k=' , this . key , '&' ] . join ( '' ) , uri , v ; query_params [ '_t' ] = ( query_params [ '_d' ] ? query_params [ '_t' ] : Date . now ( ) ) ; for ( var k in query_params ) { v = query_params [ k ] ; if ( query_string !== '' ) { query_string += '&' ; } query_string += [ k , v ] . join ( '=' ) ; } uri = encodeURI ( [ 'http' , ':' , '//' , this . host , ':' , this . port , pathname , '?' , query_string ] . join ( '' ) ) ; // should encode the = sign in the user id var regex = new RegExp ( \"&_p=\" + query_params [ \"_p\" ] + \"&\" ) ; var uri = uri . replace ( regex , \"&_p=\" + query_params [ \"_p\" ] . replace ( \"=\" , \"%3D\" ) + \"&\" ) ; request ( { uri : uri } , function ( err , res ) { if ( err ) { console . log ( 'xxx KISSmetrics error' ) ; console . log ( '    uri    : ' + uri ) ; console . log ( '    error  : ' + err . message ) ; } else if ( res . statusCode !== 200 ) { err = new Error ( 'KISSmetrics error ---> RECEIVED WRONG STATUS CODE [' + res . statusCode + ']' ) ; } callback ( err , res ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "**************************************************************************** Sets properties on a person without recording an event by making a request . [CODESPLIT] function set_kissmetrics_client ( person , properties , callback ) { var query_params = new Object ( properties ) ; query_params [ '_p' ] = person ; this . request ( '/s' , query_params , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "**************************************************************************** Aliases the user identified by person with aliases . [CODESPLIT] function alias_kissmetrics_client ( person , aliases , callback ) { var aliases = ( Array . isArray ( aliases ) ? aliases : [ aliases ] ) , that = this ; async . forEach ( aliases , function ( alias , callback ) { var query_params = { } ; query_params [ '_p' ] = person ; query_params [ '_n' ] = alias ; that . request ( '/a' , query_params , callback ) ; } , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "**************************************************************************** Records event for person . Also sets properties on the person if specified . [CODESPLIT] function record_kissmetrics_client ( ) { var args = Array . prototype . slice . call ( arguments ) , callback = args . pop ( ) , person = args . shift ( ) , event = args . shift ( ) , properties = args . shift ( ) || { } , query_params = new Object ( properties ) ; query_params [ '_p' ] = person ; query_params [ '_n' ] = event ; this . request ( '/e' , query_params , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "**************************************************************************** KISSmetrics REST client constructor . [CODESPLIT] function kissmetrics_client ( options ) { var options = options || { } ; this . host = options . host || DEFAULT_TRACKER_SERVER ; this . port = options . port || DEFAULT_TRACKER_PORT ; this . key = options . key ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO split into two functions? i . e . one for the top - level call one for the cascade [CODESPLIT] function notifyPatternObservers ( ractive , registeredKeypath , actualKeypath , isParentOfChangedKeypath , isTopLevelCall ) { var i , patternObserver , children , child , key , childActualKeypath , potentialWildcardMatches , cascade ; // First, observers that match patterns at the same level // or higher in the tree i = ractive . _patternObservers . length ; while ( i -- ) { patternObserver = ractive . _patternObservers [ i ] ; if ( patternObserver . regex . test ( actualKeypath ) ) { patternObserver . update ( actualKeypath ) ; } } if ( isParentOfChangedKeypath ) { return ; } // If the changed keypath is 'foo.bar', we need to see if there are // any pattern observer dependants of keypaths below any of // 'foo.bar', 'foo.*', '*.bar' or '*.*' (e.g. 'foo.bar.*' or 'foo.*.baz' ) cascade = function ( keypath ) { if ( children = ractive . _depsMap [ keypath ] ) { i = children . length ; while ( i -- ) { child = children [ i ] ; // foo.*.baz key = lastKey . exec ( child ) [ 0 ] ; // 'baz' childActualKeypath = actualKeypath ? actualKeypath + '.' + key : key ; // 'foo.bar.baz' notifyPatternObservers ( ractive , child , childActualKeypath ) ; } } } ; if ( isTopLevelCall ) { potentialWildcardMatches = getPotentialWildcardMatches ( actualKeypath ) ; potentialWildcardMatches . forEach ( cascade ) ; } else { cascade ( registeredKeypath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function returns all the possible true / false combinations for a given number - e . g . for two the possible combinations are [ true true ] [ true false ] [ false true ] [ false false ] . It does so by getting all the binary values between 0 and e . g . 11 [CODESPLIT] function getStarMap ( num ) { var ones = '' , max , binary , starMap , mapper , i ; if ( ! starMaps [ num ] ) { starMap = [ ] ; while ( ones . length < num ) { ones += 1 ; } max = parseInt ( ones , 2 ) ; mapper = function ( digit ) { return digit === '1' ; } ; for ( i = 0 ; i <= max ; i += 1 ) { binary = i . toString ( 2 ) ; while ( binary . length < num ) { binary = '0' + binary ; } starMap [ i ] = Array . prototype . map . call ( binary , mapper ) ; } starMaps [ num ] = starMap ; } return starMaps [ num ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO optimise this [CODESPLIT] function ( keypath , root ) { var i = queue . length , animation ; while ( i -- ) { animation = queue [ i ] ; if ( animation . root === root && animation . keypath === keypath ) { animation . stop ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method forces the evaluator to sync with the current model in the case of a smart update [CODESPLIT] function ( ) { if ( ! this . selfUpdating ) { this . deferred = true ; } var i = this . refs . length ; while ( i -- ) { this . refs [ i ] . update ( ) ; } if ( this . deferred ) { this . update ( ) ; this . deferred = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO teardown when element torn down [CODESPLIT] function ( ) { var i ; if ( this . custom ) { this . custom . teardown ( ) ; } else { this . node . removeEventListener ( this . name , genericHandler , false ) ; } i = this . proxies . length ; while ( i -- ) { this . proxies [ i ] . teardown ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO what happens if a transition is aborted? TODO use this with Animation to dedupe some code? [CODESPLIT] function ( options ) { var easing ; this . duration = options . duration ; this . step = options . step ; this . complete = options . complete ; // easing if ( typeof options . easing === 'string' ) { easing = options . root . easing [ options . easing ] ; if ( ! easing ) { warn ( 'Missing easing function (\"' + options . easing + '\"). You may need to download a plugin from [TODO]' ) ; easing = linear ; } } else if ( typeof options . easing === 'function' ) { easing = options . easing ; } else { easing = linear ; } this . easing = easing ; this . start = getTime ( ) ; this . end = this . start + this . duration ; this . running = true ; animations . add ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO maybe refactor this? [CODESPLIT] function getRefs ( token , refs ) { var i , list ; if ( token . t === types . REFERENCE ) { if ( refs . indexOf ( token . n ) === - 1 ) { refs . unshift ( token . n ) ; } } list = token . o || token . m ; if ( list ) { if ( isObject ( list ) ) { getRefs ( list , refs ) ; } else { i = list . length ; while ( i -- ) { getRefs ( list [ i ] , refs ) ; } } } if ( token . x ) { getRefs ( token . x , refs ) ; } if ( token . r ) { getRefs ( token . r , refs ) ; } if ( token . v ) { getRefs ( token . v , refs ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assign [CODESPLIT] function assign ( object , source ) { for ( var i = 1 , c = arguments . length ; i < c ; i ++ ) { for ( var x in arguments [ i ] ) { if ( arguments [ i ] . hasOwnProperty ( x ) && arguments [ i ] [ x ] !== undefined ) { object [ x ] = arguments [ i ] [ x ] ; } } } return object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Join paths [CODESPLIT] function joinPaths ( parts ) { return Array . prototype . slice . call ( arguments ) . join ( '/' ) . replace ( / \\/+ / g , '/' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parents [CODESPLIT] function parents ( el , name ) { while ( el && el . nodeName . toLowerCase ( ) !== name ) { el = el . parentNode ; } return el && el . nodeName . toLowerCase ( ) === name ? el : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse hash [CODESPLIT] function parseHash ( hash , keys ) { try { var parsed = compact ( JSON . parse ( decodeURIComponent ( hash . substr ( 2 ) ) ) ) ; return keys ? pick ( parsed , keys ) : parsed ; } catch ( e ) { return { } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse URI [CODESPLIT] function parseUri ( uri ) { var parts = uri . match ( / ^(?:([\\w+.-]+):\\/\\/([^/]+))?([^?#]*)?(\\?[^#]*)?(#.*)? / ) ; return { protocol : parts [ 1 ] || '' , host : parts [ 2 ] || '' , path : parts [ 3 ] || '' , qs : parts [ 4 ] || '' , hash : parts [ 5 ] || '' } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse QS [CODESPLIT] function parseQS ( qs , keys ) { var index = qs . indexOf ( '?' ) ; var parsed = { } ; if ( index !== - 1 ) { var pairs = qs . substr ( index + 1 ) . split ( '&' ) ; var pair = [ ] ; for ( var i = 0 , c = pairs . length ; i < c ; i ++ ) { pair = pairs [ i ] . split ( '=' ) ; if ( ( ! isEmpty ( pair [ 1 ] ) ) && ( ! isEmpty ( parseJSON ( pair [ 1 ] ) ) ) ) { parsed [ decodeForm ( decodeURIComponent ( pair [ 0 ] ) ) ] = parseJSON ( decodeForm ( decodeURIComponent ( pair [ 1 ] ) ) ) ; } } } return keys ? pick ( parsed , keys ) : parsed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pick [CODESPLIT] function pick ( object , keys ) { var data = { } ; if ( typeof keys === 'function' ) { for ( var x in object ) { if ( object . hasOwnProperty ( x ) && keys ( object [ x ] , x ) ) { data [ x ] = object [ x ] ; } } } else { for ( var i = 0 , c = keys . length ; i < c ; i ++ ) { data [ keys [ i ] ] = object [ keys [ i ] ] ; } } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scroll to [CODESPLIT] function scrollTo ( id ) { var el = document . getElementById ( id ) ; if ( el ) { window . scrollBy ( 0 , el . getBoundingClientRect ( ) . top ) ; } else { window . scrollTo ( 0 , 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stringify hash [CODESPLIT] function stringifyHash ( data ) { data = compact ( data ) ; return ! isEmpty ( data ) ? '#!' + encodeURIComponent ( stringify ( data ) ) : '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stringify QS [CODESPLIT] function stringifyQS ( data ) { var qs = '' ; for ( var x in data ) { if ( data . hasOwnProperty ( x ) && ! isEmpty ( data [ x ] ) ) { qs += '&' + encodeURIComponent ( x ) + '=' + encodeURIComponent ( stringify ( data [ x ] ) ) ; } } return qs ? '?' + qs . substr ( 1 ) : '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Router [CODESPLIT] function Router ( options ) { this . globals = options . globals || [ ] ; this . basePath = options . basePath || '' ; this . el = options . el ; this . data = options . data || function ( ) { return { } ; } ; this . history = options . history || history ; this . strictMode = ! ! options . strictMode ; this . reloadOnClick = options . reloadOnClick ; this . linksWatcher = null ; this . stateWatcher = null ; this . route = null ; this . routes = [ ] ; this . uri = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Should dispatch [CODESPLIT] function shouldDispatch ( oldUri , newUri , route ) { return oldUri . path !== newUri . path || oldUri . qs !== newUri . qs || ( decodeURIComponent ( oldUri . hash ) !== decodeURIComponent ( newUri . hash ) && ( ! route || route . observe . hash . length ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This class manages the DockerCmd and handles dockerdesc . json [CODESPLIT] function DockerCmdManager ( dockerdescPath ) { dockerdescPath = dockerdescPath || './dockerdesc.json' ; if ( ! fs . existsSync ( dockerdescPath ) ) { throw new Error ( util . format ( 'The path \"%s\" does not exists.' , dockerdescPath ) ) ; } /** @type {string} */ this . dockerdescDir = path . dirname ( dockerdescPath ) ; var dockerdescPathStat = fs . statSync ( dockerdescPath ) ; if ( dockerdescPathStat . isDirectory ( ) ) { this . dockerdescDir = dockerdescPath ; dockerdescPath = path . join ( dockerdescPath , 'dockerdesc.json' ) ; } /** @type {Dockerdesc} */ var dockerdescContent = fs . readFileSync ( dockerdescPath ) ; try { this . dockerdesc = JSON . parse ( dockerdescContent ) ; } catch ( err ) { throw new Error ( 'Problem in the dockerdesc.json file format.\\n' + err . stack ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "drilldown Safely accesses deep properties of objects . [CODESPLIT] function dd ( object , _context , _key , _root , _rootPath ) { _root = _root || object ; _rootPath = _rootPath || [ ] ; var drill = function ( key ) { var nextObject = ( object && object . hasOwnProperty ( key ) && object [ key ] || undefined ) ; return dd ( nextObject , object , key , _root , _rootPath . concat ( key ) ) ; } ; drill . val = object ; drill . exists = object !== undefined ; drill . set = function ( value ) { if ( _rootPath . length === 0 ) { return ; } var contextIterator = _root ; for ( var depth = 0 ; depth < _rootPath . length ; depth ++ ) { var key = _rootPath [ depth ] ; var isFinalDepth = ( depth === _rootPath . length - 1 ) ; if ( ! isFinalDepth ) { contextIterator [ key ] = ( contextIterator . hasOwnProperty ( key ) && typeof contextIterator [ key ] === 'object' ? contextIterator [ key ] : { } ) ; contextIterator = contextIterator [ key ] ; } else { _context = contextIterator ; _key = key ; } } _context [ _key ] = value ; drill . val = value ; drill . exists = value !== undefined ; return value ; } ; drill . update = function ( value ) { if ( drill . exists ) { _context [ _key ] = value ; drill . val = value ; return value ; } } ; drill . invoke = isFunction ( object ) ? Function . prototype . bind . call ( object , _context ) : function ( ) { } ; return drill ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "feature flag控制类，提供接口给模板调用，判断某个feature是否开启 [CODESPLIT] function ( option , req , res ) { this . params = { 'req' : req , 'res' : res } ; this . option = option ; this . features = { } ; //feature实例配置列表 this . logger = Logger . getLogger ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render output from tasks [CODESPLIT] function printTasks ( tasks , verbose ) { tasks = tasks . filterHidden ( verbose ) . sort ( ) ; var results = [ 'Usage: gulp [task] [task2] ...' , '' , 'Tasks: ' ] ; var fieldTaskLen = tasks . getLongestNameLength ( ) ; tasks . forEach ( function ( task ) { var comment = task . comment || { } ; var lines = comment . lines || [ ] ; results . push ( formatColumn ( task . name , fieldTaskLen ) + ( lines [ 0 ] || '' ) ) ; for ( var i = 1 ; i < lines . length ; i ++ ) { results . push ( formatColumn ( '' , fieldTaskLen ) + '  ' + lines [ i ] ) ; } } ) ; return results . join ( '\\n' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a text surrounded by space [CODESPLIT] function formatColumn ( text , width , offsetLeft , offsetRight ) { offsetLeft = undefined !== offsetLeft ? offsetLeft : 3 ; offsetRight = undefined !== offsetRight ? offsetRight : 3 ; return new Array ( offsetLeft + 1 ) . join ( ' ' ) + text + new Array ( Math . max ( width - text . length , 0 ) + 1 ) . join ( ' ' ) + new Array ( offsetRight + 1 ) . join ( ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a new instance that is inherited from Gulp [CODESPLIT] function inheritGulp ( ) { function TaskDoc ( ) { this . taskList = new TaskList ( ) ; gulp . Gulp . call ( this ) ; } TaskDoc . prototype = gulp ; return new TaskDoc ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////////////// main api method defined on the jazz environment in imitation of the jasmine lib src . where () accepts only a function with a commented data - table and an expectation . parses the function into data array passing each array row into a new Function () that contains the original function body s expectation statements . entire data - table with pass / fail messages is passed to the jasmine report only if an expectation fails . returns the data table values array for further use in other expectations . ////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] function where ( fn ) { if ( typeof fn != 'function' ) { throw new Error ( 'where(param) expected param should be a function' ) ; } var fnBody = fn . toString ( ) . replace ( / \\s*function[^\\(]*[\\(][^\\)]*[\\)][^\\{]*{ / , '' ) . replace ( / [\\}]$ / , '' ) ; var values = parseFnBody ( fnBody ) ; var labels = values [ 0 ] ; /**\n     * {labels} array is toString'd so the values became param symbols in the new Function.\n     * {fnBody} is what's left of the original function, mainly the expectation.\n     */ var fnTest = new Function ( labels . toString ( ) , fnBody ) ; var failedCount = 0 ; var trace = '\\n [' + labels . join ( PAD ) + '] : ' ; /*\n     * 1.x.x - jasmine.getEnv().currentSpec\n     * 2.x.x - .currentSpec is no longer exposed (leaking state) so use a shim for it with \n     *          the v2 .result property\n     */ var currentSpec = jasmine . getEnv ( ) . currentSpec || { result : { } } ; var result = /* jasmine 2.x.x. */ currentSpec . result || /* jasmine 1.x.x. */ currentSpec . results_ ; var item , message ; for ( var i = 1 ; i < values . length ; ++ i ) { message = MESSAGE ; fnTest . apply ( currentSpec , values [ i ] ) ; // TODO - extract method, perhaps... // collect any failed expectations  if ( result . failedExpectations && result . failedExpectations . length ) { /*\n         * jasmine 2.x.x.\n         */ if ( failedCount < result . failedExpectations . length ) { failedCount += 1 ; item = result . failedExpectations [ failedCount - 1 ] ; message = item . message ; item . message = trace + '\\n [' + values [ i ] . join ( PAD ) + '] (' + message + ')' ; } } else if ( result . items_ ) { /*\n         * jasmine 1.x.x.\n         */ item = result . items_ [ result . items_ . length - 1 ] ; if ( item && ! item . passed_ ) { failedCount += 1 ; message = item . message ; item . message = trace + '\\n [' + values [ i ] . join ( PAD ) + '] (' + message + ')' ; } } } // use these in further assertions  return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private method parseFn () takes a function or string and extracts the data table labels and values . returns a result object with { body } the function as a string and { table } data array . [CODESPLIT] function parseFnBody ( fnBody ) { var fs = fnBody . toString ( ) ; var table = fs . match ( / \\/(\\*){3,3}[^\\*]+(\\*){3,3}\\/ / ) ; var data = table [ 0 ] . replace ( / [\\/\\*]*[\\r]*[\\*\\/]* / g , '' ) . split ( '\\n' ) ; var rows = [ ] ; var row , size ; for ( var i = 0 ; i < data . length ; i ++ ) { row = data [ i ] . replace ( / \\b[\\s*] / , '' ) . replace ( / (\\s)*\\b / , '' ) ; if ( row . match ( / \\S+ / ) ) { row = row . replace ( / \\s+ / g , '' ) ; // empty column if ( row . match ( / [\\|][\\|] / g ) ) { throw new Error ( 'where() data table has unbalanced columns: ' + row ) ; } row = balanceRowData ( row ) ; // visiting label row if ( typeof size != 'number' ) { shouldNotHaveDuplicateLabels ( row ) ; size = row . length ; } // data row length if ( size !== row . length ) { throw new Error ( 'where-data table has unbalanced row; expected ' + size + ' columns but has ' + row . length + ': [' + row . join ( ', ' ) + ']' ) ; } convertNumerics ( row ) ; rows . push ( row ) ; } } // num rows if ( rows . length < 2 ) { throw new Error ( 'where() data table should contain at least 2 rows but has ' + rows . length ) ; } return rows ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function shouldNotHaveDuplicateLabels ( row ) { for ( var label , visited = { } , j = 0 ; j < row . length ; j += 1 ) { label = row [ j ] ; if ( visited [ label ] ) { throw new Error ( 'where-data table contains duplicate label \\'' + label + '\\' in [' + row . join ( ', ' ) + ']' ) ; } visited [ label ] = 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function convertNumerics ( row ) { for ( var t , i = 0 ; i < row . length ; i += 1 ) { t = parseFloat ( row [ i ] . replace ( / \\'|\\\"|\\, / g , '' ) ) ; isNaN ( t ) || ( row [ i ] = t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We are creating one generic version of logger . [CODESPLIT] function _log ( level ) { return function ( ) { var meta = null ; var args = arguments ; if ( arguments . length === 0 ) { // we only check here current level, but we also should more but restify uses it only for trace checks return this . _winston . level === level ; } else if ( arguments [ 0 ] instanceof Error ) { // winston supports Error in meta, so pass it as last meta = arguments [ 0 ] . toString ( ) ; args = Array . prototype . slice . call ( arguments , 1 ) ; args . push ( meta ) ; } else if ( typeof ( args [ 0 ] ) === 'string' ) { // just arrayize for level args = Array . prototype . slice . call ( arguments ) ; } else { // push provided object as meta meta = arguments [ 0 ] ; args = Array . prototype . slice . call ( arguments , 1 ) ; args . push ( meta ) ; } args . unshift ( level ) ; this . _winston . log . apply ( this . _winston , args ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility functions {{{ Try and return a value from a deeply nested object by a dotted path This is functionally the same as lodash s own _ . get () function [CODESPLIT] function getPath ( obj , path , defaultValue ) { var pointer = obj ; path . split ( '.' ) . every ( function ( slice ) { if ( pointer [ slice ] ) { pointer = pointer [ slice ] ; return true ; } else { pointer = defaultValue ; return false ; } } ) ; return pointer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try and idenfity if the given item is a promise or is promise like [CODESPLIT] function isPromise ( item ) { if ( ! item ) return false ; return ( ( util . types && util . types . isPromise && util . types . isPromise ( item ) ) || ( item . constructor && item . constructor . name == 'Promise' ) || ( ! item instanceof objectInstance && item . then && typeof item . then == 'function' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Figure out if a function declaration looks like it takes a callback Really this just checks the setup of a function for an argument - it cannot check if that argument is a function [CODESPLIT] function hasCallback ( fn ) { var fnString = fn . toString ( ) ; // console.log('---'); // console.log('GIVEN', '>>> ' + fnString + ' <<<'); var bits , fnArgs ; if ( / ^async  / . test ( fnString ) ) { // console.log('IS ASYNC'); return false ; // Its an async function and should only ever return a promise } else if ( bits = / ^function\\s*(?:.*?)\\s*\\((.*?)\\) / . exec ( fnString ) ) { // console.log('> FUNC', bits[1]); fnArgs = bits [ 1 ] ; } else if ( / ^\\(\\s*\\)\\s*=> / . test ( fnString ) ) { // console.log('ARROW (no args)'); return false ; } else if ( bits = / ^\\s\\((.*?)\\)\\s*?=> / . exec ( fnString ) ) { // console.log('> ARROW (braces)', bits[1]); fnArgs = bits [ 1 ] ; } else if ( bits = / ^(.*?)\\s*=> / . exec ( fnString ) ) { // console.log('> ARROW (no braces)', bits[1]); fnArgs = bits [ 1 ] ; } else { // console.log('> EMPTY'); return false ; } fnArgs = fnArgs . replace ( / ^\\s+ / , '' ) . replace ( / \\s+$ / , '' ) ; // Clean up args by trimming whitespace // console.log('ARGS:', fnArgs); return ! ! fnArgs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queue up a function ( s ) to execute in parallel [CODESPLIT] function parallel ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'function' , function ( callback ) { self . _struct . push ( { type : 'parallelArray' , payload : [ callback ] } ) ; } ) . ifForm ( 'string function' , function ( id , callback ) { var payload = { } ; payload [ id ] = callback ; self . _struct . push ( { type : 'parallelArray' , payload : payload } ) ; } ) . ifForm ( 'array' , function ( tasks ) { self . _struct . push ( { type : 'parallelArray' , payload : tasks } ) ; } ) . ifForm ( 'object' , function ( tasks ) { self . _struct . push ( { type : 'parallelObject' , payload : tasks } ) ; } ) // Async library compatibility {{{ . ifForm ( 'array function' , function ( tasks , callback ) { self . _struct . push ( { type : 'parallelArray' , payload : tasks } ) ; self . end ( callback ) ; } ) . ifForm ( 'object function' , function ( tasks , callback ) { self . _struct . push ( { type : 'parallelObject' , payload : tasks } ) ; self . end ( callback ) ; } ) // }}} . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .parallel(): ' + form ) ; } ) return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like parallel but only return the first non - undefined non - null result [CODESPLIT] function race ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'array' , function ( tasks ) { self . _struct . push ( { type : 'race' , payload : tasks } ) ; } ) . ifForm ( 'string array' , function ( id , tasks ) { self . _struct . push ( { type : 'race' , id : arguments [ 0 ] , payload : arguments [ 1 ] } ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .parallel(): ' + form ) ; } ) return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run an array / object though a function This is similar to the async native . each () function but chainable [CODESPLIT] function forEach ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'array function' , function ( tasks , callback ) { self . _struct . push ( { type : 'forEachArray' , payload : tasks , callback : callback } ) ; } ) . ifForm ( 'object function' , function ( tasks , callback ) { self . _struct . push ( { type : 'forEachObject' , payload : tasks , callback : callback } ) ; } ) . ifForm ( 'string function' , function ( tasks , callback ) { self . _struct . push ( { type : 'forEachLateBound' , payload : tasks , callback : callback } ) ; } ) . ifForm ( 'number function' , function ( max , callback ) { self . _struct . push ( { type : 'forEachRange' , min : 1 , max : max , callback : callback } ) ; } ) . ifForm ( 'number number function' , function ( min , max , callback ) { self . _struct . push ( { type : 'forEachRange' , min : min , max : max , callback : callback } ) ; } ) . ifForm ( 'string array function' , function ( output , tasks , callback ) { self . _struct . push ( { type : 'mapArray' , output : output , payload : tasks , callback : callback } ) ; } ) . ifForm ( 'string object function' , function ( output , tasks , callback ) { self . _struct . push ( { type : 'mapObject' , output : output , payload : tasks , callback : callback } ) ; } ) . ifForm ( 'string string function' , function ( output , tasks , callback ) { self . _struct . push ( { type : 'mapLateBound' , output : output , payload : tasks , callback : callback } ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .forEach(): ' + form ) ; } ) ; return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collection of items that have been deferred [CODESPLIT] function deferAdd ( id , task , parentChain ) { var self = this ; parentChain . waitingOn = ( parentChain . waitingOn || 0 ) + 1 ; if ( ! parentChain . waitingOnIds ) parentChain . waitingOnIds = [ ] ; parentChain . waitingOnIds . push ( id ) ; self . _deferred . push ( { id : id || null , prereq : parentChain . prereq || [ ] , payload : function ( next ) { self . _context . _id = id ; run ( self . _options . context , task , function ( err , value ) { // Glue callback function to first arg if ( id ) self . _context [ id ] = value ; self . _deferredRunning -- ; if ( -- parentChain . waitingOn == 0 ) { parentChain . completed = true ; if ( self . _struct . length && self . _struct [ self . _structPointer ] . type == 'await' ) self . _execute ( err ) ; } self . _execute ( err ) ; } , ( parentChain . prereq || [ ] ) . map ( function ( pre ) { return self . _context [ pre ] ; } ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "}}} Queue up a function ( s ) to execute as deferred - i . e . dont stop to wait for it [CODESPLIT] function defer ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'function' , function ( callback ) { self . _struct . push ( { type : 'deferArray' , payload : [ callback ] } ) ; } ) . ifForm ( 'string function' , function ( id , callback ) { var payload = { } ; payload [ id ] = callback ; self . _struct . push ( { type : 'deferObject' , payload : payload } ) ; } ) . ifForm ( 'array' , function ( tasks ) { self . _struct . push ( { type : 'deferArray' , payload : tasks } ) ; } ) . ifForm ( 'object' , function ( tasks ) { self . _struct . push ( { type : 'deferObject' , payload : tasks } ) ; } ) . ifForm ( 'array function' , function ( preReqs , callback ) { self . _struct . push ( { type : 'deferArray' , prereq : preReqs , payload : [ callback ] } ) ; } ) . ifForm ( 'string string function' , function ( preReq , id , callback ) { var payload = { } ; payload [ id ] = callback ; self . _struct . push ( { type : 'deferObject' , prereq : [ preReq ] , payload : payload } ) ; } ) . ifForm ( 'array string function' , function ( preReqs , id , callback ) { var payload = { } ; payload [ id ] = callback ; self . _struct . push ( { type : 'deferObject' , prereq : preReqs , payload : payload } ) ; } ) . ifForm ( 'string array function' , function ( id , preReqs , callback ) { var payload = { } ; payload [ id ] = callback ; self . _struct . push ( { type : 'deferObject' , prereq : preReqs , payload : payload } ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .defer():' + form ) ; } ) ; return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queue up an await point This stops the execution queue until its satisfied that dependencies have been resolved [CODESPLIT] function await ( ) { var payload = [ ] ; // Slurp all args into payload argy ( arguments ) . getForm ( ) . split ( ',' ) . forEach ( function ( type , offset ) { switch ( type ) { case '' : // Blank arguments - do nothing // Pass break ; case 'string' : payload . push ( args [ offset ] ) ; break ; case 'array' : payload . concat ( args [ offset ] ) ; break ; default : throw new Error ( 'Unknown argument type passed to .await(): ' + type ) ; } } ) ; this . _struct . push ( { type : 'await' , payload : payload } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queue up a timeout setter [CODESPLIT] function timeout ( newTimeout ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { self . _struct . push ( { type : 'timeout' , delay : false } ) ; } ) . ifForm ( 'boolean' , function ( setTimeout ) { if ( setTimeout ) throw new Error ( 'When calling .timeout(Boolean) only False is accepted to disable the timeout' ) ; self . _struct . push ( { type : 'timeout' , delay : false } ) ; } ) . ifForm ( 'number' , function ( delay ) { self . _struct . push ( { type : 'timeout' , delay : delay } ) ; } ) . ifForm ( 'function' , function ( callback ) { self . _struct . push ( { type : 'timeout' , callback : callback } ) ; } ) . ifForm ( 'number function' , function ( delay , callback ) { self . _struct . push ( { type : 'timeout' , delay : delay , callback : callback } ) ; } ) . ifForm ( 'function number' , function ( delay , callback ) { self . _struct . push ( { type : 'timeout' , delay : delay , callback : callback } ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .timeout():' + form ) ; } ) ; return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The default timeout handler This function displays a simple error message and also fires the timeout hook [CODESPLIT] function _timeoutHandler ( ) { var currentTaskIndex = this . _struct . findIndex ( function ( task ) { return ! task . completed } ) ; if ( ! currentTaskIndex < 0 ) { console . log ( 'Async-Chainable timeout on unknown task' ) ; console . log ( 'Full structure:' , this . _struct ) ; } else { console . log ( 'Async-Chainable timeout: Task #' , currentTaskIndex + 1 , '(' + this . _struct [ currentTaskIndex ] . type + ')' , 'elapsed timeout of' , this . _options . timeout + 'ms' ) ; } this . fire ( 'timeout' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queue up a varable setter ( i . e . set a hash of variables in context ) [CODESPLIT] function set ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'string scalar|array|object|date|regexp|null' , function ( id , value ) { var payload = { } ; payload [ id ] = value ; self . _struct . push ( { type : 'set' , payload : payload } ) ; } ) . ifForm ( 'object' , function ( obj ) { self . _struct . push ( { type : 'set' , payload : obj } ) ; } ) . ifForm ( 'function' , function ( callback ) { self . _struct . push ( { type : 'seriesArray' , payload : [ callback ] } ) ; } ) . ifForm ( 'string function' , function ( id , callback ) { var payload = { } ; payload [ id ] = callback ; self . _struct . push ( { type : 'seriesObject' , payload : payload } ) ; } ) . ifForm ( [ 'string' , 'string undefined' ] , function ( id ) { var payload = { } ; payload [ id ] = undefined ; self . _struct . push ( { type : 'set' , payload : payload } ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .set():' + form ) ; } ) ; return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a context items value Not to be confused with set () which is the chainable external visible version of this Unlike set () this function sets an item of _context immediately [CODESPLIT] function _set ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'string scalar|array|object|date|regexp|null' , function ( id , value ) { self . _setRaw ( id , value ) ; } ) . ifForm ( 'object' , function ( obj ) { for ( var key in obj ) self . _setRaw ( key , obj [ key ] ) ; } ) . ifForm ( 'string function' , function ( id , callback ) { self . _setRaw ( id , callback . call ( this ) ) ; } ) . ifForm ( 'function' , function ( callback ) { // Expect func to return something which is then processed via _set self . _set ( callback . call ( this ) ) ; } ) . ifForm ( [ 'string' , 'string undefined' ] , function ( id ) { self . _setRaw ( id , undefined ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .set():' + form ) ; } ) ; return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function executed at the end of the chain This can occur either in sequence ( i . e . no errors ) or a jump to this position ( i . e . an error happened somewhere ) [CODESPLIT] function _finalize ( err ) { // Sanity checks {{{ if ( this . _struct . length == 0 ) return ; // Finalize called on dead object - probably a defer() fired without an await() if ( this . _struct [ this . _struct . length - 1 ] . type != 'end' ) { throw new Error ( 'While trying to find an end point in the async-chainable structure the last item in the this._struct does not have type==end!' ) ; return ; } // }}} var self = this ; this . fire ( 'end' , function ( hookErr ) { self . _struct [ self . _struct . length - 1 ] . payload . call ( self . _options . context , err || hookErr ) ; if ( self . _options . autoReset ) self . reset ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function to execute the next pending queue item This is usually called after the completion of every asyncChainable . run call [CODESPLIT] function _execute ( err ) { var self = this ; if ( err ) return this . _finalize ( err ) ; // An error has been raised - stop exec and call finalize now if ( ! self . _executing ) { // Never before run this object - run fire('start') and defer until it finishes self . _executing = true ; return self . fire . call ( self , 'start' , self . _execute . bind ( self ) ) ; } do { var redo = false ; if ( self . _structPointer >= self . _struct . length ) return this . _finalize ( err ) ; // Nothing more to execute in struct self . _deferCheck ( ) ; // Kick off any pending deferred items var currentExec = self . _struct [ self . _structPointer ] ; // Sanity checks {{{ if ( ! currentExec . type ) { throw new Error ( 'No type is specified for async-chainable structure at offset ' + self . _structPointer ) ; return self ; } // }}} self . _structPointer ++ ; // Skip step when function supports skipping if the argument is empty {{{ if ( [ 'parallelArray' , 'parallelObject' , 'forEachArray' , 'forEachObject' , 'seriesArray' , 'seriesObject' , 'deferArray' , 'deferObject' , 'set' ] . indexOf ( currentExec . type ) > - 1 && ( ! currentExec . payload || // Not set OR ( argy . isType ( currentExec . payload , 'array' ) && ! currentExec . payload . length ) || // An empty array ( argy . isType ( currentExec . payload , 'object' ) && ! Object . keys ( currentExec . payload ) . length ) // An empty object ) ) { currentExec . completed = true ; redo = true ; continue ; } // }}} switch ( currentExec . type ) { case 'forEachRange' : var iterArray = Array ( currentExec . max - currentExec . min + 1 ) . fill ( false ) ; self . runArray ( iterArray . map ( function ( v , i ) { var val = self . _context . _item = currentExec . min + i ; var index = self . _context . _key = i ; return function ( next ) { if ( currentExec . translate ) val = currentExec . translate ( val , index , iterArray . length ) ; run ( self . _options . context , currentExec . callback , next , [ val , index , iterArray . length ] ) ; } ; } ) , self . _options . limit , function ( err ) { currentExec . completed = true ; self . _execute ( err ) ; } ) ; break ; case 'forEachArray' : self . runArray ( currentExec . payload . map ( function ( item , iter ) { self . _context . _item = item ; self . _context . _key = iter ; return function ( next ) { run ( self . _options . context , currentExec . callback , next , [ item , iter ] ) ; } ; } ) , self . _options . limit , function ( err ) { currentExec . completed = true ; self . _execute ( err ) ; } ) ; break ; case 'forEachObject' : self . runArray ( Object . keys ( currentExec . payload ) . map ( function ( key ) { return function ( next ) { self . _context . _item = currentExec . payload [ key ] ; self . _context . _key = key ; run ( self . _options . context , currentExec . callback , function ( err , value ) { self . _set ( key , value ) ; // Allocate returned value to context next ( err ) ; } , [ currentExec . payload [ key ] , key ] ) ; } ; } ) , self . _options . limit , function ( err ) { currentExec . completed = true ; self . _execute ( err ) ; } ) ; break ; case 'forEachLateBound' : if ( ! currentExec . payload || ! currentExec . payload . length ) { // Payload is blank // Goto next chain currentExec . completed = true ; redo = true ; break ; } var resolvedPayload = self . getPath ( self . _context , currentExec . payload ) ; if ( ! resolvedPayload ) { // Resolved payload is blank // Goto next chain currentExec . completed = true ; redo = true ; break ; } // Replace own exec array with actual type of payload now we know what it is {{{ if ( argy . isType ( resolvedPayload , 'array' ) ) { currentExec . type = 'forEachArray' ; } else if ( argy . isType ( resolvedPayload , 'object' ) ) { currentExec . type = 'forEachObject' ; } else { throw new Error ( 'Cannot perform forEach over unknown object type: ' + argy . getType ( resolvedPayload ) ) ; } currentExec . payload = resolvedPayload ; self . _structPointer -- ; // Force re-eval of this chain item now its been replace with its real (late-bound) type redo = true ; // }}} break ; case 'mapArray' : var output = new Array ( currentExec . payload . length ) ; self . runArray ( currentExec . payload . map ( function ( item , iter ) { self . _context . _item = item ; self . _context . _key = iter ; return function ( next ) { run ( self . _options . context , currentExec . callback , function ( err , value ) { if ( err ) return next ( err ) ; output [ iter ] = value ; next ( ) ; } , [ item , iter ] ) ; } ; } ) , self . _options . limit , function ( err ) { currentExec . completed = true ; self . _set ( currentExec . output , output ) ; self . _execute ( err ) ; } ) ; break ; case 'mapObject' : var output = { } ; self . runArray ( Object . keys ( currentExec . payload ) . map ( function ( key ) { return function ( next ) { self . _context . _item = currentExec . payload [ key ] ; self . _context . _key = key ; run ( self . _options . context , currentExec . callback , function ( err , value , outputKey ) { output [ outputKey || key ] = value ; next ( err ) ; } , [ currentExec . payload [ key ] , key ] ) ; } ; } ) , self . _options . limit , function ( err ) { currentExec . completed = true ; self . _set ( currentExec . output , output ) ; self . _execute ( err ) ; } ) ; break ; case 'mapLateBound' : if ( ! currentExec . payload || ! currentExec . payload . length ) { // Payload is blank // Goto next chain currentExec . completed = true ; redo = true ; break ; } var resolvedPayload = self . getPath ( self . _context , currentExec . payload ) ; if ( ! resolvedPayload ) { // Resolved payload is blank // Goto next chain currentExec . completed = true ; redo = true ; break ; } // Replace own exec array with actual type of payload now we know what it is {{{ if ( argy . isType ( resolvedPayload , 'array' ) ) { currentExec . type = 'mapArray' ; } else if ( argy . isType ( resolvedPayload , 'object' ) ) { currentExec . type = 'mapObject' ; } else { throw new Error ( 'Cannot perform map over unknown object type: ' + argy . getType ( resolvedPayload ) ) ; } currentExec . payload = resolvedPayload ; self . _structPointer -- ; // Force re-eval of this chain item now its been replace with its real (late-bound) type redo = true ; // }}} break ; case 'parallelArray' : case 'seriesArray' : self . runArray ( currentExec . payload . map ( function ( task ) { return function ( next ) { run ( self . _options . context , task , next ) ; } ; } ) , currentExec . type == 'parallelArray' ? self . _options . limit : 1 , function ( err ) { currentExec . completed = true ; self . _execute ( err ) ; } ) ; break ; case 'seriesObject' : case 'parallelObject' : self . runArray ( Object . keys ( currentExec . payload ) . map ( function ( key ) { return function ( next ) { run ( self . _options . context , currentExec . payload [ key ] , function ( err , value ) { self . _set ( key , value ) ; // Allocate returned value to context next ( err ) ; } ) ; } ; } ) , currentExec . type == 'parallelObject' ? self . _options . limit : 1 , function ( err ) { currentExec . completed = true ; self . _execute ( err ) ; } ) ; break ; case 'race' : var hasResult = false ; var hasError = false ; self . runArray ( currentExec . payload . map ( function ( task ) { return function ( next ) { run ( self . _options . context , task , function ( err , taskResult ) { if ( err ) { hasError = true next ( err , taskResult ) ; } else if ( ! hasResult && ! hasError && taskResult !== null && typeof taskResult !== 'undefined' ) { self . _set ( currentExec . id , taskResult ) ; // Allocate returned value to context hasResult = true ; next ( '!RACEDONE!' , taskResult ) ; // Force an error to stop the run() function } else { next ( err , taskResult ) ; } } ) ; } ; } ) , self . _options . limit , function ( err , val ) { currentExec . completed = true ; // Override race finish error as it was just to stop the race and not a real one if ( err == '!RACEDONE!' ) return self . _execute ( ) ; self . _execute ( err ) ; } ) ; break ; case 'deferArray' : currentExec . payload . forEach ( function ( task ) { self . _deferAdd ( null , task , currentExec ) ; } ) ; redo = true ; break ; case 'deferObject' : Object . keys ( currentExec . payload ) . forEach ( function ( key ) { self . _deferAdd ( key , currentExec . payload [ key ] , currentExec ) ; } ) ; redo = true ; break ; case 'await' : // Await can operate in two modes, either payload=[] (examine all) else (examine specific keys) if ( ! currentExec . payload . length ) { // Check all tasks are complete if ( self . _struct . slice ( 0 , self . _structPointer - 1 ) . every ( function ( stage ) { // Examine all items UP TO self one and check they are complete return stage . completed ; } ) ) { // All tasks up to self point are marked as completed if ( _deferTimeoutHandle ) clearTimeout ( _deferTimeoutHandle ) ; currentExec . completed = true ; redo = true ; } else { self . _structPointer -- ; // At least one task is outstanding - rewind to self stage so we repeat on next resolution } } else { // Check certain tasks are complete by key if ( currentExec . payload . every ( function ( dep ) { // Examine all named dependencies return ! ! self . _context [ dep ] ; } ) ) { // All are present if ( _deferTimeoutHandle ) clearTimeout ( _deferTimeoutHandle ) ; currentExec . completed = true ; redo = true ; } else { self . _structPointer -- ; // At least one dependency is outstanding - rewind to self stage so we repeat on next resolution } } break ; case 'limit' : // Set the options.limit variable self . _options . limit = currentExec . payload ; currentExec . completed = true ; redo = true ; // Move on to next action break ; case 'timeout' : // Set the timeout function or its timeout value if ( currentExec . delay === false ) { // Disable self . _options . timeout = false ; } else { // Set the callback if one was passed if ( currentExec . callback ) self . _options . timeoutHandler = currentExec . callback ; // Set the delay if one was passed if ( currentExec . delay ) self . _options . timeout = currentExec . delay ; } currentExec . completed = true ; redo = true ; // Move to next action break ; case 'context' : // Change the self._options.context object self . _options . context = currentExec . payload ? currentExec . payload : self . _context ; // Set context (if null use internal context) currentExec . completed = true ; redo = true ; // Move on to next action break ; case 'set' : // Set a hash of variables within context Object . keys ( currentExec . payload ) . forEach ( function ( key ) { self . _set ( key , currentExec . payload [ key ] ) ; } ) ; currentExec . completed = true ; redo = true ; // Move on to next action break ; case 'end' : // self should ALWAYS be the last item in the structure and indicates the final function call this . _finalize ( ) ; break ; default : if ( this . _plugins [ currentExec . type ] ) { // Is there a plugin that should manage this? this . _plugins [ currentExec . type ] . call ( this , currentExec ) ; } else { throw new Error ( 'Unknown async-chainable exec type: ' + currentExec . type ) ; } return ; } } while ( redo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "runArray () - dispatch an array of callbacks ( with a parallel run limit ) and run a callback when complete {{{ Internal function to run an array of functions ( usually in parallel ) Functions can be run in series by passing limit = 1 NOTE : Since this function is the central bottle - neck of the application code here is designed to run as efficiently as possible . This can make it rather messy and unpleasent to read in order to maximize thoughput . Series execution can be obtained by setting limit = 1 [CODESPLIT] function runArray ( tasks , limit , callback ) { var self = this ; var nextTaskOffset = 0 ; var running = 0 ; var err ; // Empty if ( ! tasks || ! tasks . length ) return callback ( ) ; // Timeout functionality {{{ var _timeoutTimer ; var resetTimeout = function ( setAgain ) { if ( _timeoutTimer ) clearTimeout ( _timeoutTimer ) ; if ( setAgain ) _timeoutTimer = self . _options . timeout ? setTimeout ( self . _options . timeoutHandler . bind ( self ) , self . _options . timeout ) : null ; } ; // }}} var taskFinish = function ( taskErr , taskResult ) { if ( taskErr ) err = taskErr ; -- running ; if ( err && ! running ) { resetTimeout ( false ) ; callback ( err ) ; } else if ( err ) { // Has an err - stop allocating until we empty resetTimeout ( false ) ; // Pass } else if ( ! running && nextTaskOffset > tasks . length - 1 ) { // Finished everything resetTimeout ( false ) ; callback ( err ) ; } else if ( nextTaskOffset < tasks . length ) { // Still more to alloc running ++ ; resetTimeout ( true ) ; setTimeout ( tasks [ nextTaskOffset ++ ] . bind ( this . _context , taskFinish ) ) ; } } ; var maxTasks = limit && limit <= tasks . length ? limit : tasks . length ; for ( var i = 0 ; i < maxTasks ; i ++ ) { running ++ ; setTimeout ( tasks [ i ] . bind ( this , taskFinish ) ) ; } resetTimeout ( true ) ; // Start initial timeout nextTaskOffset = maxTasks ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "}}} [CODESPLIT] function ( taskErr , taskResult ) { if ( taskErr ) err = taskErr ; -- running ; if ( err && ! running ) { resetTimeout ( false ) ; callback ( err ) ; } else if ( err ) { // Has an err - stop allocating until we empty resetTimeout ( false ) ; // Pass } else if ( ! running && nextTaskOffset > tasks . length - 1 ) { // Finished everything resetTimeout ( false ) ; callback ( err ) ; } else if ( nextTaskOffset < tasks . length ) { // Still more to alloc running ++ ; resetTimeout ( true ) ; setTimeout ( tasks [ nextTaskOffset ++ ] . bind ( this . _context , taskFinish ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run a single function promise return promise factory or any other combination - then a callback when finished Take a function reference and treat it as a callback style function If the function returns a promise this behaviour is transformed into a callback style function [CODESPLIT] function run ( context , fn , finish , args ) { // Argument mangling {{{ if ( typeof context == 'function' ) { // called as run(fn, finish, args); args = finish ; finish = fn ; fn = context ; context = this ; } // }}} if ( isPromise ( fn ) ) { // Given a promise that has already resolved? fn . then ( function ( value ) { finish . apply ( context , [ null , value ] ) ; } ) . catch ( function ( err ) { finish . call ( context , err || 'An error occured' ) ; } ) ; } else if ( hasCallback ( fn ) ) { // Callback w/ (err, result) pattern var result = fn . apply ( context , args ? [ finish ] . concat ( args ) : [ finish ] ) ; if ( isPromise ( result ) ) { result . then ( function ( value ) { // Remap result from (val) => (err, val) finish . apply ( context , [ null , value ] ) ; } ) . catch ( function ( err ) { finish . call ( context , err || 'An error occured' ) ; } ) ; } } else { // Maybe either a promise or sync function? var result ; try { result = fn . apply ( context , args || [ ] ) ; // Run the function and see what it gives us } catch ( e ) { finish . call ( context , e ) ; } if ( isPromise ( result ) ) { // Got back a promise - attach to the .then() function result . then ( function ( value ) { // Remap result from (val) => (err, val) finish . apply ( context , [ null , value ] ) ; } ) . catch ( function ( err ) { finish . call ( context , err || 'An error occured' ) ; } ) ; } else { // Didn't provide back a promise - assume it was a sync function finish . apply ( context , [ null , result ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal function to run a callback until it returns a falsy value [CODESPLIT] function runWhile ( iter , limit , callback ) { var index = 0 ; var hasExited = false ; var err ; var running = 0 ; if ( ! Number . isFinite ( limit ) ) limit = 10 ; var invoke = function ( ) { iter . call ( this . _context , function ( taskErr , taskResult ) { if ( taskErr ) err = taskErr ; if ( taskErr || ! taskResult ) hasExited = true ; -- running ; if ( err && ! running ) { callback ( err , res ) ; } else if ( running <= 0 && hasExited ) { callback ( err ) ; } else if ( ! hasExited ) { setTimeout ( invoke ) ; } } , index ++ ) ; } ; for ( var i = 0 ; i < limit ; i ++ ) { running ++ ; setTimeout ( invoke ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "}}} Reset all state variables and return the object into a pristine condition [CODESPLIT] function reset ( ) { this . _struct = [ ] ; this . _structPointer = 0 ; var reAttachContext = ( this . _options . context == this . _context ) ; // Reattach the context pointer after reset? this . _context = { _struct : this . _struct , _structPointer : this . _structPointer , _options : this . _options , _deferredRunning : this . _deferredRunning , hook : this . hook . bind ( this ) , fire : this . fire . bind ( this ) , } ; if ( reAttachContext ) this . _options . context = this . _context ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hooks {{{ Set up a hook [CODESPLIT] function hook ( ) { var self = this ; argy ( arguments ) . ifForm ( '' , function ( ) { } ) . ifForm ( 'string function' , function ( hook , callback ) { // Attach to one hook if ( ! self . _hooks [ hook ] ) self . _hooks [ hook ] = [ ] ; self . _hooks [ hook ] . push ( { cb : callback } ) ; } ) . ifForm ( 'string string function' , function ( hook , id , callback ) { // Attach a named hook if ( ! self . _hooks [ hook ] ) self . _hooks [ hook ] = [ ] ; self . _hooks [ hook ] . push ( { id : id , cb : callback } ) ; } ) . ifForm ( 'string array function' , function ( hook , prereqs , callback ) { // Attach to a hook with prerequisites if ( ! self . _hooks [ hook ] ) self . _hooks [ hook ] = [ ] ; self . _hooks [ hook ] . push ( { prereqs : prereqs , cb : callback } ) ; } ) . ifForm ( 'string string array function' , function ( hook , id , prereqs , callback ) { // Attach a named hook with prerequisites if ( ! self . _hooks [ hook ] ) self . _hooks [ hook ] = [ ] ; self . _hooks [ hook ] . push ( { id : id , prereqs : prereqs , cb : callback } ) ; } ) . ifForm ( 'array function' , function ( hooks , callback ) { // Attach to many hooks hooks . forEach ( function ( hook ) { if ( ! self . _hooks [ hook ] ) self . _hooks [ hook ] = [ ] ; self . _hooks [ hook ] . push ( { cb : callback } ) ; } ) ; } ) . ifFormElse ( function ( form ) { throw new Error ( 'Unknown call style for .on(): ' + form ) ; } ) ; return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take a callback style function and return a hybrid ( callback OR promise ) wrapper @param { function } fn The function to transform @param { function } [ finish ] The callback to optionally call when done @return { function } The hybrid function which runs as a callback but could accept promises [CODESPLIT] function hybrid ( fn , cb ) { if ( typeof cb === 'function' ) { // Already in callback style - wrap the function so that cb gets called when it completes return function ( ) { var args = Array . prototype . slice . call ( arguments , 0 ) ; fn . apply ( this , [ cb ] . concat ( args ) ) ; } ; } else { // Wrap the function in a promise return function ( ) { var args = Array . prototype . slice . call ( arguments , 0 ) ; return new Promise ( function ( resolve , reject ) { fn . apply ( this , [ function ( err , res ) { if ( err ) { reject ( err ) ; } else { resolve ( res ) ; } } ] . concat ( args ) ) ; } ) ; } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the first tag with a name = name [CODESPLIT] function tag ( name ) { if ( ! this . comment || ! this . comment . tags ) { return null ; } for ( var i = 0 ; i < this . comment . tags . length ; i ++ ) { var tagObj = this . comment . tags [ i ] ; if ( tagObj . name === name ) { return tagObj . value ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A fixed - length storage mechanism for a value ( ideally a number ) with some statistics methods . Expires oldest values to Input is not type checked but non - numeric input will be considered NULL WRT the statistical methods . [CODESPLIT] function FixedValueHistory ( maxLength , initial ) { if ( ! ( this instanceof FixedValueHistory ) ) return new FixedValueHistory ( maxLength , initial ) if ( ! isNumber ( maxLength ) || maxLength == 0 ) { throw new Error ( \"maxLength must be a positive number.\" ) } this . maxLength = Math . floor ( + maxLength ) if ( initial != null ) { this . push ( initial ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor function takes the following paramters : [CODESPLIT] function ( path , maxAge , cronTime , options ) { this . job = null ; this . path = path ; this . maxAge = maxAge ; this . cronTime = cronTime ; this . options = util . _extend ( { } , defaultOptions ) ; if ( typeof options === 'object' && options !== null ) { this . options = util . _extend ( this . options , options ) ; } if ( this . options . start === true ) { this . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper functions Checks blackList - and whitList - regex against the given file name and returns if this file can be deleted . [CODESPLIT] function checkPattern ( file , blackList , whiteList ) { if ( util . isRegExp ( blackList ) && blackList . test ( file ) ) { return false ; } if ( util . isRegExp ( whiteList ) ) { if ( whiteList . test ( file ) ) { return true ; } return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * internal helper functions [CODESPLIT] function createGetterSetter ( propName ) { function gs ( element , value ) { // if we have a value update if ( typeof value != 'undefined' ) { element . style [ propName ] = value ; } return window . getComputedStyle ( element ) [ propName ] ; } // attach the property name to the getter and setter gs . property = propName ; return gs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a new Seven object . Optionally pass a SevenConfig object to set properties . Each property of the SevenConfig object is optional . If the passed in config contains bad values an exception will be thrown . [CODESPLIT] function Seven ( _a ) { var _b = _a === void 0 ? { } : _a , height = _b . height , width = _b . width , _c = _b . angle , angle = _c === void 0 ? 10 : _c , _d = _b . ratioLtoW , ratioLtoW = _d === void 0 ? 4 : _d , _e = _b . ratioLtoS , ratioLtoS = _e === void 0 ? 32 : _e , _f = _b . digit , digit = _f === void 0 ? Digit . BLANK : _f ; /** The cononical points for a horizontal segment for the given configuration. */ this . _horizontalSegmentGeometry = [ { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } ] ; /** The cononical points for a vertical segment for the given configuration. */ this . _verticalSegmentGeometry = [ { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } , { x : 0 , y : 0 } ] ; /** The x and y shifts that must be applied to each segment. */ this . _translations = [ { x : 0 , y : 0 , a : this . _horizontalSegmentGeometry } , { x : 0 , y : 0 , a : this . _verticalSegmentGeometry } , { x : 0 , y : 0 , a : this . _verticalSegmentGeometry } , { x : 0 , y : 0 , a : this . _horizontalSegmentGeometry } , { x : 0 , y : 0 , a : this . _verticalSegmentGeometry } , { x : 0 , y : 0 , a : this . _verticalSegmentGeometry } , { x : 0 , y : 0 , a : this . _horizontalSegmentGeometry } ] ; /** The segments, A-G of the digit. */ this . segments = [ new Segment ( ) , new Segment ( ) , new Segment ( ) , new Segment ( ) , new Segment ( ) , new Segment ( ) , new Segment ( ) ] ; this . _angleDegree = angle ; this . digit = digit ; this . _ratioLtoW = ratioLtoW ; this . _ratioLtoS = ratioLtoS ; this . _height = this . _width = 100 ; //initialize so checkConfig passes, and for default case this . _isHeightFixed = true ; if ( height !== undefined ) { this . _height = height ; } else if ( width !== undefined ) { this . _width = width ; this . _isHeightFixed = false ; } //else - neither specified, default to height=100 this . _positionSegments ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new FriendsOfFriends Object with or without new javascript // mongoose is required var mongoose = require ( mongoose ) ; [CODESPLIT] function FriendsOfFriends ( mongoose , options ) { debug ( 'mongoose' , mongoose ) ; debug ( 'options' , options ) ; if ( ! ( this instanceof FriendsOfFriends ) ) { return new FriendsOfFriends ( mongoose , options ) ; } var friendship = require ( './friendship' ) , plugin = require ( './plugin' ) ; var defaults = { personModelName : 'Person' , friendshipModelName : 'Friendship' , friendshipCollectionName : undefined , } ; /**\n     * The options defined for the module instance\n     * @member      {Object} options\n     * @memberOf    FriendsOfFriends\n     * @property    {String} personModelName            - The modelName of the Person Schema. Default: `'Person'`\n     * @property    {String} friendshipModelName        - The name to call the model to be compiled from the Friendship Schema. Default: `'Friendship'`\n     * @property    {String|undefined} friendshipCollectionName   - The name to use for the Friendship Collection. Default: `undefined`.\n     */ this . options = utils . extend ( defaults , options ) ; /**\n     * The Friendship model \n     * @member      {Model}     friendship\n     * @memberOf    FriendsOfFriends\n     * @see         {@link FriendshipModel}\n     * @see         [moongoose models]{@link http://mongoosejs.com/docs/models.html}\n     */ this . Friendship = friendship ( mongoose , this . options ) ; /**\n     * Adds friends-of-friends functionality to an existing Schema\n     * @function    FriendsOfFriends.plugin\n     * @param       {Schema} schema     - The mongoose Schema that gets plugged\n     * @param       {Object} options    - Options passed to the plugin\n     * @see         {@link AccountModel}\n     */ this . plugin = plugin ( mongoose ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * PUBLIC [CODESPLIT] function totalRx ( opts ) { if ( opts ) { opts . iface = opts . iface || 'lo' ; opts . units = opts . units || 'bytes' ; } else { opts = { iface : 'lo' , units : 'bytes' , } ; } var total = parseInt ( _parseProcNetDev ( ) [ opts . iface ] . bytes . receive ) ; var converted = _bytesTo ( total , opts . units ) ; return converted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NOTE : borrowed / modifed from https : // github . com / soldair / node - procfs - stats / blob / feca2a940805b31f9e7d5c0bd07c4e3f8d3d5303 / index . js#L343 TODO : more cleaning rename the one char variables to something more expressive [CODESPLIT] function _parseProcNetDev ( ) { var buf = fs . readFileSync ( '/proc/net/dev' ) ; var lines = buf . toString ( ) . trim ( ) . split ( '\\n' ) ; var sections = lines . shift ( ) . split ( '|' ) ; var columns = lines . shift ( ) . trim ( ) . split ( '|' ) ; var s ; var l ; var c ; var p = 0 ; var map = { } ; var keys = [ ] ; for ( var i = 0 ; i < sections . length ; ++ i ) { s = sections [ i ] . trim ( ) ; l = sections [ i ] . length ; c = columns [ i ] . trim ( ) . split ( / \\s+ / g ) ; while ( c . length ) { map [ keys . length ] = s ; keys . push ( c . shift ( ) ) ; } p += s . length + 1 ; } var retObj = { } ; lines . forEach ( function ( l ) { l = l . trim ( ) . split ( / \\s+ / g ) ; var o = { } ; var iface ; for ( var i = 0 ; i < l . length ; ++ i ) { var s = map [ i ] ; //case for the Interface if ( s . indexOf ( '-' ) === s . length - 1 ) { iface = l [ i ] . substr ( 0 , l [ i ] . length - 1 ) ; //case for everything else } else { if ( ! o [ keys [ i ] ] ) { o [ keys [ i ] . toLowerCase ( ) ] = { } ; } o [ keys [ i ] . toLowerCase ( ) ] [ s . toLowerCase ( ) ] = l [ i ] ; } } retObj [ iface ] = o ; } ) ; return retObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "after dialog close wait for change [CODESPLIT] function onChange ( event ) { try { if ( remove ( ) ) { return ; } resolve ( Array . from ( input . files ) ) ; // actually got file(s) } catch ( error ) { reject ( error ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "there are no properties on a RemoveObserver every object that went as ref through this function can be used as this in any of the RemoveObserver methods [CODESPLIT] function RemoveObserver_init ( ref , node ) { let self = Self . get ( node ) ; if ( ! self ) { self = new RemoveObserverPrivate ( node ) ; Self . set ( node , self ) ; } Self . set ( ref , self ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "jsdoc [CODESPLIT] function ( done ) { async . series ( [ function ( next ) { var child = child_process . exec ( 'jsdoc -c jsdoc.conf.json lib/' ) ; child . stdout . on ( 'data' , function ( data ) { console . log ( data ) ; } ) ; child . stderr . on ( 'data' , function ( data ) { console . log ( 'stderr: ' + data ) ; var err = new Error ( 'error spawning: ' , cmd ) ; console . log ( err ) ; next ( err ) ; } ) ; child . on ( 'close' , function ( code ) { if ( code === 0 ) { next ( ) ; } else { next ( new Error ( 'error spawning:' , cmd ) ) ; } } ) ; } , function ( next ) { var cmd = util . format ( 'cp -r doc/%s/%s/* doc/' , package . name , package . version ) ; var child = child_process . exec ( cmd ) ; child . stdout . on ( 'data' , function ( data ) { console . log ( data ) ; } ) ; child . stderr . on ( 'data' , function ( data ) { console . log ( 'stderr: ' + data ) ; var err = new Error ( 'error spawning: ' , cmd ) ; console . log ( err ) ; next ( err ) ; } ) ; child . on ( 'close' , function ( code ) { if ( code === 0 ) { next ( ) ; } else { next ( new Error ( 'error spawning jsdoc' ) ) ; } } ) ; } , function ( next ) { var cmd = 'rm -rf doc/' + package . name + '/' ; var child = child_process . exec ( cmd ) ; child . stdout . on ( 'data' , function ( data ) { console . log ( data ) ; } ) ; child . stderr . on ( 'data' , function ( data ) { console . log ( 'stderr: ' + data ) ; var err = new Error ( 'error spawning: ' , cmd ) ; console . log ( err ) ; next ( err ) ; } ) ; child . on ( 'close' , function ( code ) { console . log ( 'child process exited with code ' + code ) ; if ( code === 0 ) { next ( ) ; } else { next ( new Error ( 'error spawning jsdoc' ) ) ; } } ) ; } ] , function ( err , results ) { if ( err ) done ( err ) ; else done ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "jsdoc2md [CODESPLIT] function ( done ) { console . log ( 'generating markdown docs...' ) ; var tasks = { } , taskNames = [ 'index' , 'friendship' , 'plugin' , 'relationships' ] ; // go through each task name taskNames . forEach ( function ( name ) { // add this task function to the object tasks [ name ] = function ( done ) { var sourceFilename = 'lib/' + name + '.js' ; var targetFilename = 'doc/' + name + '.md' ; console . log ( sourceFilename + ' -> ' + targetFilename ) ; var reader = fs . createReadStream ( sourceFilename ) ; // create a write stream to the new markdown file whose name is the task name var writer = fs . createWriteStream ( targetFilename , { flags : 'w+' } ) . on ( 'finish' , done ) ; // now pipe each file to jsdoc2md then pipe its output to  // the write stream reader . pipe ( jsdoc2md ( ) ) . pipe ( writer ) ; } ; } ) ; // now run our named tasks in parallel with async async . parallel ( tasks , function ( err , results ) { if ( err ) done ( err ) ; else { console . log ( 'finished generating markdown docs.' ) ; done ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds and parses the property chains in an expression . [CODESPLIT] function parsePropertyChains ( expr ) { var parsedExpr = '' , chain ; // allow recursion (e.g. into function args) by resetting propertyRegex // This is more efficient than creating a new regex for each chain, I assume var prevCurrentIndex = currentIndex ; var prevLastIndex = propertyRegex . lastIndex ; currentIndex = 0 ; propertyRegex . lastIndex = 0 ; while ( ( chain = nextChain ( expr ) ) !== false ) { parsedExpr += chain ; } // Reset indexes currentIndex = prevCurrentIndex ; propertyRegex . lastIndex = prevLastIndex ; return parsedExpr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles a function to be called in its correct scope Finds the end of the function and processes the arguments [CODESPLIT] function parseFunction ( link , index , expr ) { var call = getFunctionCall ( expr ) ; // Always call functions in the scope of the object they're a member of if ( index === 0 ) { link = addThisOrGlobal ( link ) ; } else { link = '_ref' + currentReference + link ; } var calledLink = link + '(~~insideParens~~)' ; link = 'typeof ' + link + ' !== \\'function\\' ? void 0 : ' + calledLink ; var insideParens = call . slice ( 1 , - 1 ) ; if ( expr . charAt ( propertyRegex . lastIndex ) === '.' ) { currentReference = ++ referenceCount ; var ref = '_ref' + currentReference ; link = '(' + ref + ' = (' + link + ')) == null ? void 0 : ' ; } var ref = currentReference ; link = link . replace ( '~~insideParens~~' , parsePropertyChains ( insideParens ) ) ; currentReference = ref ; return link ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles a bracketed expression to be parsed [CODESPLIT] function parseBrackets ( link , index , expr ) { var call = getFunctionCall ( expr ) ; var insideBrackets = call . slice ( 1 , - 1 ) ; var evaledLink = parsePart ( link , index ) ; index += 1 ; link = '[~~insideBrackets~~]' ; if ( expr . charAt ( propertyRegex . lastIndex ) === '.' ) { link = parsePart ( link , index ) ; } else { link = '_ref' + currentReference + link ; } link = evaledLink + link ; var ref = currentReference ; link = link . replace ( '~~insideBrackets~~' , parsePropertyChains ( insideBrackets ) ) ; currentReference = ref ; return link ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the call part of a function ( e . g . test ( 123 ) would return ( 123 ) ) [CODESPLIT] function getFunctionCall ( expr ) { var startIndex = propertyRegex . lastIndex ; var open = expr . charAt ( startIndex - 1 ) ; var close = parens [ open ] ; var endIndex = startIndex - 1 ; var parenCount = 1 ; while ( endIndex ++ < expr . length ) { var ch = expr . charAt ( endIndex ) ; if ( ch === open ) parenCount ++ ; else if ( ch === close ) parenCount -- ; if ( parenCount === 0 ) break ; } currentIndex = propertyRegex . lastIndex = endIndex + 1 ; return open + expr . slice ( startIndex , endIndex ) + close ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepends reference variable definitions [CODESPLIT] function addReferences ( expr ) { if ( referenceCount ) { var refs = [ ] ; for ( var i = 1 ; i <= referenceCount ; i ++ ) { refs . push ( '_ref' + i ) ; } expr = 'var ' + refs . join ( ', ' ) + ';\\n' + expr ; } return expr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run once and lastest one [CODESPLIT] function ( fn ) { var pending var hasNext function next ( ) { setTimeout ( function ( ) { if ( pending === false ) return pending = false if ( hasNext ) { hasNext = false fn ( next ) } } , 50 ) // call after gulp ending handler done } return function ( ) { if ( pending ) return ( hasNext = true ) pending = true fn ( next ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Minimal assert function [CODESPLIT] function assert ( t , m ) { if ( ! t ) { var err = new AssertionError ( m ) if ( Error . captureStackTrace ) Error . captureStackTrace ( err , assert ) throw err } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a custom bind function to bind arguments to a function without binding the context [CODESPLIT] function bindArguments ( func ) { function binder ( ) { return func . apply ( this , args . concat ( slice . call ( arguments ) ) ) ; } var args = slice . call ( arguments , 1 ) ; return binder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "function to convert pattern ID to route ID [CODESPLIT] function getRouteIndexFromPatternId ( pattern : string | number ) : number { const pat = transitiveNetwork . patterns . find ( p => p . pattern_id === String ( pattern ) ) if ( ! pat ) return - 1 return transitiveNetwork . routes . findIndex ( r => r . route_id === pat . route_id ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the most common paths [CODESPLIT] function getCommonPaths ( { getRouteIndexFromPatternId , log , origin , paths } : { getRouteIndexFromPatternId : ( string | number ) => number , log : Function , origin : Origin , paths : Array < PathDescriptor > } ) : Array < StopPatternStops > { paths . sort ( byStopIdAndPathIndex ) const pathCounts = paths . reduce ( countCommonPaths , [ ] ) pathCounts . sort ( byCount ) log ( ` ${ pathCounts . length } ` ) if ( pathCounts . length > MAX_TRANSITIVE_PATHS ) { log ( ` ${ pathCounts . length - MAX_TRANSITIVE_PATHS } ${ pathCounts [ MAX_TRANSITIVE_PATHS ] . count } ${ paths . length } ` ) } let allStopPatternStopSets = pathCounts . slice ( 0 , MAX_TRANSITIVE_PATHS ) . map ( ( p ) => p . path ) . filter ( uniquePathIds ) // uniquify the paths . map ( ( p ) => getStopPatternStopSets ( { log , pathDescriptor : p , origin } ) ) const inPathCount = allStopPatternStopSets . length // Sort paths by the sequence of routes they use, and choose an example, // eliminating the multiple-board/transfer-stops problem allStopPatternStopSets . sort ( ( p1 , p2 ) => { if ( p1 . length < p2 . length ) return - 1 else if ( p1 . length > p2 . length ) return 1 else { for ( let i = 0 ; i < p1 . length ; i ++ ) { const r1 = getRouteIndexFromPatternId ( p1 [ i ] [ 1 ] ) const r2 = getRouteIndexFromPatternId ( p2 [ i ] [ 1 ] ) if ( r1 < r2 ) return - 1 if ( r1 > r2 ) return 1 } // identical patterns return 0 } } ) allStopPatternStopSets = allStopPatternStopSets . filter ( ( p , i , a ) => { if ( i === 0 ) return true const prev = a [ i - 1 ] if ( p . length !== prev . length ) return true for ( let s = 0 ; s < p . length ; s ++ ) { const r1 = getRouteIndexFromPatternId ( p [ s ] [ 1 ] ) const r2 = getRouteIndexFromPatternId ( prev [ s ] [ 1 ] ) if ( r1 !== r2 ) { return true } } return false } ) const pathCountAfterMultiTransfer = allStopPatternStopSets . length // eliminate longer paths if there is a shorter path that is a subset // (eliminate the short access/egress/transfer leg problem) allStopPatternStopSets = allStopPatternStopSets . filter ( ( path , i , rest ) => { for ( const otherPath of rest ) { // longer paths cannot be subsets. Also don't evaluate the same path. if ( otherPath . length >= path . length ) continue let otherPathIsSubset = true const routes = path . map ( seg => getRouteIndexFromPatternId ( seg [ 1 ] ) ) for ( const seg of otherPath ) { if ( routes . indexOf ( getRouteIndexFromPatternId ( seg [ 1 ] ) ) === - 1 ) { otherPathIsSubset = false break } } if ( otherPathIsSubset ) { return false } } return true } ) log ( ` ${ inPathCount } ${ pathCountAfterMultiTransfer } ${ allStopPatternStopSets . length } ` ) return allStopPatternStopSets }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bundle similar journeys in transitive data together . Works by computing a score for each segment based on where the endpoints are relative to each other . It might also make sense to use a metric based on speed so that a very slow bus isn t bundled with a fast train but we don t currently do this . [CODESPLIT] function clusterJourneys ( { journeys , log , patterns , stops } : { journeys : Array < Journey > , log : Function , patterns : Array < Pattern > , stops : Array < Stop > } ) { // perform hierarchical clustering on journeys // see e.g. James et al., _An Introduction to Statistical Learning, with Applications in R_. New York: Springer, 2013, pg. 395. // convert to arrays const clusters = journeys . map ( ( j ) => [ j ] ) const inputSize = journeys . length // prevent infinite loop, makes sense only to loop until there's just one cluster left while ( clusters . length > 1 ) { // find the minimum dissimilarity let minDis = Infinity let minI = 0 let minJ = 0 for ( let i = 1 ; i < clusters . length ; i ++ ) { for ( let j = 0 ; j < i ; j ++ ) { const d = getClusterDissimilarity ( clusters [ i ] , clusters [ j ] , { patterns , stops } ) if ( d < minDis ) { minDis = d minI = i minJ = j } } } log ( ` ${ minDis } ` ) if ( minDis > MAX_DISSIMILARITY ) break // cluster the least dissimilar clusters clusters [ minI ] = clusters [ minI ] . concat ( clusters [ minJ ] ) clusters . splice ( minJ , 1 ) // remove clusters[j] } log ( ` ${ inputSize } ${ clusters . length } ` ) // merge journeys together return clusters . map ( ( c ) => { return c . reduce ( ( j1 , j2 ) => { for ( let i = 0 ; i < j1 . segments . length ; i ++ ) { if ( j1 . segments [ i ] . type !== 'TRANSIT' ) continue // convert to pattern groups if ( ! j1 . segments [ i ] . patterns ) { j1 . segments [ i ] . patterns = [ { ... j1 . segments [ i ] } ] j1 . segments [ i ] . pattern_id = j1 . segments [ i ] . from_stop_index = j1 . segments [ i ] . to_stop_index = undefined } // don't modify from and to indices, Transitive will use the stops from the first pattern // TODO replace with \"places\" (e.g. \"Farragut Square Area\") j1 . segments [ i ] . patterns . push ( { ... j2 . segments [ i ] } ) } return j1 } ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the dissimilarity between two clusters using complete linkages ( see James et al . _An Introduction to Statistical Learning with Applications in R_ . New York : Springer 2013 pg . 395 . ) [CODESPLIT] function getClusterDissimilarity ( c1 : Array < Journey > , c2 : Array < Journey > , { patterns , stops } : { patterns : Array < Pattern > , stops : Array < Stop > } ) : number { let dissimilarity = 0 for ( const j1 of c1 ) { for ( const j2 of c2 ) { // if they are not the same length, don't cluster them if ( j1 . segments . length !== j2 . segments . length ) return Infinity // otherwise compute maximum dissimilarity of stops at either start or end for ( let segment = 0 ; segment < j1 . segments . length ; segment ++ ) { const s1 = j1 . segments [ segment ] const s2 = j2 . segments [ segment ] // if one has a walk segment where the other has a transit segment these // are not comparable if ( s1 . type !== s2 . type ) return Infinity // Only cluster  on the stop positions which we get from transit segments if ( s1 . type !== 'WALK' ) { dissimilarity = Math . max ( dissimilarity , segmentDissimilarity ( s1 , s2 , { patterns , stops } ) ) // no point in continuing, these won't be merged if ( dissimilarity > MAX_DISSIMILARITY ) return Infinity } } } } return dissimilarity }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return the dissimilarity between two individual transit segments ( each with only a single pattern not yet merged ) [CODESPLIT] function segmentDissimilarity ( s1 : Segment , s2 : Segment , { patterns , stops } : { patterns : Array < Pattern > , stops : Array < Stop > } ) : number { const pat1 = patterns . find ( ( p ) => p . pattern_id === s1 . pattern_id ) const pat2 = patterns . find ( ( p ) => p . pattern_id === s2 . pattern_id ) if ( ! pat1 || ! pat2 ) return Infinity const s1f = s1 . from_stop_index const s1t = s1 . to_stop_index const s2f = s2 . from_stop_index const s2t = s2 . to_stop_index if ( s1f == null || s1t == null || s2f == null || s2t == null ) return Infinity function findStop ( id : string ) : ? Stop { return stops . find ( ( stop ) => stop . stop_id === id ) } const from1 = findStop ( pat1 . stops [ s1f ] . stop_id ) const to1 = findStop ( pat1 . stops [ s1t ] . stop_id ) const from2 = findStop ( pat2 . stops [ s2f ] . stop_id ) const to2 = findStop ( pat2 . stops [ s2t ] . stop_id ) if ( ! from1 || ! from2 || ! to1 || ! to2 ) return Infinity const d1 = stopDistance ( from1 , from2 ) const d2 = stopDistance ( to1 , to2 ) return Math . max ( d1 , d2 ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return the Ersatz ( squared ) distance between two stops in undefined units [CODESPLIT] function stopDistance ( s1 : Stop , s2 : Stop ) : number { const cosLat = Math . cos ( s1 . stop_lat * Math . PI / 180 ) return Math . pow ( s1 . stop_lat - s2 . stop_lat , 2 ) + Math . pow ( s1 . stop_lon * cosLat - s2 . stop_lon * cosLat , 2 ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Produces an object with the opener and closer exception values [CODESPLIT] function getExceptions ( ) { const openers = [ ] ; const closers = [ ] ; if ( options . braceException ) { openers . push ( '{' ) ; closers . push ( '}' ) ; } if ( options . bracketException ) { openers . push ( '[' ) ; closers . push ( ']' ) ; } if ( options . parenException ) { openers . push ( '(' ) ; closers . push ( ')' ) ; } if ( options . empty ) { openers . push ( ')' ) ; closers . push ( '(' ) ; } return { openers , closers } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if an opener paren should have a missing space after it [CODESPLIT] function shouldOpenerHaveSpace ( left , right ) { if ( sourceCode . isSpaceBetweenTokens ( left , right ) ) { return false ; } if ( ALWAYS ) { if ( astUtils . isClosingParenToken ( right ) ) { return false ; } return ! isOpenerException ( right ) ; } return isOpenerException ( right ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if an closer paren should have a missing space after it [CODESPLIT] function shouldCloserHaveSpace ( left , right ) { if ( astUtils . isOpeningParenToken ( left ) ) { return false ; } if ( sourceCode . isSpaceBetweenTokens ( left , right ) ) { return false ; } if ( ALWAYS ) { return ! isCloserException ( left ) ; } return isCloserException ( left ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if an opener paren should not have an existing space after it [CODESPLIT] function shouldOpenerRejectSpace ( left , right ) { if ( right . type === 'Line' ) { return false ; } if ( ! astUtils . isTokenOnSameLine ( left , right ) ) { return false ; } if ( ! sourceCode . isSpaceBetweenTokens ( left , right ) ) { return false ; } if ( ALWAYS ) { return isOpenerException ( right ) ; } return ! isOpenerException ( right ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if an closer paren should not have an existing space after it [CODESPLIT] function shouldCloserRejectSpace ( left , right ) { if ( astUtils . isOpeningParenToken ( left ) ) { return false ; } if ( ! astUtils . isTokenOnSameLine ( left , right ) ) { return false ; } if ( ! sourceCode . isSpaceBetweenTokens ( left , right ) ) { return false ; } if ( ALWAYS ) { return isCloserException ( left ) ; } return ! isCloserException ( left ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set a value as configurable and non - enumerable [CODESPLIT] function defineConfigurable ( obj , key , val ) { Object . defineProperty ( obj , key , { configurable : true , enumerable : false , writable : true , value : val } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "7 . 1 . 4 ToInteger [CODESPLIT] function ToInteger ( argument ) { var number = + argument ; if ( number !== number ) { return 0 ; } if ( number === 0 || number === Infinity || number === - Infinity ) { return number ; } return ( number >= 0 ? 1 : - 1 ) * Math . floor ( Math . abs ( number ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "7 . 1 . 15 ToLength [CODESPLIT] function ToLength ( argument ) { var len = ToInteger ( argument ) ; return len <= 0 ? 0 : Math . min ( len , Math . pow ( 2 , 53 ) - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "7 . 2 . 3 SameValue ( x y ) [CODESPLIT] function SameValue ( x , y ) { if ( typeof x !== typeof y ) { return false ; } if ( Type ( x ) === 'undefined' ) { return true ; } if ( Type ( x ) === 'number' ) { if ( x !== x && y !== y ) { return true ; } if ( x === 0 ) { return 1 / x === 1 / y ; } } return x === y ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "7 . 4 . 2 IteratorNext ( iterator value ) [CODESPLIT] function IteratorNext ( iterator , value ) { var result = iterator . next ( value ) ; if ( Type ( result ) !== 'object' ) { throw TypeError ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "7 . 4 . 5 IteratorStep ( iterator ) [CODESPLIT] function IteratorStep ( iterator ) { var result = IteratorNext ( iterator ) ; return IteratorComplete ( result ) === true ? false : result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "7 . 4 . 6 CreateIterResultObject ( value done ) [CODESPLIT] function CreateIterResultObject ( value , done ) { if ( Type ( done ) !== 'boolean' ) { throw TypeError ( ) ; } return { value : value , done : done } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "8 . 4 . 1 EnqueueTask ( queueName task arguments ) not a real shim but good enough [CODESPLIT] function EnqueueTask ( task , args ) { if ( typeof setImmediate === 'function' ) { setImmediate ( function ( ) { task . apply ( null , args ) ; } ) ; } else { setTimeout ( function ( ) { task . apply ( null , args ) ; } , 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "22 . 1 . 5 . 1 CreateArrayIterator Abstract Operation [CODESPLIT] function CreateArrayIterator ( array , kind ) { var O = ToObject ( array ) , iterator = Object . create ( ArrayIteratorPrototype ) ; defineInternal ( iterator , '[[IteratedObject]]' , O ) ; defineInternal ( iterator , '[[ArrayIteratorNextIndex]]' , 0 ) ; defineInternal ( iterator , '[[ArrayIteratorKind]]' , kind ) ; return iterator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "25 . 4 . 1 . 1 . 1 IfAbruptRejectPromise ( value capability ) [CODESPLIT] function IfAbruptRejectPromise ( value , capability ) { try { capability [ '[[Reject]]' ] . call ( undefined , [ value ] ) ; } catch ( e ) { return e ; } return capability ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "25 . 4 . 1 . 4 . 1 Promise Resolve Functions [CODESPLIT] function PromiseResolve ( ) { return function F ( resolution ) { var promise = F [ '[[Promise]]' ] , reactions ; if ( Type ( promise ) !== 'object' ) { throw TypeError ( ) ; } if ( promise [ '[[PromiseStatus]]' ] !== 'unresolved' ) { return undefined ; } reactions = promise [ '[[PromiseResolveReactions]]' ] ; defineInternal ( promise , '[[PromiseResult]]' , resolution ) ; defineInternal ( promise , '[[PromiseResolveReactions]]' , undefined ) ; defineInternal ( promise , '[[PromiseRejectReactions]]' , undefined ) ; defineInternal ( promise , '[[PromiseStatus]]' , 'has-resolution' ) ; return TriggerPromiseReactions ( reactions , resolution ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "25 . 4 . 1 . 5 NewPromiseCapability ( C ) [CODESPLIT] function NewPromiseCapability ( C ) { var promise ; if ( ! IsConstructor ( C ) ) { throw TypeError ( ) ; } try { promise = Object . create ( C . prototype ) ; } catch ( e ) { return e ; } return CreatePromiseCapabilityRecord ( promise , C ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "25 . 4 . 1 . 5 . 1 CreatePromiseCapabilityRecord ( promise constructor ) [CODESPLIT] function CreatePromiseCapabilityRecord ( promise , constructor ) { var promiseCapability = { } , executor , constructorResult ; defineInternal ( promiseCapability , '[[Promise]]' , promise ) ; defineInternal ( promiseCapability , '[[Resolve]]' , undefined ) ; defineInternal ( promiseCapability , '[[Reject]]' , undefined ) ; executor = new GetCapabilitiesExecutor ( ) ; defineInternal ( executor , '[[Capability]]' , promiseCapability ) ; try { constructorResult = constructor . call ( promise , executor ) ; } catch ( e ) { return e ; } if ( ! IsCallable ( promiseCapability [ '[[Resolve]]' ] ) ) { throw TypeError ( ) ; } if ( ! IsCallable ( promiseCapability [ '[[Reject]]' ] ) ) { throw TypeError ( ) ; } if ( typeof constructorResult === 'object' && ! SameValue ( promise , constructorResult ) ) { throw TypeError ( ) ; } return promiseCapability ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "25 . 4 . 1 . 5 . 2 GetCapabilitiesExecutor Functions [CODESPLIT] function GetCapabilitiesExecutor ( ) { return function F ( resolve , reject ) { var promiseCapability = F [ '[[Capability]]' ] ; if ( Type ( promiseCapability [ '[[Resolve]]' ] ) !== 'undefined' ) { throw TypeError ( ) ; } if ( Type ( promiseCapability [ '[[Reject]]' ] ) !== 'undefined' ) { throw TypeError ( ) ; } defineInternal ( promiseCapability , '[[Resolve]]' , resolve ) ; defineInternal ( promiseCapability , '[[Reject]]' , reject ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "25 . 4 . 1 . 7 TriggerPromiseReactions ( reactions argument ) [CODESPLIT] function TriggerPromiseReactions ( reactions , argument ) { reactions . forEach ( function ( reaction ) { EnqueueTask ( PromiseReactionTask , [ reaction , argument ] ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "25 . 4 . 1 . 8 UpdatePromiseFromPotentialThenable ( x promiseCapability ) [CODESPLIT] function UpdatePromiseFromPotentialThenable ( x , promiseCapability ) { var then , rejectResult , thenCallResult ; if ( Type ( x ) !== 'object' ) { return 'not a thenable' ; } try { then = x . then ; } catch ( e ) { rejectResult = promiseCapability [ '[[Reject]]' ] . call ( undefined , e ) ; return null ; } if ( ! IsCallable ( then ) ) { return 'not a thenable' ; } try { thenCallResult = then . call ( x , promiseCapability [ '[[Resolve]]' ] , promiseCapability [ '[[Reject]]' ] ) ; } catch ( e ) { rejectResult = promiseCapability [ '[[Reject]]' ] . call ( undefined , e ) ; return null ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "25 . 4 . 2 . 1 PromiseReactionTask ( reaction argument ) [CODESPLIT] function PromiseReactionTask ( reaction , argument ) { var promiseCapability = reaction [ '[[Capabilities]]' ] , handler = reaction [ '[[Handler]]' ] , handlerResult , selfResolutionError , updateResult ; try { handlerResult = handler . call ( undefined , argument ) ; } catch ( e ) { return promiseCapability [ '[[Reject]]' ] . call ( undefined , e ) ; } if ( SameValue ( handlerResult , promiseCapability [ '[[Promise]]' ] ) ) { selfResolutionError = TypeError ( ) ; return promiseCapability [ '[[Reject]]' ] . call ( undefined , selfResolutionError ) ; } updateResult = UpdatePromiseFromPotentialThenable ( handlerResult , promiseCapability ) ; if ( updateResult === 'not a thenable' ) { return promiseCapability [ '[[Resolve]]' ] . call ( undefined , handlerResult ) ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "25 . 4 . 3 . 1 Promise ( executor ) [CODESPLIT] function Promise ( executor ) { var promise = this ; if ( ! IsCallable ( executor ) ) { throw TypeError ( 'Invalid executor' ) ; } if ( Type ( promise ) !== 'object' ) { throw TypeError ( 'Invalid promise' ) ; } if ( Type ( promise [ '[[PromiseStatus]]' ] ) !== 'undefined' ) { throw TypeError ( ) ; } defineInternal ( this , '[[PromiseConstructor]]' , Promise ) ; return InitializePromise ( promise , executor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "25 . 4 . 3 . 1 . 1 InitializePromise ( promise executor ) [CODESPLIT] function InitializePromise ( promise , executor ) { var resolve , reject , completion , status ; if ( Type ( promise [ '[[PromiseStatus]]' ] ) !== 'undefined' ) { throw TypeError ( ) ; } if ( ! IsCallable ( executor ) ) { throw TypeError ( ) ; } defineInternal ( promise , '[[PromiseStatus]]' , 'unresolved' ) ; defineInternal ( promise , '[[PromiseResolveReactions]]' , [ ] ) ; defineInternal ( promise , '[[PromiseRejectReactions]]' , [ ] ) ; resolve = CreateResolveFunction ( promise ) ; reject = CreateRejectFunction ( promise ) ; try { completion = executor . call ( undefined , resolve , reject ) ; } catch ( e ) { try { status = reject . call ( undefined , e ) ; } catch ( e ) { return e ; } } return promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "25 . 4 . 5 . 3 . 2 PromiseResolutionHandlerFunctions [CODESPLIT] function PromiseResolutionHandlerFunction ( ) { return function F ( x ) { var promise = F [ '[[Promise]]' ] , fulfillmentHandler = F [ '[[FulfillmentHandler]]' ] , rejectionHandler = F [ '[[RejectionHandler]]' ] , selfResolutionError , C , promiseCapability , updateResult ; if ( SameValue ( x , promise ) ) { selfResolutionError = TypeError ( ) ; return rejectionHandler . call ( undefined , selfResolutionError ) ; } C = promise [ '[[PromiseConstructor]]' ] ; try { promiseCapability = NewPromiseCapability ( C ) ; } catch ( e ) { return e ; } try { updateResult = UpdatePromiseFromPotentialThenable ( x , promiseCapability ) ; } catch ( e ) { return e ; } if ( updateResult !== 'not a thenable' ) { return promiseCapability [ '[[Promise]]' ] . then ( fulfillmentHandler , rejectionHandler ) ; } return fulfillmentHandler . call ( undefined , x ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "custom event stuff [CODESPLIT] function ( target , sequence , t ) { //t==trigger (usually a 'click'ish event) sequence = sequence . split ( _ . splitRE ) ; for ( var i = 0 , e , props ; i < sequence . length && ( ! e || ! e . isSequenceStopped ( ) ) ; i ++ ) { props = _ . parse ( sequence [ i ] ) ; if ( props ) { props . sequence = sequence ; if ( e ) { props . previousEvent = e ; } if ( t ) { props . trigger = t ; } _ . controls ( props , target , sequence , i ) ; e = _ . event ( target , props ) ; } } return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "native DOM and event stuff [CODESPLIT] function ( e ) { var el = e . target , attr , type = e . type , key = type . indexOf ( 'key' ) === 0 ? e . which || e . keyCode || '' : '' , special = _ . special [ type + key ] ; if ( el && special ) { type = special ( e , el , el . nodeName . toLowerCase ( ) ) ; if ( ! type ) { return ; } // special said to ignore it! } el = _ . find ( el , type ) , attr = _ . attr ( el , type ) ; if ( attr ) { _ . all ( el , attr , e ) ; if ( type === 'click' && ! _ . boxRE . test ( el . type ) ) { e . preventDefault ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "extension hooks [CODESPLIT] function ( el , sequence ) { if ( typeof el === \"string\" ) { sequence = el ; el = document ; } return _ . all ( el , sequence || _ . attr ( el , 'click' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------------------------- Helpers -------------------------------------------------------------------------- Reports that there shouldn t be a space after the first token [CODESPLIT] function reportNoBeginningSpace ( node , token , tokenAfter ) { context . report ( { node : node , loc : token . loc . start , message : 'There should be no space after \\'' + token . value + '\\'' , fix : function ( fixer ) { return fixer . removeRange ( [ token . range [ 1 ] , tokenAfter . range [ 0 ] ] ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reports that there shouldn t be a space before the last token [CODESPLIT] function reportNoEndingSpace ( node , token , tokenBefore ) { context . report ( { node : node , loc : token . loc . start , message : 'There should be no space before \\'' + token . value + '\\'' , fix : function ( fixer ) { return fixer . removeRange ( [ tokenBefore . range [ 1 ] , token . range [ 0 ] ] ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reports that there should be a space after the first token [CODESPLIT] function reportRequiredBeginningSpace ( node , token ) { context . report ( { node : node , loc : token . loc . start , message : 'A space is required after \\'' + token . value + '\\'' , fix : function ( fixer ) { return fixer . insertTextAfter ( token , ' ' ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reports that there should be a space before the last token [CODESPLIT] function reportRequiredEndingSpace ( node , token ) { context . report ( { node : node , loc : token . loc . start , message : 'A space is required before \\'' + token . value + '\\'' , fix : function ( fixer ) { return fixer . insertTextBefore ( token , ' ' ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a random point offset from the origin [CODESPLIT] function generateDestinationLonLat ( { lat , lon } ) { const latOffset = ( getDistance ( ) / LAT_DEGREE ) * getSign ( ) const lonOffset = ( getDistance ( ) / ( LAT_DEGREE * Math . cos ( lat ) ) ) * getSign ( ) return { lat : lat + latOffset , lon : lon + lonOffset } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a nested value from the specified object . Returns undefined if not found . [CODESPLIT] function ( keyParts , hash ) { for ( var i = 0 ; i < keyParts . length - 1 ; ++ i ) { hash = getValue ( keyParts [ i ] , hash ) ; if ( typeof ( hash ) === 'undefined' ) { return undefined ; } } var lastKeyPartIndex = keyParts . length - 1 ; return getValue ( keyParts [ lastKeyPartIndex ] , hash ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns array of strings like firstname lastname <email [CODESPLIT] function gitAuthors ( cb ) { return exec ( 'git log --pretty=\"%an <%ae>\"' , function ( er , stdout , stderr ) { if ( er || stderr ) throw new Error ( er || stderr ) return cb ( null , stdout . split ( '\\n' ) . reverse ( ) ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "look for the email first . if no results look for the name . [CODESPLIT] function lookupGithubLogin ( p , print , callback ) { var apiURI = 'https://api.github.com/search/users?q=' var options = { json : true , headers : { 'user-agent' : pkg . name + '/' + pkg . version } } if ( process . env . OAUTH_TOKEN ) { options . headers [ 'Authorization' ] = 'token ' + process . env . OAUTH_TOKEN . trim ( ) } function cb ( err , p ) { callback ( err , p ) } if ( print ) process . stdout . write ( '.' ) request ( apiURI + encodeURIComponent ( p . email + ' in:email type:user' ) , options , onEmail ) function onEmail ( err , data ) { rateLimitExceeded = rateLimitExceeded || data . body . message if ( ! err && data . body . items && data . body . items [ 0 ] ) { p . login = data . body . items [ 0 ] . login return cb ( err , p ) } request ( apiURI + encodeURIComponent ( p . name + ' in:fullname type:user' ) , options , onName ) } function onName ( err , data ) { rateLimitExceeded = rateLimitExceeded || data . body . message if ( ! err && data . body . items && data . body . items [ 0 ] ) { p . login = data . body . items [ 0 ] . login return cb ( err , p ) } cb ( err , p ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unpacks Keyczar s output format [CODESPLIT] function _unpackOutput ( message ) { if ( message . charAt ( 0 ) != keyczar_util . VERSION_BYTE ) { throw new Error ( 'Unsupported version byte: ' + message . charCodeAt ( 0 ) ) ; } var keyhash = message . substr ( 1 , keyczar_util . KEYHASH_LENGTH ) ; message = message . substr ( 1 + keyczar_util . KEYHASH_LENGTH ) ; return { keyhash : keyhash , message : message } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the keyhash for an RSA public key . [CODESPLIT] function _rsaHash ( publicKey ) { var md = forge . md . sha1 . create ( ) ; // hash: // 4-byte big endian length // \"magnitude\" of the public modulus (trim all leading zero bytes) // same for the exponent _hashBigNumber ( md , publicKey . n ) ; _hashBigNumber ( md , publicKey . e ) ; var digest = md . digest ( ) ; return digest . getBytes ( keyczar_util . KEYHASH_LENGTH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a key object for an RSA key . [CODESPLIT] function _makeRsaKey ( rsaKey ) { var key = { keyhash : _rsaHash ( rsaKey ) , size : rsaKey . n . bitLength ( ) } ; key . encrypt = function ( plaintext ) { // needed to make this work with private keys var tempKey = forge . pki . setRsaPublicKey ( rsaKey . n , rsaKey . e ) ; var ciphertext = tempKey . encrypt ( plaintext , 'RSA-OAEP' ) ; return _packOutput ( key . keyhash , ciphertext ) ; } ; key . verify = function ( message , signature ) { signature = _unpackOutput ( signature ) ; _checkKeyHash ( key . keyhash , signature ) ; var digest = _mdForSignature ( message ) . digest ( ) . getBytes ( ) ; // needed to make this work with private keys var tempKey = forge . pki . setRsaPublicKey ( rsaKey . n , rsaKey . e ) ; return tempKey . verify ( digest , signature . message ) ; } ; return key ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extend grunt - exec [CODESPLIT] function ( ) { if ( ! result ) { var exec = grunt . config . get ( 'exec' ) ; for ( var key in exec ) { exec [ key ] . cmd = nvmUse + ' && ' + exec [ key ] . cmd ; } grunt . config . set ( 'exec' , exec ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for NVM [CODESPLIT] function ( callback ) { var command = '. ' + nvmPath ; childProcess . exec ( command , cmdOpts , function ( err , stdout , stderr ) { if ( stderr . indexOf ( 'No such file or directory' ) !== - 1 ) { if ( nvmPath === home + '/.nvm/nvm.sh' ) { nvmPath = home + '/nvm/nvm.sh' ; nvmInit = '. ' + nvmPath + ' && ' ; checkNVM ( callback ) ; } else { grunt [ options . errorLevel ] ( 'Expected node ' + expected + ', but found v' + actual + '\\nNVM does not appear to be installed.\\nPlease install (https://github.com/creationix/nvm#installation), or update the NVM path.' ) ; } } else { callback ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for globally required packages [CODESPLIT] function ( packages ) { var thisPackage ; if ( packages . length ) { thisPackage = packages . pop ( ) ; var command = nvmUse + ' && npm ls -g ' + thisPackage ; childProcess . exec ( command , cmdOpts , function ( err , stdout , stderr ) { if ( err ) { throw err ; } if ( stdout . indexOf ( 'â”€ (empty)') !==   1)      npmInstall ( thisPackage , function ( ) { checkPackages ( packages ) ; } ) ; } else { checkPackages ( packages ) ; } } ) ; } else { done ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Install missing packages [CODESPLIT] function ( thisPackage , callback ) { var command = nvmUse + ' && npm install -g ' + thisPackage ; childProcess . exec ( command , cmdOpts , function ( err , stdout , stderr ) { if ( err ) { throw err ; } grunt . verbose . writeln ( stdout ) ; grunt . log . oklns ( 'Installed ' + thisPackage ) ; callback ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prompt to install [CODESPLIT] function ( ) { prompt . start ( ) ; var prop = { name : 'yesno' , message : 'You do not have any node versions installed that satisfy this project\\'s requirements (' . white + expected . yellow + '). Would you like to install the latest compatible version? (y/n)' . white , validator : / y[es]*|n[o]? / , required : true , warning : 'Must respond yes or no' } ; prompt . get ( prop , function ( err , result ) { result = result . yesno . toLowerCase ( ) ; if ( result === 'yes' || result === 'y' ) { nvmInstall ( ) ; } else { grunt [ options . errorLevel ] ( 'Expected node v' + expected + ', but found ' + actual ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Install latest compatible node version [CODESPLIT] function ( ) { nvmLs ( 'remote' , function ( ) { bestMatch = semver . maxSatisfying ( remotes , expected ) ; nvmUse = nvmInit + 'nvm use ' + bestMatch ; var command = nvmInit + 'nvm install ' + bestMatch ; childProcess . exec ( command , cmdOpts , function ( err , stdout , stderr ) { if ( err ) { throw err ; } var nodeVersion = stdout . split ( ' ' ) [ 3 ] ; grunt . log . ok ( 'Installed node v' + bestMatch ) ; printVersion ( nodeVersion ) ; extendExec ( ) ; checkPackages ( options . globals ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for available node versions [CODESPLIT] function ( loc , callback ) { var command = nvmInit + 'nvm ls' ; if ( loc === 'remote' ) { command += '-remote' ; } childProcess . exec ( command , cmdOpts , function ( err , stdout , stderr ) { var data = stripColorCodes ( stdout . toString ( ) ) . replace ( / \\s+ / g , '|' ) , available = data . split ( '|' ) ; for ( var i = 0 ; i < available . length ; i ++ ) { // Trim whitespace available [ i ] = available [ i ] . replace ( / \\s / g , '' ) ; // Validate var ver = semver . valid ( available [ i ] ) ; if ( ver ) { if ( loc === 'remote' ) { remotes . push ( ver ) ; } else if ( loc === 'local' ) { locals . push ( ver ) ; } } } callback ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for compatible node version [CODESPLIT] function ( ) { // Make sure a node version is intalled that satisfies // the projects required engine. If not, prompt to install. nvmLs ( 'local' , function ( ) { var matches = semver . maxSatisfying ( locals , expected ) ; if ( matches ) { bestMatch = matches ; nvmUse = nvmInit + 'nvm use ' + bestMatch ; childProcess . exec ( nvmUse , cmdOpts , function ( err , stdout , stderr ) { printVersion ( stdout . split ( ' ' ) [ 3 ] ) ; extendExec ( ) ; checkPackages ( options . globals ) ; } ) ; } else { if ( options . alwaysInstall ) { nvmInstall ( ) ; } else { askInstall ( ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A subject which executes its assertions on each element of an iterable . [CODESPLIT] function EachSubject ( subject , elements , elementName , opt_noIndex ) { ProxyBase . call ( this ) ; this . elementSubjects = [ ] ; for ( var i = 0 ; i < elements . length ; ++ i ) { var es = subjectFactory . newSubject ( subject . failureStrategy , elements [ i ] ) ; es . named ( elementName + ( opt_noIndex ? '' : ( ' ' + i ) ) + ' of ' + subject . describe ( ) ) ; es . failureMessage = subject . failureMessage ; this . elementSubjects . push ( es ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A class which functions as a subject but doesn t actually execute any assertions until the promise has resolved . Once the promise succeeds any method calls will be played back on the result value of the promise . [CODESPLIT] function EventualSubject ( subject , promise ) { DeferredSubject . call ( this ) ; this . subject = subject ; var self = this ; this . promise = promise . then ( function ( value ) { // Play back the recorded calls on a new subject which is created based on the resolved // value of the promise. var valueSubject = subjectFactory . newSubject ( subject . failureStrategy , value ) ; valueSubject . failureMessage = subject . failureMessage ; self . run ( valueSubject ) ; return value ; } , function ( reason ) { subject . fail ( 'Expected promise ' + subject . describe ( ) + ' to succeed, but failed with ' + this . format ( reason ) + '.' ) ; return reason ; } ) ; // Make this object a thenable this . then = this . promise . then . bind ( this . promise ) ; this . catch = this . promise . catch . bind ( this . promise ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subject subclass which provides assertion methods for promise types . [CODESPLIT] function PromiseSubject ( failureStrategy , value ) { Subject . call ( this , failureStrategy , value ) ; // Make this object a thenable this . then = this . value . then . bind ( this . value ) ; this . catch = this . value . catch . bind ( this . value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given two arrays or strings return the first element where they differ ( shallow ) . [CODESPLIT] function firstDiff ( exp , act ) { var i ; for ( i = 0 ; i < exp . length && i < act . length ; ++ i ) { if ( exp [ i ] != act [ i ] ) { break ; } } return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function to compute the difference between two values . Note that unlike many other object diff implementations this one tries to humanize the results summarizing them for improved readability . [CODESPLIT] function compare ( exp , act , opt_path , opt_deep , opt_results ) { var path = opt_path || '' ; var i , j , strExp , strAct ; if ( sameValue ( exp , act ) ) { return true ; } var et = type ( exp ) ; var at = type ( act ) ; if ( et !== at || et === 'number' || at === 'boolean' || et === 'undefined' || exp === null || act === null ) { if ( opt_results ) { opt_results . push ( inequality ( exp , act , path ) ) ; } return false ; } else if ( et === 'object' ) { // Shallow comparison if ( ! opt_deep ) { if ( opt_results ) { opt_results . push ( inequality ( exp , act , path ) ) ; } return false ; } // Compare prototypes var eProto = Object . getPrototypeOf ( exp ) ; var aProto = Object . getPrototypeOf ( act ) ; if ( eProto != aProto ) { if ( opt_results ) { var eName = protoName ( exp ) ; var aName = protoName ( act ) ; opt_results . push ( { diff : 'type' , path : path , expected : eName , actual : aName , } ) ; } return false ; } if ( Array . isArray ( exp ) && Array . isArray ( act ) ) { if ( ! opt_results && exp . length !== act . length ) { return false ; } for ( i = 0 ; i < exp . length && i < act . length ; i += 1 ) { if ( ! compare ( exp [ i ] , act [ i ] , path + '[' + i + ']' , opt_deep , opt_results , true ) ) { if ( ! opt_results ) { return false ; } } } var strEl ; if ( i < exp . length ) { for ( j = i ; j < exp . length && j < i + 3 ; j += 1 ) { strEl = format ( exp [ j ] , { clip : 128 } ) ; opt_results . push ( { diff : 'element' , path : path + '[' + j + ']' , // expected: eName, actual : strEl , } ) ; } if ( j < exp . length ) { opt_results . push ( { diff : 'more' , more : ( exp . length - j ) } ) ; } } if ( i < act . length ) { strEl = format ( act [ i ] , { clip : 128 } ) ; for ( j = i ; j < act . length && j < i + 3 ; j += 1 ) { strEl = format ( act [ j ] , { clip : 128 } ) ; opt_results . push ( { diff : 'element' , path : path + '[' + j + ']' , expected : strEl , } ) ; } if ( j < act . length ) { opt_results . push ( { diff : 'more' , more : ( act . length - j ) } ) ; } } return false ; } // Handle regular expression objects. if ( exp instanceof RegExp ) { if ( opt_deep && ( exp + '' ) === ( act + '' ) ) { return true ; } if ( opt_results ) { opt_results . push ( inequality ( exp , act , path ) ) ; } return false ; } // Handle 'date' objects. if ( exp instanceof Date ) { if ( opt_deep && exp . getTime ( ) === act . getTime ( ) ) { return true ; } if ( opt_results ) { opt_results . push ( inequality ( exp , act , path ) ) ; } return false ; } // Compare individual properties. var same = true ; var eKeys = propertyKeys ( exp ) ; var aKeys = propertyKeys ( act ) ; eKeys . sort ( ) ; aKeys . sort ( ) ; // Check all keys in exp for ( i = 0 ; i < eKeys . length ; ++ i ) { var k = eKeys [ i ] ; if ( act . hasOwnProperty ( k ) ) { if ( ! compare ( exp [ k ] , act [ k ] , path + '.' + k , opt_deep , opt_results , true ) ) { if ( ! opt_results ) { return false ; } same = false ; } } else { same = false ; if ( opt_results ) { // opt_results.push(propertyAbsent(exp[k], null, path + '.' + k)); strExp = format ( exp [ k ] , { clip : 128 } ) ; var keyExp = path + '.' + k ; opt_results . push ( { diff : 'property' , path : keyExp , expected : strExp , // actual: aName, } ) ; } } } // Check all keys in act for ( i = 0 ; i < aKeys . length ; ++ i ) { var k2 = aKeys [ i ] ; if ( ! exp . hasOwnProperty ( k2 ) ) { if ( ! opt_results ) { return false ; } same = false ; strAct = format ( act [ k2 ] , { clip : 128 } ) ; var keyAct = path + '.' + k2 ; opt_results . push ( { diff : 'property' , path : keyAct , // expected: eName, actual : strAct , } ) ; } } return same ; } else if ( et === 'string' ) { if ( opt_results ) { // See if the values have line breaks var eLines = exp . split ( '\\n' ) ; var aLines = act . split ( '\\n' ) ; var col = 0 ; var start ; if ( eLines . length > 2 || aLines . length > 2 ) { // find the first line where they differ var line = firstDiff ( eLines , aLines ) ; // find the first character where the lines differ var expLine = line < eLines . length ? eLines [ line ] : '' ; var actLine = line < aLines . length ? aLines [ line ] : '' ; col = firstDiff ( expLine , actLine ) ; start = Math . max ( col - 16 , 0 ) ; strExp = sliceWithEllipsis ( expLine , start , Math . min ( col + 40 , expLine . length ) ) ; strAct = sliceWithEllipsis ( actLine , start , Math . min ( col + 40 , actLine . length ) ) ; opt_results . push ( { diff : 'string' , path : path , line : line , col : col , expected : strExp , actual : strAct } ) ; } else { // find the first character where they differ col = firstDiff ( exp , act ) ; // if that index < 16 or strings are short, then show the whole thing: if ( col < 16 || ( exp . length < 30 && act . length < 30 ) ) { opt_results . push ( inequality ( exp , act , path ) ) ; return false ; } // Only show the part of the string that differs. start = Math . max ( col - 16 , 0 ) ; strExp = sliceWithEllipsis ( exp , start , Math . min ( col + 40 , exp . length ) ) ; strAct = sliceWithEllipsis ( act , start , Math . min ( col + 40 , act . length ) ) ; opt_results . push ( { diff : 'string' , path : path , index : col , expected : strExp , actual : strAct } ) ; } // opt_results.push(msg); return false ; } return false ; } else { // buffer // arguments throw new Error ( 'Type not handled: ' + et ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Return path to write file to inside outputDir . [CODESPLIT] function defaultDestRewriter ( pathObj : Object , innerPath : string , options : Object ) { let fileName = pathObj . base ; if ( options . fileSuffix ) { fileName . replace ( options . fileSuffix , '.svg' ) ; } else { fileName = fileName . replace ( '.svg' , '.js' ) ; } fileName = fileName . replace ( / (^.)|(_)(.) / g , ( match , p1 , p2 , p3 ) => ( p1 || p3 ) . toUpperCase ( ) ) ; return path . join ( innerPath , fileName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve value stored at key Empty / null / undefined key returns all data [CODESPLIT] function get ( store , key , options ) { if ( key === '' || key == null ) { return store . _data ; } return doGet ( store , key , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve value stored at key [CODESPLIT] function doGet ( store , key , options = { } ) { // Resolve back to original key if referenced key = store . _resolveRefKey ( key ) ; const { referenceDepth = 1 } = options ; const cacheKey = ` ${ key } ${ referenceDepth } ` ; const shouldCache = ! store . _isWritable ; if ( shouldCache ) { if ( store . _getCache [ cacheKey ] ) { return store . _getCache [ cacheKey ] ; } } let value = property . get ( store . _data , key ) ; if ( referenceDepth > 0 ) { value = resolveReferences ( store , value , referenceDepth ) ; } if ( shouldCache ) { store . _getCache [ cacheKey ] = value ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve all references in value up to max depth [CODESPLIT] function resolveReferences ( store , value , depth ) { if ( -- depth < 0 ) { return value ; } if ( Array . isArray ( value ) ) { const n = value . length ; const v = new Array ( n ) ; let item ; for ( let i = n - 1 ; i >= 0 ; i -- ) { item = value [ i ] ; v [ i ] = resolveReferences ( store , store . _isRefValue ( item ) ? property . get ( store . _data , store . _parseRefKey ( item ) ) : item , depth ) ; } value = v ; } else if ( isPlainObject ( value ) ) { const v = { } ; let item ; for ( const prop in value ) { item = value [ prop ] ; v [ prop ] = resolveReferences ( store , store . _isRefValue ( item ) ? property . get ( store . _data , store . _parseRefKey ( item ) ) : item , depth ) ; } value = v ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a string value to a printable string representation . [CODESPLIT] function formatString ( value , options ) { var opts = options || { } ; var result = value . replace ( / [\\0-\\37] / g , function ( ch ) { switch ( ch ) { case '\\n' : return '\\\\n' ; case '\\r' : return '\\\\r' ; case '\\t' : return '\\\\t' ; case '\\b' : return '\\\\b' ; case '\\v' : return '\\\\v' ; case '\\f' : return '\\\\f' ; default : return '\\\\' + ch . charCodeAt ( 0 ) . toString ( 8 ) ; } } ) ; if ( opts . clip && result . length > opts . clip ) { result = result . slice ( 0 , Math . max ( 0 , opts . clip - 3 ) ) + '...' ; } return '\"' + result + '\"' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------ Utilities ------------------------------------ [CODESPLIT] function base ( ) { const args = [ config . path_base ] . concat ( [ ] . slice . call ( arguments ) ) ; return path . resolve . apply ( path , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A fluent context object containing the value of the field that was just tested . Used for additional assertions about a field . [CODESPLIT] function KeyValue ( subject , key ) { this . subject = subject ; this . key = key ; this . format = subject . format ; this . value = subject . value . get ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an object value to a printable string representation . [CODESPLIT] function formatObject ( value , options ) { if ( value === undefined ) { return 'undefined' ; } if ( value === null ) { return 'null' ; } if ( typeof ( value ) == 'object' ) { if ( value instanceof RegExp || value instanceof Date ) { return value + '' ; } var opts = options || { } ; var innerOpts = Object . assign ( { } , opts , { clip : false } ) ; // If it's a plain object var proto = Object . getPrototypeOf ( value ) ; if ( proto === Object . prototype || proto === null ) { var keys = [ ] ; for ( var k in value ) { keys . push ( k ) ; } keys . sort ( ) ; var parts = [ '{' ] ; var length = 4 ; // Include both open and close brace. for ( var i = 0 ; i < keys . length ; ++ i ) { var key = keys [ i ] ; var sep = i > 0 ? ', ' : ' ' ; var s = registry . format ( value [ key ] , innerOpts ) ; length += sep . length + key . length + 2 + s . length ; if ( opts . clip && opts . clip < length ) { parts . push ( ', ...' ) ; break ; } parts . push ( sep ) ; parts . push ( key ) ; parts . push ( ': ' ) ; parts . push ( s ) ; } if ( keys . length > 0 ) { parts . push ( ' ' ) ; } parts . push ( '}' ) ; return parts . join ( '' ) ; } if ( typeof value . toString == 'function' ) { return value . toString ( ) ; } return String ( value ) ; } throw new Error ( 'Implement' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a new keyczar containing the public part of key which must be an asymmetric key . [CODESPLIT] function _exportPublicKey ( key ) { var t = key . metadata . type ; var p = key . metadata . purpose ; if ( ! ( t == keyczar . TYPE_RSA_PRIVATE && ( p == keyczar . PURPOSE_DECRYPT_ENCRYPT || p == keyczar . PURPOSE_SIGN_VERIFY ) ) ) { throw new Error ( 'Unsupported key type/purpose:' + t + '/' + p ) ; } var publicPurpose = keyczar . PURPOSE_ENCRYPT ; if ( p == keyczar . PURPOSE_SIGN_VERIFY ) { publicPurpose = keyczar . PURPOSE_VERIFY ; } var metadata = { name : key . metadata . name , purpose : publicPurpose , type : keyczar . TYPE_RSA_PUBLIC , encrypted : false , // TODO: Probably should do a deep copy versions : key . metadata . versions } ; if ( key . metadata . versions . length != 1 ) { throw new Error ( 'TODO: Support key sets with multiple keys' ) ; } var primaryVersion = _getPrimaryVersion ( key . metadata ) ; var data = { meta : JSON . stringify ( metadata ) } ; data [ String ( primaryVersion ) ] = key . primary . exportPublicKeyJson ( ) ; return _makeKeyczar ( data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find the primary version ; ensure we don t have more than one [CODESPLIT] function _getPrimaryVersion ( metadata ) { var primaryVersion = null ; for ( var i = 0 ; i < metadata . versions . length ; i ++ ) { if ( metadata . versions [ i ] . status == STATUS_PRIMARY ) { if ( primaryVersion !== null ) { throw new Error ( 'Invalid key: multiple primary keys' ) ; } primaryVersion = metadata . versions [ i ] . versionNumber ; } } if ( primaryVersion === null ) { throw new Error ( 'No primary key' ) ; } return primaryVersion ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Keyczar object from data . [CODESPLIT] function _makeKeyczar ( data , password ) { var instance = { } ; instance . metadata = JSON . parse ( data . meta ) ; if ( instance . metadata . encrypted !== false ) { if ( ! password ) { throw new Error ( 'Key is encrypted; you must provide the password' ) ; } if ( password . length === 0 ) { throw new Error ( 'Must supply a password length > 0' ) ; } } else if ( password ) { throw new Error ( 'Key is not encrypted but password provided' ) ; } var primaryVersion = _getPrimaryVersion ( instance . metadata ) ; var primaryKeyString = data [ String ( primaryVersion ) ] ; if ( instance . metadata . encrypted ) { primaryKeyString = _decryptKey ( primaryKeyString , password ) ; } var t = instance . metadata . type ; var p = instance . metadata . purpose ; if ( t == keyczar . TYPE_RSA_PRIVATE ) { instance . primary = keyczar_util . privateKeyFromKeyczar ( primaryKeyString ) ; instance . exportPublicKey = function ( ) { return _exportPublicKey ( instance ) ; } ; } else if ( t == keyczar . TYPE_RSA_PUBLIC ) { instance . primary = keyczar_util . publicKeyFromKeyczar ( primaryKeyString ) ; } else if ( t == keyczar . TYPE_AES && p == keyczar . PURPOSE_DECRYPT_ENCRYPT ) { instance . primary = keyczar_util . aesFromKeyczar ( primaryKeyString ) ; } else { throw new Error ( 'Unsupported key type: ' + t ) ; } if ( p == keyczar . PURPOSE_ENCRYPT || p == keyczar . PURPOSE_DECRYPT_ENCRYPT ) { // Takes a raw byte string, returns a raw byte string instance . encryptBinary = function ( plaintext ) { // TODO: assert that plaintext does not contain special characters return instance . primary . encrypt ( plaintext ) ; } ; instance . encrypt = function ( plaintext ) { // encode as UTF-8 in case plaintext contains non-ASCII characters plaintext = forge . util . encodeUtf8 ( plaintext ) ; var message = instance . encryptBinary ( plaintext ) ; message = keyczar_util . encodeBase64Url ( message ) ; return message ; } ; // only include decryption if supported by this key type if ( p == keyczar . PURPOSE_DECRYPT_ENCRYPT ) { instance . decryptBinary = function ( message ) { return instance . primary . decrypt ( message ) ; } ; instance . decrypt = function ( message ) { message = keyczar_util . decodeBase64Url ( message ) ; var plaintext = instance . primary . decrypt ( message ) ; plaintext = forge . util . decodeUtf8 ( plaintext ) ; return plaintext ; } ; } } else if ( p == keyczar . PURPOSE_VERIFY || p == keyczar . PURPOSE_SIGN_VERIFY ) { instance . verify = function ( message , signature ) { message = forge . util . encodeUtf8 ( message ) ; signature = keyczar_util . decodeBase64Url ( signature ) ; return instance . primary . verify ( message , signature ) ; } ; if ( p == keyczar . PURPOSE_SIGN_VERIFY ) { instance . sign = function ( message ) { message = forge . util . encodeUtf8 ( message ) ; var signature = instance . primary . sign ( message ) ; return keyczar_util . encodeBase64Url ( signature ) ; } ; } } var _toJsonObject = function ( ) { var out = { } ; out . meta = JSON . stringify ( instance . metadata ) ; // TODO: Store and serialize ALL keys. For now this works if ( instance . metadata . versions . length != 1 ) { throw new Error ( 'TODO: Support keyczars with multiple keys' ) ; } var primaryVersion = _getPrimaryVersion ( instance . metadata ) ; out [ String ( primaryVersion ) ] = instance . primary . toJson ( ) ; return out ; } ; // Returns the JSON serialization of this keyczar instance. instance . toJson = function ( ) { if ( instance . metadata . encrypted ) { throw new Error ( 'Key is encrypted; use toJsonEncrypted() instead' ) ; } var out = _toJsonObject ( ) ; return JSON . stringify ( out ) ; } ; // Returns the decrypted version of this password-protected key. // WARNING: This is dangerous as it can be used to leak a password-protected key instance . exportDecryptedJson = function ( ) { if ( ! instance . metadata . encrypted ) { throw new Error ( 'Key is not encrypted; use toJson() instead' ) ; } var unencrypted = _toJsonObject ( ) ; // hack the metadata to mark it as unencrypted var meta = JSON . parse ( unencrypted . meta ) ; meta . encrypted = false ; unencrypted . meta = JSON . stringify ( meta ) ; return JSON . stringify ( unencrypted ) ; } ; instance . toJsonEncrypted = function ( password ) { // TODO: Enforce some sort of minimum length? if ( password . length === 0 ) { throw new Error ( 'Password length must be > 0' ) ; } // get the unencrypted JSON object var unencrypted = _toJsonObject ( ) ; // set metadata.encrypted = true var meta = JSON . parse ( unencrypted . meta ) ; meta . encrypted = true ; unencrypted . meta = JSON . stringify ( meta ) ; // encrypt each key for ( var property in unencrypted ) { if ( property == 'meta' ) continue ; unencrypted [ property ] = _encryptKey ( unencrypted [ property ] , password ) ; } return JSON . stringify ( unencrypted ) ; } ; return instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Return path to write file to inside outputDir . [CODESPLIT] function kebabDestRewriter ( pathObj : Object , innerPath : string , options : Object ) { let fileName = pathObj . base ; if ( options . fileSuffix ) { fileName . replace ( options . fileSuffix , '.svg' ) ; } else { fileName = fileName . replace ( '.svg' , '.js' ) ; } fileName = fileName . replace ( / _ / g , '-' ) ; return path . join ( innerPath , fileName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Store value at key [CODESPLIT] function set ( store , key , value , options ) { return doSet ( store , key , value , Object . assign ( { } , DEFAULT_OPTIONS , options ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Store value at key [CODESPLIT] function doSet ( store , key , value , options ) { if ( ! key || typeof key !== 'string' ) { return false ; } // Returns same if no change const newData = property . set ( store . _data , key , value , options ) ; if ( options . immutable ) { if ( newData !== store . _data ) { store . _data = newData ; } else { store . debug ( 'WARNING no change after set \"%s' , key ) ; return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a map value to a printable string representation . [CODESPLIT] function formatMap ( value , options ) { return 'Map(' + registry . format ( Array . from ( value . entries ( ) ) , options ) + ')' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch data . If expired load from url and store at key [CODESPLIT] function fetch ( store , key , url , options ) { options = Object . assign ( { } , DEFAULT_LOAD_OPTIONS , options ) ; options . cacheControl = parseCacheControl ( options . cacheControl ) ; if ( ! key ) { return Promise . resolve ( { body : undefined , duration : 0 , headers : { } , key , status : 400 } ) ; } return doFetch ( store , key , url , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch data . If expired load from url and store at key [CODESPLIT] function doFetch ( store , key , url , options ) { const { cacheControl , rejectOnError } = options ; const value = get ( store , key ) ; const isMissing = ! value ; let isExpired = hasExpired ( value && value [ store . EXPIRY_KEY ] , false ) ; store . debug ( 'fetch %s from %s' , key , url ) ; // Load if missing or expired if ( isMissing || isExpired ) { if ( ! url ) { return Promise . resolve ( { body : value , duration : 0 , headers : { } , key , status : 400 } ) ; } return new Promise ( ( resolve , reject ) => { load ( store , key , url , options ) . then ( res => { store . debug ( 'fetched %s from %s' , key , url ) ; const body = get ( store , key ) ; resolve ( { body , duration : res . duration , headers : generateResponseHeaders ( body [ store . EXPIRY_KEY ] , cacheControl ) , key , status : res . status } ) ; } ) . catch ( err => { // Abort if already destroyed if ( store . destroyed ) { return null ; } isExpired = hasExpired ( value && value [ store . EXPIRY_KEY ] , true ) ; if ( rejectOnError && isExpired ) { return reject ( err ) ; } store . debug ( 'fetched stale %s after load error' , key ) ; return resolve ( { body : isExpired ? undefined : value , duration : 0 , error : err , headers : generateResponseHeaders ( value && value [ store . EXPIRY_KEY ] , cacheControl , true ) , key , status : isExpired ? err . status : 200 } ) ; } ) ; } ) ; } store . debug ( 'fetched %s' , key ) ; return Promise . resolve ( { body : value , duration : 0 , headers : generateResponseHeaders ( value && value [ store . EXPIRY_KEY ] , cacheControl ) , key , status : 200 } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load data from url and store at key [CODESPLIT] function load ( store , key , url , options ) { const { cacheControl , rejectOnError , retry , timeout } = options ; options . id = key ; store . debug ( 'load %s from %s' , key , url ) ; return agent . get ( url , options ) . timeout ( timeout ) . retry ( retry ) . then ( res => { // Abort if already destroyed if ( store . destroyed ) { throw Error ( 'store destroyed' ) ; } store . debug ( 'loaded \"%s\" in %dms' , key , res . duration ) ; // Guard against empty data if ( res . body ) { // Parse cache-control headers if ( res . headers && 'expires' in res . headers ) { res . body [ store . EXPIRY_KEY ] = generateExpiry ( res . headers , cacheControl ) ; } // Enable handling by not calling inner set() store . set ( key , res . body , options ) ; } return res ; } ) . catch ( err => { // Abort if already destroyed if ( store . destroyed ) { throw err ; } store . debug ( 'unable to load \"%s\" from %s' , key , url ) ; if ( rejectOnError ) { store . set ( key , undefined , options ) ; } throw err ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse cacheControlString [CODESPLIT] function parseCacheControl ( cacheControlString ) { let maxAge = 0 ; let staleIfError = 0 ; if ( cacheControlString && typeof cacheControlString === 'string' ) { let match ; while ( ( match = RE_CACHE_CONTROL . exec ( cacheControlString ) ) ) { if ( match [ 1 ] ) { maxAge = parseInt ( match [ 1 ] , 10 ) * 1000 ; } else if ( match [ 2 ] ) { staleIfError = parseInt ( match [ 2 ] , 10 ) * 1000 ; } } } return { maxAge , staleIfError } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge cacheControl with defaults [CODESPLIT] function mergeCacheControl ( cacheControl , defaultCacheControl ) { if ( cacheControl == null ) { return Object . assign ( { } , defaultCacheControl ) ; } return { maxAge : 'maxAge' in cacheControl ? cacheControl . maxAge : defaultCacheControl . maxAge , staleIfError : 'staleIfError' in cacheControl ? cacheControl . staleIfError : defaultCacheControl . staleIfError } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate expiry object from headers [CODESPLIT] function generateExpiry ( headers = { } , defaultCacheControl ) { const cacheControl = mergeCacheControl ( parseCacheControl ( headers [ 'cache-control' ] ) , defaultCacheControl ) ; const now = Date . now ( ) ; let expires = now ; if ( headers . expires ) { expires = typeof headers . expires === 'string' ? Number ( new Date ( headers . expires ) ) : headers . expires ; } if ( now >= expires ) { expires = now + cacheControl . maxAge ; } return { expires , expiresIfError : expires + cacheControl . staleIfError } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate serialized headers object for response [CODESPLIT] function generateResponseHeaders ( expiry = { } , defaultCacheControl , isError ) { const now = Date . now ( ) ; let maxAge ; if ( isError ) { maxAge = expiry && expiry . expiresIfError > now && expiry . expiresIfError - now < defaultCacheControl . maxAge ? Math . ceil ( ( expiry . expiresIfError - now ) / 1000 ) : defaultCacheControl . maxAge / 1000 ; } else { // Round up to nearest second maxAge = expiry && expiry . expires > now ? Math . ceil ( ( expiry . expires - now ) / 1000 ) : defaultCacheControl . maxAge / 1000 ; } return { // TODO: add stale-if-error 'cache-control' : ` ${ maxAge } ` , expires : new Date ( now + maxAge * 1000 ) . toUTCString ( ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if expired [CODESPLIT] function hasExpired ( expiry , isError ) { if ( ! expiry ) { return true ; } // Round up to nearest second return Math . ceil ( Date . now ( ) / 1000 ) * 1000 > ( isError ? expiry . expiresIfError : expiry . expires ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a set value to a printable string representation . [CODESPLIT] function formatSet ( value , options ) { return 'Set(' + registry . format ( Array . from ( value . values ( ) ) , options ) + ')' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an array value to a printable string representation . [CODESPLIT] function formatArray ( value , options ) { var opts = options || { } ; var innerOpts = Object . assign ( { } , opts , { clip : false } ) ; var parts = [ '[' ] ; var length = 2 ; // Include both open and close bracket. for ( var i = 0 ; i < value . length ; ++ i ) { var sep = i > 0 ? ', ' : '' ; var s = registry . format ( value [ i ] , innerOpts ) ; length += sep . length + s . length ; if ( opts . clip && opts . clip < length ) { parts . push ( ', ...' ) ; break ; } parts . push ( sep ) ; parts . push ( s ) ; } parts . push ( ']' ) ; return parts . join ( '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//// Function init Initialises an instance of a PromiseP . init! :: [CODESPLIT] function _init ( client , uri , options ) { Promise . init . call ( this ) this . client = client this . uri = uri this . options = options return this }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * otherwise [CODESPLIT] function _timeout ( delay ) { this . clearTimer ( ) this . timer = setTimeout ( function ( ) { this . flush ( 'timeouted' , 'failed' ) . fail ( 'timeouted' ) this . forget ( ) } . bind ( this ) , delay * 1000 ) return this }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/// Function request Makes an HTTP request to the given URI and returns a PromiseP that such request will be fulfilled . Any actual work is carried over after the promise is returned from this method . As such the user can freely manipulate the promise object synchronously before the connection with the endpoint is even opened . Aside from the event queues flushed after the promise has been fulfilled ( or failed ) the promise will also fire events from time to time or depending on certain occurrences — as soon as they happen . Callbacks registered for those events may be invoked more than once and may be invoked before the promise is fulfilled . request :: String { String - > String } - > PromiseP [CODESPLIT] function request ( uri , options ) { var client , promise , method , serialise_body_p , mime options = options || { } options . headers = options . headers || { } method = ( options . method || 'GET' ) . toUpperCase ( ) uri = build_uri ( uri , options . query , options . body ) options . headers [ 'X-Requested-With' ] = 'XMLHttpRequest' serialise_body_p = object_p ( options . body ) if ( serialise_body_p ) { mime = options . headers [ 'Content-Type' ] || 'application/x-www-form-urlencoded' options . body = serialise_for_type ( mime , options . body ) options . headers [ 'Content-Type' ] = mime } client = make_xhr ( ) promise = PromiseP . make ( client , uri , options ) setup_listeners ( ) setTimeout ( function ( ) { client . open ( method , uri , true , options . username , options . password ) setup_headers ( options . headers || { } ) client . send ( options . body ) } ) active . push ( promise ) return promise // Sticks a serialised query and body object at the end of an URI. // build-uri :: String, { String -> String }, { String -> String }? -> String function build_uri ( uri , query , body ) { uri = build_query_string ( uri , query ) return method == 'GET' ? build_query_string ( uri , body ) : /* otherwise */ uri } // Setups the headers for the HTTP request // setup-headers :: { String -> String | [String] } -> Undefined function setup_headers ( headers ) { keys ( headers ) . forEach ( function ( key ) { client . setRequestHeader ( key , headers [ key ] ) } ) } // Generates a handler for the given type of error // make-error-handler :: String -> Event -> Undefined function make_error_handler ( type ) { return function ( ev ) { promise . flush ( type , 'failed' ) . fail ( type , ev ) } } // Invokes an error handler for the given type // raise :: String -> Undefined function raise ( type ) { make_error_handler ( type ) ( ) } // Setups the event listeners for the HTTP request client // setup-listeners :: () -> Undefined function setup_listeners ( ) { client . onerror = make_error_handler ( 'errored' ) client . onabort = make_error_handler ( 'forgotten' ) client . ontimeout = make_error_handler ( 'timeouted' ) client . onloadstart = function ( ev ) { promise . fire ( 'load:start' , ev ) } client . onprogress = function ( ev ) { promise . fire ( 'load:progress' , ev ) } client . onloadend = function ( ev ) { promise . fire ( 'load:end' , ev ) } client . onload = function ( ev ) { promise . fire ( 'load:success' , ev ) } client . onreadystatechange = function ( ) { var response , status , state state = client . readyState promise . fire ( 'state:' + state_map [ state ] ) if ( state == 4 ) { var binding_state = success . test ( status ) ? 'ok' : error . test ( status ) ? 'failed' : /* otherwise */ 'any' response = client . responseText status = normalise_status ( client . status ) active . splice ( active . indexOf ( promise ) , 1 ) promise . flush ( 'status:' + status ) . flush ( 'status:' + status_type ( status ) ) status == 0 ? raise ( 'errored' ) : success . test ( status ) ? promise . bind ( response , status ) : error . test ( status ) ? promise . fail ( response , status ) : /* otherwise */ promise . done ( [ response , status ] ) } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sticks a serialised query and body object at the end of an URI . build - uri :: String { String - > String } { String - > String } ? - > String [CODESPLIT] function build_uri ( uri , query , body ) { uri = build_query_string ( uri , query ) return method == 'GET' ? build_query_string ( uri , body ) : /* otherwise */ uri }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setups the headers for the HTTP request setup - headers :: { String - > String | [ String ] } - > Undefined [CODESPLIT] function setup_headers ( headers ) { keys ( headers ) . forEach ( function ( key ) { client . setRequestHeader ( key , headers [ key ] ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setups the event listeners for the HTTP request client setup - listeners :: () - > Undefined [CODESPLIT] function setup_listeners ( ) { client . onerror = make_error_handler ( 'errored' ) client . onabort = make_error_handler ( 'forgotten' ) client . ontimeout = make_error_handler ( 'timeouted' ) client . onloadstart = function ( ev ) { promise . fire ( 'load:start' , ev ) } client . onprogress = function ( ev ) { promise . fire ( 'load:progress' , ev ) } client . onloadend = function ( ev ) { promise . fire ( 'load:end' , ev ) } client . onload = function ( ev ) { promise . fire ( 'load:success' , ev ) } client . onreadystatechange = function ( ) { var response , status , state state = client . readyState promise . fire ( 'state:' + state_map [ state ] ) if ( state == 4 ) { var binding_state = success . test ( status ) ? 'ok' : error . test ( status ) ? 'failed' : /* otherwise */ 'any' response = client . responseText status = normalise_status ( client . status ) active . splice ( active . indexOf ( promise ) , 1 ) promise . flush ( 'status:' + status ) . flush ( 'status:' + status_type ( status ) ) status == 0 ? raise ( 'errored' ) : success . test ( status ) ? promise . bind ( response , status ) : error . test ( status ) ? promise . fail ( response , status ) : /* otherwise */ promise . done ( [ response , status ] ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//// Function request_with_method Generates a specialised request function for the given method . request - with - method :: String - > String { String - > String } - > PromiseP [CODESPLIT] function request_with_method ( method ) { return function ( uri , options ) { options = options || { } options . method = method . toUpperCase ( ) return request ( uri , options ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------------- [CODESPLIT] function isLinkWorking ( link , options ) { options = Object . assign ( { checkConnectivity : false , followRedirect : true , timeout : 15000 , retries : 3 , agent : null , } , options ) ; const gotOptions = { timeout : options . timeout , followRedirect : options . followRedirect , retries : options . retries , agent : options . agent , headers : { 'user-agent' : ` ${ pkg . version } ` , } , } ; return tryHead ( link , gotOptions ) . catch ( ( ) => tryGet ( link , options , gotOptions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A fluent context object containing the value of the field that was just tested . Used for additional assertions about a field . [CODESPLIT] function FieldValue ( subject , name , value ) { this . subject = subject ; this . name = name ; this . value = subject . value [ name ] ; this . format = subject . format ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "class Sapi [CODESPLIT] function Sapi ( key , opts ) { opts = opts || { } ; function _authRequire ( result , cb ) { // SAPI does not differentiate required authentication and failed authentication // since both return status code 403, need to check key param existence to differentiate the two if ( key ) { cb ( new Error ( 'Authentication failed -  invalid key ' + key ) ) ; } else { cb ( new Error ( 'Authentication required - set API key in Sapi constructor' ) ) ; } } this . params = { key : key } ; this . url = ( opts . url || 'http://api.sensis.com.au/ob-20110511/test' ) . replace ( / \\/$ / , '' ) ; this . opts = { handlers : { 403 : _authRequire } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LeakError copied from https : // github . com / substack / node - syntax - error [CODESPLIT] function LeakError ( opts , src , file ) { Error . call ( this ) ; this . message = 'global leak detected: ' + opts . variable ; this . line = opts . line - 1 ; this . column = opts . column ; this . annotated = '\\n' + ( file || '(anonymous file)' ) + ':' + this . line + '\\n' + src . split ( '\\n' ) [ this . line ] + '\\n' + Array ( this . column + 1 ) . join ( ' ' ) + '^' + '\\n' + 'LeakError: ' + this . message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strategy constructor . [CODESPLIT] function Strategy ( options , verify ) { options = options || { } ; this . serverURL = options . serverURL || 'https://account.lab.fiware.org' ; this . isLegacy = options . isLegacy === true ? options . isLegacy : false ; if ( this . serverURL . endsWith ( '/' ) ) { this . serverURL = this . serverURL . slice ( 0 , - 1 ) ; } options . authorizationURL = this . serverURL + '/oauth2/authorize' ; options . tokenURL = this . serverURL + '/oauth2/token' ; // Authorization: Basic BASE64(CLIENT_ID:CLIENT_SECRET) var authorizationHeader = 'Basic ' + new Buffer ( options . clientID + ':' + options . clientSecret ) . toString ( 'base64' ) options . customHeaders = { 'Authorization' : authorizationHeader } OAuth2Strategy . call ( this , options , verify ) ; this . name = 'fiware' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset underlying data [CODESPLIT] function reset ( store , data ) { store . debug ( 'reset' ) ; store . _data = data ; store . changed = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve serialisable data [CODESPLIT] function serialise ( key , data , config ) { if ( isPlainObject ( data ) ) { const obj = { } ; for ( const prop in data ) { const keyChain = key ? ` ${ key } ${ prop } ` : prop ; const value = data [ prop ] ; if ( config [ keyChain ] !== false ) { if ( isPlainObject ( value ) ) { obj [ prop ] = serialise ( keyChain , value , config ) ; } else if ( value != null && typeof value === 'object' && 'toJSON' in value ) { obj [ prop ] = value . toJSON ( ) ; } else { obj [ prop ] = value ; } } } return obj ; } return config [ key ] !== false ? data : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve all nested references for data [CODESPLIT] function explode ( store , data ) { if ( isPlainObject ( data ) ) { const obj = { } ; for ( const prop in data ) { obj [ prop ] = explode ( store , data [ prop ] ) ; } return obj ; } else if ( Array . isArray ( data ) ) { return data . map ( value => explode ( store , value ) ) ; } else if ( store . _isRefValue ( data ) ) { return explode ( store , store . get ( store . _parseRefKey ( data ) ) ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "// --- Utilities ------------------------------------------------------------ [CODESPLIT] function serialise ( data ) { return keys ( data || { } ) . map ( encode_pair ) . filter ( Boolean ) . join ( '&' ) function encode_pair ( key ) { return data [ key ] != null ? encode ( key ) + '=' + encode ( data [ key ] ) : /* otherwise */ null } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents the value being checked and provides assertion methods . Can be subclassed to provide assertion methods that are type - specific . [CODESPLIT] function Subject ( failureStrategy , value ) { this . failureStrategy = failureStrategy ; this . value = value ; this . name = null ; this . format = format ; this . failureMessage = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FamilySearch user . [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof User ) ) { return new User ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( User . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "folder structure generator class [CODESPLIT] function fsGenerator ( configs ) { var deferred = Q . defer ( ) ; var dirName = \"\" ; var destDir = \"\" ; var tmpDir = \"\" ; var refSrcDir = \"\" ; var destFolderDir = \"\" ; var dirType = \"\" ; var tempFolderName = \"\" ; var contentReplaceRegx = new RegExp ( \"\" , 'g' ) ; var replaceContentLength = 0 ; var ignoreExtentions = [ ] ; var ignoreFolders = [ ] ; /**\n     * initilize create directory process\n     */ var init = function ( ) { for ( var fls in configs ) { dirName = utils . folderName ( configs [ fls ] [ 'input' ] , configs [ fls ] [ 'folderName' ] ) ; dirType = configs [ fls ] [ 'type' ] ; destFolderDir = path . join ( configs [ fls ] [ 'destinationSourcePath' ] , dirName ) ; destDir = configs [ fls ] [ 'destinationSourcePath' ] ; tmpDir = configs [ fls ] [ 'tempFolderPath' ] ; tempFolderName = utils . getBaseFolderName ( tmpDir ) ; refSrcDir = configs [ fls ] [ 'refrenceSourcePath' ] ; ignoreExtentions = configs [ fls ] [ 'ignoreExts' ] || [ ] ; ignoreFolders = configs [ fls ] [ 'ignoreFolders' ] || [ ] ; contentReplaceRegx = new RegExp ( utils . regxContent ( configs [ fls ] [ 'replaceContent' ] ) , 'g' ) ; if ( configs [ fls ] [ 'replaceContent' ] ) { replaceContentLength = Object . keys ( configs [ fls ] [ 'replaceContent' ] ) . length ; } console . log ( ':::~~' + fls + ':::~~' ) ; folderSync ( configs [ fls ] ) ; } } ; /**\n     * sync folder to create new directories with provided Configurations\n     * @param {*} fls \n     */ var folderSync = function ( fls ) { if ( fs . existsSync ( destFolderDir ) ) { console . log ( ':::~~' + dirName + ' exists, please pick another name or delete previous to create new~~:::' ) deferred . reject ( fls . type + ' exists, please pick another name.' ) ; } else { console . log ( ':::~~' + dirName + ' does not exists, creating new~~:::' ) ; if ( ! fs . existsSync ( destFolderDir ) ) { fse . ensureDirSync ( destFolderDir ) ; console . log ( ':::~~Created new directory:' + fls . type + \"/\" + dirName + '~~:::' ) ; } //copy refrence directroy data in temporry directory folder copyRefToTemp ( ) ; //update folder names, file names and file content in temp folder updateTempSubDirNames ( fls ) ; //copy temporary directroy data in destination directory folder copyTempToDest ( ) ; // add tasks to create folder  // addWebpackTasks(); deferred . resolve ( 'successfuly created directory' ) ; } return deferred . promise ; } ; /**\n     * Copy refrence directory in temporary directory\n     */ var copyRefToTemp = function ( ) { fse . emptyDirSync ( tmpDir ) ; fse . copySync ( refSrcDir , tmpDir , { overwrite : true } , err => { if ( err ) { console . log ( ':::~~error in copying to temp directory:' + err + '~~:::' ) ; fse . removeSync ( destFolderDir ) ; fse . emptyDirSync ( tmpDir ) ; deferred . reject ( 'Error in copying to temp directory' ) ; } console . log ( ':::~~ temp directory created~~:::' ) ; } ) ; } ; /**\n     * Process temp directory recently copied\n     * @param {*} fls \n     */ var updateTempSubDirNames = function ( fls ) { fs . readdirSync ( tmpDir ) . map ( function ( dir ) { var tempFolderPath = path . join ( tmpDir , dir ) ; if ( fs . statSync ( tempFolderPath ) . isDirectory ( ) ) { // Process files in tmpDir. nestedDirectory ( tempFolderPath , fls ) ; } else { // This is a file - just process it. processTempFolder ( tempFolderPath , fls ) ; } } ) ; } ; /**\n     * Process nested folders in temp directory recently copied\n     * @param {*} tempFolderPath \n     */ var nestedDirectory = function ( tempFolderPath , fls ) { fs . readdirSync ( tempFolderPath ) . map ( function ( dir ) { var newTempFolderPath = path . join ( tempFolderPath , dir ) ; if ( fs . statSync ( newTempFolderPath ) . isDirectory ( ) ) { nestedDirectory ( newTempFolderPath , fls ) ; } else { processTempFolder ( newTempFolderPath , fls ) ; } } ) ; } /**\n     * Process files that were recently copied in temp directory\n     * @param {*} oldPath \n     * @param {*} fls \n     */ var processTempFolder = function ( oldPath , fls ) { console . log ( \":::~~processing your temp folder and file~~:::\" + oldPath ) ; var parsedPath = updateFileNamePath ( path . parse ( oldPath ) , fls ) ; var newPath = path . format ( parsedPath ) ; var firstFolderName = utils . getFirstFolderName ( oldPath , tempFolderName ) ; fs . renameSync ( oldPath , newPath ) ; if ( replaceContentLength > 0 && ignoreExtentions . indexOf ( parsedPath . ext ) < 0 && ignoreFolders . indexOf ( firstFolderName ) < 0 ) { console . log ( \":::~~writing your temp file~~:::\" + newPath ) ; var oldContent = fs . readFileSync ( newPath , 'utf8' ) ; var newContent = updateFileContent ( oldContent , fls . replaceContent , fls ) ; fs . writeFileSync ( newPath , newContent ) ; } else { console . log ( \":::~~skipping writing of your temp file~~:::\" + newPath ) ; } } /**\n     * update refrence directory files names as per config provided by replaceFileName key\n     * @param {*} parsedPath \n     * @param {*} fls \n     */ var updateFileNamePath = function ( parsedPath , fls ) { // parsedPath.dir, parsedPath.base, parsedPath.ext, parsedPath.name var newName = \"\" ; var fileConfigs = \"\" ; var folderDirArray = getNestedFolderName ( parsedPath ) ; parsedPath [ 'folderName' ] = utils . getBaseFolderName ( parsedPath . dir ) != tempFolderName ? utils . getBaseFolderName ( parsedPath . dir ) : \"\" ; //fileConfigs = parsedPath.folderName ? fls.replaceFileName[parsedPath.folderName][parsedPath.base] : fls.replaceFileName[parsedPath.base]; if ( folderDirArray == \"base\" && fls . replaceFileName [ parsedPath . base ] ) { fileConfigs = fls . replaceFileName [ parsedPath . base ] ; } else if ( Array . isArray ( folderDirArray ) ) { var replaceFileNameArray = fls . replaceFileName ; for ( var i in folderDirArray ) { if ( replaceFileNameArray [ folderDirArray [ i ] ] && Object . keys ( replaceFileNameArray [ folderDirArray [ i ] ] ) . length > 0 ) { replaceFileNameArray = replaceFileNameArray [ folderDirArray [ i ] ] ; } else { replaceFileNameArray = [ ] ; break ; } } if ( replaceFileNameArray && replaceFileNameArray [ parsedPath . base ] ) { fileConfigs = replaceFileNameArray [ parsedPath . base ] ; } else { fileConfigs = [ ] ; } } else { fileConfigs = [ ] } console . log ( \":::~~Configurations from replaceFileName~~:::\" + fileConfigs ) ; newName = utils . getupdatedFileName ( parsedPath . name , fileConfigs , fls . input ) ; parsedPath . base = newName + parsedPath . ext ; parsedPath . name = newName ; return parsedPath ; } ; /**\n     * get array of folders from base temp path\n     * @param {*} parsedPath \n     */ var getNestedFolderName = function ( parsedPath ) { var tempPathArray = tmpDir . split ( \"\\\\\" ) ; var parsedPathArray = parsedPath . dir . split ( \"\\\\\" ) ; if ( parseInt ( tempPathArray . length ) === parseInt ( parsedPathArray . length ) ) { return \"base\" ; } else if ( parseInt ( tempPathArray . length ) < parseInt ( parsedPathArray . length ) ) { var folderNameArray = [ ] ; for ( var i in parsedPathArray ) { if ( i > parseInt ( tempPathArray . length ) - 1 ) { folderNameArray . push ( parsedPathArray [ i ] ) ; } } return folderNameArray ; } } /**\n     * update content of refrence directory files as per config provided by replaceContent key\n     * @param {*} oldContent \n     * @param {*} replaceConfig \n     * @param {*} fls \n     */ var updateFileContent = function ( oldContent , replaceConfig , fls ) { var newContent = oldContent . replace ( contentReplaceRegx , function ( e ) { for ( var cont in replaceConfig ) { var contRegex = new RegExp ( cont , 'g' ) ; if ( e . match ( contRegex ) ) { var replaceValue = utils . getReplacableContent ( fls . input , replaceConfig [ cont ] ) ; return replaceValue ; } } } ) ; return newContent ; } ; /**\n     * copy data from writed temp directory to destination drive\n     */ var copyTempToDest = function ( ) { fse . emptyDirSync ( destFolderDir ) ; fse . copySync ( tmpDir , destFolderDir , { overwrite : true } , err => { if ( err ) { console . log ( ':::~~error in copying to destination directory:' + err + '~~:::' ) ; fse . removeSync ( destFolderDir ) ; fse . emptyDirSync ( tmpDir ) ; deferred . reject ( 'Error in copying to destination directory' ) ; } console . log ( ':::~~ destination directory created:' + dirName + '~~:::' ) ; } ) ; fse . emptyDirSync ( tmpDir ) ; console . log ( ':::~~Created new ' + dirType + \" / \" + dirName + ':::~~' ) ; } ; /**\n     * Call fsGEnerator init\n     */ init ( configs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initilize create directory process [CODESPLIT] function ( ) { for ( var fls in configs ) { dirName = utils . folderName ( configs [ fls ] [ 'input' ] , configs [ fls ] [ 'folderName' ] ) ; dirType = configs [ fls ] [ 'type' ] ; destFolderDir = path . join ( configs [ fls ] [ 'destinationSourcePath' ] , dirName ) ; destDir = configs [ fls ] [ 'destinationSourcePath' ] ; tmpDir = configs [ fls ] [ 'tempFolderPath' ] ; tempFolderName = utils . getBaseFolderName ( tmpDir ) ; refSrcDir = configs [ fls ] [ 'refrenceSourcePath' ] ; ignoreExtentions = configs [ fls ] [ 'ignoreExts' ] || [ ] ; ignoreFolders = configs [ fls ] [ 'ignoreFolders' ] || [ ] ; contentReplaceRegx = new RegExp ( utils . regxContent ( configs [ fls ] [ 'replaceContent' ] ) , 'g' ) ; if ( configs [ fls ] [ 'replaceContent' ] ) { replaceContentLength = Object . keys ( configs [ fls ] [ 'replaceContent' ] ) . length ; } console . log ( ':::~~' + fls + ':::~~' ) ; folderSync ( configs [ fls ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sync folder to create new directories with provided Configurations [CODESPLIT] function ( fls ) { if ( fs . existsSync ( destFolderDir ) ) { console . log ( ':::~~' + dirName + ' exists, please pick another name or delete previous to create new~~:::' ) deferred . reject ( fls . type + ' exists, please pick another name.' ) ; } else { console . log ( ':::~~' + dirName + ' does not exists, creating new~~:::' ) ; if ( ! fs . existsSync ( destFolderDir ) ) { fse . ensureDirSync ( destFolderDir ) ; console . log ( ':::~~Created new directory:' + fls . type + \"/\" + dirName + '~~:::' ) ; } //copy refrence directroy data in temporry directory folder copyRefToTemp ( ) ; //update folder names, file names and file content in temp folder updateTempSubDirNames ( fls ) ; //copy temporary directroy data in destination directory folder copyTempToDest ( ) ; // add tasks to create folder  // addWebpackTasks(); deferred . resolve ( 'successfuly created directory' ) ; } return deferred . promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy refrence directory in temporary directory [CODESPLIT] function ( ) { fse . emptyDirSync ( tmpDir ) ; fse . copySync ( refSrcDir , tmpDir , { overwrite : true } , err => { if ( err ) { console . log ( ':::~~error in copying to temp directory:' + err + '~~:::' ) ; fse . removeSync ( destFolderDir ) ; fse . emptyDirSync ( tmpDir ) ; deferred . reject ( 'Error in copying to temp directory' ) ; } console . log ( ':::~~ temp directory created~~:::' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process files that were recently copied in temp directory [CODESPLIT] function ( oldPath , fls ) { console . log ( \":::~~processing your temp folder and file~~:::\" + oldPath ) ; var parsedPath = updateFileNamePath ( path . parse ( oldPath ) , fls ) ; var newPath = path . format ( parsedPath ) ; var firstFolderName = utils . getFirstFolderName ( oldPath , tempFolderName ) ; fs . renameSync ( oldPath , newPath ) ; if ( replaceContentLength > 0 && ignoreExtentions . indexOf ( parsedPath . ext ) < 0 && ignoreFolders . indexOf ( firstFolderName ) < 0 ) { console . log ( \":::~~writing your temp file~~:::\" + newPath ) ; var oldContent = fs . readFileSync ( newPath , 'utf8' ) ; var newContent = updateFileContent ( oldContent , fls . replaceContent , fls ) ; fs . writeFileSync ( newPath , newContent ) ; } else { console . log ( \":::~~skipping writing of your temp file~~:::\" + newPath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "update refrence directory files names as per config provided by replaceFileName key [CODESPLIT] function ( parsedPath , fls ) { // parsedPath.dir, parsedPath.base, parsedPath.ext, parsedPath.name var newName = \"\" ; var fileConfigs = \"\" ; var folderDirArray = getNestedFolderName ( parsedPath ) ; parsedPath [ 'folderName' ] = utils . getBaseFolderName ( parsedPath . dir ) != tempFolderName ? utils . getBaseFolderName ( parsedPath . dir ) : \"\" ; //fileConfigs = parsedPath.folderName ? fls.replaceFileName[parsedPath.folderName][parsedPath.base] : fls.replaceFileName[parsedPath.base]; if ( folderDirArray == \"base\" && fls . replaceFileName [ parsedPath . base ] ) { fileConfigs = fls . replaceFileName [ parsedPath . base ] ; } else if ( Array . isArray ( folderDirArray ) ) { var replaceFileNameArray = fls . replaceFileName ; for ( var i in folderDirArray ) { if ( replaceFileNameArray [ folderDirArray [ i ] ] && Object . keys ( replaceFileNameArray [ folderDirArray [ i ] ] ) . length > 0 ) { replaceFileNameArray = replaceFileNameArray [ folderDirArray [ i ] ] ; } else { replaceFileNameArray = [ ] ; break ; } } if ( replaceFileNameArray && replaceFileNameArray [ parsedPath . base ] ) { fileConfigs = replaceFileNameArray [ parsedPath . base ] ; } else { fileConfigs = [ ] ; } } else { fileConfigs = [ ] } console . log ( \":::~~Configurations from replaceFileName~~:::\" + fileConfigs ) ; newName = utils . getupdatedFileName ( parsedPath . name , fileConfigs , fls . input ) ; parsedPath . base = newName + parsedPath . ext ; parsedPath . name = newName ; return parsedPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get array of folders from base temp path [CODESPLIT] function ( parsedPath ) { var tempPathArray = tmpDir . split ( \"\\\\\" ) ; var parsedPathArray = parsedPath . dir . split ( \"\\\\\" ) ; if ( parseInt ( tempPathArray . length ) === parseInt ( parsedPathArray . length ) ) { return \"base\" ; } else if ( parseInt ( tempPathArray . length ) < parseInt ( parsedPathArray . length ) ) { var folderNameArray = [ ] ; for ( var i in parsedPathArray ) { if ( i > parseInt ( tempPathArray . length ) - 1 ) { folderNameArray . push ( parsedPathArray [ i ] ) ; } } return folderNameArray ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "update content of refrence directory files as per config provided by replaceContent key [CODESPLIT] function ( oldContent , replaceConfig , fls ) { var newContent = oldContent . replace ( contentReplaceRegx , function ( e ) { for ( var cont in replaceConfig ) { var contRegex = new RegExp ( cont , 'g' ) ; if ( e . match ( contRegex ) ) { var replaceValue = utils . getReplacableContent ( fls . input , replaceConfig [ cont ] ) ; return replaceValue ; } } } ) ; return newContent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy data from writed temp directory to destination drive [CODESPLIT] function ( ) { fse . emptyDirSync ( destFolderDir ) ; fse . copySync ( tmpDir , destFolderDir , { overwrite : true } , err => { if ( err ) { console . log ( ':::~~error in copying to destination directory:' + err + '~~:::' ) ; fse . removeSync ( destFolderDir ) ; fse . emptyDirSync ( tmpDir ) ; deferred . reject ( 'Error in copying to destination directory' ) ; } console . log ( ':::~~ destination directory created:' + dirName + '~~:::' ) ; } ) ; fse . emptyDirSync ( tmpDir ) ; console . log ( ':::~~Created new ' + dirType + \" / \" + dirName + ':::~~' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "string = > array [CODESPLIT] function scan ( text ) { let sr = SReader . create ( text ) ; let tokens = [ ] ; while ( ! sr . isDone ( ) ) { tokens . push ( readNext ( sr ) ) ; } return tokens ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "object = > object [CODESPLIT] function readNext ( sr ) { if ( sr . accept ( \"<!\" ) ) { return readComment ( sr ) ; } if ( sr . accept ( \"<\" ) ) { return readTag ( sr ) ; } return readText ( sr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "object = > object [CODESPLIT] function readText ( sr ) { let start = sr . getPos ( ) ; let value = sr . expectRE ( RE_TEXT ) ; return { type : \"text\" , start , value } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "object = > object [CODESPLIT] function readComment ( sr ) { let start = sr . getPos ( ) - 2 ; sr . expect ( \"--\" ) ; if ( ! sr . goto ( \"-->\" ) ) { throw Tools . syntaxError ( \"Unterminated comment\" , start ) ; } sr . expect ( \"-->\" ) ; return { type : \"comment\" , start } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "object = > object [CODESPLIT] function readTag ( sr ) { let start = sr . getPos ( ) - 1 ; let name ; if ( sr . accept ( \"/\" ) ) { name = sr . expectRE ( RE_TAG_NAME ) ; sr . expect ( \">\" ) ; return { type : \"tag_2\" , start , name } ; } name = sr . expectRE ( RE_TAG_NAME ) ; let props = { } ; while ( true ) { sr . acceptRE ( RE_WS ) ; if ( sr . accept ( \">\" ) ) { return { type : \"tag_1\" , start , name , props } ; } if ( sr . accept ( \"/\" ) ) { sr . expect ( \">\" ) ; return { type : \"tag_0\" , start , name , props } ; } let pName = sr . expectRE ( RE_PROP_NAME ) ; sr . acceptRE ( RE_WS ) ; sr . expect ( \"=\" ) ; sr . acceptRE ( RE_WS ) ; sr . expect ( '\"' ) ; let pValue = sr . expectRE ( RE_PROP_VALUE ) ; sr . expect ( '\"' ) ; props [ pName ] = pValue ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OpenStack Keystone Identity API client . [CODESPLIT] function KeystoneClient ( url , options ) { options = options || { } ; if ( options . username ) { if ( ! options . password && ! options . apiKey ) { throw new Error ( 'If username is provided you also need to provide password or apiKey' ) ; } } this . _url = url ; this . _username = options . username ; this . _apiKey = options . apiKey ; this . _password = options . password ; this . _extraArgs = options . extraArgs || { } ; this . _cacheTokenFor = options . cacheTokenFor || DEFAULT_CACHE_TOKEN_FOR ; this . _token = null ; this . _tokenExpires = null ; this . _refreshTokenCompletions = [ ] ; this . _tokenUpdated = 0 ; this . _tenantId = null ; this . _serviceCatalog = [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "object = > ( array | string ) [CODESPLIT] function packNode ( node ) { if ( node . type === \"#\" ) { return node . text ; } let item = [ node . type ] ; let hasProps = ( Object . keys ( node . props ) . length !== 0 ) ; if ( hasProps ) { item . push ( node . props ) ; } if ( node . children . length === 0 ) { return item ; } if ( ! hasProps ) { item . push ( 0 ) ; } node . children . forEach ( child => item . push ( packNode ( child ) ) ) ; return item ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( array | string ) = > array [CODESPLIT] function unpackNode ( item ) { if ( ! Array . isArray ( item ) ) { return { type : \"#\" , text : item } ; } let node = { type : item [ 0 ] , props : item [ 1 ] || { } , children : [ ] } ; for ( let i = 2 ; i < item . length ; i ++ ) { node . children . push ( unpackNode ( item [ i ] ) ) ; } return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A recursive function that finds all the parents of a given class . [CODESPLIT] function findAllParents ( p ) { var lastParent = p [ 0 ] ; var lastParentsParent = parents [ lastParent ] ; if ( lastParentsParent === undefined ) { return p ; } else { p . unshift ( lastParentsParent ) ; return findAllParents ( p ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds all the direct children of a given class name . [CODESPLIT] function findDirectChildren ( className ) { var children = [ ] ; for ( var longname in parents ) { if ( parents [ longname ] === className ) { children . push ( longname ) ; } } return children ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive function that creates a nested list of a class parents . [CODESPLIT] function makeHierarchyList ( classes ) { if ( classes . length === 0 ) { return '' ; } else { var className = classes . shift ( ) ; return '<ul><li>' + linkTo ( className ) + ' ' + makeHierarchyList ( classes ) + '</li></ul>' } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a list of child classes . [CODESPLIT] function makeChildrenList ( classes ) { var list = '<ul>' ; classes . forEach ( function ( className ) { list += '<li>' + linkTo ( className ) + '</li>' ; } ) list += '</ul>' ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add names to the parents map for every new doclet [CODESPLIT] function ( e ) { var doclet = e . doclet ; if ( doclet . kind === 'class' && doclet . augments !== undefined && doclet . augments . length > 0 ) { parents [ doclet . longname ] = doclet . augments [ 0 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * interface StringTransformOptions { contents : String fetcher : Fetcher filePath : String index : FetcherIndex } transform ( opts : StringTransformOptions ) = > String [CODESPLIT] function transform ( opts ) { var contents = opts . contents ; var index = opts . index ; var $ = cheerio . load ( contents ) ; $ ( 'link[href]' ) . each ( function ( ) { var el$ = $ ( this ) ; var href = el$ . attr ( 'href' ) ; var newHref = index . resolveLocalUrl ( href ) ; if ( href && href !== newHref ) { el$ . attr ( { 'data-appcache-href' : href , href : newHref } ) ; } } ) ; return $ . html ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A tag in the FamilySearch system . [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof Tag ) ) { return new Tag ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( Tag . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle the event of an option being seen . [CODESPLIT] function gotOption ( option ) { if ( map [ option ] ) { option = map [ option ] var name = option [ 0 ] // Assume a boolean, and set to true because the argument is present. var value = true // If it takes arguments, override with a value. var count = option [ 2 ] while ( count -- ) { value = argv [ ++ index ] if ( argv . length === index ) { return cli . error ( 'The \"' + name + '\" option requires an argument.' ) } } // If it needs type conversion, do it. var type = option [ 1 ] if ( type === 'Array' ) { value = value . split ( ',' ) } else if ( type === 'RegExp' ) { try { value = new RegExp ( value ) } catch ( e ) { return cli . error ( 'The \"' + name + '\" option received an invalid expression: \"' + value + '\".' ) } } else if ( type === 'Number' ) { var number = value * 1 if ( isNaN ( number ) ) { return cli . error ( 'The \"' + name + '\" option received a non-numerical argument: \"' + value + '\".' ) } } args [ name ] = value } else { return cli . error ( 'Unknown option: \"' + option + '\".' ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A common representation of an error on the FamilySearch platform . [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof Error ) ) { return new Error ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( Error . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ------- Base Writer ------- [CODESPLIT] function Writer ( options ) { this . options = _ . defaults ( options || { } , { template : '' , data : _ . identity } ) ; Writable . call ( this , { objectMode : true } ) ; this . _commits = [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The FamilySearch - proprietary model for a relationship between a child and a pair of parents . [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof ChildAndParentsRelationship ) ) { return new ChildAndParentsRelationship ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( ChildAndParentsRelationship . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "issues assumig format is Issues #issue [ #issue [ #issue ]] [CODESPLIT] function parse_issues ( body ) { var issues = null ; var content = body . match ( / \\s+(?:issues|closes)(?:,?\\s#([^,\\n]+))+ / i ) ; if ( content ) { issues = content [ 0 ] . match ( / #([^,\\n\\s]+) / g ) . map ( function ( issue ) { return issue . slice ( 1 ) ; } ) ; } return issues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LDS ordinance [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof Ordinance ) ) { return new Ordinance ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( Ordinance . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the paths and put their contents to a single list ( and optionally slice the contents ) [CODESPLIT] function getAllPathsAndOptionallySlice ( paths , state , slice = Immutable . List ( ) ) { let gotPaths = Immutable . List ( ) ; gotPaths = gotPaths . withMutations ( ( mutable ) => { paths . forEach ( ( gen ) => { if ( state . hasIn ( gen ) ) { let got = state . getIn ( gen ) ; if ( Immutable . List . isList ( got ) ) { if ( slice . size > 0 ) { mutable . push ( ... got . slice ( ... slice ) ) } else { mutable . push ( ... got ) } } else { mutable . push ( got ) ; } } } ) } ) ; return gotPaths ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A representation of metadata about an artifact such as a memory . [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof ArtifactMetadata ) ) { return new ArtifactMetadata ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( ArtifactMetadata . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Class description [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof Merge ) ) { return new Merge ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( Merge . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( array object ) = > array [CODESPLIT] function execute ( template , data ) { let result = [ ] ; template . forEach ( node => executeNode ( node , data , result ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( object object array ) = > undefined [CODESPLIT] function executeNode ( node , data , result ) { if ( node . type === \"#\" ) { executeText ( node , data , result ) ; return ; } if ( node . props . each ) { executeEach ( node , data , result ) ; return ; } if ( node . props . if ) { executeIf ( node , data , result ) ; return ; } if ( node . props . fi ) { executeFi ( node , data , result ) ; return ; } let props = { } ; Object . keys ( node . props ) . forEach ( key => { if ( key !== \"each\" && key !== \"if\" && key !== \"fi\" ) { props [ key ] = Extender . processProp ( node . props [ key ] , data ) ; } } ) ; let children = [ ] ; node . children . forEach ( child => executeNode ( child , data , children ) ) ; result . push ( { type : node . type , props , children } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( object object array ) = > undefined [CODESPLIT] function executeText ( node , data , result ) { result . push ( { type : \"#\" , text : Extender . processText ( node . text , data ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( object object array ) = > undefined [CODESPLIT] function executeEach ( node , data , result ) { let each = Extender . processEach ( node . props . each , data ) ; if ( ! each ) { return ; } let nextNode = { type : node . type , props : Object . assign ( { } , node . props ) , children : node . children } ; nextNode . props . each = null ; let nextData = Object . assign ( { } , data ) ; each . items . forEach ( item => { nextData [ each . item ] = item ; executeNode ( nextNode , nextData , result ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( object object array ) = > undefined [CODESPLIT] function executeFi ( node , data , result ) { if ( Extender . processExpr ( node . props . fi , data ) ) { return ; } let nextNode = { type : node . type , props : Object . assign ( { } , node . props ) , children : node . children } ; nextNode . props . fi = null ; executeNode ( nextNode , data , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * The constructor has some optional parameters : [CODESPLIT] function GracefulExpress ( options ) { options = options || { } ; this . server = null ; this . graceful = null ; var startFile = process . mainModule . filename ; this . _setOption ( 'inProcessTest' , options , / mocha$ / . test ( startFile ) ) ; this . reaperPollInterval = options . reaperPollInterval || 500 ; util . verifyType ( 'number' , this , 'reaperPollInterval' ) ; this . shuttingDown = false ; this . _serverClosed = false ; this . _responses = [ ] ; this . _sockets = [ ] ; this . _activeSockets = [ ] ; //both here for symmetry; unlikely that both of these are available on construction this . setGraceful ( options . graceful || Graceful . instance ) ; this . setServer ( options . server ) ; this . middleware = this . middleware . bind ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A description of a FamilySearch feature . [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof FeatureSet ) ) { return new FeatureSet ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( FeatureSet . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private instance methods ------------------------ [CODESPLIT] function invokeCallback ( cb , invokeMethod , valueOrReason , promise , type ) { var cbValue , cbError , errorThrown ; try { cbValue = cb [ invokeMethod ] ( null , valueOrReason ) ; } catch ( err ) { errorThrown = true , cbError = err ; } // send return values in promise chain to downstream promise if ( type === 'fulfill' ) { promise . _values = this . _values . concat ( [ valueOrReason ] ) ; } if ( ! errorThrown && cbValue && typeof cbValue . then === 'function' ) { cbValue . then ( function ( value ) { promise . fulfill ( value ) ; } , function ( reason ) { promise . reject ( reason ) ; } ) ; } else { ! errorThrown ? promise . fulfill ( cbValue ) : promise . reject ( cbError ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a cookie [CODESPLIT] function ( key ) { var tmp = window . document . cookie . match ( ( new RegExp ( key + '=[^;]+($|;)' , 'gi' ) ) ) ; if ( ! tmp || ! tmp [ 0 ] ) { return null ; } else { return window . unescape ( tmp [ 0 ] . substring ( key . length + 1 , tmp [ 0 ] . length ) . replace ( ';' , '' ) ) || null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set cookie use options to optionally specify days ( default = 1 ) path session only cookie etc ... [CODESPLIT] function ( key , value , options ) { var cookie = [ key + '=' + window . escape ( value ) ] , seconds , minutes , days , months , years , expiryDate , addDays ; //\tEnsure we have options options = options || { } ; if ( ! options . session ) { days = ( isNaN ( parseInt ( options . days , 10 ) ) ) ? 1 : parseInt ( options . days , 10 ) ; expiryDate = new Date ( ) ; addDays = ( days * 24 * 60 * 60 * 1000 ) ; expiryDate . setTime ( expiryDate . getTime ( ) + addDays ) ; cookie . push ( 'expires=' + expiryDate . toGMTString ( ) ) ; } if ( options . path ) { cookie . push ( 'path=' + options . path ) ; } if ( options . domain ) { cookie . push ( 'domain=' + options . domain ) ; } if ( options . secure ) { cookie . push ( 'secure' ) ; } if ( options . httponly ) { cookie . push ( 'httponly' ) ; } window . document . cookie = cookie . join ( '; ' ) ; return window . document . cookie ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Global config object - exposed to all plugins via get and set functions in the core [CODESPLIT] function ( name , info ) { if ( triggerPluginErrors ) { //\tIf we can notify the console //\tTODO: solejs support if ( window . console && console . error ) { if ( pluginErrors . hasOwnProperty ( name ) ) { console . error ( 'ulib ' + name + ' - ' + pluginErrors [ name ] + ( ( info ) ? info : '' ) ) ; } else { console . error ( 'ulib ' + name + ' - ' + pluginErrors . TriggerError + ( ( info ) ? info : '' ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Global config object - exposed to all plugins via get and set functions in the core [CODESPLIT] function ( coreArgs ) { var obj = { } , i ; //\tExtending ensures that we don't override the core by using 'this' in plugins for ( i in coreObj ) { if ( coreObj . hasOwnProperty ( i ) ) { obj [ i ] = coreObj [ i ] ; } } //\tOverride / add any properties for ( i in coreArgs ) { if ( coreArgs . hasOwnProperty ( i ) ) { obj [ i ] = coreArgs [ i ] ; } } //\tTODO: This only happens on setup; core is also called in the event manager //\tafter that, but it is re-evaluated, so we don't have the plugin name anymore ... doh. if ( typeof coreArgs . name !== undefined ) { obj . pluginName = coreArgs . name ; } else { handleError ( 'PluginDoesnotExist' , ' name not specified' ) ; } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Listen to events in the events manager [CODESPLIT] function ( name , func , pluginName ) { if ( pluginName !== undefined ) { currentPluginName = pluginName ; } var eventCurrentPluginName = currentPluginName , //\tCreate an event we can bind and register myEventFunc = function ( ) { var pubsubCore = pubsub . getCore ( ) ; currentPluginName = eventCurrentPluginName ; func . apply ( ( pubsubCore ? pubsubCore ( ) : pubsub ) , arguments ) ; } ; //\tRegister the plugin events and bind using pubsub pluginBindings [ this . pluginName ] = pluginBindings [ this . pluginName ] || [ ] ; pluginBindings [ this . pluginName ] . push ( { name : name , func : myEventFunc } ) ; pubsub . on ( name , myEventFunc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Global config object - exposed to all plugins via get and set functions in the core [CODESPLIT] function ( eve ) { capEve = eve . type . substring ( 0 , 1 ) . toUpperCase ( ) + eve . type . substring ( 1 ) ; coreObj [ 'on' + capEve ] = makeEvent ( eve . type ) ; pubsub . addEventType ( eve ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Global config object - exposed to all plugins via get and set functions in the core [CODESPLIT] function ( name ) { var i ; for ( i = 0 ; i < plugins . length ; i += 1 ) { if ( plugins [ i ] . name === name ) { return plugins [ i ] ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Global config object - exposed to all plugins via get and set functions in the core [CODESPLIT] function ( name , pluginObj ) { var hasPlugin = ! ! ( getPlugin ( name ) ) , i , j ; currentPluginName = name ; if ( ! hasPlugin ) { plugins . push ( { name : name , obj : pluginObj } ) ; setupPlugin ( plugins [ plugins . length - 1 ] ) ; } else { if ( pluginOverride ) { for ( i = 0 ; i < plugins . length ; i += 1 ) { if ( plugins [ i ] . name === name ) { //\tRemove events from the pubsub. if ( pluginBindings [ name ] ) { for ( j = 0 ; j < pluginBindings [ name ] . length ; j += 1 ) { pubsub . off ( pluginBindings [ name ] [ j ] . name , pluginBindings [ name ] [ j ] . func ) ; } } //\tRemove old plugin function, and setup new plugin delete plugins [ i ] . obj ; plugins [ i ] . obj = pluginObj ; setupPlugin ( plugins [ i ] ) ; return plugins [ i ] ; } } } else { handleError ( 'PluginAlreadyExists' , name ) ; return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Global config object - exposed to all plugins via get and set functions in the core [CODESPLIT] function ( plugin , config ) { var i , pc = pluginConfig [ \"*\" ] ; config = ( config !== undefined ) ? config : pluginConfig [ plugin . name ] ; //\tAdd properties from generic config if available if ( pc ) { config = config || { } ; for ( i in pc ) { if ( pc . hasOwnProperty ( i ) ) { if ( ! config . hasOwnProperty ( i ) ) { config [ i ] = pc [ i ] ; } } } } //  Use apply to expose core plugin . obj . apply ( core ( { name : plugin . name } ) , [ ( config !== undefined ) ? config : { } ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Information about a change . [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof ChangeInfo ) ) { return new ChangeInfo ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( ChangeInfo . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure that there is a github remote named github . [CODESPLIT] function ( repo ) { return p . spawn ( 'git' , [ 'remote' , 'show' , program . remote ] , CHILD_IGNORE ) . then ( function ( ) { /* OK, github already exists. */ } , function ( e ) { /* Doesn't exist, create it! */ return p . spawn ( 'git' , [ 'remote' , 'add' , program . remote , 'git@github.com:' + repo ] ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push to github . [CODESPLIT] function ( repo , branchname ) { return ensureRemote ( repo ) . then ( function ( ) { return p . spawn ( 'git' , [ 'push' , program . remote , 'HEAD:refs/heads/' + branchname ] , CHILD_IGNORE ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * interface StringTransformOptions { contents : String fetcher : Fetcher filePath : String index : FetcherIndex } transform ( opts : StringTransformOptions ) = > String [CODESPLIT] function transform ( opts ) { var contents = opts . contents ; var filePath = opts . filePath ; var lastScript$ ; var $ = cheerio . load ( contents ) ; if ( path . basename ( filePath ) === 'index.html' ) { lastScript$ = findLastScript ( $ ) ; if ( lastScript$ ) { lastScript$ . after ( '<script src=\"require.load.js\"></script>' ) ; } else { $ ( 'body' ) . append ( '<script src=\"require.load.js\"></script>' ) ; } } return $ . html ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * interface StringTransformOptions { contents : String fetcher : Fetcher filePath : String index : FetcherIndex } transform ( opts : StringTransformOptions ) = > String [CODESPLIT] function transform ( opts ) { var contents = opts . contents ; var filePath = opts . filePath ; var index = opts . index ; // original remote URL for the given CSS file var cssRemoteUrl = index . resolveRemoteUrl ( path . basename ( filePath ) ) ; return contents . replace ( / url\\(['\"\\s]*[^()'\"]+['\"\\s]*\\) / g , ( cssUrlStmt ) => { var cssUrl = cssUrlStmt . replace ( / url\\(['\"\\s]*([^()'\"]+)['\"\\s]*\\) / , '$1' ) ; var remoteUrl ; var localUrl ; if ( cssUrl . indexOf ( 'data:' ) === 0 ) { return cssUrlStmt ; // noop for Data URIs } remoteUrl = url . resolve ( cssRemoteUrl , cssUrl ) ; localUrl = index . resolveLocalUrl ( remoteUrl ) ; return 'url(' + localUrl + ')' ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Handle errors [CODESPLIT] function _filterToShape ( mutable , obj , shape , path = [ ] , fullObj = null ) { if ( fullObj === null ) { fullObj = obj ; } // Filter object (Complex filter operation) if ( isImmutableJsMap ( shape ) && shape . has ( SHAPE_FILTER_KEY ) && shape . get ( SHAPE_FILTER_KEY ) === true ) { processFilterObject ( mutable , shape , obj , path , fullObj ) ; return ; } shape . forEach ( ( value , key ) => { // TRUE (Get full key subtree) if ( value === true ) { if ( obj . has ( key ) ) { mutable . setIn ( path . concat ( key ) , obj . get ( key ) ) ; } } // STRING (Edit path) else if ( typeof value === 'string' ) { if ( obj . has ( key ) ) { let editedPath = processShapeEditPath ( value , path . concat ( key ) ) if ( editedPath . size <= 0 ) { return ; } mutable . setIn ( editedPath , obj . get ( key ) ) ; } } // LIST (Select keys) else if ( Immutable . List . isList ( value ) ) { processList ( mutable , key , value , obj , path , fullObj ) ; } // MAP (Go deeper) else // filter key { // Consider maps only if ( isImmutableJsMap ( value ) ) { if ( obj . has ( key ) ) { // Nested filter _filterToShape ( mutable , obj . get ( key ) , shape . get ( key ) , cloneDeep ( path . concat ( key ) ) , fullObj ) ; } } } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Incorporate a speed sampling into the mean speed and ( running ) variance . [CODESPLIT] function recordSpeed ( child , speed ) { child . runCount += sampleSize if ( passCount > 1 ) { var square = Math . pow ( speed - child . speed , 2 ) child . variance += ( square - child . variance ) / ( passCount - 1 ) } child . speed += ( speed - child . speed ) / passCount }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reference the next child ( if possible ) and start running its function . [CODESPLIT] function nextChild ( ) { child = children [ childIndex ++ ] if ( child ) { fn = child . fn runIndex = 0 var runFn = / ^function.*?\\([^\\s\\)] / . test ( fn . toString ( ) ) ? runAsync : runSync start = process . hrtime ( ) runFn ( ) } else { calculateStats ( ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the current child s test function synchronously . [CODESPLIT] function runSync ( ) { for ( runIndex = 0 ; runIndex < sampleSize ; runIndex ++ ) { fn . call ( child ) } setTimeout ( finishChild , 0 ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the current child s test function asynchronously . [CODESPLIT] function runAsync ( ) { if ( runIndex ++ < sampleSize ) { fn . call ( child , function ( ) { setTimeout ( runAsync , 0 ) } ) } else { setTimeout ( finishChild , 0 ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this module fileToReadable ( file : VFile ) = > stream . Readable [CODESPLIT] function fileToReadable ( file ) { class VFileReadable extends stream . Readable { _read ( ) { this . push ( file ) ; this . push ( null ) ; } } return new VFileReadable ( { objectMode : true } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "interface TransformDOMTextOptions { filePath : String getText : ( el$ : CheerioElement ) = > String el$ : CheerioElement setText : ( el$ : CheerioElement text : String ) = > Void transforms : stream . Transform [] } transformText ( opts : TransformTextOptions ) = > Promise [CODESPLIT] function transformDOMText ( opts ) { return new Promise ( ( resolve , reject ) => { var file = new VFile ( { path : opts . filePath , contents : new Buffer ( opts . getText ( opts . el$ ) , 'utf8' ) // eslint-disable-line node/no-deprecated-api // TODO: drop Node.js 4.x support, use `Buffer.from()` instead } ) ; var readable = fileToReadable ( file ) ; utils . pipeTransforms ( readable , opts . transforms ) . on ( 'error' , reject ) . on ( 'end' , ( ) => { opts . setText ( opts . el$ , file . contents . toString ( 'utf8' ) ) ; resolve ( ) ; } ) . resume ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * interface StringTransformOptions { contents : String fetcher : Fetcher filePath : String index : FetcherIndex } transform ( opts : StringTransformOptions ) = > String [CODESPLIT] function transform ( opts ) { var contents = opts . contents ; var $ = cheerio . load ( contents ) ; var cssTransforms = opts . fetcher . transforms . css . map ( ( tf ) => tf ( { fetcher : opts . fetcher , index : opts . index } ) ) ; // start parallel processing streams, one for each style tag var tasks = [ ] . concat ( // style attributes $ ( '[style]' ) . toArray ( ) . map ( ( el ) => transformDOMText ( { filePath : opts . filePath , getText : getAttrText , // get from attribute el$ : $ ( el ) , setText : setAttrText , // set attribute transforms : cssTransforms } ) ) , // style tags $ ( 'style' ) . toArray ( ) . map ( ( el ) => transformDOMText ( { filePath : opts . filePath , getText : getTagText , // get from textContent el$ : $ ( el ) , setText : setTagText , // set textContent transforms : cssTransforms } ) ) ) ; return Promise . all ( tasks ) // all styles have been processed, output correct HTML . then ( ( ) => $ . html ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Comment on a discussion [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof Comment ) ) { return new Comment ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( Comment . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( object object ) = > object [CODESPLIT] function instance ( state , methods ) { let api = { } ; Object . keys ( methods ) . forEach ( key => { api [ key ] = methods [ key ] . bind ( null , state ) ; } ) ; return api ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( string number ) = > object [CODESPLIT] function syntaxError ( message , pos ) { let err = Error ( message ) ; err . name = \"SyntaxError\" ; err . pos = pos ; return err ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recurse to find directories we can watch . [CODESPLIT] function watch ( dir ) { if ( ! ignoreDir . test ( dir ) && ! map [ dir ] ) { fs . lstat ( dir , function ( e , stat ) { if ( ! e ) { if ( stat . isSymbolicLink ( ) ) { var source = dir fs . readlink ( source , function ( e , link ) { if ( ! e ) { var dest = link if ( dest [ 0 ] !== '/' ) { while ( dest . substr ( 0 , 3 ) === '../' ) { dest = dest . substr ( 3 ) source = source . replace ( / \\/[^\\/]+$ / , '' ) } if ( dest . substr ( 0 , 2 ) === './' ) { dest = dest . substr ( 2 ) } dest = source + '/' + dest } watch ( dest ) } } ) } else if ( stat . isDirectory ( ) ) { addDir ( dir , stat ) } else { dir = dirname ( dir ) map [ dir ] = Math . max ( map [ dir ] , stat . mtime . getTime ( ) ) } } } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a watchable directory to the map and list of directories we re watching . [CODESPLIT] function addDir ( dir , stat ) { var mtime = stat . mtime . getTime ( ) if ( ! map [ dir ] && list . length <= maxListSize ) { map [ dir ] = mtime list . push ( dir ) clearTimeout ( sortList . timer ) sortList . timer = setTimeout ( sortList , checkInterval ) fs . readdir ( dir , function ( e , files ) { if ( ! e ) { files . forEach ( function ( file ) { watch ( dir + '/' + file ) } ) } } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate over the age - prioritized list and start fs watches . [CODESPLIT] function startWatches ( ) { list . forEach ( function ( dir , i ) { if ( i < maxFsWatches ) { try { fs . watch ( dir , function ( op , file ) { notify ( dir + '/' + file ) } ) } catch ( e ) { // fs.watch is known to be unstable. } } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check a directory for changes . [CODESPLIT] function checkDir ( ) { var n = indexes [ i ] if ( i > 44 ) { indexes [ i ] = ( indexes [ i ] + 5 ) % list . length } i = ( i + 1 ) % indexes . length var dir = list [ n ] if ( dir ) { fs . stat ( dir , function ( e , stat ) { if ( ! e && ( stat . mtime > okToNotifyAfter ) ) { fs . readdir ( dir , function ( e , files ) { if ( ! e ) { files . forEach ( function ( file ) { var path = dir + '/' + file fs . stat ( path , function ( e , stat ) { if ( ! e && ( stat . mtime > okToNotifyAfter ) ) { notify ( path ) } } ) } ) } } ) } } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notify the master process that something changed . [CODESPLIT] function notify ( path ) { var now = Date . now ( ) if ( ( now > okToNotifyAfter ) && ! ignoreFile . test ( path ) ) { process . send ( path ) okToNotifyAfter = now + notifyInterval sortList ( ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * The constructor has no required parameters . Optional parameters : [CODESPLIT] function Graceful ( options ) { /*jshint maxcomplexity: 9 */ options = options || { } ; this . shuttingDown = false ; this . _checks = [ ] ; this . _sending = false ; this . pollInterval = options . pollInterval || 250 ; localUtil . verifyType ( 'number' , this , 'pollInterval' ) ; this . timeout = options . timeout || 5 * 1000 ; localUtil . verifyType ( 'number' , this , 'timeout' ) ; this . messenger = options . messenger || require ( 'thehelp-last-ditch' ) ; localUtil . verifyType ( 'function' , this , 'messenger' ) ; this . log = options . log || logShim ( 'thehelp-cluster:graceful' ) ; localUtil . verifyLog ( this . log ) ; var _this = this ; this . addCheck ( function areWeSending ( ) { return _this . _sending === false ; } ) ; this . _process = options . _process || process ; this . _cluster = options . _cluster || cluster ; this . _logPrefix = localUtil . getLogPrefix ( ) ; this . _setupListeners ( ) ; if ( Graceful . instance ) { this . log . warn ( 'More than one Graceful instance created in this process. ' + 'There are now duplicate process-level wireups!' ) ; } Graceful . instance = this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decorate a mock function with chainable methods . [CODESPLIT] function decorateFn ( fn ) { fn . returns = function ( value ) { fn . _returns = value return fn } return fn }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a MockDate using a Date constructor value . [CODESPLIT] function MockDate ( value ) { // A MockDate constructs an inner date and exposes its methods. var innerDate // If a value is specified, use it to construct a real date. if ( arguments . length ) { innerDate = new timers . Date ( value ) // If time isn't currently mocked, construct a real date for the real time. } else if ( global . Date === timers . Date ) { innerDate = new timers . Date ( ) // If there's no value and time is mocked, use the current mock time. } else { innerDate = new timers . Date ( mock . time . _CURRENT_TIME ) } Object . defineProperty ( this , '_INNER_DATE' , { enumerable : false , value : innerDate } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If mock time is moving forward schedule a time check . [CODESPLIT] function moveTime ( ) { if ( mock . time . _SPEED ) { // Remember what the real time was before updating. mock . time . _PREVIOUS_TIME = realNow ( ) // Set time to be incremented. setTimeout ( function ( ) { var now = realNow ( ) var elapsed = now - mock . time . _PREVIOUS_TIME if ( elapsed ) { var add = elapsed * mock . time . _SPEED mock . time . add ( add ) } moveTime ( ) } , 0 ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The getScheduler returns mocks for setTimeout and setInterval . [CODESPLIT] function getScheduler ( isInterval ) { return function ( fn , time ) { schedules . push ( { id : ++ schedules . id , fn : fn , time : Date . now ( ) + time , interval : isInterval ? time : false } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The getUnscheduler returns mocks for clearTimeout and clearInterval . [CODESPLIT] function getUnscheduler ( ) { // TODO: Create a map of IDs if the schedules array gets large. return function ( id ) { for ( var i = 0 , l = schedules . length ; i < l ; i ++ ) { var schedule = schedules [ i ] if ( schedule . id === id ) { schedules . splice ( i , 1 ) break } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When mock . time . add is called run schedules whose time has come . [CODESPLIT] function runSchedules ( ) { // Sort by descending time order. schedules . sort ( function ( a , b ) { return b . time - a . time } ) // Track the soonest interval run time, in case we're already there. var minNewTime = Number . MAX_VALUE // Iterate, from the end until we reach the current mock time. var i = schedules . length - 1 var schedule = schedules [ i ] while ( schedule && ( schedule . time <= mock . time . _CURRENT_TIME ) ) { schedule . fn ( ) // setTimeout schedules can be deleted. if ( ! schedule . interval ) { schedules . splice ( i , 1 ) // setInterval schedules should schedule the next run. } else { schedule . time += schedule . interval minNewTime = Math . min ( minNewTime , schedule . time ) } schedule = schedules [ -- i ] } // If an interval schedule is in the past, catch it up. if ( minNewTime <= mock . time . _CURRENT_TIME ) { process . nextTick ( runSchedules ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * The constructor requires only one parameter worker a callback which starts a worker process . Optional parameters : [CODESPLIT] function Startup ( options ) { /*jshint maxcomplexity: 11 */ options = options || { } ; this . _logPrefix = util . getLogPrefix ( ) ; this . worker = options . worker ; if ( ! this . worker ) { throw new Error ( 'Need to provide a worker callback!' ) ; } util . verifyType ( 'function' , this , 'worker' ) ; this . _stats = options . stats || new StatsD ( { prefix : process . env . THEHELP_APP_NAME + '.' } ) ; this . log = options . log || logShim ( 'thehelp-cluster:startup' ) ; util . verifyLog ( this . log ) ; this . masterOptions = options . masterOptions ; this . master = options . master || this . _defaultMasterStart . bind ( this ) ; util . verifyType ( 'function' , this , 'master' ) ; this . graceful = options . graceful || Graceful . instance ; // graceful supercedes messenger if ( ! this . graceful ) { this . messenger = options . messenger || require ( 'thehelp-last-ditch' ) ; util . verifyType ( 'function' , this , 'messenger' ) ; } else { util . verifyGraceful ( this . graceful ) ; } this . _domain = domain . create ( ) ; this . _domain . on ( 'error' , this . _onError . bind ( this ) ) ; this . _process = options . _process || process ; this . _cluster = options . _cluster || cluster ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start a gc task if options dictate it . GC task will kick off occasionally to reap expired versions of records . [CODESPLIT] function startGc ( db , options ) { this . options = options || { } var freqMs = options . gcFreqMs || 60000 var maxVersions = options . gcMaxVersions var maxAge = options . gcMaxAge var backup = options . gcBackup var callback = options . gcCallback if ( maxAge || maxVersions ) { maxAge = maxAge || Math . pow ( 2 , 53 ) maxVersion = maxVersions || Math . pow ( 2 , 53 ) function filter ( record ) { if ( record . version != null ) { if ( Date . now ( ) - record . version > maxAge ) return true } if ( record . key != this . currentKey ) { this . currentKey = record . key this . currentCount = 0 } return this . currentCount ++ >= maxVersions } this . scanner = gc ( db , filter , backup ) return looseInterval ( scanner . run . bind ( scanner ) , freqMs , callback ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this module pipeTransforms ( stream : Readable transforms : Transforms [] ) = > Readable [CODESPLIT] function pipeTransforms ( stream , transforms ) { var head , rest ; if ( ! Array . isArray ( transforms ) || ! transforms . length ) { return stream ; } head = transforms [ 0 ] ; rest = transforms . slice ( 1 ) ; // recursively pipe to remaining Transforms return pipeTransforms ( stream . pipe ( head ) , rest ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "streamify ( { index : FetcherIndex } transform : Function ) = > Stream [CODESPLIT] function streamify ( opts , transform ) { return through2 . obj ( // (vfile: VinylFile, enc: String, cb: Function) ( vfile , enc , cb ) => { var contents = vfile . contents . toString ( enc ) ; var result ; var onSuccess = ( contents ) => { vfile . contents = new Buffer ( contents , enc ) ; // eslint-disable-line node/no-deprecated-api // TODO: drop Node.js 4.x support, use `Buffer.from()` instead cb ( null , vfile ) ; } ; var onError = ( err ) => { cb ( err ) ; } ; try { result = transform ( { contents : contents , fetcher : opts . fetcher , filePath : vfile . path , index : opts . index } ) ; } catch ( err ) { onError ( err ) ; return ; } if ( isPromise ( result ) ) { result . then ( onSuccess ) . catch ( onError ) ; return ; } onSuccess ( result ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "intended to be used with Array#filter () [CODESPLIT] function ( entry ) { var parsed = url . parse ( entry , true , true ) ; return ! parsed . protocol || values . FETCH_PROTOCOLS . indexOf ( parsed . protocol ) !== - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extra information about a name form . [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof NameFormInfo ) ) { return new NameFormInfo ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( NameFormInfo . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Class description [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof MergeConflict ) ) { return new MergeConflict ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( MergeConflict . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OAuth 2 token responses [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof OAuth2 ) ) { return new OAuth2 ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( OAuth2 . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets value back to the given min - max range if necessary [CODESPLIT] function forceInRange ( value , min , max ) { if ( value > max ) { return max ; } else if ( value < min ) { return min ; } else { return value ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert item into the list at a given position [CODESPLIT] function insertIntoList ( item , position , list ) { var before = list . slice ( 0 , position ) ; var after = list . slice ( position ) ; return before . push ( item ) . concat ( after ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "array = > array [CODESPLIT] function parse ( tokens ) { let tr = TReader . create ( prepareTokens ( tokens ) ) ; let nodes = [ ] ; while ( true ) { if ( tr . accept ( \"$\" ) ) { return nodes ; } if ( tr . accept ( \"text\" ) ) { nodes . push ( parseText ( tr ) ) ; } else if ( tr . accept ( \"tag_0\" ) ) { nodes . push ( parseTag0 ( tr ) ) ; } else { tr . expect ( \"tag_1\" ) ; nodes . push ( parseTag1 ( tr ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "array = > array [CODESPLIT] function prepareTokens ( tokens ) { let result = [ ] ; let lastToken = null ; tokens . forEach ( token => { let newToken = null ; if ( token . type === \"text\" ) { let value = token . value . replace ( GRE_WS , \" \" ) . trim ( ) ; if ( value !== \"\" ) { if ( lastToken && lastToken . type === \"text\" ) { lastToken . value += value ; } else { newToken = { type : \"text\" , start : token . start , value } ; } } } else if ( token . type !== \"comment\" ) { newToken = token ; } if ( newToken ) { result . push ( newToken ) ; lastToken = newToken ; } } ) ; result . push ( { type : \"$\" } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "object = > object [CODESPLIT] function parseTag1 ( tr ) { let startToken = tr . getToken ( ) ; let node = initTagNode ( startToken ) ; while ( true ) { if ( tr . accept ( \"text\" ) ) { node . children . push ( parseText ( tr ) ) ; } else if ( tr . accept ( \"tag_0\" ) ) { node . children . push ( parseTag0 ( tr ) ) ; } else if ( tr . accept ( \"tag_1\" ) ) { node . children . push ( parseTag1 ( tr ) ) ; } else if ( tr . accept ( \"tag_2\" ) ) { let token = tr . getToken ( ) ; if ( token . name !== startToken . name ) { let msg = ` ${ token . name } ` ; throw Tools . syntaxError ( msg , token . start ) ; } return node ; } else { let msg = ` ${ startToken . name } ` ; throw Tools . syntaxError ( msg , startToken . start ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "object = > object [CODESPLIT] function initTagNode ( token ) { validateProps ( token ) ; return { type : token . name , props : token . props , children : [ ] } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "object = > undefined [CODESPLIT] function validateProps ( token ) { Object . keys ( token . props ) . forEach ( key => { if ( ! validateProp ( key , token . props [ key ] ) ) { throw Tools . syntaxError ( ` ${ key } ` , token ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( string string ) = > boolean [CODESPLIT] function validateProp ( key , value ) { switch ( key ) { case \"each\" : return Extender . validateEach ( value ) ; case \"if\" : case \"fi\" : return Extender . validateExpr ( value ) ; default : return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( string object ) = > any [CODESPLIT] function processProp ( value , data ) { return RE_EXPR . test ( value ) ? processExpr ( value , data ) : processText ( value , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( string object ) = > string [CODESPLIT] function processText ( value , data ) { return value . replace ( GRE_EXPR , m => { let res = processExpr ( m , data ) ; return Tools . isVoid ( res ) ? \"\" : res + \"\" ; } ) . replace ( GRE_WS , \" \" ) . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( string object ) = > any [CODESPLIT] function processExpr ( value , data ) { if ( value === \"true\" ) { return true ; } if ( value === \"false\" ) { return false ; } let m = value . match ( RE_EXPR ) ; if ( ! m ) { return null ; } return m [ 1 ] ? processPath ( m [ 1 ] , data ) : parseFloat ( m [ 2 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( string object ) = > object | null [CODESPLIT] function processEach ( value , data ) { let m = value . match ( RE_EACH ) ; if ( ! m ) { return null ; } let items = processPath ( m [ 2 ] , data ) ; if ( ! Array . isArray ( items ) ) { items = [ ] ; } return { item : m [ 1 ] , items } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( array object ) = > any [CODESPLIT] function processPathArray ( path , data ) { if ( ! data ) { return null ; } let value = data [ path [ 0 ] ] ; return path . length > 1 ? processPathArray ( path . slice ( 1 ) , value ) : value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A named event [CODESPLIT] function Event ( name , attributes ) { this . _name = name ; this . _stopped = false ; this . _attrs = { } ; if ( attributes ) { this . setAttributes ( attributes ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "readInt32BE ( value number [ offest ] ) [CODESPLIT] function readUInt64BE ( buf , offset ) { if ( offset ) { buf = buf . slice ( offset , offset + 8 ) ; } // create a hex equivalent string: let str = buf . toString ( 'hex' ) ; str = str . split ( '' ) ; let solution = 0 ; let mul = 15 ; str . forEach ( ( num ) => { let dec = getDecimal ( num ) ; solution += dec * Math . pow ( 16 , mul ) ; mul -- ; } ) ; return solution ; // (value position 0 * 16^15) + (value position 1 * 16^14) + ... +  (value position 7 * 16^0) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "string = > object [CODESPLIT] function create ( text ) { return Tools . instance ( { text , pos : 0 } , { isDone , getPos , expect , accept , expectRE , acceptRE , goto } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( object object ) = > string [CODESPLIT] function expectRE ( $ , regexp ) { let str = acceptRE ( $ , regexp ) ; if ( str === null ) { throw Tools . syntaxError ( \"Unexpected character\" , $ . pos ) ; } return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( object string ) = > boolean [CODESPLIT] function accept ( $ , str ) { if ( ! $ . text . startsWith ( str , $ . pos ) ) { return false ; } $ . pos += str . length ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( object object ) = > string | null [CODESPLIT] function acceptRE ( $ , regexp ) { let m = $ . text . substr ( $ . pos ) . match ( regexp ) ; if ( ! m ) { return null ; } let str = m [ 0 ] ; $ . pos += str . length ; return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( object string ) = > boolean [CODESPLIT] function goto ( $ , str ) { let index = $ . text . indexOf ( \"-->\" , $ . pos ) ; if ( index === - 1 ) { return false ; } $ . pos = index ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * interface StringTransformOptions { contents : String fetcher : Fetcher filePath : String index : FetcherIndex } transform ( opts : StringTransformOptions ) = > String [CODESPLIT] function transform ( opts ) { var contents = opts . contents ; var $ = cheerio . load ( contents ) ; $ ( 'html' ) . removeAttr ( 'manifest' ) ; // drop AppCache manifest attributes return $ . html ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Information about feedback for places . [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof FeedbackInfo ) ) { return new FeedbackInfo ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( FeedbackInfo . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LDS ordinance reservation [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof Reservation ) ) { return new Reservation ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( Reservation . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( object string ) = > undefined [CODESPLIT] function expect ( $ , type ) { if ( ! accept ( $ , type ) ) { let token = $ . tokens [ $ . pos ] ; throw Tools . syntaxError ( \"Unexpected token\" , token . start ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( object string ) = > boolean [CODESPLIT] function accept ( $ , type ) { let token = $ . tokens [ $ . pos ] ; if ( token . type !== type ) { return false ; } $ . pos ++ ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * The constructor has no required parameters . Optional parameters : [CODESPLIT] function Master ( options ) { /*jshint maxcomplexity: 12 */ options = options || { } ; this . _workers = { } ; this . shuttingDown = false ; this . spinTimeout = options . spinTimeout || 10 * 1000 ; util . verifyType ( 'number' , this , 'spinTimeout' ) ; this . delayStart = options . delayStart || 60 * 1000 ; util . verifyType ( 'number' , this , 'delayStart' ) ; this . pollInterval = options . pollInterval || 500 ; util . verifyType ( 'number' , this , 'pollInterval' ) ; this . killTimeout = options . killTimeout || 7000 ; util . verifyType ( 'number' , this , 'killTimeout' ) ; this . numberWorkers = options . numberWorkers || parseInt ( process . env . THEHELP_NUMBER_WORKERS , 10 ) || 1 ; util . verifyType ( 'number' , this , 'numberWorkers' ) ; this . setGraceful ( options . graceful || Graceful . instance ) ; this . log = options . log || logShim ( 'thehelp-cluster:master' ) ; util . verifyLog ( options . log ) ; this . _cluster = options . _cluster || cluster ; this . _cluster . on ( 'disconnect' , this . _restartWorker . bind ( this ) ) ; if ( Master . instance ) { this . log . warn ( 'More than one Master instance created in this process. ' + 'You\\'ll have more worker processes than you signed up for!' ) ; } Master . instance = this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Information about a search . [CODESPLIT] function ( json ) { // Protect against forgetting the new keyword when calling the constructor if ( ! ( this instanceof SearchInfo ) ) { return new SearchInfo ( json ) ; } // If the given object is already an instance then just return it. DON'T copy it. if ( SearchInfo . isInstance ( json ) ) { return json ; } this . init ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscription topic [CODESPLIT] function Topic ( name , options , emitter ) { this . name = name ; this . subscribers = [ ] ; this . queue = [ ] ; this . publishedEvents = { } ; this . options = options || { } ; this . emitter = emitter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscription manager [CODESPLIT] function PubSub ( name , options ) { EventEmitter . call ( this ) ; this . name = name ; this . topics = { } ; this . options = options || { strict : true } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simultaneously processes all items in the given array . [CODESPLIT] function asyncForEach ( array , iterator , done ) { if ( array . length === 0 ) { // NOTE: Normally a bad idea to mix sync and async, but it's safe here because // of the way that this method is currently used by DirectoryReader. done ( ) ; return ; } // Simultaneously process all items in the array. let pending = array . length ; array . forEach ( item => { iterator ( item , ( ) => { if ( -- pending === 0 ) { done ( ) ; } } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the buffered output from an asynchronous { @link DirectoryReader } via an error - first callback or a { @link Promise } . [CODESPLIT] function readdirAsync ( dir , options , callback , internalOptions ) { if ( typeof options === 'function' ) { callback = options ; options = undefined ; } return maybe ( callback , new Promise ( ( ( resolve , reject ) => { let results = [ ] ; internalOptions . facade = asyncFacade ; let reader = new DirectoryReader ( dir , options , internalOptions ) ; let stream = reader . stream ; stream . on ( 'error' , err => { reject ( err ) ; stream . pause ( ) ; } ) ; stream . on ( 'data' , result => { results . push ( result ) ; } ) ; stream . on ( 'end' , ( ) => { resolve ( results ) ; } ) ; } ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls a function with the given arguments and ensures that the error - first callback is _always_ invoked exactly once even if the function throws an error . [CODESPLIT] function safeCall ( fn , args ) { // Get the function arguments as an array args = Array . prototype . slice . call ( arguments , 1 ) ; // Replace the callback function with a wrapper that ensures it will only be called once let callback = call . once ( args . pop ( ) ) ; args . push ( callback ) ; try { fn . apply ( null , args ) ; } catch ( err ) { callback ( err ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a wrapper function that ensures the given callback function is only called once . Subsequent calls are ignored unless the first argument is an Error in which case the error is thrown . [CODESPLIT] function callOnce ( fn ) { let fulfilled = false ; return function onceWrapper ( err ) { if ( ! fulfilled ) { fulfilled = true ; return fn . apply ( this , arguments ) ; } else if ( err ) { // The callback has already been called, but now an error has occurred // (most likely inside the callback function). So re-throw the error, // so it gets handled further up the call stack throw err ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Aynchronous readdir ( accepts an error - first callback or returns a { @link Promise } ) . Results are an array of { @link fs . Stats } objects . [CODESPLIT] function readdirAsyncStat ( dir , options , callback ) { return readdirAsync ( dir , options , callback , { stats : true } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@typedef { Object } FSFacade @property { fs . readdir } readdir @property { fs . stat } stat @property { fs . lstat } lstat Validates and normalizes the options argument [CODESPLIT] function normalizeOptions ( options , internalOptions ) { if ( options === null || options === undefined ) { options = { } ; } else if ( typeof options !== 'object' ) { throw new TypeError ( 'options must be an object' ) ; } let recurseDepth , recurseFn , recurseRegExp , recurseGlob , deep = options . deep ; if ( deep === null || deep === undefined ) { recurseDepth = 0 ; } else if ( typeof deep === 'boolean' ) { recurseDepth = deep ? Infinity : 0 ; } else if ( typeof deep === 'number' ) { if ( deep < 0 || isNaN ( deep ) ) { throw new Error ( 'options.deep must be a positive number' ) ; } else if ( Math . floor ( deep ) !== deep ) { throw new Error ( 'options.deep must be an integer' ) ; } else { recurseDepth = deep ; } } else if ( typeof deep === 'function' ) { recurseDepth = Infinity ; recurseFn = deep ; } else if ( deep instanceof RegExp ) { recurseDepth = Infinity ; recurseRegExp = deep ; } else if ( typeof deep === 'string' && deep . length > 0 ) { recurseDepth = Infinity ; recurseGlob = globToRegExp ( deep , { extended : true , globstar : true } ) ; } else { throw new TypeError ( 'options.deep must be a boolean, number, function, regular expression, or glob pattern' ) ; } let filterFn , filterRegExp , filterGlob , filter = options . filter ; if ( filter !== null && filter !== undefined ) { if ( typeof filter === 'function' ) { filterFn = filter ; } else if ( filter instanceof RegExp ) { filterRegExp = filter ; } else if ( typeof filter === 'string' && filter . length > 0 ) { filterGlob = globToRegExp ( filter , { extended : true , globstar : true } ) ; } else { throw new TypeError ( 'options.filter must be a function, regular expression, or glob pattern' ) ; } } let sep = options . sep ; if ( sep === null || sep === undefined ) { sep = path . sep ; } else if ( typeof sep !== 'string' ) { throw new TypeError ( 'options.sep must be a string' ) ; } let basePath = options . basePath ; if ( basePath === null || basePath === undefined ) { basePath = '' ; } else if ( typeof basePath === 'string' ) { // Append a path separator to the basePath, if necessary if ( basePath && basePath . substr ( - 1 ) !== sep ) { basePath += sep ; } } else { throw new TypeError ( 'options.basePath must be a string' ) ; } // Convert the basePath to POSIX (forward slashes) // so that glob pattern matching works consistently, even on Windows let posixBasePath = basePath ; if ( posixBasePath && sep !== '/' ) { posixBasePath = posixBasePath . replace ( new RegExp ( '\\\\' + sep , 'g' ) , '/' ) ; /* istanbul ignore if */ if ( isWindows ) { // Convert Windows root paths (C:\\) and UNCs (\\\\) to POSIX root paths posixBasePath = posixBasePath . replace ( / ^([a-zA-Z]\\:\\/|\\/\\/) / , '/' ) ; } } // Determine which facade methods to use let facade ; if ( options . fs === null || options . fs === undefined ) { // The user didn't provide their own facades, so use our internal ones facade = internalOptions . facade ; } else if ( typeof options . fs === 'object' ) { // Merge the internal facade methods with the user-provided `fs` facades facade = Object . assign ( { } , internalOptions . facade ) ; facade . fs = Object . assign ( { } , internalOptions . facade . fs , options . fs ) ; } else { throw new TypeError ( 'options.fs must be an object' ) ; } return { recurseDepth , recurseFn , recurseRegExp , recurseGlob , filterFn , filterRegExp , filterGlob , sep , basePath , posixBasePath , facade , emit : ! ! internalOptions . emit , stats : ! ! internalOptions . stats , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the { @link fs . Stats } for the given path . If the path is a symbolic link then the Stats of the symlink s target are returned instead . If the symlink is broken then the Stats of the symlink itself are returned . [CODESPLIT] function stat ( fs , path , callback ) { let isSymLink = false ; call . safe ( fs . lstat , path , ( err , lstats ) => { if ( err ) { // fs.lstat threw an eror return callback ( err ) ; } try { isSymLink = lstats . isSymbolicLink ( ) ; } catch ( err2 ) { // lstats.isSymbolicLink() threw an error // (probably because fs.lstat returned an invalid result) return callback ( err2 ) ; } if ( isSymLink ) { // Try to resolve the symlink symlinkStat ( fs , path , lstats , callback ) ; } else { // It's not a symlink, so return the stats as-is callback ( null , lstats ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the { @link fs . Stats } for the target of the given symlink . If the symlink is broken then the Stats of the symlink itself are returned . [CODESPLIT] function symlinkStat ( fs , path , lstats , callback ) { call . safe ( fs . stat , path , ( err , stats ) => { if ( err ) { // The symlink is broken, so return the stats for the link itself return callback ( null , lstats ) ; } try { // Return the stats for the resolved symlink target, // and override the `isSymbolicLink` method to indicate that it's a symlink stats . isSymbolicLink = ( ) => true ; } catch ( err2 ) { // Setting stats.isSymbolicLink threw an error // (probably because fs.stat returned an invalid result) return callback ( err2 ) ; } callback ( null , stats ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link stream . Readable } of an asynchronous { @link DirectoryReader } . [CODESPLIT] function readdirStream ( dir , options , internalOptions ) { internalOptions . facade = streamFacade ; let reader = new DirectoryReader ( dir , options , internalOptions ) ; return reader . stream ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A facade that allows { @link Array . forEach } to be called as though it were asynchronous . [CODESPLIT] function syncForEach ( array , iterator , done ) { array . forEach ( item => { iterator ( item , ( ) => { // Note: No error-handling here because this is currently only ever called // by DirectoryReader, which never passes an `error` parameter to the callback. // Instead, DirectoryReader emits an \"error\" event if an error occurs. } ) ; } ) ; done ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the buffered output from a synchronous { @link DirectoryReader } . [CODESPLIT] function readdirSync ( dir , options , internalOptions ) { internalOptions . facade = syncFacade ; let reader = new DirectoryReader ( dir , options , internalOptions ) ; let stream = reader . stream ; let results = [ ] ; let data = stream . read ( ) ; while ( data !== null ) { results . push ( data ) ; data = stream . read ( ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronous API . [CODESPLIT] function stat ( path , opts ) { return new Promise ( ( resolve , reject ) => { statProvider . async ( path , optionsManager . prepare ( opts ) , ( err , stats ) => err ? reject ( err ) : resolve ( stats ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "there s 3 implementations written in increasing order of efficiency 1 - no Set type is defined [CODESPLIT] function uniqNoSet ( arr ) { var ret = [ ] ; for ( var i = 0 ; i < arr . length ; i ++ ) { if ( ret . indexOf ( arr [ i ] ) === - 1 ) { ret . push ( arr [ i ] ) ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "3 - a standard Set type is defined and it has a forEach method [CODESPLIT] function uniqSetWithForEach ( arr ) { var ret = [ ] ; ( new Set ( arr ) ) . forEach ( function ( el ) { ret . push ( el ) ; } ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "V8 currently has a broken implementation https : // github . com / joyent / node / issues / 8449 [CODESPLIT] function doesForEachActuallyWork ( ) { var ret = false ; ( new Set ( [ true ] ) ) . forEach ( function ( el ) { ret = el ; } ) ; return ret === true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of Base with the given config and options . [CODESPLIT] function Base ( config , options ) { if ( ! ( this instanceof Base ) ) { return new Base ( config , options ) ; } Cache . call ( this , config ) ; this . is ( 'base' ) ; this . initBase ( config , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the given braces pattern into a regex - compatible string . By default only one string is generated for every input string . Set options . expand to true to return an array of patterns ( similar to Bash or minimatch . Before using options . expand it s recommended that you read the [ performance notes ] ( #performance )) . [CODESPLIT] function braces ( pattern , options ) { var key = utils . createKey ( String ( pattern ) , options ) ; var arr = [ ] ; var disabled = options && options . cache === false ; if ( ! disabled && cache . hasOwnProperty ( key ) ) { return cache [ key ] ; } if ( Array . isArray ( pattern ) ) { for ( var i = 0 ; i < pattern . length ; i ++ ) { arr . push . apply ( arr , braces . create ( pattern [ i ] , options ) ) ; } } else { arr = braces . create ( pattern , options ) ; } if ( options && options . nodupes === true ) { arr = unique ( arr ) ; } if ( ! disabled ) { cache [ key ] = arr ; } return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Memoize a generated regex or function . A unique key is generated from the method name pattern and user - defined options . Set options . memoize to false to disable . [CODESPLIT] function memoize ( type , pattern , options , fn ) { var key = utils . createKey ( type + ':' + pattern , options ) ; var disabled = options && options . cache === false ; if ( disabled ) { braces . clearCache ( ) ; return fn ( pattern , options ) ; } if ( cache . hasOwnProperty ( key ) ) { return cache [ key ] ; } var res = fn ( pattern , options ) ; cache [ key ] = res ; return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply the segments in the current brace level [CODESPLIT] function multiply ( queue , n , options ) { return utils . flatten ( utils . repeat ( utils . arrayify ( queue ) , n ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if regex parens should be used for sets . If the parent type is not brace then we re on a root node which means we should never expand segments and open / close braces should be {} ( since this indicates a brace is missing from the set ) [CODESPLIT] function isOptimized ( node , options ) { if ( node . parent . isOptimized ) return true ; return isType ( node . parent , 'brace' ) && ! isEscaped ( node . parent ) && options . expand !== true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the given node does not have an inner value . [CODESPLIT] function noInner ( node , type ) { if ( node . parent . queue . length === 1 ) { return true ; } var nodes = node . parent . nodes ; return nodes . length === 3 && isType ( nodes [ 0 ] , 'brace.open' ) && ! isType ( nodes [ 1 ] , 'text' ) && isType ( nodes [ 2 ] , 'brace.close' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combine text nodes and calculate empty sets ( { } ) [CODESPLIT] function concatNodes ( pos , node , parent , options ) { node . orig = node . val ; var prev = this . prev ( ) ; var last = utils . last ( prev . nodes ) ; var isEscaped = false ; if ( node . val . length > 1 ) { var a = node . val . charAt ( 0 ) ; var b = node . val . slice ( - 1 ) ; isEscaped = ( a === '\"' && b === '\"' ) || ( a === \"'\" && b === \"'\" ) || ( a === '`' && b === '`' ) ; } if ( isEscaped && options . unescape !== false ) { node . val = node . val . slice ( 1 , node . val . length - 1 ) ; node . escaped = true ; } if ( node . match ) { var match = node . match [ 1 ] ; if ( ! match || match . indexOf ( '}' ) === - 1 ) { match = node . match [ 0 ] ; } // replace each set with a single \",\" var val = match . replace ( / \\{ / g , ',' ) . replace ( / \\} / g , '' ) ; node . multiplier *= val . length ; node . val = '' ; } var simpleText = last . type === 'text' && last . multiplier === 1 && node . multiplier === 1 && node . val ; if ( simpleText ) { last . val += node . val ; return ; } prev . push ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables a debug mode by namespaces . This can include modes separated by a colon and wildcards . [CODESPLIT] function enable ( namespaces ) { exports . save ( namespaces ) ; exports . names = [ ] ; exports . skips = [ ] ; var i ; var split = ( typeof namespaces === 'string' ? namespaces : '' ) . split ( / [\\s,]+ / ) ; var len = split . length ; for ( i = 0 ; i < len ; i ++ ) { if ( ! split [ i ] ) continue ; // ignore empty strings namespaces = split [ i ] . replace ( / \\* / g , '.*?' ) ; if ( namespaces [ 0 ] === '-' ) { exports . skips . push ( new RegExp ( '^' + namespaces . substr ( 1 ) + '$' ) ) ; } else { exports . names . push ( new RegExp ( '^' + namespaces + '$' ) ) ; } } for ( i = 0 ; i < exports . instances . length ; i ++ ) { var instance = exports . instances [ i ] ; instance . enabled = exports . enabled ( instance . namespace ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the given POSIX character class pattern and returns a string that can be used for creating regular expressions for matching . [CODESPLIT] function brackets ( pattern , options ) { debug ( 'initializing from <%s>' , __filename ) ; var res = brackets . create ( pattern , options ) ; return res . output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Brackets parsers [CODESPLIT] function parsers ( brackets ) { brackets . state = brackets . state || { } ; brackets . parser . sets . bracket = brackets . parser . sets . bracket || [ ] ; brackets . parser . capture ( 'escape' , function ( ) { if ( this . isInside ( 'bracket' ) ) return ; var pos = this . position ( ) ; var m = this . match ( / ^\\\\(.) / ) ; if ( ! m ) return ; return pos ( { type : 'escape' , val : m [ 0 ] } ) ; } ) /**\n     * Text parser\n     */ . capture ( 'text' , function ( ) { if ( this . isInside ( 'bracket' ) ) return ; var pos = this . position ( ) ; var m = this . match ( not ) ; if ( ! m || ! m [ 0 ] ) return ; return pos ( { type : 'text' , val : m [ 0 ] } ) ; } ) /**\n     * POSIX character classes: \"[[:alpha:][:digits:]]\"\n     */ . capture ( 'posix' , function ( ) { var pos = this . position ( ) ; var m = this . match ( / ^\\[:(.*?):\\](?=.*\\]) / ) ; if ( ! m ) return ; var inside = this . isInside ( 'bracket' ) ; if ( inside ) { brackets . posix ++ ; } return pos ( { type : 'posix' , insideBracket : inside , inner : m [ 1 ] , val : m [ 0 ] } ) ; } ) /**\n     * Bracket (noop)\n     */ . capture ( 'bracket' , function ( ) { } ) /**\n     * Open: '['\n     */ . capture ( 'bracket.open' , function ( ) { var parsed = this . parsed ; var pos = this . position ( ) ; var m = this . match ( / ^\\[(?=.*\\]) / ) ; if ( ! m ) return ; var prev = this . prev ( ) ; var last = utils . last ( prev . nodes ) ; if ( parsed . slice ( - 1 ) === '\\\\' && ! this . isInside ( 'bracket' ) ) { last . val = last . val . slice ( 0 , last . val . length - 1 ) ; return pos ( { type : 'escape' , val : m [ 0 ] } ) ; } var open = pos ( { type : 'bracket.open' , val : m [ 0 ] } ) ; if ( last . type === 'bracket.open' || this . isInside ( 'bracket' ) ) { open . val = '\\\\' + open . val ; open . type = 'bracket.inner' ; open . escaped = true ; return open ; } var node = pos ( { type : 'bracket' , nodes : [ open ] } ) ; define ( node , 'parent' , prev ) ; define ( open , 'parent' , node ) ; this . push ( 'bracket' , node ) ; prev . nodes . push ( node ) ; } ) /**\n     * Bracket text\n     */ . capture ( 'bracket.inner' , function ( ) { if ( ! this . isInside ( 'bracket' ) ) return ; var pos = this . position ( ) ; var m = this . match ( not ) ; if ( ! m || ! m [ 0 ] ) return ; var next = this . input . charAt ( 0 ) ; var val = m [ 0 ] ; var node = pos ( { type : 'bracket.inner' , val : val } ) ; if ( val === '\\\\\\\\' ) { return node ; } var first = val . charAt ( 0 ) ; var last = val . slice ( - 1 ) ; if ( first === '!' ) { val = '^' + val . slice ( 1 ) ; } if ( last === '\\\\' || ( val === '^' && next === ']' ) ) { val += this . input [ 0 ] ; this . consume ( 1 ) ; } node . val = val ; return node ; } ) /**\n     * Close: ']'\n     */ . capture ( 'bracket.close' , function ( ) { var parsed = this . parsed ; var pos = this . position ( ) ; var m = this . match ( / ^\\] / ) ; if ( ! m ) return ; var prev = this . prev ( ) ; var last = utils . last ( prev . nodes ) ; if ( parsed . slice ( - 1 ) === '\\\\' && ! this . isInside ( 'bracket' ) ) { last . val = last . val . slice ( 0 , last . val . length - 1 ) ; return pos ( { type : 'escape' , val : m [ 0 ] } ) ; } var node = pos ( { type : 'bracket.close' , rest : this . input , val : m [ 0 ] } ) ; if ( last . type === 'bracket.open' ) { node . type = 'bracket.inner' ; node . escaped = true ; return node ; } var bracket = this . pop ( 'bracket' ) ; if ( ! this . isType ( bracket , 'bracket' ) ) { if ( this . options . strict ) { throw new Error ( 'missing opening \"[\"' ) ; } node . type = 'bracket.inner' ; node . escaped = true ; return node ; } bracket . nodes . push ( node ) ; define ( node , 'parent' , bracket ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a range of numbers or letters . [CODESPLIT] function fillRange ( a , b , step , options , fn ) { if ( a == null || b == null ) { throw new Error ( 'fill-range expects the first and second args to be strings.' ) ; } if ( typeof step === 'function' ) { fn = step ; options = { } ; step = null ; } if ( typeof options === 'function' ) { fn = options ; options = { } ; } if ( isObject ( step ) ) { options = step ; step = '' ; } var expand , regex = false , sep = '' ; var opts = options || { } ; if ( typeof opts . silent === 'undefined' ) { opts . silent = true ; } step = step || opts . step ; // store a ref to unmodified arg var origA = a , origB = b ; b = ( b . toString ( ) === '-0' ) ? 0 : b ; if ( opts . optimize || opts . makeRe ) { step = step ? ( step += '~' ) : step ; expand = true ; regex = true ; sep = '~' ; } // handle special step characters if ( typeof step === 'string' ) { var match = stepRe ( ) . exec ( step ) ; if ( match ) { var i = match . index ; var m = match [ 0 ] ; // repeat string if ( m === '+' ) { return repeat ( a , b ) ; // randomize a, `b` times } else if ( m === '?' ) { return [ randomize ( a , b ) ] ; // expand right, no regex reduction } else if ( m === '>' ) { step = step . substr ( 0 , i ) + step . substr ( i + 1 ) ; expand = true ; // expand to an array, or if valid create a reduced // string for a regex logic `or` } else if ( m === '|' ) { step = step . substr ( 0 , i ) + step . substr ( i + 1 ) ; expand = true ; regex = true ; sep = m ; // expand to an array, or if valid create a reduced // string for a regex range } else if ( m === '~' ) { step = step . substr ( 0 , i ) + step . substr ( i + 1 ) ; expand = true ; regex = true ; sep = m ; } } else if ( ! isNumber ( step ) ) { if ( ! opts . silent ) { throw new TypeError ( 'fill-range: invalid step.' ) ; } return null ; } } if ( / [.&*()[\\]^%$#@!] / . test ( a ) || / [.&*()[\\]^%$#@!] / . test ( b ) ) { if ( ! opts . silent ) { throw new RangeError ( 'fill-range: invalid range arguments.' ) ; } return null ; } // has neither a letter nor number, or has both letters and numbers // this needs to be after the step logic if ( ! noAlphaNum ( a ) || ! noAlphaNum ( b ) || hasBoth ( a ) || hasBoth ( b ) ) { if ( ! opts . silent ) { throw new RangeError ( 'fill-range: invalid range arguments.' ) ; } return null ; } // validate arguments var isNumA = isNumber ( zeros ( a ) ) ; var isNumB = isNumber ( zeros ( b ) ) ; if ( ( ! isNumA && isNumB ) || ( isNumA && ! isNumB ) ) { if ( ! opts . silent ) { throw new TypeError ( 'fill-range: first range argument is incompatible with second.' ) ; } return null ; } // by this point both are the same, so we // can use A to check going forward. var isNum = isNumA ; var num = formatStep ( step ) ; // is the range alphabetical? or numeric? if ( isNum ) { // if numeric, coerce to an integer a = + a ; b = + b ; } else { // otherwise, get the charCode to expand alpha ranges a = a . charCodeAt ( 0 ) ; b = b . charCodeAt ( 0 ) ; } // is the pattern descending? var isDescending = a > b ; // don't create a character class if the args are < 0 if ( a < 0 || b < 0 ) { expand = false ; regex = false ; } // detect padding var padding = isPadded ( origA , origB ) ; var res , pad , arr = [ ] ; var ii = 0 ; // character classes, ranges and logical `or` if ( regex ) { if ( shouldExpand ( a , b , num , isNum , padding , opts ) ) { // make sure the correct separator is used if ( sep === '|' || sep === '~' ) { sep = detectSeparator ( a , b , num , isNum , isDescending ) ; } return wrap ( [ origA , origB ] , sep , opts ) ; } } while ( isDescending ? ( a >= b ) : ( a <= b ) ) { if ( padding && isNum ) { pad = padding ( a ) ; } // custom function if ( typeof fn === 'function' ) { res = fn ( a , isNum , pad , ii ++ ) ; // letters } else if ( ! isNum ) { if ( regex && isInvalidChar ( a ) ) { res = null ; } else { res = String . fromCharCode ( a ) ; } // numbers } else { res = formatPadding ( a , pad ) ; } // add result to the array, filtering any nulled values if ( res !== null ) arr . push ( res ) ; // increment or decrement if ( isDescending ) { a -= num ; } else { a += num ; } } // now that the array is expanded, we need to handle regex // character classes, ranges or logical `or` that wasn't // already handled before the loop if ( ( regex || expand ) && ! opts . noexpand ) { // make sure the correct separator is used if ( sep === '|' || sep === '~' ) { sep = detectSeparator ( a , b , num , isNum , isDescending ) ; } if ( arr . length === 1 || a < 0 || b < 0 ) { return arr ; } return wrap ( arr , sep , opts ) ; } return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap the string with the correct regex syntax . [CODESPLIT] function wrap ( arr , sep , opts ) { if ( sep === '~' ) { sep = '-' ; } var str = arr . join ( sep ) ; var pre = opts && opts . regexPrefix ; // regex logical `or` if ( sep === '|' ) { str = pre ? pre + str : str ; str = '(' + str + ')' ; } // regex character class if ( sep === '-' ) { str = ( pre && pre === '^' ) ? pre + str : str ; str = '[' + str + ']' ; } return [ str ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for invalid characters [CODESPLIT] function isCharClass ( a , b , step , isNum , isDescending ) { if ( isDescending ) { return false ; } if ( isNum ) { return a <= 9 && b <= 9 ; } if ( a < b ) { return step === 1 ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detect the correct separator to use [CODESPLIT] function shouldExpand ( a , b , num , isNum , padding , opts ) { if ( isNum && ( a > 9 || b > 9 ) ) { return false ; } return ! padding && num === 1 && a < b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detect the correct separator to use [CODESPLIT] function detectSeparator ( a , b , step , isNum , isDescending ) { var isChar = isCharClass ( a , b , step , isNum , isDescending ) ; if ( ! isChar ) { return '|' ; } return '~' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format padding taking leading - into account [CODESPLIT] function formatPadding ( ch , pad ) { var res = pad ? pad + ch : ch ; if ( pad && ch . toString ( ) . charAt ( 0 ) === '-' ) { res = '-' + pad + ch . toString ( ) . substr ( 1 ) ; } return res . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for invalid characters [CODESPLIT] function isInvalidChar ( str ) { var ch = toStr ( str ) ; return ch === '\\\\' || ch === '[' || ch === ']' || ch === '^' || ch === '(' || ch === ')' || ch === '`' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the string is padded returns a curried function with the a cached padding string or false if no padding . [CODESPLIT] function isPadded ( origA , origB ) { if ( hasZeros ( origA ) || hasZeros ( origB ) ) { var alen = length ( origA ) ; var blen = length ( origB ) ; var len = alen >= blen ? alen : blen ; return function ( a ) { return repeatStr ( '0' , len - length ( a ) ) ; } ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Customize Snapdragon parser and renderer [CODESPLIT] function Extglob ( options ) { this . options = extend ( { source : 'extglob' } , options ) ; this . snapdragon = this . options . snapdragon || new Snapdragon ( this . options ) ; this . snapdragon . patterns = this . snapdragon . patterns || { } ; this . compiler = this . snapdragon . compiler ; this . parser = this . snapdragon . parser ; compilers ( this . snapdragon ) ; parsers ( this . snapdragon ) ; /**\n   * Override Snapdragon `.parse` method\n   */ define ( this . snapdragon , 'parse' , function ( str , options ) { var parsed = Snapdragon . prototype . parse . apply ( this , arguments ) ; parsed . input = str ; // escape unmatched brace/bracket/parens var last = this . parser . stack . pop ( ) ; if ( last && this . options . strict !== true ) { var node = last . nodes [ 0 ] ; node . val = '\\\\' + node . val ; var sibling = node . parent . nodes [ 1 ] ; if ( sibling . type === 'star' ) { sibling . loose = true ; } } // add non-enumerable parser reference define ( parsed , 'parser' , this . parser ) ; return parsed ; } ) ; /**\n   * Decorate `.parse` method\n   */ define ( this , 'parse' , function ( ast , options ) { return this . snapdragon . parse . apply ( this . snapdragon , arguments ) ; } ) ; /**\n   * Decorate `.compile` method\n   */ define ( this , 'compile' , function ( ast , options ) { return this . snapdragon . compile . apply ( this . snapdragon , arguments ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The main function takes a list of strings and one or more glob patterns to use for matching . [CODESPLIT] function micromatch ( list , patterns , options ) { patterns = utils . arrayify ( patterns ) ; list = utils . arrayify ( list ) ; var len = patterns . length ; if ( list . length === 0 || len === 0 ) { return [ ] ; } if ( len === 1 ) { return micromatch . match ( list , patterns [ 0 ] , options ) ; } var omit = [ ] ; var keep = [ ] ; var idx = - 1 ; while ( ++ idx < len ) { var pattern = patterns [ idx ] ; if ( typeof pattern === 'string' && pattern . charCodeAt ( 0 ) === 33 /* ! */ ) { omit . push . apply ( omit , micromatch . match ( list , pattern . slice ( 1 ) , options ) ) ; } else { keep . push . apply ( keep , micromatch . match ( list , pattern , options ) ) ; } } var matches = utils . diff ( keep , omit ) ; if ( ! options || options . nodupes !== false ) { return utils . unique ( matches ) ; } return matches ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Memoize a generated regex or function . A unique key is generated from the type ( usually method name ) the pattern and user - defined options . [CODESPLIT] function memoize ( type , pattern , options , fn ) { var key = utils . createKey ( type + '=' + pattern , options ) ; if ( options && options . cache === false ) { return fn ( pattern , options ) ; } if ( cache . has ( type , key ) ) { return cache . get ( type , key ) ; } var val = fn ( pattern , options ) ; cache . set ( type , key , val ) ; return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visit node with the given fn [CODESPLIT] function visit ( node , fn ) { return node . nodes ? mapVisit ( node . nodes , fn ) : fn ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map visit over array of nodes . [CODESPLIT] function mapVisit ( nodes , fn ) { var len = nodes . length ; var idx = - 1 ; while ( ++ idx < len ) { visit ( nodes [ idx ] , fn ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create text regex [CODESPLIT] function textRegex ( pattern ) { var notStr = regexNot . create ( pattern , { contains : true , strictClose : false } ) ; var prefix = '(?:[\\\\^]|\\\\\\\\|' ; return toRegex ( prefix + notStr + ')' , { strictClose : false } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronous API . [CODESPLIT] function sync ( source , opts ) { var works = getWorks ( source , reader_sync_1 . default , opts ) ; return arrayUtils . flatten ( works ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronous API . [CODESPLIT] function async ( source , opts ) { var works = getWorks ( source , reader_async_1 . default , opts ) ; return Promise . all ( works ) . then ( arrayUtils . flatten ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stream API . [CODESPLIT] function stream ( source , opts ) { var works = getWorks ( source , reader_stream_1 . default , opts ) ; return merge2 ( works ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a set of tasks based on provided patterns . [CODESPLIT] function generateTasks ( source , opts ) { var patterns = [ ] . concat ( source ) ; var options = optionsManager . prepare ( opts ) ; return taskManager . generate ( patterns , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a set of works based on provided tasks and class of the reader . [CODESPLIT] function getWorks ( source , _Reader , opts ) { var patterns = [ ] . concat ( source ) ; var options = optionsManager . prepare ( opts ) ; var tasks = taskManager . generate ( patterns , options ) ; var reader = new _Reader ( options ) ; return tasks . map ( reader . read , reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate tasks based on parent directory of each pattern . [CODESPLIT] function generate ( patterns , options ) { var unixPatterns = patterns . map ( patternUtils . unixifyPattern ) ; var unixIgnore = options . ignore . map ( patternUtils . unixifyPattern ) ; var positivePatterns = getPositivePatterns ( unixPatterns ) ; var negativePatterns = getNegativePatternsAsPositive ( unixPatterns , unixIgnore ) ; var staticPatterns = positivePatterns . filter ( patternUtils . isStaticPattern ) ; var dynamicPatterns = positivePatterns . filter ( patternUtils . isDynamicPattern ) ; var staticTasks = convertPatternsToTasks ( staticPatterns , negativePatterns , /* dynamic */ false ) ; var dynamicTasks = convertPatternsToTasks ( dynamicPatterns , negativePatterns , /* dynamic */ true ) ; return staticTasks . concat ( dynamicTasks ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert patterns to tasks based on parent directory of each pattern . [CODESPLIT] function convertPatternsToTasks ( positive , negative , dynamic ) { var positivePatternsGroup = groupPatternsByBaseDirectory ( positive ) ; var negativePatternsGroup = groupPatternsByBaseDirectory ( negative ) ; // When we have a global group – there is no reason to divide the patterns into independent tasks. // In this case, the global task covers the rest. if ( '.' in positivePatternsGroup ) { var task = convertPatternGroupToTask ( '.' , positive , negative , dynamic ) ; return [ task ] ; } return convertPatternGroupsToTasks ( positivePatternsGroup , negativePatternsGroup , dynamic ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return only negative patterns . [CODESPLIT] function getNegativePatternsAsPositive ( patterns , ignore ) { var negative = patternUtils . getNegativePatterns ( patterns ) . concat ( ignore ) ; var positive = negative . map ( patternUtils . convertToPositivePattern ) ; return positive ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Group patterns by base directory of each pattern . [CODESPLIT] function groupPatternsByBaseDirectory ( patterns ) { return patterns . reduce ( function ( collection , pattern ) { var base = patternUtils . getBaseDirectory ( pattern ) ; if ( base in collection ) { collection [ base ] . push ( pattern ) ; } else { collection [ base ] = [ pattern ] ; } return collection ; } , { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert group of patterns to tasks . [CODESPLIT] function convertPatternGroupsToTasks ( positive , negative , dynamic ) { var globalNegative = '.' in negative ? negative [ '.' ] : [ ] ; return Object . keys ( positive ) . map ( function ( base ) { var localNegative = findLocalNegativePatterns ( base , negative ) ; var fullNegative = localNegative . concat ( globalNegative ) ; return convertPatternGroupToTask ( base , positive [ base ] , fullNegative , dynamic ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns those negative patterns whose base paths includes positive base path . [CODESPLIT] function findLocalNegativePatterns ( positiveBase , negative ) { return Object . keys ( negative ) . reduce ( function ( collection , base ) { if ( base . startsWith ( positiveBase ) ) { collection . push . apply ( collection , __spread ( negative [ base ] ) ) ; } return collection ; } , [ ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a task for positive and negative patterns . [CODESPLIT] function convertPatternGroupToTask ( base , positive , negative , dynamic ) { return { base : base , dynamic : dynamic , patterns : [ ] . concat ( positive , negative . map ( patternUtils . convertToNegativePattern ) ) , positive : positive , negative : negative } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns «true» when pattern ends with a slash and globstar or the last partial of the pattern is static pattern . [CODESPLIT] function isAffectDepthOfReadingPattern ( pattern ) { var basename = path . basename ( pattern ) ; return endsWithSlashGlobStar ( pattern ) || isStaticPattern ( basename ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the entry match any of the given RegExp s . [CODESPLIT] function matchAny ( entry , patternsRe ) { try { for ( var patternsRe_1 = __values ( patternsRe ) , patternsRe_1_1 = patternsRe_1 . next ( ) ; ! patternsRe_1_1 . done ; patternsRe_1_1 = patternsRe_1 . next ( ) ) { var regexp = patternsRe_1_1 . value ; if ( regexp . test ( entry ) ) { return true ; } } } catch ( e_1_1 ) { e_1 = { error : e_1_1 } ; } finally { try { if ( patternsRe_1_1 && ! patternsRe_1_1 . done && ( _a = patternsRe_1 . return ) ) _a . call ( patternsRe_1 ) ; } finally { if ( e_1 ) throw e_1 . error ; } } return false ; var e_1 , _a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sync the files and persist them to the cache [CODESPLIT] function ( ) { removeNotFoundFiles ( ) ; var entries = normalizedEntries ; var keys = Object . keys ( entries ) ; if ( keys . length === 0 ) { return ; } keys . forEach ( function ( entryName ) { var cacheEntry = entries [ entryName ] ; try { var stat = fs . statSync ( cacheEntry . key ) ; var meta = assign ( cacheEntry . meta , { size : stat . size , mtime : stat . mtime . getTime ( ) } ) ; cache . setKey ( entryName , meta ) ; } catch ( err ) { // if the file does not exists we don't save it // other errors are just thrown if ( err . code !== 'ENOENT' ) { throw err ; } } } ) ; cache . save ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a range of numbers or letters . [CODESPLIT] function fillRange ( start , stop , step , options ) { if ( typeof start === 'undefined' ) { return [ ] ; } if ( typeof stop === 'undefined' || start === stop ) { // special case, for handling negative zero var isString = typeof start === 'string' ; if ( isNumber ( start ) && ! toNumber ( start ) ) { return [ isString ? '0' : 0 ] ; } return [ start ] ; } if ( typeof step !== 'number' && typeof step !== 'string' ) { options = step ; step = undefined ; } if ( typeof options === 'function' ) { options = { transform : options } ; } var opts = extend ( { step : step } , options ) ; if ( opts . step && ! isValidNumber ( opts . step ) ) { if ( opts . strictRanges === true ) { throw new TypeError ( 'expected options.step to be a number' ) ; } return [ ] ; } opts . isNumber = isValidNumber ( start ) && isValidNumber ( stop ) ; if ( ! opts . isNumber && ! isValid ( start , stop ) ) { if ( opts . strictRanges === true ) { throw new RangeError ( 'invalid range arguments: ' + util . inspect ( [ start , stop ] ) ) ; } return [ ] ; } opts . isPadded = isPadded ( start ) || isPadded ( stop ) ; opts . toString = opts . stringify || typeof opts . step === 'string' || typeof start === 'string' || typeof stop === 'string' || ! opts . isNumber ; if ( opts . isPadded ) { opts . maxLength = Math . max ( String ( start ) . length , String ( stop ) . length ) ; } // support legacy minimatch/fill-range options if ( typeof opts . optimize === 'boolean' ) opts . toRegex = opts . optimize ; if ( typeof opts . makeRe === 'boolean' ) opts . toRegex = opts . makeRe ; return expand ( start , stop , opts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load a cache identified by the given Id . If the element does not exists then initialize an empty cache storage . If specified cacheDir will be used as the directory to persist the data to . If omitted then the cache module directory . / cache will be used instead [CODESPLIT] function ( docId , cacheDir ) { var me = this ; me . _visited = { } ; me . _persisted = { } ; me . _pathToFile = cacheDir ? path . resolve ( cacheDir , docId ) : path . resolve ( __dirname , './.cache/' , docId ) ; if ( fs . existsSync ( me . _pathToFile ) ) { me . _persisted = utils . tryParse ( me . _pathToFile , { } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the cache from the provided file [CODESPLIT] function ( pathToFile ) { var me = this ; var dir = path . dirname ( pathToFile ) ; var fName = path . basename ( pathToFile ) ; me . load ( fName , dir ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove keys that were not accessed / set since the last time the prune method was called . [CODESPLIT] function ( ) { var me = this ; var obj = { } ; var keys = Object . keys ( me . _visited ) ; // no keys visited for either get or set value if ( keys . length === 0 ) { return ; } keys . forEach ( function ( key ) { obj [ key ] = me . _persisted [ key ] ; } ) ; me . _visited = { } ; me . _persisted = obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the state of the cache identified by the docId to disk as a JSON structure [CODESPLIT] function ( noPrune ) { var me = this ; ( ! noPrune ) && me . _prune ( ) ; writeJSON ( me . _pathToFile , me . _persisted ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load a cache identified by the given Id . If the element does not exists then initialize an empty cache storage . [CODESPLIT] function ( docId , cacheDir ) { var obj = Object . create ( cache ) ; obj . load ( docId , cacheDir ) ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear the cache identified by the given id . Caches stored in a different cache directory can be deleted directly [CODESPLIT] function ( docId , cacheDir ) { var filePath = cacheDir ? path . resolve ( cacheDir , docId ) : path . resolve ( __dirname , './.cache/' , docId ) ; return del ( filePath , { force : true } ) . length > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a value for property key on cache name [CODESPLIT] function ( cacheName , key , val ) { var cache = this . cache ( cacheName ) ; cache . set ( key , val ) ; return cache ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get name or if specified the value of key . Invokes the [ cache ] () method so that cache name will be created it doesn t already exist . If key is not passed the entire cache ( name ) is returned . [CODESPLIT] function ( name , key ) { var cache = this . cache ( name ) ; if ( typeof key === 'string' ) { return cache . get ( key ) ; } return cache ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "walk down the path swapping out linked pathparts for their real values [CODESPLIT] function LOOP ( ) { // stop if scanned past end of path if ( pos >= p . length ) { if ( cache ) cache [ original ] = p ; return cb ( null , p ) ; } // find the next part nextPartRe . lastIndex = pos ; var result = nextPartRe . exec ( p ) ; previous = current ; current += result [ 0 ] ; base = previous + result [ 1 ] ; pos = nextPartRe . lastIndex ; // continue if not a symlink if ( knownHard [ base ] || ( cache && cache [ base ] === base ) ) { return process . nextTick ( LOOP ) ; } if ( cache && Object . prototype . hasOwnProperty . call ( cache , base ) ) { // known symbolic link.  no need to stat again. return gotResolvedLink ( cache [ base ] ) ; } return fs . lstat ( base , gotStat ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ignore patterns are always in dot : true mode . [CODESPLIT] function ignoreMap ( pattern ) { var gmatcher = null if ( pattern . slice ( - 3 ) === '/**' ) { var gpattern = pattern . replace ( / (\\/\\*\\*)+$ / , '' ) gmatcher = new Minimatch ( gpattern , { dot : true } ) } return { matcher : new Minimatch ( pattern , { dot : true } ) , gmatcher : gmatcher } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "lotta situps ... [CODESPLIT] function makeAbs ( self , f ) { var abs = f if ( f . charAt ( 0 ) === '/' ) { abs = path . join ( self . root , f ) } else if ( isAbsolute ( f ) || f === '' ) { abs = f } else if ( self . changedCwd ) { abs = path . resolve ( self . cwd , f ) } else { abs = path . resolve ( f ) } if ( process . platform === 'win32' ) abs = abs . replace ( / \\\\ / g , '/' ) return abs }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if pattern ends with globstar ** for the accompanying parent directory . Ex : - If node_modules / ** is the pattern add node_modules to ignore list along with it s contents [CODESPLIT] function isIgnored ( self , path ) { if ( ! self . ignore . length ) return false return self . ignore . some ( function ( item ) { return item . matcher . match ( path ) || ! ! ( item . gmatcher && item . gmatcher . match ( path ) ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If you need to support Safari 5 - 7 ( 8 - 10 yr - old browser ) take a look at https : // github . com / feross / is - buffer [CODESPLIT] function isBuffer ( val ) { return val . constructor && typeof val . constructor . isBuffer === 'function' && val . constructor . isBuffer ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The main function . Pass an array of filepaths and a string or array of glob patterns [CODESPLIT] function micromatch ( files , patterns , opts ) { if ( ! files || ! patterns ) return [ ] ; opts = opts || { } ; if ( typeof opts . cache === 'undefined' ) { opts . cache = true ; } if ( ! Array . isArray ( patterns ) ) { return match ( files , patterns , opts ) ; } var len = patterns . length , i = 0 ; var omit = [ ] , keep = [ ] ; while ( len -- ) { var glob = patterns [ i ++ ] ; if ( typeof glob === 'string' && glob . charCodeAt ( 0 ) === 33 /* ! */ ) { omit . push . apply ( omit , match ( files , glob . slice ( 1 ) , opts ) ) ; } else { keep . push . apply ( keep , match ( files , glob , opts ) ) ; } } return utils . diff ( keep , omit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an array of files that match the given glob pattern . [CODESPLIT] function match ( files , pattern , opts ) { if ( utils . typeOf ( files ) !== 'string' && ! Array . isArray ( files ) ) { throw new Error ( msg ( 'match' , 'files' , 'a string or array' ) ) ; } files = utils . arrayify ( files ) ; opts = opts || { } ; var negate = opts . negate || false ; var orig = pattern ; if ( typeof pattern === 'string' ) { negate = pattern . charAt ( 0 ) === '!' ; if ( negate ) { pattern = pattern . slice ( 1 ) ; } // we need to remove the character regardless, // so the above logic is still needed if ( opts . nonegate === true ) { negate = false ; } } var _isMatch = matcher ( pattern , opts ) ; var len = files . length , i = 0 ; var res = [ ] ; while ( i < len ) { var file = files [ i ++ ] ; var fp = utils . unixify ( file , opts ) ; if ( ! _isMatch ( fp ) ) { continue ; } res . push ( fp ) ; } if ( res . length === 0 ) { if ( opts . failglob === true ) { throw new Error ( 'micromatch.match() found no matches for: \"' + orig + '\".' ) ; } if ( opts . nonull || opts . nullglob ) { res . push ( utils . unescapeGlob ( orig ) ) ; } } // if `negate` was defined, diff negated files if ( negate ) { res = utils . diff ( files , res ) ; } // if `ignore` was defined, diff ignored filed if ( opts . ignore && opts . ignore . length ) { pattern = opts . ignore ; opts = utils . omit ( opts , [ 'ignore' ] ) ; res = utils . diff ( res , micromatch ( res , pattern , opts ) ) ; } if ( opts . nodupes ) { return utils . unique ( res ) ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a function that takes a glob pattern or array of glob patterns to be used with Array#filter () . ( Internally this function generates the matching function using the [ matcher ] method ) . [CODESPLIT] function filter ( patterns , opts ) { if ( ! Array . isArray ( patterns ) && typeof patterns !== 'string' ) { throw new TypeError ( msg ( 'filter' , 'patterns' , 'a string or array' ) ) ; } patterns = utils . arrayify ( patterns ) ; var len = patterns . length , i = 0 ; var patternMatchers = Array ( len ) ; while ( i < len ) { patternMatchers [ i ] = matcher ( patterns [ i ++ ] , opts ) ; } return function ( fp ) { if ( fp == null ) return [ ] ; var len = patternMatchers . length , i = 0 ; var res = true ; fp = utils . unixify ( fp , opts ) ; while ( i < len ) { var fn = patternMatchers [ i ++ ] ; if ( ! fn ( fp ) ) { res = false ; break ; } } return res ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the filepath contains the given pattern . Can also return a function for matching . [CODESPLIT] function isMatch ( fp , pattern , opts ) { if ( typeof fp !== 'string' ) { throw new TypeError ( msg ( 'isMatch' , 'filepath' , 'a string' ) ) ; } fp = utils . unixify ( fp , opts ) ; if ( utils . typeOf ( pattern ) === 'object' ) { return matcher ( fp , pattern ) ; } return matcher ( pattern , opts ) ( fp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the filepath matches the given pattern . [CODESPLIT] function contains ( fp , pattern , opts ) { if ( typeof fp !== 'string' ) { throw new TypeError ( msg ( 'contains' , 'pattern' , 'a string' ) ) ; } opts = opts || { } ; opts . contains = ( pattern !== '' ) ; fp = utils . unixify ( fp , opts ) ; if ( opts . contains && ! utils . isGlob ( pattern ) ) { return fp . indexOf ( pattern ) !== - 1 ; } return matcher ( pattern , opts ) ( fp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if a file path matches any of the given patterns . [CODESPLIT] function any ( fp , patterns , opts ) { if ( ! Array . isArray ( patterns ) && typeof patterns !== 'string' ) { throw new TypeError ( msg ( 'any' , 'patterns' , 'a string or array' ) ) ; } patterns = utils . arrayify ( patterns ) ; var len = patterns . length ; fp = utils . unixify ( fp , opts ) ; while ( len -- ) { var isMatch = matcher ( patterns [ len ] , opts ) ; if ( isMatch ( fp ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter the keys of an object with the given glob pattern and options [CODESPLIT] function matchKeys ( obj , glob , options ) { if ( utils . typeOf ( obj ) !== 'object' ) { throw new TypeError ( msg ( 'matchKeys' , 'first argument' , 'an object' ) ) ; } var fn = matcher ( glob , options ) ; var res = { } ; for ( var key in obj ) { if ( obj . hasOwnProperty ( key ) && fn ( key ) ) { res [ key ] = obj [ key ] ; } } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a function for matching based on the given pattern and options . [CODESPLIT] function matcher ( pattern , opts ) { // pattern is a function if ( typeof pattern === 'function' ) { return pattern ; } // pattern is a regex if ( pattern instanceof RegExp ) { return function ( fp ) { return pattern . test ( fp ) ; } ; } if ( typeof pattern !== 'string' ) { throw new TypeError ( msg ( 'matcher' , 'pattern' , 'a string, regex, or function' ) ) ; } // strings, all the way down... pattern = utils . unixify ( pattern , opts ) ; // pattern is a non-glob string if ( ! utils . isGlob ( pattern ) ) { return utils . matchPath ( pattern , opts ) ; } // pattern is a glob string var re = makeRe ( pattern , opts ) ; // `matchBase` is defined if ( opts && opts . matchBase ) { return utils . hasFilename ( re , opts ) ; } // `matchBase` is not defined return function ( fp ) { fp = utils . unixify ( fp , opts ) ; return re . test ( fp ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create and cache a regular expression for matching file paths . [CODESPLIT] function toRegex ( glob , options ) { // clone options to prevent  mutating the original object var opts = Object . create ( options || { } ) ; var flags = opts . flags || '' ; if ( opts . nocase && flags . indexOf ( 'i' ) === - 1 ) { flags += 'i' ; } var parsed = expand ( glob , opts ) ; // pass in tokens to avoid parsing more than once opts . negated = opts . negated || parsed . negated ; opts . negate = opts . negated ; glob = wrapGlob ( parsed . pattern , opts ) ; var re ; try { re = new RegExp ( glob , flags ) ; return re ; } catch ( err ) { err . reason = 'micromatch invalid regex: (' + re + ')' ; if ( opts . strict ) throw new SyntaxError ( err ) ; } // we're only here if a bad pattern was used and the user // passed `options.silent`, so match nothing return / $^ / ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the regex to do the matching . If the leading character in the glob is ! a negation regex is returned . [CODESPLIT] function wrapGlob ( glob , opts ) { var prefix = ( opts && ! opts . contains ) ? '^' : '' ; var after = ( opts && ! opts . contains ) ? '$' : '' ; glob = ( '(?:' + glob + ')' + after ) ; if ( opts && opts . negate ) { return prefix + ( '(?!^' + glob + ').*$' ) ; } return prefix + glob ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create and cache a regular expression for matching file paths . If the leading character in the glob is ! a negation regex is returned . [CODESPLIT] function makeRe ( glob , opts ) { if ( utils . typeOf ( glob ) !== 'string' ) { throw new Error ( msg ( 'makeRe' , 'glob' , 'a string' ) ) ; } return utils . cache ( toRegex , glob , opts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expand a glob pattern to resolve braces and similar patterns before converting to regex . [CODESPLIT] function expand ( pattern , options ) { if ( typeof pattern !== 'string' ) { throw new TypeError ( 'micromatch.expand(): argument should be a string.' ) ; } var glob = new Glob ( pattern , options || { } ) ; var opts = glob . options ; if ( ! utils . isGlob ( pattern ) ) { glob . pattern = glob . pattern . replace ( / ([\\/.]) / g , '\\\\$1' ) ; return glob ; } glob . pattern = glob . pattern . replace ( / (\\+)(?!\\() / g , '\\\\$1' ) ; glob . pattern = glob . pattern . split ( '$' ) . join ( '\\\\$' ) ; if ( typeof opts . braces !== 'boolean' && typeof opts . nobraces !== 'boolean' ) { opts . braces = true ; } if ( glob . pattern === '.*' ) { return { pattern : '\\\\.' + star , tokens : tok , options : opts } ; } if ( glob . pattern === '*' ) { return { pattern : oneStar ( opts . dot ) , tokens : tok , options : opts } ; } // parse the glob pattern into tokens glob . parse ( ) ; var tok = glob . tokens ; tok . is . negated = opts . negated ; // dotfile handling if ( ( opts . dotfiles === true || tok . is . dotfile ) && opts . dot !== false ) { opts . dotfiles = true ; opts . dot = true ; } if ( ( opts . dotdirs === true || tok . is . dotdir ) && opts . dot !== false ) { opts . dotdirs = true ; opts . dot = true ; } // check for braces with a dotfile pattern if ( / [{,]\\. / . test ( glob . pattern ) ) { opts . makeRe = false ; opts . dot = true ; } if ( opts . nonegate !== true ) { opts . negated = glob . negated ; } // if the leading character is a dot or a slash, escape it if ( glob . pattern . charAt ( 0 ) === '.' && glob . pattern . charAt ( 1 ) !== '/' ) { glob . pattern = '\\\\' + glob . pattern ; } /**\n   * Extended globs\n   */ // expand braces, e.g `{1..5}` glob . track ( 'before braces' ) ; if ( tok . is . braces ) { glob . braces ( ) ; } glob . track ( 'after braces' ) ; // expand extglobs, e.g `foo/!(a|b)` glob . track ( 'before extglob' ) ; if ( tok . is . extglob ) { glob . extglob ( ) ; } glob . track ( 'after extglob' ) ; // expand brackets, e.g `[[:alpha:]]` glob . track ( 'before brackets' ) ; if ( tok . is . brackets ) { glob . brackets ( ) ; } glob . track ( 'after brackets' ) ; // special patterns glob . _replace ( '[!' , '[^' ) ; glob . _replace ( '(?' , '(%~' ) ; glob . _replace ( / \\[\\] / , '\\\\[\\\\]' ) ; glob . _replace ( '/[' , '/' + ( opts . dot ? dotfiles : nodot ) + '[' , true ) ; glob . _replace ( '/?' , '/' + ( opts . dot ? dotfiles : nodot ) + '[^/]' , true ) ; glob . _replace ( '/.' , '/(?=.)\\\\.' , true ) ; // windows drives glob . _replace ( / ^(\\w):([\\\\\\/]+?) / gi , '(?=.)$1:$2' , true ) ; // negate slashes in exclusion ranges if ( glob . pattern . indexOf ( '[^' ) !== - 1 ) { glob . pattern = negateSlash ( glob . pattern ) ; } if ( opts . globstar !== false && glob . pattern === '**' ) { glob . pattern = globstar ( opts . dot ) ; } else { glob . pattern = balance ( glob . pattern , '[' , ']' ) ; glob . escape ( glob . pattern ) ; // if the pattern has `**` if ( tok . is . globstar ) { glob . pattern = collapse ( glob . pattern , '/**' ) ; glob . pattern = collapse ( glob . pattern , '**/' ) ; glob . _replace ( '/**/' , '(?:/' + globstar ( opts . dot ) + '/|/)' , true ) ; glob . _replace ( / \\*{2,} / g , '**' ) ; // 'foo/*' glob . _replace ( / (\\w+)\\*(?!\\/) / g , '$1[^/]*?' , true ) ; glob . _replace ( / \\*\\*\\/\\*(\\w) / g , globstar ( opts . dot ) + '\\\\/' + ( opts . dot ? dotfiles : nodot ) + '[^/]*?$1' , true ) ; if ( opts . dot !== true ) { glob . _replace ( / \\*\\*\\/(.) / g , '(?:**\\\\/|)$1' ) ; } // 'foo/**' or '{**,*}', but not 'foo**' if ( tok . path . dirname !== '' || / ,\\*\\*|\\*\\*, / . test ( glob . orig ) ) { glob . _replace ( '**' , globstar ( opts . dot ) , true ) ; } } // ends with /* glob . _replace ( / \\/\\*$ / , '\\\\/' + oneStar ( opts . dot ) , true ) ; // ends with *, no slashes glob . _replace ( / (?!\\/)\\*$ / , star , true ) ; // has 'n*.' (partial wildcard w/ file extension) glob . _replace ( / ([^\\/]+)\\* / , '$1' + oneStar ( true ) , true ) ; // has '*' glob . _replace ( '*' , oneStar ( opts . dot ) , true ) ; glob . _replace ( '?.' , '?\\\\.' , true ) ; glob . _replace ( '?:' , '?:' , true ) ; glob . _replace ( / \\?+ / g , function ( match ) { var len = match . length ; if ( len === 1 ) { return qmark ; } return qmark + '{' + len + '}' ; } ) ; // escape '.abc' => '\\\\.abc' glob . _replace ( / \\.([*\\w]+) / g , '\\\\.$1' ) ; // fix '[^\\\\\\\\/]' glob . _replace ( / \\[\\^[\\\\\\/]+\\] / g , qmark ) ; // '///' => '\\/' glob . _replace ( / \\/+ / g , '\\\\/' ) ; // '\\\\\\\\\\\\' => '\\\\' glob . _replace ( / \\\\{2,} / g , '\\\\' ) ; } // unescape previously escaped patterns glob . unescape ( glob . pattern ) ; glob . _replace ( '__UNESC_STAR__' , '*' ) ; // escape dots that follow qmarks glob . _replace ( '?.' , '?\\\\.' ) ; // remove unnecessary slashes in character classes glob . _replace ( '[^\\\\/]' , qmark ) ; if ( glob . pattern . length > 1 ) { if ( / ^[\\[?*] / . test ( glob . pattern ) ) { // only prepend the string if we don't want to match dotfiles glob . pattern = ( opts . dot ? dotfiles : nodot ) + glob . pattern ; } } return glob ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collapse repeated character sequences . [CODESPLIT] function collapse ( str , ch ) { var res = str . split ( ch ) ; var isFirst = res [ 0 ] === '' ; var isLast = res [ res . length - 1 ] === '' ; res = res . filter ( Boolean ) ; if ( isFirst ) res . unshift ( '' ) ; if ( isLast ) res . push ( '' ) ; return res . join ( ch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Negate slashes in exclusion ranges per glob spec : [CODESPLIT] function negateSlash ( str ) { return str . replace ( / \\[\\^([^\\]]*?)\\] / g , function ( match , inner ) { if ( inner . indexOf ( '/' ) === - 1 ) { inner = '\\\\/' + inner ; } return '[^' + inner + ']' ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escape imbalanced braces / bracket . This is a very basic naive implementation that only does enough to serve the purpose . [CODESPLIT] function balance ( str , a , b ) { var aarr = str . split ( a ) ; var alen = aarr . join ( '' ) . length ; var blen = str . split ( b ) . join ( '' ) . length ; if ( alen !== blen ) { str = aarr . join ( '\\\\' + a ) ; return str . split ( b ) . join ( '\\\\' + b ) ; } return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expand { foo bar } or { 1 .. 5 } braces in the given string . [CODESPLIT] function braces ( str , arr , options ) { if ( str === '' ) { return [ ] ; } if ( ! Array . isArray ( arr ) ) { options = arr ; arr = [ ] ; } var opts = options || { } ; arr = arr || [ ] ; if ( typeof opts . nodupes === 'undefined' ) { opts . nodupes = true ; } var fn = opts . fn ; var es6 ; if ( typeof opts === 'function' ) { fn = opts ; opts = { } ; } if ( ! ( patternRe instanceof RegExp ) ) { patternRe = patternRegex ( ) ; } var matches = str . match ( patternRe ) || [ ] ; var m = matches [ 0 ] ; switch ( m ) { case '\\\\,' : return escapeCommas ( str , arr , opts ) ; case '\\\\.' : return escapeDots ( str , arr , opts ) ; case '\\/.' : return escapePaths ( str , arr , opts ) ; case ' ' : return splitWhitespace ( str ) ; case '{,}' : return exponential ( str , opts , braces ) ; case '{}' : return emptyBraces ( str , arr , opts ) ; case '\\\\{' : case '\\\\}' : return escapeBraces ( str , arr , opts ) ; case '${' : if ( ! / \\{[^{]+\\{ / . test ( str ) ) { return arr . concat ( str ) ; } else { es6 = true ; str = tokens . before ( str , es6Regex ( ) ) ; } } if ( ! ( braceRe instanceof RegExp ) ) { braceRe = braceRegex ( ) ; } var match = braceRe . exec ( str ) ; if ( match == null ) { return [ str ] ; } var outter = match [ 1 ] ; var inner = match [ 2 ] ; if ( inner === '' ) { return [ str ] ; } var segs , segsLength ; if ( inner . indexOf ( '..' ) !== - 1 ) { segs = expand ( inner , opts , fn ) || inner . split ( ',' ) ; segsLength = segs . length ; } else if ( inner [ 0 ] === '\"' || inner [ 0 ] === '\\'' ) { return arr . concat ( str . split ( / ['\"] / ) . join ( '' ) ) ; } else { segs = inner . split ( ',' ) ; if ( opts . makeRe ) { return braces ( str . replace ( outter , wrap ( segs , '|' ) ) , opts ) ; } segsLength = segs . length ; if ( segsLength === 1 && opts . bash ) { segs [ 0 ] = wrap ( segs [ 0 ] , '\\\\' ) ; } } var len = segs . length ; var i = 0 , val ; while ( len -- ) { var path = segs [ i ++ ] ; if ( / (\\.[^.\\/]) / . test ( path ) ) { if ( segsLength > 1 ) { return segs ; } else { return [ str ] ; } } val = splice ( str , outter , path ) ; if ( / \\{[^{}]+?\\} / . test ( val ) ) { arr = braces ( val , arr , opts ) ; } else if ( val !== '' ) { if ( opts . nodupes && arr . indexOf ( val ) !== - 1 ) { continue ; } arr . push ( es6 ? tokens . after ( val ) : val ) ; } } if ( opts . strict ) { return filter ( arr , filterEmpty ) ; } return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expand exponential ranges [CODESPLIT] function exponential ( str , options , fn ) { if ( typeof options === 'function' ) { fn = options ; options = null ; } var opts = options || { } ; var esc = '__ESC_EXP__' ; var exp = 0 ; var res ; var parts = str . split ( '{,}' ) ; if ( opts . nodupes ) { return fn ( parts . join ( '' ) , opts ) ; } exp = parts . length - 1 ; res = fn ( parts . join ( esc ) , opts ) ; var len = res . length ; var arr = [ ] ; var i = 0 ; while ( len -- ) { var ele = res [ i ++ ] ; var idx = ele . indexOf ( esc ) ; if ( idx === - 1 ) { arr . push ( ele ) ; } else { ele = ele . split ( '__ESC_EXP__' ) . join ( '' ) ; if ( ! ! ele && opts . nodupes !== false ) { arr . push ( ele ) ; } else { var num = Math . pow ( 2 , exp ) ; arr . push . apply ( arr , repeat ( ele , num ) ) ; } } } return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap a value with parens brackets or braces based on the given character / separator . [CODESPLIT] function wrap ( val , ch ) { if ( ch === '|' ) { return '(' + val . join ( ch ) + ')' ; } if ( ch === ',' ) { return '{' + val . join ( ch ) + '}' ; } if ( ch === '-' ) { return '[' + val . join ( ch ) + ']' ; } if ( ch === '\\\\' ) { return '\\\\{' + val + '\\\\}' ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle empty braces : {} [CODESPLIT] function emptyBraces ( str , arr , opts ) { return braces ( str . split ( '{}' ) . join ( '\\\\{\\\\}' ) , arr , opts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle patterns with whitespace [CODESPLIT] function splitWhitespace ( str ) { var segs = str . split ( ' ' ) ; var len = segs . length ; var res = [ ] ; var i = 0 ; while ( len -- ) { res . push . apply ( res , braces ( segs [ i ++ ] ) ) ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle escaped braces : \\\\ { foo bar } [CODESPLIT] function escapeBraces ( str , arr , opts ) { if ( ! / \\{[^{]+\\{ / . test ( str ) ) { return arr . concat ( str . split ( '\\\\' ) . join ( '' ) ) ; } else { str = str . split ( '\\\\{' ) . join ( '__LT_BRACE__' ) ; str = str . split ( '\\\\}' ) . join ( '__RT_BRACE__' ) ; return map ( braces ( str , arr , opts ) , function ( ele ) { ele = ele . split ( '__LT_BRACE__' ) . join ( '{' ) ; return ele . split ( '__RT_BRACE__' ) . join ( '}' ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle escaped dots : { 1 \\\\ . 2 } [CODESPLIT] function escapePaths ( str , arr , opts ) { str = str . split ( '\\/.' ) . join ( '__ESC_PATH__' ) ; return map ( braces ( str , arr , opts ) , function ( ele ) { return ele . split ( '__ESC_PATH__' ) . join ( '\\/.' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle escaped commas : { a \\\\ b } [CODESPLIT] function escapeCommas ( str , arr , opts ) { if ( ! / \\w, / . test ( str ) ) { return arr . concat ( str . split ( '\\\\' ) . join ( '' ) ) ; } else { str = str . split ( '\\\\,' ) . join ( '__ESC_COMMA__' ) ; return map ( braces ( str , arr , opts ) , function ( ele ) { return ele . split ( '__ESC_COMMA__' ) . join ( ',' ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Faster alternative to String . replace () when the index of the token to be replaces can t be supplied [CODESPLIT] function splice ( str , token , replacement ) { var i = str . indexOf ( token ) ; return str . substr ( 0 , i ) + replacement + str . substr ( i + token . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fast array filter [CODESPLIT] function filter ( arr , cb ) { if ( arr == null ) return [ ] ; if ( typeof cb !== 'function' ) { throw new TypeError ( 'braces: filter expects a callback function.' ) ; } var len = arr . length ; var res = arr . slice ( ) ; var i = 0 ; while ( len -- ) { if ( ! cb ( arr [ len ] , i ++ ) ) { res . splice ( len , 1 ) ; } } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the given extglob string to a regex - compatible string . [CODESPLIT] function extglob ( str , opts ) { opts = opts || { } ; var o = { } , i = 0 ; // fix common character reversals // '*!(.js)' => '*.!(js)' str = str . replace ( / !\\(([^\\w*()]) / g , '$1!(' ) ; // support file extension negation str = str . replace ( / ([*\\/])\\.!\\([*]\\) / g , function ( m , ch ) { if ( ch === '/' ) { return escape ( '\\\\/[^.]+' ) ; } return escape ( '[^.]+' ) ; } ) ; // create a unique key for caching by // combining the string and options var key = str + String ( ! ! opts . regex ) + String ( ! ! opts . contains ) + String ( ! ! opts . escape ) ; if ( cache . hasOwnProperty ( key ) ) { return cache [ key ] ; } if ( ! ( re instanceof RegExp ) ) { re = regex ( ) ; } opts . negate = false ; var m ; while ( m = re . exec ( str ) ) { var prefix = m [ 1 ] ; var inner = m [ 3 ] ; if ( prefix === '!' ) { opts . negate = true ; } var id = '__EXTGLOB_' + ( i ++ ) + '__' ; // use the prefix of the _last_ (outtermost) pattern o [ id ] = wrap ( inner , prefix , opts . escape ) ; str = str . split ( m [ 0 ] ) . join ( id ) ; } var keys = Object . keys ( o ) ; var len = keys . length ; // we have to loop again to allow us to convert // patterns in reverse order (starting with the // innermost/last pattern first) while ( len -- ) { var prop = keys [ len ] ; str = str . split ( prop ) . join ( o [ prop ] ) ; } var result = opts . regex ? toRegex ( str , opts . contains , opts . negate ) : str ; result = result . split ( '.' ) . join ( '\\\\.' ) ; // cache the result and return it return ( cache [ key ] = result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert string to a regex string . [CODESPLIT] function wrap ( inner , prefix , esc ) { if ( esc ) inner = escape ( inner ) ; switch ( prefix ) { case '!' : return '(?!' + inner + ')[^/]' + ( esc ? '%%%~' : '*?' ) ; case '@' : return '(?:' + inner + ')' ; case '+' : return '(?:' + inner + ')+' ; case '*' : return '(?:' + inner + ')' + ( esc ? '%%' : '*' ) case '?' : return '(?:' + inner + '|)' ; default : return inner ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the regex to do the matching . If the leading character in the pattern is ! a negation regex is returned . [CODESPLIT] function toRegex ( pattern , contains , isNegated ) { var prefix = contains ? '^' : '' ; var after = contains ? '$' : '' ; pattern = ( '(?:' + pattern + ')' + after ) ; if ( isNegated ) { pattern = prefix + negate ( pattern ) ; } return new RegExp ( prefix + pattern ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy properties from the source object to the target object . [CODESPLIT] function copy ( val , key ) { if ( key === '__proto__' ) { return ; } var obj = this [ key ] ; if ( isObject ( val ) && isObject ( obj ) ) { mixinDeep ( obj , val ) ; } else { this [ key ] = val ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Advance to the next non - escaped character [CODESPLIT] function advanceTo ( input , endChar ) { var ch = input . charAt ( 0 ) ; var tok = { len : 1 , val : '' , esc : '' } ; var idx = 0 ; function advance ( ) { if ( ch !== '\\\\' ) { tok . esc += '\\\\' + ch ; tok . val += ch ; } ch = input . charAt ( ++ idx ) ; tok . len ++ ; if ( ch === '\\\\' ) { advance ( ) ; advance ( ) ; } } while ( ch && ch !== endChar ) { advance ( ) ; } return tok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create text regex [CODESPLIT] function createTextRegex ( pattern ) { if ( cached ) return cached ; var opts = { contains : true , strictClose : false } ; var not = regexNot . create ( pattern , opts ) ; var re = toRegex ( '^(?:[*]\\\\((?=.)|' + not + ')' , opts ) ; return ( cached = re ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new { @link Processor } instance that will apply plugins as CSS processors . [CODESPLIT] function postcss ( ) { for ( var _len = arguments . length , plugins = Array ( _len ) , _key = 0 ; _key < _len ; _key ++ ) { plugins [ _key ] = arguments [ _key ] ; } if ( plugins . length === 1 && Array . isArray ( plugins [ 0 ] ) ) { plugins = plugins [ 0 ] ; } return new _processor2 . default ( plugins ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A BasicSourceMapConsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source . [CODESPLIT] function BasicSourceMapConsumer ( aSourceMap , aSourceMapURL ) { var sourceMap = aSourceMap ; if ( typeof aSourceMap === 'string' ) { sourceMap = util . parseSourceMapInput ( aSourceMap ) ; } var version = util . getArg ( sourceMap , 'version' ) ; var sources = util . getArg ( sourceMap , 'sources' ) ; // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util . getArg ( sourceMap , 'names' , [ ] ) ; var sourceRoot = util . getArg ( sourceMap , 'sourceRoot' , null ) ; var sourcesContent = util . getArg ( sourceMap , 'sourcesContent' , null ) ; var mappings = util . getArg ( sourceMap , 'mappings' ) ; var file = util . getArg ( sourceMap , 'file' , null ) ; // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if ( version != this . _version ) { throw new Error ( 'Unsupported version: ' + version ) ; } if ( sourceRoot ) { sourceRoot = util . normalize ( sourceRoot ) ; } sources = sources . map ( String ) // Some source maps produce relative source paths like \"./foo.js\" instead of // \"foo.js\".  Normalize these first so that future comparisons will succeed. // See bugzil.la/1090768. . map ( util . normalize ) // Always ensure that absolute sources are internally stored relative to // the source root, if the source root is absolute. Not doing this would // be particularly problematic when the source root is a prefix of the // source (valid, but why??). See github issue #199 and bugzil.la/1188982. . map ( function ( source ) { return sourceRoot && util . isAbsolute ( sourceRoot ) && util . isAbsolute ( source ) ? util . relative ( sourceRoot , source ) : source ; } ) ; // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this . _names = ArraySet . fromArray ( names . map ( String ) , true ) ; this . _sources = ArraySet . fromArray ( sources , true ) ; this . _absoluteSources = this . _sources . toArray ( ) . map ( function ( s ) { return util . computeSourceURL ( sourceRoot , s , aSourceMapURL ) ; } ) ; this . sourceRoot = sourceRoot ; this . sourcesContent = sourcesContent ; this . _mappings = mappings ; this . _sourceMapURL = aSourceMapURL ; this . file = file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Comparator between two mappings where the original positions are compared . [CODESPLIT] function compareByOriginalPositions ( mappingA , mappingB , onlyCompareOriginal ) { var cmp = strcmp ( mappingA . source , mappingB . source ) ; if ( cmp !== 0 ) { return cmp ; } cmp = mappingA . originalLine - mappingB . originalLine ; if ( cmp !== 0 ) { return cmp ; } cmp = mappingA . originalColumn - mappingB . originalColumn ; if ( cmp !== 0 || onlyCompareOriginal ) { return cmp ; } cmp = mappingA . generatedColumn - mappingB . generatedColumn ; if ( cmp !== 0 ) { return cmp ; } cmp = mappingA . generatedLine - mappingB . generatedLine ; if ( cmp !== 0 ) { return cmp ; } return strcmp ( mappingA . name , mappingB . name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Comparator between two mappings with deflated source and name indices where the generated positions are compared . [CODESPLIT] function compareByGeneratedPositionsDeflated ( mappingA , mappingB , onlyCompareGenerated ) { var cmp = mappingA . generatedLine - mappingB . generatedLine ; if ( cmp !== 0 ) { return cmp ; } cmp = mappingA . generatedColumn - mappingB . generatedColumn ; if ( cmp !== 0 || onlyCompareGenerated ) { return cmp ; } cmp = strcmp ( mappingA . source , mappingB . source ) ; if ( cmp !== 0 ) { return cmp ; } cmp = mappingA . originalLine - mappingB . originalLine ; if ( cmp !== 0 ) { return cmp ; } cmp = mappingA . originalColumn - mappingB . originalColumn ; if ( cmp !== 0 ) { return cmp ; } return strcmp ( mappingA . name , mappingB . name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the URL of a source given the the source root the source s URL and the source map s URL . [CODESPLIT] function computeSourceURL ( sourceRoot , sourceURL , sourceMapURL ) { sourceURL = sourceURL || '' ; if ( sourceRoot ) { // This follows what Chrome does. if ( sourceRoot [ sourceRoot . length - 1 ] !== '/' && sourceURL [ 0 ] !== '/' ) { sourceRoot += '/' ; } // The spec says: //   Line 4: An optional source root, useful for relocating source //   files on a server or removing repeated values in the //   “sources” entry.  This value is prepended to the individual //   entries in the “source” field. sourceURL = sourceRoot + sourceURL ; } // Historically, SourceMapConsumer did not take the sourceMapURL as // a parameter.  This mode is still somewhat supported, which is why // this code block is conditional.  However, it's preferable to pass // the source map URL to SourceMapConsumer, so that this function // can implement the source URL resolution algorithm as outlined in // the spec.  This block is basically the equivalent of: //    new URL(sourceURL, sourceMapURL).toString() // ... except it avoids using URL, which wasn't available in the // older releases of node still supported by this library. // // The spec says: //   If the sources are not absolute URLs after prepending of the //   “sourceRoot”, the sources are resolved relative to the //   SourceMap (like resolving script src in a html document). if ( sourceMapURL ) { var parsed = urlParse ( sourceMapURL ) ; if ( ! parsed ) { throw new Error ( \"sourceMapURL could not be parsed\" ) ; } if ( parsed . path ) { // Strip the last path component, but keep the \"/\". var index = parsed . path . lastIndexOf ( '/' ) ; if ( index >= 0 ) { parsed . path = parsed . path . substring ( 0 , index + 1 ) ; } } sourceURL = join ( urlGenerate ( parsed ) , sourceURL ) ; } return normalize ( sourceURL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It seems a linked list but it is not there will be only 2 of these for each stream [CODESPLIT] function CorkedRequest ( state ) { var _this = this ; this . next = null ; this . entry = null ; this . finish = function ( ) { onCorkedFinish ( _this , state ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if there s something in the buffer waiting then process it [CODESPLIT] function clearBuffer ( stream , state ) { state . bufferProcessing = true ; var entry = state . bufferedRequest ; if ( stream . _writev && entry && entry . next ) { // Fast case, write everything using _writev() var l = state . bufferedRequestCount ; var buffer = new Array ( l ) ; var holder = state . corkedRequestsFree ; holder . entry = entry ; var count = 0 ; var allBuffers = true ; while ( entry ) { buffer [ count ] = entry ; if ( ! entry . isBuf ) allBuffers = false ; entry = entry . next ; count += 1 ; } buffer . allBuffers = allBuffers ; doWrite ( stream , state , true , state . length , buffer , '' , holder . finish ) ; // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state . pendingcb ++ ; state . lastBufferedRequest = null ; if ( holder . next ) { state . corkedRequestsFree = holder . next ; holder . next = null ; } else { state . corkedRequestsFree = new CorkedRequest ( state ) ; } state . bufferedRequestCount = 0 ; } else { // Slow case, write chunks one-by-one while ( entry ) { var chunk = entry . chunk ; var encoding = entry . encoding ; var cb = entry . callback ; var len = state . objectMode ? 1 : chunk . length ; doWrite ( stream , state , false , len , chunk , encoding , cb ) ; entry = entry . next ; state . bufferedRequestCount -- ; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if ( state . writing ) { break ; } } if ( entry === null ) state . lastBufferedRequest = null ; } state . bufferedRequest = entry ; state . bufferProcessing = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * < / replacement > undocumented cb () API needed for core not for public API [CODESPLIT] function destroy ( err , cb ) { var _this = this ; var readableDestroyed = this . _readableState && this . _readableState . destroyed ; var writableDestroyed = this . _writableState && this . _writableState . destroyed ; if ( readableDestroyed || writableDestroyed ) { if ( cb ) { cb ( err ) ; } else if ( err && ( ! this . _writableState || ! this . _writableState . errorEmitted ) ) { pna . nextTick ( emitErrorNT , this , err ) ; } return this ; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if ( this . _readableState ) { this . _readableState . destroyed = true ; } // if this is a duplex stream mark the writable part as destroyed as well if ( this . _writableState ) { this . _writableState . destroyed = true ; } this . _destroy ( err || null , function ( err ) { if ( ! cb && err ) { pna . nextTick ( emitErrorNT , _this , err ) ; if ( _this . _writableState ) { _this . _writableState . errorEmitted = true ; } } else if ( cb ) { cb ( err ) ; } } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new AST Node with the given val and type . [CODESPLIT] function Node ( val , type , parent ) { if ( typeof type !== 'string' ) { parent = type ; type = null ; } define ( this , 'parent' , parent ) ; define ( this , 'isNode' , true ) ; define ( this , 'expect' , null ) ; if ( typeof type !== 'string' && isObject ( val ) ) { lazyKeys ( ) ; var keys = Object . keys ( val ) ; for ( var i = 0 ; i < keys . length ; i ++ ) { var key = keys [ i ] ; if ( ownNames . indexOf ( key ) === - 1 ) { this [ key ] = val [ key ] ; } } } else { this . type = type ; this . val = val ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shim to ensure the . append methods work with any version of snapdragon [CODESPLIT] function append ( compiler , val , node ) { if ( typeof compiler . append !== 'function' ) { return compiler . emit ( val , node ) ; } return compiler . append ( val , node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new instance of Snapdragon with the given options . [CODESPLIT] function Snapdragon ( options ) { Base . call ( this , null , options ) ; this . options = utils . extend ( { source : 'string' } , this . options ) ; this . compiler = new Compiler ( this . options ) ; this . parser = new Parser ( this . options ) ; Object . defineProperty ( this , 'compilers' , { get : function ( ) { return this . compiler . compilers ; } } ) ; Object . defineProperty ( this , 'parsers' , { get : function ( ) { return this . parser . parsers ; } } ) ; Object . defineProperty ( this , 'regex' , { get : function ( ) { return this . parser . regex ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Compiler with the given options . [CODESPLIT] function Compiler ( options , state ) { debug ( 'initializing' , __filename ) ; this . options = utils . extend ( { source : 'string' } , options ) ; this . state = state || { } ; this . compilers = { } ; this . output = '' ; this . set ( 'eos' , function ( node ) { return this . emit ( node . val , node ) ; } ) ; this . set ( 'noop' , function ( node ) { return this . emit ( node . val , node ) ; } ) ; this . set ( 'bos' , function ( node ) { return this . emit ( node . val , node ) ; } ) ; use ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throw an error message with details including the cursor position . [CODESPLIT] function ( msg , node ) { var pos = node . position || { start : { column : 0 } } ; var message = this . options . source + ' column:' + pos . start . column + ': ' + msg ; var err = new Error ( message ) ; err . reason = msg ; err . column = pos . start . column ; err . source = this . pattern ; if ( this . options . silent ) { this . errors . push ( err ) ; } else { throw err ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visit node . [CODESPLIT] function ( node , nodes , i ) { var fn = this . compilers [ node . type ] ; this . idx = i ; if ( typeof fn !== 'function' ) { throw this . error ( 'compiler \"' + node . type + '\" is not registered' , node ) ; } return fn . call ( this , node , nodes , i ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map visit over array of nodes . [CODESPLIT] function ( nodes ) { if ( ! Array . isArray ( nodes ) ) { throw new TypeError ( 'expected an array' ) ; } var len = nodes . length ; var idx = - 1 ; while ( ++ idx < len ) { this . visit ( nodes [ idx ] , nodes , idx ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile ast . [CODESPLIT] function ( ast , options ) { var opts = utils . extend ( { } , this . options , options ) ; this . ast = ast ; this . parsingErrors = this . ast . errors ; this . output = '' ; // source map support if ( opts . sourcemap ) { var sourcemaps = require ( './source-maps' ) ; sourcemaps ( this ) ; this . mapVisit ( this . ast . nodes ) ; this . applySourceMaps ( ) ; this . map = opts . sourcemap === 'generator' ? this . map : this . map . toJSON ( ) ; return this ; } this . mapVisit ( this . ast . nodes ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Parser with the given input and options . [CODESPLIT] function Parser ( options ) { debug ( 'initializing' , __filename ) ; this . options = utils . extend ( { source : 'string' } , options ) ; this . init ( this . options ) ; use ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mark position and patch node . position . [CODESPLIT] function ( ) { var start = { line : this . line , column : this . column } ; var self = this ; return function ( node ) { define ( node , 'position' , new Position ( start , self ) ) ; return node ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set parser name with the given fn [CODESPLIT] function ( type , fn ) { if ( this . types . indexOf ( type ) === - 1 ) { this . types . push ( type ) ; } this . parsers [ type ] = fn . bind ( this ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push a token onto the type stack . [CODESPLIT] function ( type , token ) { this . sets [ type ] = this . sets [ type ] || [ ] ; this . count ++ ; this . stack . push ( token ) ; return this . sets [ type ] . push ( token ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pop a token off of the type stack [CODESPLIT] function ( type ) { this . sets [ type ] = this . sets [ type ] || [ ] ; this . count -- ; this . stack . pop ( ) ; return this . sets [ type ] . pop ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the previous AST node [CODESPLIT] function ( n ) { return this . stack . length > 0 ? utils . last ( this . stack , n ) : utils . last ( this . nodes , n ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update column based on str . [CODESPLIT] function ( str , len ) { var lines = str . match ( / \\n / g ) ; if ( lines ) this . line += lines . length ; var i = str . lastIndexOf ( '\\n' ) ; this . column = ~ i ? len - i : this . column + len ; this . parsed += str ; this . consume ( len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Capture type with the given regex . [CODESPLIT] function ( type , regex ) { if ( typeof regex === 'function' ) { return this . set . apply ( this , arguments ) ; } this . regex . set ( type , regex ) ; this . set ( type , function ( ) { var parsed = this . parsed ; var pos = this . position ( ) ; var m = this . match ( regex ) ; if ( ! m || ! m [ 0 ] ) return ; var prev = this . prev ( ) ; var node = pos ( { type : type , val : m [ 0 ] , parsed : parsed , rest : this . input } ) ; if ( m [ 1 ] ) { node . inner = m [ 1 ] ; } define ( node , 'inside' , this . stack . length > 0 ) ; define ( node , 'parent' , prev ) ; prev . nodes . push ( node ) ; } . bind ( this ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a parser with open and close for parens brackets or braces [CODESPLIT] function ( type , openRegex , closeRegex , fn ) { this . sets [ type ] = this . sets [ type ] || [ ] ; /**\n     * Open\n     */ this . set ( type + '.open' , function ( ) { var parsed = this . parsed ; var pos = this . position ( ) ; var m = this . match ( openRegex ) ; if ( ! m || ! m [ 0 ] ) return ; var val = m [ 0 ] ; this . setCount ++ ; this . specialChars = true ; var open = pos ( { type : type + '.open' , val : val , rest : this . input } ) ; if ( typeof m [ 1 ] !== 'undefined' ) { open . inner = m [ 1 ] ; } var prev = this . prev ( ) ; var node = pos ( { type : type , nodes : [ open ] } ) ; define ( node , 'rest' , this . input ) ; define ( node , 'parsed' , parsed ) ; define ( node , 'prefix' , m [ 1 ] ) ; define ( node , 'parent' , prev ) ; define ( open , 'parent' , node ) ; if ( typeof fn === 'function' ) { fn . call ( this , open , node ) ; } this . push ( type , node ) ; prev . nodes . push ( node ) ; } ) ; /**\n     * Close\n     */ this . set ( type + '.close' , function ( ) { var pos = this . position ( ) ; var m = this . match ( closeRegex ) ; if ( ! m || ! m [ 0 ] ) return ; var parent = this . pop ( type ) ; var node = pos ( { type : type + '.close' , rest : this . input , suffix : m [ 1 ] , val : m [ 0 ] } ) ; if ( ! this . isType ( parent , type ) ) { if ( this . options . strict ) { throw new Error ( 'missing opening \"' + type + '\"' ) ; } this . setCount -- ; node . escaped = true ; return node ; } if ( node . suffix === '\\\\' ) { parent . escaped = true ; node . escaped = true ; } parent . nodes . push ( node ) ; define ( node , 'parent' , parent ) ; } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Capture end - of - string [CODESPLIT] function ( ) { var pos = this . position ( ) ; if ( this . input ) return ; var prev = this . prev ( ) ; while ( prev . type !== 'root' && ! prev . visited ) { if ( this . options . strict === true ) { throw new SyntaxError ( 'invalid syntax:' + util . inspect ( prev , null , 2 ) ) ; } if ( ! hasDelims ( prev ) ) { prev . parent . escaped = true ; prev . escaped = true ; } visit ( prev , function ( node ) { if ( ! hasDelims ( node . parent ) ) { node . parent . escaped = true ; node . escaped = true ; } } ) ; prev = prev . parent ; } var tok = pos ( { type : 'eos' , val : this . append || '' } ) ; define ( tok , 'parent' , this . ast ) ; return tok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run parsers to advance the cursor position [CODESPLIT] function ( ) { var parsed = this . parsed ; var len = this . types . length ; var idx = - 1 ; var tok ; while ( ++ idx < len ) { if ( ( tok = this . parsers [ this . types [ idx ] ] . call ( this ) ) ) { define ( tok , 'rest' , this . input ) ; define ( tok , 'parsed' , parsed ) ; this . last = tok ; return tok ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given string . [CODESPLIT] function ( input ) { if ( typeof input !== 'string' ) { throw new TypeError ( 'expected a string' ) ; } this . init ( this . options ) ; this . orig = input ; this . input = input ; var self = this ; function parse ( ) { // check input before calling `.next()` input = self . input ; // get the next AST ndoe var node = self . next ( ) ; if ( node ) { var prev = self . prev ( ) ; if ( prev ) { define ( node , 'parent' , prev ) ; if ( prev . nodes ) { prev . nodes . push ( node ) ; } } if ( self . sets . hasOwnProperty ( prev . type ) ) { self . currentType = prev . type ; } } // if we got here but input is not changed, throw an error if ( self . input && input === self . input ) { throw new Error ( 'no parsers registered for: \"' + self . input . slice ( 0 , 5 ) + '\"' ) ; } } while ( this . input ) parse ( ) ; if ( this . stack . length && this . options . strict ) { var node = this . stack . pop ( ) ; throw this . error ( 'missing opening ' + node . type + ': \"' + this . orig + '\"' ) ; } var eos = this . eos ( ) ; var tok = this . prev ( ) ; if ( tok . type !== 'eos' ) { this . ast . nodes . push ( eos ) ; } return this . ast ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visit node with the given fn [CODESPLIT] function visit ( node , fn ) { if ( ! node . visited ) { define ( node , 'visited' , true ) ; return node . nodes ? mapVisit ( node . nodes , fn ) : fn ( node ) ; } return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mixin source map support into compiler . [CODESPLIT] function mixin ( compiler ) { define ( compiler , '_comment' , compiler . comment ) ; compiler . map = new utils . SourceMap . SourceMapGenerator ( ) ; compiler . position = { line : 1 , column : 1 } ; compiler . content = { } ; compiler . files = { } ; for ( var key in exports ) { define ( compiler , key , exports [ key ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For UTF - 8 a replacement character is added when ending on a partial character . [CODESPLIT] function utf8End ( buf ) { var r = buf && buf . length ? this . write ( buf ) : '' ; if ( this . lastNeed ) return r + '\\ufffd' ; return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a range to a regex pattern [CODESPLIT] function rangeToPattern ( start , stop , options ) { if ( start === stop ) { return { pattern : String ( start ) , digits : [ ] } ; } var zipped = zip ( String ( start ) , String ( stop ) ) ; var len = zipped . length , i = - 1 ; var pattern = '' ; var digits = 0 ; while ( ++ i < len ) { var numbers = zipped [ i ] ; var startDigit = numbers [ 0 ] ; var stopDigit = numbers [ 1 ] ; if ( startDigit === stopDigit ) { pattern += startDigit ; } else if ( startDigit !== '0' || stopDigit !== '9' ) { pattern += toCharacterClass ( startDigit , stopDigit ) ; } else { digits += 1 ; } } if ( digits ) { pattern += options . shorthand ? '\\\\d' : '[0-9]' ; } return { pattern : pattern , digits : [ digits ] } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Zip strings ( for in can be used on string characters ) [CODESPLIT] function zip ( a , b ) { var arr = [ ] ; for ( var ch in a ) arr . push ( [ a [ ch ] , b [ ch ] ] ) ; return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call plugin fn . If a function is returned push it into the fns array to be called by the run method . [CODESPLIT] function use ( type , fn , options ) { var offset = 1 ; if ( typeof type === 'string' || Array . isArray ( type ) ) { fn = wrap ( type , fn ) ; offset ++ ; } else { options = fn ; fn = type ; } if ( typeof fn !== 'function' ) { throw new TypeError ( 'expected a function' ) ; } var self = this || app ; var fns = self [ prop ] ; var args = [ ] . slice . call ( arguments , offset ) ; args . unshift ( self ) ; if ( typeof opts . hook === 'function' ) { opts . hook . apply ( self , args ) ; } var val = fn . apply ( self , args ) ; if ( typeof val === 'function' && fns . indexOf ( val ) === - 1 ) { fns . push ( val ) ; } return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap a named plugin function so that it s only called on objects of the given type [CODESPLIT] function wrap ( type , fn ) { return function plugin ( ) { return this . type === type ? fn . apply ( this , arguments ) : plugin ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ methods /// [CODESPLIT] function processArguments ( ) { var arg ; for ( var i = 2 ; i < process . argv . length ; ++ i ) { arg = process . argv [ i ] ; if ( arg === \"-l\" || arg === \"-log\" ) enableLog = true ; else if ( arg === \"-m\" || arg === \"--minify\" ) enableMinify = true ; else if ( arg === \"-f\" || arg === \"--folder\" ) inputIsFolder = true ; else if ( arg === \"-s\" || arg === \"--silent\" ) enableSilent = true ; else if ( arg === \"-i\" || arg === \"--input\" ) input = process . argv [ ++ i ] ; else if ( arg === \"-o\" || arg === \"--output\" ) output = process . argv [ ++ i ] ; else if ( arg === \"-e\" || arg === \"--ensure\" ) includeInq = true ; else if ( arg === \"-d\" || arg === \"--define\" ) definitions = process . argv [ ++ i ] . split ( ' ' ) ; else console . error ( \"[WARNING] Unknown compiler flag: \" + arg ) ; } if ( ! output ) output = input + ( inputIsFolder ? \"\" : \".js\" ) ; return ! ! input ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ private methods /// [CODESPLIT] function tryInit ( ) { var temp , i , files ; if ( ! processors . length ) { var processorsPath = path . resolve ( __dirname , \"processor\" ) ; files = fs . readdirSync ( processorsPath ) ; for ( i = 0 ; i < files . length ; ++ i ) { temp = require ( path . resolve ( processorsPath , files [ i ] ) ) ; processors . push ( temp ) ; processorsNamed [ temp . name ] = temp ; } } if ( ! complexExpressions . length ) { var expressionsPath = path . resolve ( __dirname , \"combination\" ) ; files = fs . readdirSync ( expressionsPath ) ; for ( i = 0 ; i < files . length ; ++ i ) { temp = require ( path . resolve ( expressionsPath , files [ i ] ) ) ; complexExpressions [ temp . name ] = temp . value ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CalEvent object [CODESPLIT] function CalEvent ( name , startDate , endDate , description , location , uid ) { if ( startDate instanceof Date ) { this . startDate = startDate ; } else { return null ; } if ( endDate instanceof Date ) { this . endDate = endDate ; } else { return null ; } this . uid = uid == null ? ( util . guid ( ) + '@node-cal-event.js' ) : uid ; this . summary = name ; this . location = location ; this . description = description ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public functions [CODESPLIT] function ask ( questions ) { \"use strict\" ; let answers = { } ; let i = 0 ; return new Promise ( function ( resolve , reject ) { function askQuestion ( item ) { let key = item . key ; let msg = item . msg ; let fn = fnList [ item . fn ] ; if ( ! key ) { throw new Error ( 'A value for `key` must be defined for question ' + i ) ; } if ( ! msg ) { throw new Error ( 'A value for `msg` must be defined for question ' + i ) ; } if ( ! fn ) { throw new Error ( 'A value for `fn` must be \"prompt\", \"confirm\", or \"multiline\" for question ' + i ) ; } if ( fn ) { fn ( msg , key , answers ) . then ( function ( ) { next ( ) ; } ) ; } } function next ( ) { if ( i < questions . length ) { var question = questions [ i ] ; i ++ ; askQuestion ( question ) ; } else { resolve ( answers ) ; } } next ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private functions [CODESPLIT] function promiseFn ( msg , key , answers , fn ) { \"use strict\" ; answers = answers || { } ; return fn ( msg ) . then ( function ( resp ) { answers [ key ] = resp ; return answers ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a middleware stack ( obj obj [ fn ( obj obj fn? ) ] fn ) - > null [CODESPLIT] function httpMiddleware ( req , res , arr , done ) { done = done || noop assert . ok ( isReq ( req ) , 'is incoming message' ) assert . ok ( isRes ( res ) , 'is server response' ) assert . ok ( Array . isArray ( arr ) , 'is array' ) assert . equal ( typeof done , 'function' , 'is function' ) mapLimit ( arr , 1 , iterator , done ) function iterator ( fn , next ) { next = dezalgo ( next ) if ( fn . length === 3 ) return fn ( req , res , next ) fn ( req , res ) next ( ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Caches results of unary or binary function . [CODESPLIT] function memoize ( fun ) { // Making cache = {} an optional ES6 parameter breaks coverage. Why? /** @type {({ [key: string]: any })} */ const cache = { } ; if ( fun . length === 1 ) { return ( /** @type {any} */ arg ) => { if ( arg in cache ) { return cache [ arg ] ; } const result = fun ( arg ) ; cache [ arg ] = result ; return result ; } ; } return ( /** @type {any} */ arg1 , /** @type {any} */ arg2 ) => { if ( cache [ arg1 ] && arg2 in cache [ arg1 ] ) { return cache [ arg1 ] [ arg2 ] ; } const result = fun ( arg1 , arg2 ) ; if ( ! cache [ arg1 ] ) { cache [ arg1 ] = { } ; } cache [ arg1 ] [ arg2 ] = result ; return result ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates all the task definition to shut down ( detach ) all instances in origin . [CODESPLIT] function generateDetachTasks ( planner , origin , opts ) { _ . forIn ( origin . topology . containers , function ( container ) { var stopSubTask = { cmd : 'stop' , id : container . id , parent : container . containedBy } ; var removeSubTask = { cmd : 'remove' , id : container . id , parent : container . containedBy } ; var unlinkSubTask = { cmd : 'unlink' , id : container . id , parent : container . containedBy } ; var detachOp = { preconditions : containerStatus ( container , 'running' ) , subTasks : [ unlinkSubTask , stopSubTask , removeSubTask ] } ; var unlinkPreconditions = containerStatus ( container , 'running' ) ; var stopPrecondition = containerStatus ( container , 'started' ) ; var removePrecondition = containerStatus ( container , 'added' ) ; container . contains . forEach ( function ( contained ) { var status = containerStatus ( { id : contained } , 'started' ) ; stopPrecondition = _ . merge ( stopPrecondition , status ) ; detachOp . subTasks . splice ( 1 , 0 , { cmd : 'detach' , id : contained } ) ; } ) ; if ( opts . mode === 'safe' ) { allParentsIds ( origin , container ) . forEach ( function ( id ) { detachOp . subTasks . unshift ( { cmd : 'unlink' , id : id , parent : origin . topology . containers [ id ] . containedBy } ) ; detachOp . subTasks . push ( { cmd : 'link' , id : id , parent : origin . topology . containers [ id ] . containedBy } ) ; } ) ; } planner . addTask ( { cmd : 'detach' , id : container . id } , { preconditions : containerStatus ( container , 'detached' ) , subTasks : [ { cmd : 'nop' } ] } ) ; planner . addTask ( { cmd : 'detach' , id : container . id } , detachOp ) ; planner . addTask ( unlinkSubTask , { preconditions : unlinkPreconditions , effects : containerStatus ( container , { running : false } ) } ) ; planner . addTask ( unlinkSubTask , { preconditions : containerStatus ( container , { running : false } ) , subTasks : [ { cmd : 'nop' } ] } ) ; planner . addTask ( stopSubTask , { preconditions : containerStatus ( container , 'started' ) , effects : containerStatus ( container , 'added' ) } ) ; planner . addTask ( stopSubTask , { preconditions : containerStatus ( container , { running : false , started : false } ) , subTasks : [ { cmd : 'nop' } ] } ) ; planner . addTask ( removeSubTask , { preconditions : removePrecondition , effects : containerStatus ( container , 'detached' ) } ) ; planner . addTask ( removeSubTask , { preconditions : containerStatus ( container , 'detached' ) , subTasks : [ { cmd : 'nop' } ] } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Protects the given object by wrapping it in a Proxy . [CODESPLIT] function keyblade ( obj , opts ) { opts = Object . assign ( { message : _defaultMessage , logBeforeThrow : true , ignore : [ ] } , opts ) opts . ignore = ( opts . ignore && Array . isArray ( opts . ignore ) ) ? opts . ignore : [ ] return new Proxy ( obj , { get ( target , propKey , receiver ) { const useGetter = Reflect . has ( target , propKey , receiver ) || _isReserved ( propKey , opts . ignore ) if ( useGetter ) { return Reflect . get ( target , propKey , receiver ) } // Leave symbols alone. if ( typeof propKey === 'symbol' ) { return Reflect . get ( target , propKey , receiver ) } const message = opts . message ( propKey ) if ( opts . logBeforeThrow ) { if ( typeof opts . logBeforeThrow === 'function' ) { opts . logBeforeThrow ( message , propKey ) } else { console . error ( message ) } } throw new UndefinedKeyError ( message ) } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LINEAR CORRELATION // FUNCTION : pcorr ( arr1 [ arr2 ... ] ) Computes Pearson product - moment correlation coefficients between one or more numeric arrays . [CODESPLIT] function pcorr ( ) { var args , nArgs , len , deltas , delta , means , stdevs , C , cov , corr , arr , N , r , A , B , sum , val , sigma , i , j , n ; args = Array . prototype . slice . call ( arguments ) ; nArgs = args . length ; if ( ! nArgs ) { throw new Error ( 'pcorr()::insufficient input arguments. Must provide array arguments.' ) ; } for ( i = 0 ; i < nArgs ; i ++ ) { if ( ! Array . isArray ( args [ i ] ) ) { throw new TypeError ( 'pcorr()::invalid input argument. Must provide array arguments.' ) ; } } if ( Array . isArray ( args [ 0 ] [ 0 ] ) ) { // If the first argument is an array of arrays, calculate the correlation matrix over the nested arrays, disregarding any other arguments... args = args [ 0 ] ; } nArgs = args . length ; len = args [ 0 ] . length ; for ( i = 1 ; i < nArgs ; i ++ ) { if ( args [ i ] . length !== len ) { throw new Error ( 'pcorr()::invalid input argument. All arrays must have equal length.' ) ; } } // [0] Initialization... deltas = new Array ( nArgs ) ; means = new Array ( nArgs ) ; stdevs = new Array ( nArgs ) ; C = new Array ( nArgs ) ; cov = new Array ( nArgs ) ; corr = new Array ( nArgs ) ; for ( i = 0 ; i < nArgs ; i ++ ) { means [ i ] = args [ i ] [ 0 ] ; arr = new Array ( nArgs ) ; for ( j = 0 ; j < nArgs ; j ++ ) { arr [ j ] = 0 ; } C [ i ] = arr ; cov [ i ] = arr . slice ( ) ; // copy! corr [ i ] = arr . slice ( ) ; // copy! } if ( len < 2 ) { return corr ; } // [1] Compute the covariance... for ( n = 1 ; n < len ; n ++ ) { N = n + 1 ; r = n / N ; // [a] Extract the values and compute the deltas... for ( i = 0 ; i < nArgs ; i ++ ) { deltas [ i ] = args [ i ] [ n ] - means [ i ] ; } // [b] Update the covariance between one array and every other array... for ( i = 0 ; i < nArgs ; i ++ ) { arr = C [ i ] ; delta = deltas [ i ] ; for ( j = i ; j < nArgs ; j ++ ) { A = arr [ j ] ; B = r * delta * deltas [ j ] ; sum = A + B ; // Exploit the fact that the covariance matrix is symmetric... if ( i !== j ) { C [ j ] [ i ] = sum ; } arr [ j ] = sum ; } // end FOR j } // end FOR i // [c] Update the means... for ( i = 0 ; i < nArgs ; i ++ ) { means [ i ] += deltas [ i ] / N ; } } // end FOR n // [2] Normalize the co-moments... n = N - 1 ; for ( i = 0 ; i < nArgs ; i ++ ) { arr = C [ i ] ; for ( j = i ; j < nArgs ; j ++ ) { val = arr [ j ] / n ; cov [ i ] [ j ] = val ; if ( i !== j ) { cov [ j ] [ i ] = val ; } } } // [3] Compute the standard deviations... for ( i = 0 ; i < nArgs ; i ++ ) { // Diagonal elements of covariance matrix... stdevs [ i ] = Math . sqrt ( cov [ i ] [ i ] ) ; } // [4] Set the diagonal elements to 1: for ( i = 0 ; i < nArgs ; i ++ ) { corr [ i ] [ i ] = 1 ; } // [5] Compute the correlation coefficients... for ( i = 0 ; i < nArgs ; i ++ ) { arr = cov [ i ] ; sigma = stdevs [ i ] ; for ( j = i + 1 ; j < nArgs ; j ++ ) { val = arr [ j ] / ( sigma * stdevs [ j ] ) ; // Address floating point errors introduced by taking the sqrt and enforce strict [-1,1] bounds... if ( val > 1 ) { val = 1 ; } else if ( val < - 1 ) { val = - 1 ; } corr [ i ] [ j ] = val ; corr [ j ] [ i ] = val ; } } return corr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get or build a sub register for an object . [CODESPLIT] function subRegister ( obj , name ) { var res ; res = isPrimitive ( obj [ name ] ) ? { } : obj [ name ] ; return obj [ name ] = mixable ( res ) . mixin ( proto , 'register' , 'extend' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to handle with require () . [CODESPLIT] function registerMod ( leaf , dir , name ) { var modPath ; try { modPath = require . resolve ( dir ) ; } catch ( _error ) { } if ( modPath == null ) { return false ; } // Define a getter with the base name. name = path . basename ( name , path . extname ( name ) ) ; Object . defineProperty ( leaf , name , { configurable : true , enumerable : true , get : function ( ) { if ( require . cache [ modPath ] == null ) { debug ( 'loading %s.' , modPath ) ; } return require ( modPath ) ; } } ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to handle as a directory . [CODESPLIT] function registerDir ( leaf , dir , name ) { var files ; try { files = fs . readdirSync ( dir ) ; } catch ( _error ) { } if ( files == null ) { return false ; } if ( name != null ) { leaf = subRegister ( leaf , name ) ; } for ( var i = 0 , len = files . length ; i < len ; i ++ ) { name = files [ i ] ; leaf . register ( dir , name ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register . [CODESPLIT] function register ( root ) { var leaf = this ; // jscs:ignore safeContextKeyword // TODO: default base path? var dir = path . resolve ( root ) ; // Try as a directory if no name given. if ( arguments . length <= 1 ) { registerDir ( this , dir ) ; return this ; } // The names are not only path to the files but also path to the attributes. for ( var i = 1 , len = arguments . length - 1 ; i < len ; i ++ ) { var sub = arguments [ i ] ; leaf = subRegister ( leaf , sub ) ; dir = path . resolve ( dir , sub ) ; } // Only the last name is registered (others are used as the path; see above). var name = arguments [ i ++ ] ; dir = path . resolve ( dir , name ) ; // Handle with require if possible. if ( registerMod ( leaf , dir , name ) ) { return this ; } // Handle as a directory if possible. registerDir ( leaf , dir , name ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A small helper which allows us to just use all of our existing . / middleware / * . js and . / params / * . js targeted at express with socket . io . This is in an effort to reuse as much code as possible and lower the probability of oops bugs as in Oops! I changed it in middleware / ns . js and tested it but I forgot got to update it in io . js : ( . [CODESPLIT] function applyMiddleware ( socket , req , done ) { // A stub for the `res` argument express usually provides. var res = { } ; // Map the socket.io request into a `req` like stub as well. var params = clone ( req ) ; assign ( params , { session_id : socket . decoded_token . session_id , deployment_id : socket . decoded_token . deployment_id } ) ; req = { params : params , query : { } , body : { } } ; // Yay! Now we can just use all of our existing middleware! series ( { 'Load token data' : partial ( Token . load , socket . decoded_token , req ) , 'Add typed param getters' : partial ( typedParams , req , res ) , 'Parse the namespace param if presented' : function ( next ) { unpackNamespaceParam ( req , res , next , req . params . ns ) ; } , 'The collection must already exist' : partial ( collectionRequired , req , res ) , 'Parse sample options' : partial ( sampleOptions , req , res ) } , function ( err ) { if ( err ) { return done ( err ) ; } debug ( 'middleware applied successfully' , req ) ; done ( null , req ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates all the task definition to configure dest based on origin and the opts . [CODESPLIT] function generateConfigureTasks ( planner , origin , dest , opts ) { _ . forIn ( dest . topology . containers , function ( container ) { var addSubTask = { cmd : 'add' , id : container . id , parent : container . containedBy } ; var startSubTask = { cmd : 'start' , id : container . id , parent : container . containedBy } ; var linkSubTask = { cmd : 'link' , id : container . id , parent : container . containedBy } ; var configureOp = { preconditions : containerStatus ( container , 'detached' ) , subTasks : [ addSubTask , startSubTask , linkSubTask ] } ; var configureNop = { preconditions : containerStatus ( container , 'started' ) , subTasks : [ { cmd : 'nop' } ] } ; var addPreconditions = containerStatus ( container , 'detached' ) ; var linkPreconditions = containerStatus ( container , { started : true , running : false } ) ; var oldContainer = origin . topology . containers [ container . id ] ; if ( oldContainer ) { // let's detach all removed containers oldContainer . contains . filter ( function ( contained ) { return container . contains . indexOf ( contained ) === - 1 && ! dest . topology . containers [ contained ] ; } ) . map ( function ( contained ) { // the current contained is NOT included in the dest status // so we detach it return { cmd : 'detach' , id : contained } ; } ) . reduce ( function ( list , op ) { list . push ( op ) ; return list ; } , configureNop . subTasks ) ; } // the children container must be configured before linking container . contains . forEach ( function ( contained ) { var oldContained = origin . topology . containers [ contained ] ; linkPreconditions = _ . merge ( linkPreconditions , containerStatus ( { id : contained , containedBy : container . id } , 'running' ) ) ; // we need to add those before the link if ( oldContained && oldContained . containedBy !== container . id ) { configureOp . subTasks . splice ( configureOp . subTasks . length - 1 , 0 , { cmd : 'detach' , id : contained } ) ; configureNop . subTasks . push ( { cmd : 'detach' , id : contained } ) ; } configureOp . subTasks . splice ( configureOp . subTasks . length - 1 , 0 , { cmd : 'configure' , id : contained } ) ; configureNop . subTasks . push ( { cmd : 'configure' , id : contained } ) ; } ) ; if ( opts . mode === 'safe' && oldContainer && oldContainer . containedBy !== container . containedBy ) { // we should unlink the parent before doing anything // and link back after allParentsIds ( origin , container ) . forEach ( function ( id ) { var op = configureOp ; var nop = configureNop ; op . subTasks . unshift ( { cmd : 'unlink' , id : id , parent : origin . topology . containers [ id ] . containedBy } ) ; nop . subTasks . unshift ( { cmd : 'unlink' , id : id , parent : origin . topology . containers [ id ] . containedBy } ) ; op . subTasks . push ( { cmd : 'link' , id : id , parent : origin . topology . containers [ id ] . containedBy } ) ; nop . subTasks . push ( { cmd : 'link' , id : id , parent : origin . topology . containers [ id ] . containedBy } ) ; } ) ; } if ( opts . mode === 'safe' && configureNop . subTasks . length > 1 && container . containedBy !== container . id ) { configureNop . subTasks . unshift ( { cmd : 'unlink' , id : container . id , parent : container . containedBy } ) ; configureNop . subTasks . push ( { cmd : 'link' , id : container . id , parent : container . containedBy } ) ; } // if a container is already running, there is nothing to do planner . addTask ( { cmd : 'configure' , id : container . id } , configureNop ) ; // real configure task planner . addTask ( { cmd : 'configure' , id : container . id } , configureOp ) ; planner . addTask ( addSubTask , { preconditions : addPreconditions , effects : containerStatus ( container , 'added' ) } ) ; planner . addTask ( startSubTask , { preconditions : containerStatus ( container , 'added' ) , effects : containerStatus ( container , 'started' ) } ) ; planner . addTask ( linkSubTask , { preconditions : containerStatus ( container , 'running' ) , subTasks : [ { cmd : 'nop' } ] } ) ; planner . addTask ( linkSubTask , { preconditions : linkPreconditions , effects : containerStatus ( container , 'running' ) } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module lib / allParentsIds Returns all parents of the passed container minus the root . [CODESPLIT] function allParentsIds ( context , container , parents ) { var isLeaf = parents === undefined ; parents = parents || [ ] ; // doing this before pushing skips the root if ( ! container . containedBy || container . containedBy === container . id ) { return parents ; } if ( ! isLeaf ) { parents . push ( container . id ) ; } // let's order them by tree order return allParentsIds ( context , context . topology . containers [ container . containedBy ] , parents ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a container status to be used as a precondition [CODESPLIT] function containerStatus ( original , status , parent ) { var state = { topology : { containers : { } } } ; var container = { id : original . id } ; if ( parent === null ) { // nothing to do } else if ( parent !== undefined ) { container . containedBy = parent ; } else { container . containedBy = original . containedBy ; } if ( typeof status === 'string' ) { switch ( status ) { case 'detached' : container . added = false ; container . started = false ; container . running = false ; break ; case 'added' : container . added = true ; break ; case 'started' : container . started = true ; break ; case 'running' : container . running = true ; break ; default : throw new Error ( 'unknown state' ) ; } } else { _ . forIn ( status , function ( value , key ) { container [ key ] = value ; } ) ; } if ( container . added === false ) { delete container . containedBy ; } state . topology . containers [ container . id ] = container ; return state ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------ CONSTRUCTOR ---------------------------------- [CODESPLIT] function ( opt ) { EventEmitter . call ( this ) ; opt = opt || { } ; // the id of the service that the node will provide this . _service = opt . service || 'unnamedService' ; // cluster which the node belongs to this . _cluster = opt . cluster || 'defaultCluster' ; // id of the node this . _id = opt . id || uuid . v4 ( ) ; // port in which the node will be publishing messages this . _pubPort = opt . port ; // if port is not defined, a free one is used // interface in which the node will bind this . _address = opt . address || '0.0.0.0' ; // status flags this . _inCluster = false ; this . _advertising = false ; // used to store information about the other nodes in the cluster this . _clusterTopology = { } ; // pub and sub sockets this . _pub = null ; this . _sub = null ; // mdns advertiser/browser this . _ad = null ; this . _browser = null ; // information that is used to advertise the service this . _adInfo = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update information about directory s content with lstat . [CODESPLIT] async function lstatFiles ( dirPath , dirContent ) { const readFiles = dirContent . map ( async ( relativePath ) => { const path = join ( dirPath , relativePath ) const ls = await makePromise ( lstat , path ) return { lstat : ls , path , relativePath , } } ) const res = await Promise . all ( readFiles ) return res }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a directory and return its structure as an object . Only Files Directories and Symlinks are included! [CODESPLIT] async function readDirStructure ( dirPath ) { if ( ! dirPath ) { throw new Error ( 'Please specify a path to the directory' ) } const ls = await makePromise ( lstat , dirPath ) if ( ! ls . isDirectory ( ) ) { const err = new Error ( 'Path is not a directory' ) err . code = 'ENOTDIR' throw err } const dir = /** @type {!Array<string>} */ ( await makePromise ( readdir , dirPath ) ) const lsr = await lstatFiles ( dirPath , dir ) const directories = lsr . filter ( isDirectory ) // reduce at once const notDirectories = lsr . filter ( isNotDirectory ) const files = notDirectories . reduce ( ( acc , current ) => { const type = getType ( current ) return { ... acc , [ current . relativePath ] : { type , } , } } , { } ) const dirs = await directories . reduce ( async ( acc , { path , relativePath } ) => { const res = await acc const structure = await readDirStructure ( path ) return { ... res , [ relativePath ] : structure , } } , { } ) const content = { ... files , ... dirs , } return { content , type : 'Directory' , } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * input [ Any ] [CODESPLIT] function parsePolicies ( input ) { var type = typeof input ; if ( type === 'object' ) { for ( var i in input ) { input [ i ] = this . parsePolicies ( input [ i ] ) ; } return input ; } if ( type === 'string' ) { var parsedString = esprima . parse ( input ) . body [ 0 ] . expression ; return this . parseEsprima ( parsedString ) ; } return input ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * input [ Esprima Object ] fromFactory [ Boolean ] set to true the result will be interpreted by a factory [CODESPLIT] function parseEsprima ( input , fromFactory ) { var type = input . type ; if ( type === esprimaType . value ) { return input . value ; } if ( type === esprimaType . policy ) { var policyName = input . name ; if ( fromFactory ) { return require ( sails . config . paths . policies + '/' + policyName ) ; } return policyName ; } if ( type === esprimaType . factory ) { var factoryName = input . callee . name ; try { var factory = require ( sails . config . paths . policyFactories + '/' + factoryName ) ; } catch ( e ) { return require ( sails . config . paths . policies + '/' + factoryName ) ; } var args = input . arguments . map ( function ( arg ) { return this . parseEsprima ( arg , true ) ; } , this ) ; return factory . apply ( this , args ) ; } throw new Error ( 'esprima type unhandled: ' + type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function converts dataset property name someValue to data - some - value . [CODESPLIT] function propertyNameToAttribute ( name ) { var result = name . replace ( / ([A-Z]) / g , function ( match , letter ) { return '-' + letter . toLowerCase ( ) ; } ) ; return 'data-' + result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the configure and detach commands for all root elements . [CODESPLIT] function generateCommands ( origin , dest ) { var destCmds = _ . chain ( dest . topology . containers ) . values ( ) . filter ( function ( container ) { return container . containedBy === container . id || ! container . containedBy ; } ) . map ( function ( container ) { return { cmd : 'configure' , id : container . id } ; } ) . value ( ) ; var originCmds = _ . chain ( origin . topology . containers ) . values ( ) . map ( function ( container ) { if ( ! dest . topology . containers [ container . id ] ) { return { cmd : 'detach' , id : container . id } ; } return null ; } ) . filter ( function ( container ) { return container !== null ; } ) . value ( ) ; return destCmds . concat ( originCmds ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * istanbul ignore next [CODESPLIT] function class_1 ( ) { var args = [ ] ; for ( var _i = 0 ; _i < arguments . length ; _i ++ ) { args [ _i ] = arguments [ _i ] ; } var _this = _super . apply ( this , args [ 0 ] . injector . args ( Class ) ) || this ; var params = args [ 0 ] ; _this . _injector = params . injector ; _this . _store = params . store ; _this . _aggregates = params . aggregates ; _this . _viewHandlers = params . viewHandlers ; _this . _logger = _this . _injector . get ( Logger ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Because req . param () was deprecated . [CODESPLIT] function _param ( req , key , _default ) { var src = req . params [ key ] ; if ( src === undefined ) { src = req . body [ key ] ; } if ( src === undefined ) { src = req . query [ key ] ; } if ( src === undefined ) { src = _default ; } return src ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "> Initialize Limon with input and options . Both are completely optional . You can pass plugins and tokens to options . [CODESPLIT] function Limon ( input , options ) { if ( ! ( this instanceof Limon ) ) { return new Limon ( input , options ) } lazy . use ( this , { fn : function ( app , opts ) { app . options = lazy . utils . extend ( app . options , opts ) } } ) this . defaults ( input , options ) this . use ( lazy . plugin . prevNext ( ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * converts between json and xlsx - only the first worksheet gets converted - cells are merged as a visual convenience but they hold no special meaning [CODESPLIT] function colLetterToNumber ( letters ) { var number = 0 , i = 0 ; for ( i = 0 ; i < letters . length ; i += 1 ) { //number += (letters.length - i - 1) * (letters.charCodeAt(i) - 64); number += Math . pow ( 26 , i ) * ( letters . charCodeAt ( letters . length - i - 1 ) - 64 ) ; } return number ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new planner [CODESPLIT] function planner ( origin , dest , opts ) { var tasks = new TaskPlanner ( ) ; var cmds = generateCommands ( origin , dest ) ; var state = _ . cloneDeep ( origin ) ; var result ; opts = xtend ( defaults , opts ) ; assert ( opts . mode === 'quick' || opts . mode === 'safe' , 'unknown mode' ) ; tasks . addTask ( { cmd : 'nop' } , { } ) ; generateDetachTasks ( tasks , origin , opts ) ; generateDetachTasks ( tasks , dest , opts ) ; // needed because of safe mode generateConfigureTasks ( tasks , origin , dest , opts ) ; _ . forIn ( state . topology . containers , function ( container ) { container . running = true ; container . started = true ; container . added = true ; } ) ; _ . forIn ( dest . topology . containers , function ( container ) { var containers = state . topology . containers ; if ( ! containers [ container . id ] ) { containers [ container . id ] = { id : container . id , containedBy : container . containedBy , running : false , started : false , added : false } ; } } ) ; result = cmds . reduce ( function ( acc , cmd ) { var plan = tasks . plan ( state , cmd ) ; if ( ! plan ) { throw new Error ( 'unable to generate ' + cmd . cmd + ' for id ' + cmd . id ) ; } return acc . concat ( plan ) ; } , [ ] ) . filter ( function ( cmd ) { return cmd && cmd . cmd !== 'nop' ; } ) ; if ( ! opts . noLinkUnlinkRemove ) { result = linkFilter ( result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - destructive replacement . The block is commented out by adding an opening / * and closing * / . It does not account for internal block comments! [CODESPLIT] function replaceBlocks ( file , blocks ) { blocks . forEach ( block => { const index = file . search ( block [ 0 ] ) ; if ( index > - 1 ) { // Don't comment out blocks that have already been processed if ( file . substring ( index - 3 , index ) !== \"/* \" ) { file = file . replace ( block [ 0 ] , \"/* $1 */\\n\" + block [ 1 ] ) ; } } else { maybeCompatible = false ; console . log ( ` ${ block [ 0 ] . toString ( ) } ` ) ; } } ) ; return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@module lib / linkUnlinkFilter Removes consequent link / unlink ( or unlink / link ) commands with the same id [CODESPLIT] function linkUnlinkFilter ( list ) { var skipNext ; var needsFiltering = true ; function doFilter ( cmd , i , cmds ) { if ( skipNext ) { skipNext = false ; return false ; } if ( ! cmds [ i + 1 ] ) { return true ; } if ( cmds [ i + 1 ] . id !== cmd . id ) { return true ; } var unlinkLink = ( cmd . cmd === 'unlink' && cmds [ i + 1 ] . cmd === 'link' ) ; var linkUnlink = ( cmd . cmd === 'link' && cmds [ i + 1 ] . cmd === 'unlink' ) ; if ( linkUnlink || unlinkLink ) { needsFiltering = true ; skipNext = true ; return false ; } return true ; } while ( needsFiltering ) { needsFiltering = false ; skipNext = false ; list = list . filter ( doFilter ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Success call [CODESPLIT] function ( branchName ) { var storyId = extractStoryId ( branchName ) , commandString ; argv . message = '\"' + getHumanReadableStoryId ( storyId ) + ' - ' + argv . message + '\"' ; commandString = compileCommandString ( 'git' ) ; return executeCommand ( commandString ) . fail ( function ( failure ) { if ( ! sjl . empty ( failure ) ) { log ( failure ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates a new pixel strip which is the collection of LEDs . Resolves this strip within a Promise . See : https : // github . com / ajfisher / node - pixel#strip [CODESPLIT] function ( ) { return new Promise ( function ( resolve , reject ) { board . on ( 'ready' , function ( ) { var strip = new pixel . Strip ( { data : 6 , length : 12 , board : this , controller : \"FIRMATA\" } ) ; strip . on ( 'ready' , function ( ) { resolve ( strip ) ; } ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the strip to a loading pattern . Triggered when the tests have started . [CODESPLIT] function ( strip ) { if ( ! strip ) { console . log ( messagingTexts . noStrip ) ; } if ( ! ( strip instanceof pixel . Strip ) ) { console . log ( messagingTexts . wrongStrip ) ; } pattern . reset ( strip , interval ) ; interval = pattern . domino ( strip , 'white' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flash the strip with green lights indicating tests were successful . [CODESPLIT] function ( strip ) { if ( ! strip ) { console . log ( messagingTexts . noStrip ) ; } if ( ! ( strip instanceof pixel . Strip ) ) { console . log ( messagingTexts . wrongStrip ) ; } pattern . reset ( strip , interval ) ; setTimeout ( function ( ) { pattern . flash ( strip , 'green' , 2 ) ; } , 10 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function return copy of element and if request deep copy of element [CODESPLIT] function cloneAnyNode ( element , deep ) { switch ( element . nodeType ) { case _Node2 [ 'default' ] . DOCUMENT_FRAGMENT_NODE : return cloneDocumentFragment ( element , deep ) ; case _Node2 [ 'default' ] . ELEMENT_NODE : return cloneElementNode ( element , deep ) ; case _Node2 [ 'default' ] . TEXT_NODE : return cloneTextNode ( element ) ; default : throw new _DOMException2 [ 'default' ] ( _DOMException2 [ 'default' ] . DATA_CLONE_ERR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ private methods /// [CODESPLIT] function tryInit ( ) { if ( ! processors . length ) { var processorsPath = path . resolve ( __dirname , \"processor\" ) ; var files = fs . readdirSync ( processorsPath ) ; for ( var i = 0 ; i < files . length ; ++ i ) { var processor = require ( path . resolve ( processorsPath , files [ i ] ) ) ; //processor.name = processor.name || files[i]; if ( processor . priority ) processors . unshift ( processor ) ; else processors . push ( processor ) ; processorIndex [ processor . name ] = processor ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function return copy of element and if request deep copy of element [CODESPLIT] function cloneAnyNode ( element , deep ) { switch ( element . nodeType ) { case Node . DOCUMENT_FRAGMENT_NODE : return cloneDocumentFragment ( element , deep ) ; case Node . ELEMENT_NODE : return cloneElementNode ( element , deep ) ; case Node . TEXT_NODE : return cloneTextNode ( element ) ; default : throw new DOMException ( DOMException . DATA_CLONE_ERR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * istanbul ignore next [CODESPLIT] function class_1 ( ) { var args = [ ] ; for ( var _i = 0 ; _i < arguments . length ; _i ++ ) { args [ _i ] = arguments [ _i ] ; } var _this = _super . apply ( this , args [ 0 ] . injector . args ( Class ) ) || this ; var params = args [ 0 ] ; _this . _injector = params . injector ; _this . _store = params . store ; _this . _transports = params . transports ; _this . _aggregate = params . aggregate ; _this . _logger = _this . _injector . get ( Logger ) ; return _this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param { Element } element @param { Object } rules @return { boolean } [CODESPLIT] function processRules ( element , rules ) { if ( rules . type === 'selectors' ) { return processSelectors ( element , rules . selectors ) ; } else if ( rules . type === 'ruleSet' ) { return processRule ( element , rules . rule ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes the url to the tournament or flight [CODESPLIT] function scopeUrl ( options , inst ) { options = _ . extend ( _ . clone ( options || { } ) , inst ) if ( ! options . venue_id ) throw new Error ( 'venue_id required to make subvenue api calls' ) return ngin . Venue . urlRoot ( ) + '/' + options . venue_id + '/subvenues' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "project config [CODESPLIT] function fetchConfig ( filename ) { var data ; filename = path . resolve ( filename ) ; try { data = fs . readFileSync ( filename , 'utf-8' ) ; } catch ( e ) { console . error ( 'Config read error: ' + e ) ; process . exit ( 2 ) ; } try { data = JSON . parse ( data ) ; } catch ( e ) { console . error ( 'Config parse error: ' + e ) ; process . exit ( 2 ) ; } return { filename : filename , path : path . dirname ( filename ) , data : data } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Router ====== constructor ----------- create a router ### optional arguments ** routes ** : routes to add [CODESPLIT] function Router ( routes ) { this . _routes = [ ] ; this . _not_found = null ; this . _not_found_path = '/404' ; if ( arguments . length === 1 ) { this . addRoutes ( routes ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "http : // www . eq - 3 . de / Downloads / eq3 / download%20bereich / hm_web_ui_doku / HM_XmlRpc_API . pdf http : // www . eq - 3 . de / Downloads / eq3 / download%20bereich / hm_web_ui_doku / HMIP_XmlRpc_API_Addendum . pdf [CODESPLIT] function Hmif ( config , status , log ) { if ( ! ( this instanceof Hmif ) ) return new Hmif ( config , status , log ) ; if ( ! log ) { log = { } ; log . debug = log . info = log . warn = log . error = log . setLevel = function ( ) { } ; } var that = this ; this . status = status ; this . status . homematic = { interfaces : { } } ; if ( ! config ) return ; this . config = config ; log . info ( pkg . name + ' ' + pkg . version + ' starting' ) ; this . _iface = { } ; this . _values = { } ; this . _paramsetDescriptions = pjson . load ( 'paramsetDescriptions.json' ) || { } ; this . _names = { } ; var xmlrpcServer ; var binrpcServer ; function meta ( params ) { var iface = params [ 0 ] ; var address = params [ 1 ] ; var datapoint = params [ 2 ] ; var value = params [ 3 ] ; var dev = that . _iface [ iface ] . devices [ address ] ; var ident = paramsetIdent ( dev , 'VALUES' ) ; var desc = that . _paramsetDescriptions [ ident ] [ datapoint ] ; var meta = { } ; if ( address . indexOf ( ':' ) !== - 1 ) { meta . channelName = that . _names [ address ] ; meta . deviceName = that . _names [ address . replace ( / :[0-9]+$ / , '' ) ] ; } else { meta . deviceName = that . _names [ address . replace ( / :[0-9]+$ / , '' ) ] ; } if ( desc . TYPE === 'ENUM' ) meta . enumValue = desc . VALUE_LIST [ value ] ; return meta ; } function paramsetIdent ( dev , paramset ) { var ident = '' ; if ( dev . PARENT_TYPE ) ident = ident + dev . PARENT_TYPE + '/' ; ident = ident + dev . TYPE ; if ( dev . SUBTYPE ) ident = ident + '/' + dev . SUBTYPE ; ident = ident + '/' + dev . VERSION + '/' + paramset ; return ident ; } function getParamsetDescriptions ( iface ) { var calls = [ ] ; var requests = [ ] ; Object . keys ( that . _iface [ iface ] . devices ) . forEach ( function ( address ) { var dev = that . _iface [ iface ] . devices [ address ] ; dev . PARAMSETS . forEach ( function ( paramset ) { var ident = paramsetIdent ( dev , paramset ) ; if ( ( ! that . _paramsetDescriptions [ ident ] ) && ( requests . indexOf ( ident ) === - 1 ) ) { requests . push ( ident ) ; calls . push ( function ( cb ) { log . debug ( 'getParamsetDescription' , ident ) ; that . _iface [ iface ] . rpc . methodCall ( 'getParamsetDescription' , [ dev . ADDRESS , paramset ] , function ( err , res ) { if ( ! err ) { that . _paramsetDescriptions [ ident ] = res ; } else { log . error ( err ) ; } cb ( ) ; } ) ; } ) ; } } ) } ) ; async . series ( calls , function ( ) { log . debug ( 'getParamsetDescriptions' , iface , 'done' ) ; pjson . save ( 'paramsetDescriptions.json' , that . _paramsetDescriptions ) ; } ) ; } this . methods = { 'system.multicall' : function multicall ( err , params , callback ) { log . debug ( 'rpc < system.multicall' , err , '(' + params [ 0 ] . length + ')' ) ; var res = [ ] ; params [ 0 ] . forEach ( function ( c ) { that . methods . event ( null , c . params ) ; res . push ( '' ) ; } ) ; log . debug ( 're  >' , null , res ) ; callback ( null , res ) ; } , 'system.listMethods' : function listMethods ( err , params , callback ) { log . debug ( 'rpc < system.listMethods' , err , params ) ; log . debug ( 're  >' , null , JSON . stringify ( Object . keys ( that . methods ) ) ) ; callback ( null , Object . keys ( that . methods ) ) ; } , 'event' : function event ( err , params , callback ) { log . debug ( 'rpc < event' , err , params ) ; that . _iface [ params [ 0 ] ] . lastEvent = ( new Date ( ) ) . getTime ( ) ; if ( params [ 1 ] === 'CENTRAL' && params [ 2 ] === 'PONG' ) return ; if ( ! that . _values [ params [ 0 ] ] [ params [ 1 ] ] ) { that . _values [ params [ 0 ] ] [ params [ 1 ] ] = { } ; } if ( params [ 3 ] !== that . _values [ params [ 0 ] ] [ params [ 1 ] ] [ params [ 2 ] ] ) { log . debug ( 'rpc < change' , err , params , that . _names [ params [ 1 ] ] ) ; //if (params[1].indexOf(':') === -1) { that . emit ( 'change' , params , meta ( params ) ) ; //} else { //    that.emit('change', params, meta(params)); //} } that . _values [ params [ 0 ] ] [ params [ 1 ] ] [ params [ 2 ] ] = params [ 3 ] ; if ( params [ 1 ] . indexOf ( ':' ) === - 1 ) { that . emit ( 'rpc' , 'event' , params , meta ( params ) ) ; } else { that . emit ( 'rpc' , 'event' , params , meta ( params ) ) ; } if ( typeof callback === 'function' ) { log . debug ( 're  >' , null , JSON . stringify ( '' ) ) ; callback ( null , '' ) ; } } , 'listDevices' : function listDevices ( err , params , callback ) { log . debug ( 'rpc < listDevices' , err , params ) ; var re = [ ] ; Object . keys ( that . _iface [ params [ 0 ] ] . devices ) . forEach ( function ( d ) { var dev = that . _iface [ params [ 0 ] ] . devices [ d ] ; if ( that . _iface [ params [ 0 ] ] . type === 'hmip' ) { re . push ( { 'ADDRESS' : dev . ADDRESS , 'VERSION' : dev . VERSION } ) ; } else { re . push ( { 'ADDRESS' : dev . ADDRESS , 'VERSION' : dev . VERSION } ) ; } } ) ; log . debug ( 're  >' , null , re . length ) ; callback ( null , re ) ; } , 'newDevices' : function newDevices ( err , params , callback ) { log . debug ( 'rpc < newDevices' , err , params [ 0 ] , params [ 1 ] ) ; //.length); that . emit ( 'rpc' , 'newDevices' , params ) ; params [ 1 ] . forEach ( function ( dev ) { that . _iface [ params [ 0 ] ] . devices [ dev . ADDRESS ] = dev ; } ) ; pjson . save ( that . _iface [ params [ 0 ] ] . host + '-' + that . _iface [ params [ 0 ] ] . port + '-devices.json' , that . _iface [ params [ 0 ] ] . devices ) ; log . debug ( 're  >' , null , JSON . stringify ( '' ) ) ; callback ( null , '' ) ; getParamsetDescriptions ( params [ 0 ] ) ; } , 'deleteDevices' : function deleteDevices ( err , params , callback ) { log . debug ( 'rpc < deleteDevices' , err , params [ 0 ] , params [ 1 ] . length ) ; params [ 1 ] . forEach ( function ( dev ) { delete that . _iface [ params [ 0 ] ] . devices [ dev . ADDRESS ] ; } ) ; pjson . save ( that . _iface [ params [ 0 ] ] . host + '-' + that . _iface [ params [ 0 ] ] . port + '-devices.json' , that . _iface [ params [ 0 ] ] . devices ) ; that . emit ( 'rpc' , 'deleteDevices' , params ) ; log . debug ( 're  >' , null , JSON . stringify ( '' ) ) ; callback ( null , '' ) ; } } ; function getRegaNames ( ) { log . debug ( 'rega > reganames.fn' ) ; that . regaFile ( 'regascripts/reganames.fn' , function ( err , res ) { if ( ! err ) { that . _names = res ; log . debug ( 'rega < ' + Object . keys ( res ) . length ) ; } else { log . error ( err ) ; } } ) ; } function createClients ( callback ) { if ( ! that . config . type ) return ; switch ( that . config . type . toLowerCase ( ) ) { case 'ccu' : case 'ccu2' : getRegaNames ( ) ; createBinrpcServer ( ) ; createInterface ( 'rf' , that . config . address , 2001 , 'rf' , 'binrpc' , 90000 ) ; checkservice ( that . config . address , 2000 , function ( err ) { if ( ! err ) createInterface ( 'wired' , that . config . address , 2000 , 'wired' , 'binrpc' , 90000 ) ; } ) ; checkservice ( that . config . address , 2010 , function ( err ) { createXmlrpcServer ( ) ; if ( ! err ) createInterface ( 'hmip' , that . config . address , 2010 , 'hmip' , 'xmlrpc' , 0 ) ; } ) ; checkservice ( that . config . address , 8701 , function ( err ) { if ( ! err ) createInterface ( 'cux' , that . config . address , 8701 , 'cux' , 'binrpc' , 0 ) ; } ) ; break ; case 'hmipserver' : case 'hmip' : that . _names = pjson . load ( this . config . address + '-names.json' ) || { } ; createXmlrpcServer ( ) ; createInterface ( that . config . type , that . config . address , that . config . port || 2010 , 'hmip' , 'xmlrpc' , 0 ) ; break ; case 'hs485d' : case 'wired' : that . _names = pjson . load ( this . config . address + '-names.json' ) || { } ; if ( that . config . protocol === 'binrpc' ) { createBinrpcServer ( ) ; } else { createXmlrpcServer ( ) ; } createInterface ( that . config . type , that . config . address , that . config . port || 2000 , 'wired' , that . config . protocol , that . config . iface . checkEventTime ) ; break ; case 'rfd' : case 'rf' : that . _names = pjson . load ( this . config . address + '-names.json' ) || { } ; if ( that . config . protocol === 'binrpc' ) { createBinrpcServer ( ) ; } else { createXmlrpcServer ( ) ; } createInterface ( that . config . type , that . config . address , that . config . port || 2001 , 'rf' , that . config . protocol , that . config . iface . checkEventTime ) ; break ; case 'cuxd' : case 'cux' : that . _names = pjson . load ( this . config . address + '-names.json' ) || { } ; createBinrpcServer ( ) ; createInterface ( that . config . type , that . config . address , that . config . port || 8701 , 'cux' , 'binrpc' , that . config . iface . checkEventTime ) ; break ; default : log . error ( 'unknown interface type ' + that . config . interfaces [ i ] . type + ' for ' ) } setTimeout ( callback , 2500 ) ; } function createInterface ( id , host , port , type , protocol , checkEventTime ) { log . debug ( 'creating interface' , id , host + ':' + port ) ; that . _iface [ id ] = { init : false , host : host , port : port , protocol : protocol , type : type , devices : pjson . load ( host + '-' + port + '-devices.json' ) || { } , values : { } , lastEvent : ( new Date ( ) ) . getTime ( ) , checkEventTime : ( typeof checkEventTime === 'undefined' ? 30000 : checkEventTime ) } ; that . status . homematic . interfaces [ id ] = { init : false , host : host , port : port , protocol : protocol , type : type , checkEventTime : ( typeof checkEventTime === 'undefined' ? 30000 : checkEventTime ) } ; that . _values [ id ] = { } ; switch ( protocol ) { case 'binrpc' : case 'xmlrpc_bin' : log . debug ( 'binrpc.createClient' , host + ':' + port ) ; that . _iface [ id ] . rpc = binrpc . createClient ( { host : host , port : port } ) ; break ; default : log . debug ( 'xmlrpc.createClient' , host + ':' + port ) ; that . _iface [ id ] . rpc = xmlrpc . createClient ( { host : host , port : port , path : '/' } ) ; break ; } } function getIfaceInfos ( callback ) { var calls = [ ] ; Object . keys ( that . _iface ) . forEach ( function ( i ) { var url = 'http://' + that . config . listenAddress + ':' + that . config . listenPort ; log . debug ( 'rpc >' , i , 'system.listMethods' , JSON . stringify ( [ ] ) ) ; calls . push ( function ( cb ) { that . _iface [ i ] . rpc . methodCall ( 'system.listMethods' , [ ] , function ( err , res ) { log . debug ( 're  <' , i , err , JSON . stringify ( res ) ) ; that . _iface [ i ] . methods = res ; if ( res . indexOf ( 'getVersion' ) !== - 1 ) { log . debug ( 'rpc >' , i , 'getVersion' , [ ] ) ; that . _iface [ i ] . rpc . methodCall ( 'getVersion' , [ ] , function ( err , res ) { log . debug ( 're  <' , i , err , JSON . stringify ( res ) ) ; that . _iface [ i ] . version = res ; cb ( ) ; } ) ; } else { cb ( ) ; } } ) ; } ) ; } ) ; async . series ( calls , callback ) ; } function subscribe ( callback ) { var calls = [ ] ; Object . keys ( that . _iface ) . forEach ( function ( i ) { var url = 'http://' + that . config . listenAddress + ':' + that . config . listenPort ; var params = [ url , i ] ; calls . push ( function ( cb ) { log . debug ( 'rpc >' , i , 'init' , params ) ; that . _iface [ i ] . rpc . methodCall ( 'init' , params , function ( err , res ) { log . debug ( 're  <' , i , err , JSON . stringify ( res ) ) ; if ( ! err ) { log . info ( 'init succesful ' + i + ' (' + that . _iface [ i ] . host + ':' + that . _iface [ i ] . port + ')' ) ; that . status . homematic . interfaces [ i ] . init = true ; } checkEvents ( i ) ; cb ( ) ; } ) ; } ) ; } ) ; async . series ( calls , callback ) ; } function checkEvents ( iface ) { if ( ! that . _iface [ iface ] . checkEventTime ) { log . warn ( 'no checkEventTime for ' + iface ) ; that . status . homematic . interfaces [ iface ] . checkEventTime = null ; return ; } that . status . homematic . interfaces [ iface ] . checkEventTime = that . _iface [ iface ] . checkEventTime ; that . _iface [ iface ] . checkEventInterval = setInterval ( function ( ) { var now = ( new Date ( ) ) . getTime ( ) ; var le = that . _iface [ iface ] . lastEvent ; var elapsed = now - le ; log . debug ( 'checkEvents' , now , le , elapsed ) ; if ( elapsed > ( 2 * that . _iface [ iface ] . checkEventTime ) ) { that . status . homematic . interfaces [ iface ] . init = false ; var url = 'http://' + that . config . listenAddress + ':' + that . config . listenPort ; var params = [ url , iface ] ; log . debug ( 'rpc >' , iface , 'init' , params ) ; that . _iface [ iface ] . rpc . methodCall ( 'init' , params , function ( err , res ) { that . _iface [ iface ] . lastEvent = ( new Date ( ) ) . getTime ( ) ; log . debug ( 're  <' , iface , err , JSON . stringify ( res ) ) ; } ) ; } else if ( ( now - that . _iface [ iface ] . lastEvent ) > that . _iface [ iface ] . checkEventTime ) { if ( that . _iface [ iface ] . methods . indexOf ( 'ping' ) !== - 1 ) { log . debug ( 'rpc >' , iface , 'ping' , [ iface ] ) ; that . _iface [ iface ] . rpc . methodCall ( 'ping' , [ iface ] , function ( err , res ) { log . debug ( 're  <' , iface , err , JSON . stringify ( res ) ) ; } ) ; } else { // how to provoke event without ping? } } } , ( that . _iface [ iface ] . checkEventTime / 2 ) ) ; } function createXmlrpcServer ( ) { xmlrpcServer = xmlrpc . createServer ( { host : that . config . listenAddress , port : that . config . listenPort } ) ; log . info ( 'xmlrpc server listening on ' + that . config . listenAddress + ':' + that . config . listenPort ) ; xmlrpcServer . on ( 'NotFound' , function ( method , params ) { log . warn ( 'rpc < Method ' + method + ' does not exist' , params ) ; } ) ; that . status . homematic . xmlrpcServer = true ; that . status . homematic . xmlrpcServerPort = that . config . listenPort ; that . status . homematic . xmlrpcServerAddress = that . config . listenAddress ; createHandlers ( xmlrpcServer ) ; } function createBinrpcServer ( ) { binrpcServer = binrpc . createServer ( { host : that . config . listenAddress , port : that . config . listenPortBin } ) ; log . info ( 'binrpc server listening on ' + that . config . listenAddress + ':' + that . config . listenPortBin ) ; that . status . homematic . binrpcServer = true ; that . status . homematic . binrpcServerPort = that . config . listenPort ; that . status . homematic . binrpcServerAddress = that . config . listenAddress ; createHandlers ( binrpcServer ) ; } function createHandlers ( server ) { Object . keys ( that . methods ) . forEach ( function ( m ) { server . on ( m , that . methods [ m ] ) ; } ) ; } this . rpc = function rpc ( iface , method , params , callback ) { this . _iface [ iface ] . rpc . methodCall ( method , params , function ( err , res ) { if ( typeof callback === 'function' ) callback ( err , res ) ; } ) ; } ; this . rega = function rega ( script , callback ) { var post_options = { host : this . config . address , port : '8181' , path : '/rega.exe' , method : 'POST' , headers : { 'Content-Type' : 'application/x-www-form-urlencoded' , 'Content-Length' : script . length } } ; var post_req = http . request ( post_options , function ( res ) { var data = '' ; res . setEncoding ( 'utf8' ) ; res . on ( 'data' , function ( chunk ) { data += chunk . toString ( ) ; } ) ; res . on ( 'end' , function ( ) { var pos = data . lastIndexOf ( \"<xml>\" ) ; var stdout = unescape ( data . substring ( 0 , pos ) ) ; try { var result = stdout ; callback ( null , result ) ; } catch ( e ) { callback ( e ) } } ) ; } ) ; post_req . on ( 'error' , function ( e ) { callback ( e ) ; } ) ; post_req . write ( script ) ; post_req . end ( ) ; } ; this . regaFile = function regaFile ( file , callback ) { var that = this ; fs . readFile ( path . join ( __dirname , file ) , 'utf8' , function ( err , script ) { if ( err ) { callback ( err ) ; return false ; } that . rega ( script , function ( err , res ) { if ( ! err ) { try { callback ( null , JSON . parse ( res ) ) ; } catch ( e ) { callback ( e ) ; } } else { callback ( err ) ; } } ) ; } ) ; } ; this . _findIface = function findIface ( address ) { for ( var i in this . _iface ) { for ( var a in this . _iface [ i ] . devices ) { if ( a === address ) return i ; } } } ; this . setValue = function rpc ( address , datapoint , value , callback ) { var iface = this . _findIface ( address ) ; if ( ! iface ) { callback ( new Error ( 'no suitable interface found for address ' + address ) ) ; } else { this . _iface [ iface ] . rpc . methodCall ( 'setValue' , [ address , datapoint , value ] , function ( err , res ) { if ( typeof callback === 'function' ) callback ( err , res ) ; } ) ; } } ; this . unsubscribe = function unsubscribe ( callback ) { var that = this ; var calls = [ ] ; if ( that . _iface ) { Object . keys ( that . _iface ) . forEach ( function ( i ) { var url = 'http://' + that . config . listenAddress + ':' + that . config . listenPort ; var params = [ url , '' ] ; log . debug ( 'rpc >' , i , 'init' , params ) ; calls . push ( function ( cb ) { that . _iface [ i ] . rpc . methodCall ( 'init' , params , function ( err , res ) { log . debug ( 're  <' , i , err , JSON . stringify ( res ) ) ; cb ( ) ; } ) ; } ) ; } ) ; async . series ( calls , callback ) ; } else { callback ( ) ; } } ; createClients ( function ( ) { getIfaceInfos ( function ( ) { log . debug ( 'getIfaces done' ) ; subscribe ( function ( ) { log . debug ( 'subscriptions done' ) ; } ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new resource . [CODESPLIT] function create ( parent , baseUrl , params , callback ) { parent . getClient ( ) . post ( baseUrl , params , function ( err , definition , response ) { if ( err ) return callback ( err ) ; callback ( null , new this ( parent , definition ) ) ; } . bind ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register Loader of different Language [CODESPLIT] function register ( type , lang , handler ) { if ( Array . isArray ( lang ) ) { lang . forEach ( ( v ) => store [ type ] . langs [ v ] = handler ) ; return ; } store [ type ] . langs [ lang ] = handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Require extension vue hook [CODESPLIT] function loader ( module , filePath ) { let content = fs . readFileSync ( filePath , 'utf8' ) ; let moduleId = ` ${ hash ( filePath ) } ` ; let vueTemplate = '' ; let vueComponent = compiler . parseComponent ( stripBom ( content ) ) ; let script = vueComponent . script ; let styles = vueComponent . styles ; let template = vueComponent . template ; let scoped = styles . some ( ( { attrs } ) => attrs . scoped ) ; [ ] . concat ( script , template , styles ) . forEach ( ( tag , index ) => { if ( tag ) { let type = tag . type ; let content = tag . content ; let lang = tag . attrs . lang || store [ type ] . defaults ; let handler = store [ type ] . langs [ lang ] ; if ( handler ) { content = handler ( content , filePath , index , module ) ; } switch ( type ) { case 'style' : if ( browserEnv ) { /**\n                         * Only in Browser Environment, append style to head\n                         */ if ( tag . attrs . scoped ) { let ast = css . parse ( content ) ; ast . stylesheet . rules . forEach ( ( rule ) => { rule . selectors = rule . selectors . map ( ( selector ) => { let [ patterns ] = cssWhat ( selector ) ; let index = patterns . length - 1 ; for ( ; index >= 0 ; index -- ) { let { type } = patterns [ index ] ; if ( type !== 'pseudo' && type !== 'pseudo-element' ) { break ; } } patterns . splice ( index + 1 , 0 , { value : '' , name : moduleId , action : 'exists' , type : 'attribute' , ignoreCase : false , } ) ; return cssWhat . stringify ( [ patterns ] ) ; } ) ; } ) ; content = css . stringify ( ast ) ; } let style = document . createElement ( 'style' ) ; style . innerHTML = content ; store . style . exports . call ( module . exports , style , { index , styles , filePath , } ) ; } break ; case 'script' : module . _compile ( content , filePath ) ; break ; case 'template' : if ( browserEnv ) { /**\n                         * Only in Browser Environment, set Attribute for each element\n                         */ if ( scoped ) { let div = document . createElement ( 'div' ) ; div . innerHTML = content ; let root = div . firstElementChild ; let walk = function walk ( element , handler ) { handler ( element ) ; let children = element . children || [ ] ; [ ] . forEach . call ( children , ( child ) => { walk ( child , handler ) ; } ) ; } ; walk ( root , ( element ) => { element . setAttribute ( moduleId , '' ) ; } ) ; content = div . innerHTML ; } } vueTemplate = content ; break ; } } } ) ; module . exports . vueComponent = vueComponent ; module . exports . template = vueTemplate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "WMURL . addCacheBustingKeyword ( url : URLString keyword : String = t ) : URLString --- implements ------------------------------------------ [CODESPLIT] function WMURL_isValid ( url , // @arg URLString|URLStringArray - absolute/relative url(s) canonical ) { // @arg Boolean = false - TBD // @ret Boolean // @desc validate URL //{@dev $valid ( typeof url === \"string\" || Array . isArray ( url ) , WMURL_isValid , \"url\" ) ; //}@dev var urls = Array . isArray ( url ) ? url : [ url ] ; for ( var i = 0 , iz = urls . length ; i < iz ; ++ i ) { if ( ! _parse ( urls [ i ] , true ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] function _parseQuery ( _ , key , value ) { var encodedKey = global [ \"encodeURIComponent\" ] ( key ) , encodedValue = global [ \"encodeURIComponent\" ] ( value ) ; if ( rv [ encodedKey ] ) { if ( Array . isArray ( rv [ encodedKey ] ) ) { rv [ encodedKey ] . push ( encodedValue ) ; } else { rv [ encodedKey ] = [ rv [ encodedKey ] , encodedValue ] ; } } else { rv [ encodedKey ] = encodedValue ; } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generator to add callbacks to a bucked and possible fire them [CODESPLIT] function ( kind , promisesDfd ) { return function ( ) { // operate on this unless we forced a deferred to work on var dfd = promisesDfd || this ; var fnSet = [ ] . slice . call ( arguments ) ; // as long as this is a progress handler or the state isn't reached add it // otherwise call it right now if ( kind === 'progress' || dfd . state === 'pending' ) { dfd [ kind + 's' ] . push ( fnSet ) ; } else { callSet . call ( dfd , fnSet , this [ kind + 'Args' ] ) ; } // if we forced a promiseDfd, return the promise if ( promisesDfd ) { return dfd . promise ; } // otherwise return the root deferred like normal return dfd ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "call a callback set [CODESPLIT] function ( set , args ) { // nothing to see here folks if ( set . length < 1 ) { return ; } // the args to call with var apply = [ ] ; // we passed inline arguments if ( set . length > 1 ) { for ( var i = 1 ; i < set . length ; i ++ ) { // is it one of those cool perform.arg(X) thingies? // if not, just put the passed args in there if ( set [ i ] instanceof Argument ) { apply [ i ] = args [ set [ i ] . num ] ; } else { apply [ i ] = set [ i ] ; } apply = apply . slice ( 1 ) ; } } else { apply = args ; } // actually call the fn with the appropriate args set [ 0 ] . apply ( this , apply ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "call all the callback sets in a callback bucket [CODESPLIT] function ( kind , args ) { var bucket = this [ kind + 's' ] ; for ( var i = 0 ; i < bucket . length ; i ++ ) { callSet . call ( this , bucket [ i ] , args ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "promise generator - psuedo read - only [CODESPLIT] function ( ) { var dfd = this ; // since people might be used to .promise() var promise = function ( ) { return promise ; } ; promise . done = stackNFire ( 'done' , dfd ) ; promise . fail = stackNFire ( 'fail' , dfd ) ; promise . progress = stackNFire ( 'progress' , dfd ) ; promise . state = dfd . state ; return promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pass judgement onto thy deferred [CODESPLIT] function ( kind ) { return function ( ) { if ( this . state === 'pending' ) { if ( kind !== 'progress' ) { this [ kind + 'Args' ] = arguments ; this . state = this . promise . state = kind ; } callSets . call ( this , kind , arguments ) ; } return this ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the heart of the beast [CODESPLIT] function ( ) { this . dones = [ ] ; this . doneArgs = [ ] ; this . fails = [ ] ; this . failArgs = [ ] ; this . pendings = [ ] ; this . pendingArgs = [ ] ; this . state = 'pending' ; // expose the promise this . promise = iPromise . call ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "upon any action on the dependencies check the resolution [CODESPLIT] function ( performer ) { // everything checks out var state = performer . state ; // everything resolved if ( state . allCount === 0 ) { var args = [ ] ; for ( var i = 0 ; i < performer . args . length ; i ++ ) { args = args . concat ( [ ] . concat ( performer . args [ i ] . args ) ) ; } // either fail/done are 0 or something went wrong if ( state . targetCount === 0 ) { performer . _dfd . resolve . apply ( performer . _dfd , args ) ; } else { performer . _dfd . reject . apply ( performer . _dfd , args ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Define a relaxed toposort which does not check for ( or worry about ) cyclic dependencies . [CODESPLIT] function toposort ( dependencies ) { var sorted = [ ] , visited = { } ; function visit ( key ) { if ( ! visited [ key ] ) { visited [ key ] = true ; if ( ! dependencies [ key ] ) { throw new Error ( 'A dependency is given which is not defined' + key ) ; } dependencies [ key ] . dependencies . forEach ( visit ) ; sorted . push ( key ) ; } } for ( var key in dependencies ) { visit ( key ) ; } return sorted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bolty main class [CODESPLIT] function ( schema ) { this . _decoders = decoders ; this . _encoders = encoders ; this . _schemas = { } ; // Allow to pass the fields direclty if ( Object . keys ( schema ) . join ( ',' ) !== 'name,fields' ) { schema = { name : '_auto-' + new Date ( ) . getTime ( ) , fields : schema } ; } this . _schema = schema ; this . _fieldIndex = Object . keys ( schema . fields ) ; this . _schemas [ schema . name ] = schema ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a functional CSS rule [CODESPLIT] function ( selector , properties , value ) { let rule = postcss . rule ( { selector : selector } ) let decls = _ . map ( properties , function ( property ) { return postcss . decl ( { prop : property , value : value } ) } ) rule . append ( decls ) return rule }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a complete set of responsive spacing helpers [CODESPLIT] function ( breakpoints , spacingScale ) { return _ . map ( breakpoints , function ( breakpointValue , breakpointKey ) { let mediaQuery = postcss . atRule ( { name : 'media' , params : breakpointValue , } ) let rules = _ . flatMap ( spacingScale , function ( scaleValue , scaleKey ) { return _ . map ( helpers , function ( helperValues , helperKey ) { return makeFunctionalRule ( ` ${ breakpointKey } ${ helperKey } ${ scaleKey } ` , helperValues , scaleValue ) } ) } ) return mediaQuery . append ( rules ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "断言 val 的数据类型是否为 type 对应的数据类型 [CODESPLIT] function _assertDataType ( type , val ) { var dataType ; if ( val === UNDEFINED ) { dataType = OBJECT_UNDEFINED ; } else if ( val === NULL ) { dataType = OBJECT_NULL ; } else { dataType = _toString . call ( val ) ; } var lowerCaseType = dataType . replace ( DATA_TYPE_REPLACE_REX , '' ) . toLowerCase ( ) ; return lowerCaseType === type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### Function branchMatching Returns the branch matching a dispatch value . :: A [ branch A ] - > maybe ( branch A ) [CODESPLIT] function branchMatching ( value , branches ) { var i = branches . length while ( i -- ) if ( equal ( value , branches [ i ] . condition ) ) return branches [ i ] return { condition : null , code : null } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### Function method Constructs a multi - method . :: ( A ... - > B ) - > method [CODESPLIT] function method ( dispatch ) { var branches = [ ] var baseline = function ( a ) { throw noBranchFor ( a ) } var dispatchTable = new DispatchTable ( ) dispatch = dispatch || identity return makeMethod ( function ( ) { var value = dispatch . apply ( null , arguments ) var branch = dispatchTable . getBranch ( value ) . code || branchMatching ( value , branches ) . code || baseline return branch . apply ( null , arguments ) } ) // #### Function makeMethod // // Adds modification methods to a multi-method. // // :: method -> method function makeMethod ( f ) { f . when = when f . fallback = fallback f . remove = remove f . clone = clone return f } // ### Function when // // Adds a branch to a multi-method. // // :: @method => A, (B... -> C) -> method function when ( condition , f ) { if ( branchMatching ( condition , branches ) . code ) throw ambiguousBranch ( condition ) branches . push ( { condition : condition , code : f } ) dispatchTable . add ( condition , f ) return this } // ### Function fallback // // Adds a baseline branch, which is evaluated if no other branches // match a given dispatch value. // // :: @method => (A... -> B) -> method function fallback ( f ) { baseline = f return this } // ### Function remove // // Removes a branch from the multi-method. // // :: @method => A -> method function remove ( condition ) { branches = branches . filter ( function ( a ) { return ! equal ( condition , a . condition ) } ) return this } // ### Function clone // // Creates a new multi-method that fallsback to this one. // // :: @method => Unit -> method function clone ( ) { var instance = method ( dispatch ) instance . fallback ( this ) return instance } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#### Function makeMethod Adds modification methods to a multi - method . :: method - > method [CODESPLIT] function makeMethod ( f ) { f . when = when f . fallback = fallback f . remove = remove f . clone = clone return f }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### Function when Adds a branch to a multi - method . :: [CODESPLIT] function when ( condition , f ) { if ( branchMatching ( condition , branches ) . code ) throw ambiguousBranch ( condition ) branches . push ( { condition : condition , code : f } ) dispatchTable . add ( condition , f ) return this }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### Function remove Removes a branch from the multi - method . :: [CODESPLIT] function remove ( condition ) { branches = branches . filter ( function ( a ) { return ! equal ( condition , a . condition ) } ) return this }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows a resource to be deleted . [CODESPLIT] function destroy ( callback ) { this . getClient ( ) . destroy ( this . definition . _links . self . href , function ( err , definition , response ) { if ( err ) return callback ( err ) ; callback ( ) ; } . bind ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns current config [CODESPLIT] function load_config ( ) { let config = { } ; if ( fs . existsSync ( pgrunner_config_file ) ) { config = JSON . parse ( fs . readFileSync ( pgrunner_config_file , { 'encoding' : 'utf8' } ) ) ; if ( argv . v ) { debug . log ( 'Loaded from ' , pgrunner_config_file ) ; } } if ( ! is . array ( config . servers ) ) { config . servers = [ ] ; } return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save current config [CODESPLIT] function save_config ( config ) { fs . writeFileSync ( pgrunner_config_file , JSON . stringify ( config , null , 2 ) , { 'encoding' : 'utf8' } ) ; if ( argv . v ) { debug . log ( 'Saved to ' , pgrunner_config_file ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strip argv [CODESPLIT] function strip_argv ( a ) { let o = { } ; return Object . keys ( a ) . filter ( k => k !== '_' ) . map ( k => { o [ k ] = a [ k ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strip keys [CODESPLIT] function strip_server_opts ( old_opts ) { debug . assert ( old_opts ) . is ( 'object' ) ; let opts = { } ; [ 'pgconfig' , 'host' , 'port' , 'user' , 'database' ] . forEach ( key => { if ( old_opts [ key ] !== undefined ) { opts [ key ] = old_opts [ key ] ; } } ) ; return opts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns server options [CODESPLIT] function get_server_opts ( opts ) { debug . assert ( opts ) . is ( 'object' ) ; debug . assert ( opts . settings ) . is ( 'object' ) ; return { 'dbconfig' : opts . dbconfig , 'host' : opts . settings . host , 'port' : opts . settings . port , 'user' : opts . settings . user , 'database' : opts . settings . database } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为 JSON 对象 [CODESPLIT] function _isJSON ( val ) { if ( ! _isString ( val ) ) { return false ; } try { // @TODO // 引用: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse // JSON support, 在 ECMAScript 5.1 定义, 在 JavaScript 1.7 实现 var jsonObj = JSON . parse ( val ) ; return _isPlainObject ( jsonObj ) ; } catch ( e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "fn returns true / false to callback [CODESPLIT] function custom ( fn ) { return function ( req , res , next ) { fn ( req , function ( result ) { if ( result === true ) { return next ( ) ; } next ( new ErrorUnauthorized ( 'Authentication Failed' ) ) ; } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Also allow multiple users / methods [CODESPLIT] function http_basic ( username , password ) { return function ( req , res , next ) { var credentials = basic_auth ( req ) ; if ( credentials !== undefined ) { if ( credentials . name && credentials . name === username ) { if ( credentials . pass && credentials . pass === password ) { return next ( ) ; } } } res . set ( 'WWW-Authenticate' , 'Basic' ) ; next ( new ErrorUnauthorized ( 'Authentication Failed' ) ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "API data resource on local IndexedDB [CODESPLIT] function getResources ( domains ) { return store . getResources ( ) . then ( rsrcs => { return rsrcs . filter ( e => domains . includes ( e . domain ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * The BaseController is deliberatly not an ES6 class . This is because ES6 classes don t play nice with CoffeeScript classes . ES6 classes may only be constructed with the new keyword while CoffeeScript classes when extending another class construct their parent by explicitely calling the parent constructor . This means that CoffeeScript classes cannot extend ES6 classes . [CODESPLIT] function BaseController ( context ) { Object . defineProperties ( this , { body : { enumerable : true , get ( ) { return context . body ; } , set ( val ) { context . body = val ; } , } , context : { enumerable : true , get ( ) { return context ; } , } , response : { enumerable : true , get ( ) { return context . response ; } , } , request : { enumerable : true , get ( ) { return context . request ; } , } , query : { enumerable : true , get ( ) { return context . query ; } , } , } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Note : must declare params as optional . [CODESPLIT] function packRanges ( fromIndex , toIndex , bucketThreshold , sparseIterationThreshold , getOwnPropertyNamesThreshold ) { var ownPropertyNames = null ; var consecutiveRange = ( toIndex - fromIndex >= sparseIterationThreshold ) && ArrayBuffer . isView ( this ) ; var skipGetOwnPropertyNames = consecutiveRange && ( toIndex - fromIndex >= getOwnPropertyNamesThreshold ) ; function * arrayIndexes ( object ) { if ( toIndex - fromIndex < sparseIterationThreshold ) { for ( var i = fromIndex ; i <= toIndex ; ++ i ) { if ( i in object ) yield i ; } } else { ownPropertyNames = ownPropertyNames || Object . getOwnPropertyNames ( object ) ; for ( var i = 0 ; i < ownPropertyNames . length ; ++ i ) { var name = ownPropertyNames [ i ] ; var index = name >>> 0 ; if ( ( \"\" + index ) === name && fromIndex <= index && index <= toIndex ) yield index ; } } } var count = 0 ; if ( consecutiveRange ) { count = toIndex - fromIndex + 1 ; } else { for ( var i of arrayIndexes ( this ) ) ++ count ; } var bucketSize = count ; if ( count <= bucketThreshold ) bucketSize = count ; else bucketSize = Math . pow ( bucketThreshold , Math . ceil ( Math . log ( count ) / Math . log ( bucketThreshold ) ) - 1 ) ; var ranges = [ ] ; if ( consecutiveRange ) { for ( var i = fromIndex ; i <= toIndex ; i += bucketSize ) { var groupStart = i ; var groupEnd = groupStart + bucketSize - 1 ; if ( groupEnd > toIndex ) groupEnd = toIndex ; ranges . push ( [ groupStart , groupEnd , groupEnd - groupStart + 1 ] ) ; } } else { count = 0 ; var groupStart = - 1 ; var groupEnd = 0 ; for ( var i of arrayIndexes ( this ) ) { if ( groupStart === - 1 ) groupStart = i ; groupEnd = i ; if ( ++ count === bucketSize ) { ranges . push ( [ groupStart , groupEnd , count ] ) ; count = 0 ; groupStart = - 1 ; } } if ( count > 0 ) ranges . push ( [ groupStart , groupEnd , count ] ) ; } return { ranges : ranges , skipGetOwnPropertyNames : skipGetOwnPropertyNames } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "format a parsed object into a url string [CODESPLIT] function urlFormat ( obj ) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if ( isString ( obj ) ) { obj = urlParse ( obj ) ; } else if ( ! isObject ( obj ) || isNull ( obj ) ) { throw new TypeError ( 'Parameter \"urlObj\" must be an object, not ' + isNull ( obj ) ? 'null' : typeof obj ) ; } else if ( ! ( obj instanceof Url ) ) { return Url . prototype . format . call ( obj ) ; } else { return obj . format ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writelnColor ( msg color mgs2 color2 .. msgN colorN ) writeln msg in color [CODESPLIT] function writelnColor ( ) { for ( var i = 0 ; i < arguments . length ; i = i + 2 ) grunt . log . write ( arguments [ i ] [ arguments [ i + 1 ] ] ) ; grunt . log . writeln ( '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param { object } ray - Object that looks like { start : { x : number y : number } end : { x : number y : number } } [CODESPLIT] function rayVsCircle ( ray , circle ) { var rayStart = new Vec2 ( ray . start ) ; if ( circleContainsPoint ( circle . position , circle . radius , ray . start ) ) { return rayStart ; } var intersections = rayLineVsCircle ( ray , circle ) ; if ( intersections . length ) { return rayStart . nearest ( intersections . filter ( within ( ray ) ) ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Treats ray like an infinite line see where it intersects circle . [CODESPLIT] function rayLineVsCircle ( ray , circle ) { var rayLine = new Line2 ( ray . start . x , ray . start . y , ray . end . x , ray . end . y ) ; return rayLine . intersectCircle ( circle . position , circle . radius ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes the url to the tournament league or flight [CODESPLIT] function scopeUrl ( options , inst ) { options = _ . extend ( _ . clone ( options || { } ) , inst ) if ( typeof options !== 'object' && ( ! options . tournament_id || ! options . flight_id ) ) throw new Error ( 'tournament_id or flight_id required to make tibreak preference api calls' ) var url = '' if ( options . tournament_id ) { url += ngin . Tournament . urlRoot ( ) + '/' + options . tournament_id } else if ( options . flight_id ) { url += ngin . Flight . urlRoot ( ) + '/' + options . flight_id } return url + TiebreakPreference . urlRoot ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch is used by Tournament and list is being used by Flight . Can those be consolidated? [CODESPLIT] function ( options , callback ) { var url = scopeUrl ( options , this ) return Super . fetch . call ( this , url , options , callback ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JSON RPC library entry point [CODESPLIT] function ( module , debug ) { this . debug = debug || false ; this . jsonrpc = \"2.0\" ; // check & load the methods in module this . methods = module ; if ( handy . getType ( module ) == 'string' ) { this . methods = require ( module ) ; } if ( this . debug ) { logger . debug ( 'Loaded with methods:' + _ . functions ( this . methods ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the function parameters [CODESPLIT] function _getParamNames ( func ) { var funStr = func . toString ( ) ; return funStr . slice ( funStr . indexOf ( '(' ) + 1 , funStr . indexOf ( ')' ) ) . match ( / ([^\\s,]+) / g ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get only changed properties as a hash . [CODESPLIT] function _getChangedProperties ( ) { var retVal = { } , key ; for ( key in this . _changed ) { retVal [ key ] = this . _changed [ key ] ; } return retVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows a resource to be updated . [CODESPLIT] function update ( properties , callback ) { if ( typeof properties == 'function' ) { callback = properties ; properties = { } ; } var key , changed ; var exceptions = [ 'addresses_update_action' , 'emails_update_action' , 'phone_numbers_update_action' ] ; for ( key in properties ) { if ( 'set' + inflection . camelize ( key ) in this ) { this [ 'set' + inflection . camelize ( key ) ] ( properties [ key ] ) ; } else if ( exceptions . indexOf ( key ) != - 1 ) { this . _changed [ key ] = properties [ key ] ; } } changed = this . _getChangedProperties ( ) ; this . getClient ( ) . patch ( this . definition . _links . self . href , changed , function ( err , definition , response ) { if ( err ) return callback ( err ) ; this . definition = definition ; this . _setup ( ) ; callback ( null , this ) ; } . bind ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--- implements ------------------------------------------ [CODESPLIT] function DataType_Uint8Array_clone ( source , // @arg Uint8Array begin , // @arg Integer = 0 - begin offset end ) { // @arg Integer = source.length - end offset // @ret Uint8Array // @desc make clone (not reference) //{@dev $valid ( $type ( source , \"Uint8Array\" ) , DataType_Uint8Array_clone , \"source\" ) ; $valid ( $type ( begin , \"Integer|omit\" ) , DataType_Uint8Array_clone , \"begin\" ) ; $valid ( $type ( end , \"Integer|omit\" ) , DataType_Uint8Array_clone , \"end\" ) ; //}@dev if ( end !== undefined ) { return new Uint8Array ( source . buffer . slice ( begin , end ) ) ; } return new Uint8Array ( source . buffer . slice ( begin || 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "By class name [CODESPLIT] function byClass ( c ) { c = classnames ( c ) if ( / ^\\. / . test ( c ) ) { throw new Error ( 'No need to \".\" on start' ) } return bySelector ( ` ${ c } ` ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called automatically by JsDoc Toolkit . [CODESPLIT] function publish ( symbolSet ) { publish . conf = { // trailing slash expected for dirs ext : \".html\" , outDir : JSDOC . opt . d || SYS . pwd + \"../out/jsdoc/\" , templatesDir : JSDOC . opt . t || SYS . pwd + \"../templates/jsdoc/\" , staticDir : \"static/\" , symbolsDir : \"symbols/\" , srcDir : \"symbols/src/\" , cssDir : \"css/\" , fontsDir : \"css/fonts/\" , jsDir : \"javascript/\" , templateName : \"Codeview\" , templateVersion : \"1.2\" , templateLink : \"http://www.thebrightlines.com/2010/05/06/new-template-for-jsdoctoolkit-codeview/\" } ; // is source output is suppressed, just display the links to the source file if ( JSDOC . opt . s && defined ( Link ) && Link . prototype . _makeSrcLink ) { Link . prototype . _makeSrcLink = function ( srcFilePath ) { return \"&lt;\" + srcFilePath + \"&gt;\" ; } } // create the folders and subfolders to hold the output IO . mkPath ( ( publish . conf . outDir + publish . conf . cssDir ) ) ; IO . mkPath ( ( publish . conf . outDir + publish . conf . fontsDir ) ) ; IO . mkPath ( ( publish . conf . outDir + publish . conf . jsDir ) ) ; IO . mkPath ( ( publish . conf . outDir + \"symbols/src\" ) . split ( \"/\" ) ) ; // used to allow Link to check the details of things being linked to Link . symbolSet = symbolSet ; // create the required templates try { var classTemplate = new JSDOC . JsPlate ( publish . conf . templatesDir + \"class.tmpl\" ) ; } catch ( e ) { print ( \"Couldn't create the required templates: \" + e ) ; quit ( ) ; } // some utility filters function hasNoParent ( $ ) { return ( $ . memberOf == \"\" ) } function isaFile ( $ ) { return ( $ . is ( \"FILE\" ) ) } function isaClass ( $ ) { return ( ( $ . is ( \"CONSTRUCTOR\" ) || $ . isNamespace ) && ( $ . alias != \"_global_\" || ! JSDOC . opt . D . noGlobal ) ) } // get an array version of the symbolset, useful for filtering var symbols = symbolSet . toArray ( ) ; // create the hilited source code files var files = JSDOC . opt . srcFiles ; for ( var i = 0 , l = files . length ; i < l ; i ++ ) { var file = files [ i ] ; var srcDir = publish . conf . outDir + publish . conf . srcDir ; makeSrcFile ( file , srcDir ) ; } // get a list of all the classes in the symbolset publish . classes = symbols . filter ( isaClass ) . sort ( makeSortby ( \"alias\" ) ) ; // create a filemap in which outfiles must be to be named uniquely, ignoring case if ( JSDOC . opt . u ) { var filemapCounts = { } ; Link . filemap = { } ; for ( var i = 0 , l = publish . classes . length ; i < l ; i ++ ) { var lcAlias = publish . classes [ i ] . alias . toLowerCase ( ) ; if ( ! filemapCounts [ lcAlias ] ) filemapCounts [ lcAlias ] = 1 ; else filemapCounts [ lcAlias ] ++ ; Link . filemap [ publish . classes [ i ] . alias ] = ( filemapCounts [ lcAlias ] > 1 ) ? lcAlias + \"_\" + filemapCounts [ lcAlias ] : lcAlias ; } } // create each of the class pages for ( var i = 0 , l = publish . classes . length ; i < l ; i ++ ) { var symbol = publish . classes [ i ] ; symbol . events = symbol . getEvents ( ) ; // 1 order matters symbol . methods = symbol . getMethods ( ) ; // 2 var output = \"\" ; output = classTemplate . process ( symbol ) ; IO . saveFile ( publish . conf . outDir + publish . conf . symbolsDir , ( ( JSDOC . opt . u ) ? Link . filemap [ symbol . alias ] : symbol . alias ) + publish . conf . ext , output ) ; } // create the class index page try { var classesindexTemplate = new JSDOC . JsPlate ( publish . conf . templatesDir + \"allclasses.tmpl\" ) ; } catch ( e ) { print ( e . message ) ; quit ( ) ; } var classesIndex = classesindexTemplate . process ( publish . classes ) ; IO . saveFile ( publish . conf . outDir , ( JSDOC . opt . D . index == \"files\" ? \"allclasses\" : \"index\" ) + publish . conf . ext , classesIndex ) ; classesindexTemplate = classesIndex = classes = null ; // create the file index page try { var fileindexTemplate = new JSDOC . JsPlate ( publish . conf . templatesDir + \"allfiles.tmpl\" ) ; } catch ( e ) { print ( e . message ) ; quit ( ) ; } var documentedFiles = symbols . filter ( isaFile ) ; // files that have file-level docs var allFiles = [ ] ; // not all files have file-level docs, but we need to list every one for ( var i = 0 ; i < files . length ; i ++ ) { allFiles . push ( new JSDOC . Symbol ( files [ i ] , [ ] , \"FILE\" , new JSDOC . DocComment ( \"/** */\" ) ) ) ; } for ( var i = 0 ; i < documentedFiles . length ; i ++ ) { var offset = files . indexOf ( documentedFiles [ i ] . alias ) ; allFiles [ offset ] = documentedFiles [ i ] ; } allFiles = allFiles . sort ( makeSortby ( \"name\" ) ) ; // output the file index page var filesIndex = fileindexTemplate . process ( allFiles ) ; IO . saveFile ( publish . conf . outDir , ( JSDOC . opt . D . index == \"files\" ? \"index\" : \"files\" ) + publish . conf . ext , filesIndex ) ; fileindexTemplate = filesIndex = files = null ; // copy static files IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . cssDir + \"all.css\" , publish . conf . outDir + \"/\" + publish . conf . cssDir ) ; IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . cssDir + \"screen.css\" , publish . conf . outDir + \"/\" + publish . conf . cssDir ) ; IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . cssDir + \"handheld.css\" , publish . conf . outDir + \"/\" + publish . conf . cssDir ) ; IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . jsDir + \"all.js\" , publish . conf . outDir + \"/\" + publish . conf . jsDir ) ; IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . jsDir + \"html5.js\" , publish . conf . outDir + \"/\" + publish . conf . jsDir ) ; IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . fontsDir + \"mplus-1m-regular-webfont.eot\" , publish . conf . outDir + \"/\" + publish . conf . fontsDir ) ; IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . fontsDir + \"mplus-1m-regular-webfont.svg\" , publish . conf . outDir + \"/\" + publish . conf . fontsDir ) ; IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . fontsDir + \"mplus-1m-regular-webfont.ttf\" , publish . conf . outDir + \"/\" + publish . conf . fontsDir ) ; IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . fontsDir + \"mplus-1m-regular-webfont.woff\" , publish . conf . outDir + \"/\" + publish . conf . fontsDir ) ; IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . fontsDir + \"mplus-1m-bold-webfont.eot\" , publish . conf . outDir + \"/\" + publish . conf . fontsDir ) ; IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . fontsDir + \"mplus-1m-bold-webfont.svg\" , publish . conf . outDir + \"/\" + publish . conf . fontsDir ) ; IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . fontsDir + \"mplus-1m-bold-webfont.ttf\" , publish . conf . outDir + \"/\" + publish . conf . fontsDir ) ; IO . copyFile ( publish . conf . templatesDir + \"/\" + publish . conf . fontsDir + \"mplus-1m-bold-webfont.woff\" , publish . conf . outDir + \"/\" + publish . conf . fontsDir ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Include a sub - template in the current template specifying a data object [CODESPLIT] function subtemplate ( template , data ) { try { return new JSDOC . JsPlate ( publish . conf . templatesDir + template ) . process ( data ) ; } catch ( e ) { print ( e . message ) ; quit ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build output for displaying function parameters . [CODESPLIT] function makeSignature ( params ) { if ( ! params ) return \"()\" ; var signature = \"(\" + params . filter ( function ( $ ) { return ! / \\w+\\.\\w+ / . test ( $ . name ) ; } ) . map ( function ( $ ) { var name = $ . isOptional ? '[' + $ . name + ']' : $ . name ; return name ; } ) . join ( \", \" ) + \")\" ; return signature ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find symbol { [CODESPLIT] function resolveLinks ( str , from ) { str = str . replace ( / \\{@link ([^}]+)\\} / gi , function ( match , symbolName ) { symbolName = symbolName . trim ( ) ; var index = symbolName . indexOf ( ' ' ) ; if ( index > 0 ) { var label = symbolName . substring ( index + 1 ) ; symbolName = symbolName . substring ( 0 , index ) ; return new Link ( ) . toSymbol ( symbolName ) . withText ( label ) ; } else { return new Link ( ) . toSymbol ( symbolName ) ; } } ) ; return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GameDefaults Class [CODESPLIT] function formatQuery ( options ) { var requiredParams if ( options && typeof options !== 'function' ) { options . query = requiredParams = _ . pick ( _ . extend ( { } , options , options . query ) , 'tournament_id' , 'league_id' , 'flight_id' , 'division_id' ) } if ( _ . isEmpty ( requiredParams ) ) throw new Error ( 'tournament_id, league_id, flight_id or division_id are required.' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Approach the desired contrast ratio by modifying the given component from the given starting value . [CODESPLIT] function approach ( index , x , onAxis ) { while ( 0 <= x && x <= 1 ) { candidateHSVA [ index ] = x ; WebInspector . Color . hsva2rgba ( candidateHSVA , candidateRGBA ) ; WebInspector . Color . blendColors ( candidateRGBA , bgRGBA , blendedRGBA ) ; var fgLuminance = WebInspector . Color . luminance ( blendedRGBA ) ; var dLuminance = fgLuminance - desiredLuminance ; if ( Math . abs ( dLuminance ) < ( onAxis ? epsilon / 10 : epsilon ) ) return x ; else x += ( index === V ? - dLuminance : dLuminance ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get data [CODESPLIT] function colorControlInput ( id ) { const data = { id : id , column : d3form . optionData ( ` ${ id } ` ) } ; const preset = d3form . optionData ( ` ${ id } ` ) ; if ( preset . scale . scale === 'ordinal' ) { data . scale = preset . scale ; return data ; } data . scale = { scale : d3form . value ( ` ${ id } ` ) , domain : [ d3form . value ( ` ${ id } ` ) , d3form . value ( ` ${ id } ` ) ] , unknown : '#696969' } ; const range = [ d3form . value ( ` ${ id } ` ) ] ; if ( d3form . checked ( ` ${ id } ` ) ) { range . push ( d3form . value ( ` ${ id } ` ) ) ; } range . push ( d3form . value ( ` ${ id } ` ) ) ; data . scale . range = range ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update DOM attributes [CODESPLIT] function updateNodeColor ( data ) { d3 . selectAll ( '.node' ) . select ( '.node-symbol' ) . style ( 'fill' , d => d3scale . scaleFunction ( data . scale ) ( d [ data . column . key ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate controlBox elements [CODESPLIT] function mainControlBox ( ) { d3 . select ( '#show-struct' ) . on ( 'change' , function ( ) { const data = nodeContentInput ( ) ; d3 . select ( '#main-control' ) . datum ( data ) ; updateNodeStructure ( data ) ; } ) . dispatch ( 'change' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bootstraps the setup of the graph . [CODESPLIT] function bootstrap ( ) { // Hook up controllers $ ( '.control-zoom button' ) . on ( 'click' , onControlZoomClicked ) ; $ ( '.control-level input' ) . on ( 'change' , onControlLevelChanged ) ; $ ( '.control-deps input' ) . on ( 'click' , onControlDepsClicked ) ; $ ( '.control-links input' ) . on ( 'click' , onControlLinksClicked ) ; $ ( '.control-menu li' ) . on ( 'click' , onControlMenuClicked ) ; $ ( '#contextpopup li[data-action]' ) . on ( 'click' , onNodeContextMenuClick ) ; // Gather current level and scope from template values. appOptions . currentLevel = parseInt ( $ ( '.control-level input' ) . val ( ) ) ; appOptions . currentScope = $ ( '.control-deps input:radio[name=dep]:checked' ) . val ( ) ; zoom = d3 . behavior . zoom ( ) ; zoom . scaleExtent ( [ minScaleExtent , maxScaleExtent ] ) ; zoom . on ( 'zoom' , onZoomChanged ) ; graphWidth = window . innerWidth ; graphHeight = window . innerHeight ; d3 . select ( window ) . on ( 'resize' , onResize ) ; // Setup layout layout = d3 . layout . force ( ) . gravity ( .05 ) . charge ( - 300 ) . linkDistance ( 80 ) . size ( [ graphWidth , graphHeight ] ) . on ( 'tick' , onTick ) ; // Setup drag callbacks for nodes. If a node is clicked and dragged it becomes fixed. layout . drag ( ) . on ( 'dragstart' , function ( targetNode ) { d3 . event . sourceEvent . stopPropagation ( ) ; d3 . select ( this ) . classed ( 'dragging' , true ) . classed ( 'fixed' , targetNode . fixed = true ) ; detectAllNodesFixed ( ) ; } ) . on ( 'drag' , function ( targetNode ) { d3 . select ( this ) . attr ( 'cx' , targetNode . x = d3 . event . x ) . attr ( 'cy' , targetNode . y = d3 . event . y ) ; } ) . on ( 'dragend' , function ( ) { d3 . select ( this ) . classed ( 'dragging' , false ) ; } ) ; // Setup graph d3 . select ( '.graph' ) . append ( 'svg' ) . attr ( 'transform' , 'rotate(0)' ) . on ( 'contextmenu' , function ( ) { d3 . event . preventDefault ( ) ; } ) . attr ( 'pointer-events' , 'all' ) . call ( zoom ) . on ( 'dblclick.zoom' , null ) ; // Markers Def d3 . select ( '.graph svg' ) . append ( 'defs' ) . selectAll ( 'marker' ) . data ( [ 'regular' ] ) . enter ( ) . append ( 'marker' ) . attr ( 'id' , String ) . attr ( 'viewBox' , '0 -5 10 10' ) . attr ( 'refX' , 15 ) . attr ( 'refY' , - 1.5 ) . attr ( 'markerWidth' , 6 ) . attr ( 'markerHeight' , 6 ) . attr ( 'orient' , 'auto' ) . append ( 'path' ) . attr ( 'd' , 'M0,-5L10,0L0,5' ) ; // Top level SVGGElement for dragging / centering graph graph = d3 . select ( '.graph svg' ) . append ( getSVG ( 'g' ) ) . attr ( 'width' , graphWidth ) . attr ( 'height' , graphHeight ) . attr ( 'transform' , 'translate(' + zoom . translate ( ) + ')' + ' scale(' + zoom . scale ( ) + ')' ) ; // Initialize tablesorter $ ( '#nodeTable' ) . tablesorter ( { widgets : [ 'stickyHeaders' ] , widgetOptions : { stickyHeaders_filteredToTop : true , stickyHeaders_cloneId : '-sticky' , stickyHeaders_attachTo : '.control-table-inner' } , sortMultiSortKey : '' } ) ; updateAll ( ) ; // Center graph w/ zoom fit w/ 1 second transition applied after 4 seconds delay for debounce. centerGraph ( zoomFit , 1000 , 4000 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Centers the graph . All parameters can be either a number or a function evaluated for a number result . [CODESPLIT] function centerGraph ( newScale , duration , delay ) { if ( typeof delay === 'function' ) { delay = delay . call ( this ) ; } delay = typeof delay === 'number' ? delay : 0 ; setTimeout ( function ( ) { if ( typeof newScale === 'function' ) { newScale = newScale . call ( this ) ; } if ( typeof duration === 'function' ) { duration = duration . call ( this ) ; } newScale = typeof newScale === 'number' ? newScale : zoom . scale ( ) ; duration = typeof duration === 'number' ? duration : 200 ; if ( typeof newScale !== 'number' ) { throw new TypeError ( \"centerGraph error: 'newScale' is not a 'number'.\" ) ; } if ( typeof duration !== 'number' ) { throw new TypeError ( \"centerGraph error: 'duration' is not a 'number'.\" ) ; } var bounds = graph . node ( ) . getBBox ( ) ; var centerSVGX = ( graphWidth * newScale / 2 ) ; var centerSVGY = ( graphHeight * newScale / 2 ) ; var centerGraphX = ( bounds . x * newScale ) + ( bounds . width * newScale / 2 ) ; var centerGraphY = ( bounds . y * newScale ) + ( bounds . height * newScale / 2 ) ; // Translate var centerTranslate = [ ( graphWidth / 2 ) - centerSVGX + ( centerSVGX - centerGraphX ) , ( graphHeight / 2 ) - centerSVGY + ( centerSVGY - centerGraphY ) ] ; // Store values zoom . translate ( centerTranslate ) . scale ( newScale ) ; // Render transition graph . transition ( ) . duration ( duration ) . attr ( 'transform' , 'translate(' + zoom . translate ( ) + ')' + ' scale(' + zoom . scale ( ) + ')' ) ; // Hides any existing node context menu. hideNodeContextMenu ( ) ; } , delay ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper function to determin if all nodes are fixed . This is run after any node is dragged and set to fixed . [CODESPLIT] function detectAllNodesFixed ( ) { if ( data ) { var currentNodesFixed = data . allNodesFixed ; var allNodesFixed = true ; data . nodes . forEach ( function ( node ) { if ( ! node . fixed ) { allNodesFixed = false ; } } ) ; data . allNodesFixed = allNodesFixed ; if ( currentNodesFixed !== allNodesFixed ) { updateMenuUI ( ) ; } // Update freeze / unfreeze menu option. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fades and unfades connected nodes to a given targetNode . [CODESPLIT] function fadeRelatedNodes ( targetNode , selected , nodes , links ) { var opacity = selected ? 0.1 : 1 ; var elm = findElementByNode ( 'circle' , targetNode ) ; // Highlight circle elm . classed ( 'selected' , opacity < 1 ) ; // Clean links $ ( 'path.link' ) . removeAttr ( 'data-show' ) ; // Traverse all nodes and set `dimmed` class to nodes that are dimmed / not connected in addition to setting // fill and stroke opacity. nodes . style ( 'stroke-opacity' , function ( otherNode ) { var thisOpacity = isConnected ( targetNode , otherNode ) ? 1 : opacity ; this . setAttribute ( 'fill-opacity' , thisOpacity ) ; this . setAttribute ( 'stroke-opacity' , thisOpacity ) ; // Depending on opacity add or remove 'dimmed' class. this . classList [ thisOpacity === 1 ? 'remove' : 'add' ] ( 'dimmed' ) ; return thisOpacity ; } ) ; // Traverse all links and set `data-show` and `marker-end` for connected links given the `targetNode`. links . style ( 'stroke-opacity' , function ( otherNode ) { if ( otherNode . source === targetNode ) { // Highlight target / sources of the link var elmNodes = graph . selectAll ( '.' + formatClassName ( 'node' , otherNode . target ) ) ; elmNodes . attr ( 'fill-opacity' , 1 ) ; elmNodes . attr ( 'stroke-opacity' , 1 ) ; elmNodes . classed ( 'dimmed' , false ) ; // Highlight arrows var elmCurrentLink = $ ( 'path.link[data-source=' + otherNode . source . index + ']' ) ; elmCurrentLink . attr ( 'data-show' , true ) ; elmCurrentLink . attr ( 'marker-end' , 'url(#regular)' ) ; return 1 ; } else { return opacity ; } } ) ; // Modify all links that have not had 'data-show' added above. var elmAllLinks = $ ( 'path.link:not([data-show])' ) ; elmAllLinks . attr ( 'marker-end' , opacity === 1 ? 'url(#regular)' : '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A helper to select a given SVG element from given node data . [CODESPLIT] function findElementByNode ( prefix , node ) { var selector = '.' + formatClassName ( prefix , node ) ; return graph . select ( selector ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pass in the element and the screen coordinates are returned . [CODESPLIT] function getElementCoords ( element ) { var ctm = element . getCTM ( ) ; return { x : ctm . e + element . getAttribute ( 'cx' ) * ctm . a , y : ctm . f + element . getAttribute ( 'cy' ) * ctm . d } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a recycled SVG element from the pool svgElementMap or creates a new element for the given type . Any data specified by D3 will be copied to the element . Returns a function which is evaluated by D3 . [CODESPLIT] function getSVG ( elementType ) { var returnVal ; var svgElement ; var cached ; switch ( elementType ) { case 'circle' : case 'g' : case 'path' : case 'text' : returnVal = function ( data ) { svgElement = svgElementMap [ elementType ] . pop ( ) ; cached = svgElement != null ; svgElement = svgElement != null ? svgElement : document . createElementNS ( 'http://www.w3.org/2000/svg' , elementType ) ; // Copy data to SVG element. if ( typeof data === 'object' ) { for ( var key in data ) { svgElement . setAttribute ( key , data [ key ] ) ; } } return svgElement ; } ; break ; default : throw new TypeError ( 'getSVG error: unknown elementType.' ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hides the node context menu if visible and removes any node highlighting . If an event is supplied it is checked against any existing context menu and is ignored if the context menu is within the parent hierarchy . [CODESPLIT] function hideNodeContextMenu ( event ) { // Provide an early out if there is no selected context node. if ( typeof selectedContextNode === 'undefined' ) { return ; } var contextMenuButton = $ ( '#context-menu' ) ; var popupmenu = $ ( '#contextpopup .mdl-menu__container' ) ; // If an event is defined then make sure it isn't targeting the context menu. if ( event ) { event . preventDefault ( ) ; // Picked element is not the menu if ( ! $ ( event . target ) . parents ( '#contextpopup' ) . length > 0 ) { // Hide menu if currently visible if ( popupmenu . hasClass ( 'is-visible' ) ) { contextMenuButton . click ( ) ; } fadeRelatedNodes ( selectedContextNode , false , nodes , links ) ; selectedContextNode = undefined ; } } else // No event defined so always close context menu and remove node highlighting. { // Hide menu if currently visible if ( popupmenu . hasClass ( 'is-visible' ) ) { contextMenuButton . click ( ) ; } fadeRelatedNodes ( selectedContextNode , false , nodes , links ) ; selectedContextNode = undefined ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a target node is connected to another given node by checking index or the linkedByIndex map . [CODESPLIT] function isConnected ( targetNode , otherNode ) { return targetNode . index === otherNode . index || linkedByIndex [ targetNode . index + ',' + otherNode . index ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles responding to the dependencies radio group . [CODESPLIT] function onControlDepsClicked ( ) { // Do nothing if scope has not changed if ( this . value === appOptions . currentScope ) { return ; } // If max depth is set to sticky and current level is equal max level of old scope then set max level for // the new scope. if ( appOptions . maxDepthSticky && appOptions . currentLevel === dataPackageMap [ appOptions . currentScope ] . maxLevel ) { appOptions . currentLevel = dataPackageMap [ this . value ] . maxLevel } appOptions . currentScope = this . value ; var maxLevel = dataPackageMap [ appOptions . currentScope ] . maxLevel ; // Adjust current level if it is greater than max level for current scope. if ( appOptions . currentLevel > maxLevel ) { appOptions . currentLevel = maxLevel ; } // Update control level UI based on current and max level for given scope. $ ( '.control-level input' ) . attr ( { max : maxLevel } ) ; $ ( '.control-level input' ) . val ( appOptions . currentLevel ) ; $ ( '.control-level label' ) . html ( appOptions . currentLevel ) ; // Redraw graph data updateAll ( { redrawOnly : true } ) ; // Center graph w/ zoom fit w/ 1 second transition applied after a potential 2 seconds delay for debounce. centerGraph ( zoomFit , 1000 , data . allNodesFixed ? 0 : 2000 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles responding to the level slider . [CODESPLIT] function onControlLevelChanged ( ) { appOptions . currentLevel = parseInt ( this . value ) ; $ ( '.control-level input' ) . val ( appOptions . currentLevel ) ; $ ( '.control-level label' ) . html ( appOptions . currentLevel ) ; // Redraw graph data updateAll ( { redrawOnly : true } ) ; // Center graph w/ zoom fit w/ 1 second transition applied after a potential 2 seconds delay for debounce. centerGraph ( zoomFit , 1000 , data . allNodesFixed ? 0 : 2000 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles responding to overflow menu selections . [CODESPLIT] function onControlMenuClicked ( ) { switch ( $ ( this ) . data ( 'action' ) ) { case 'toggleFreezeAllNodes' : setNodesFixed ( ! data . allNodesFixed ) ; break ; case 'showFullNames' : appOptions . showFullNames = ! appOptions . showFullNames ; updateAll ( { redrawOnly : true } ) ; break ; case 'showTableView' : appOptions . showTableView = ! appOptions . showTableView ; $ ( '.control-table' ) . toggleClass ( 'hidden' , ! appOptions . showTableView ) ; updateTableUIExtent ( ) ; break ; case 'maxDepthSticky' : appOptions . maxDepthSticky = ! appOptions . maxDepthSticky ; break ; } // Defer updating menu UI until menu is hidden. setTimeout ( updateMenuUI , 200 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles a context click on a table row showing the related node context menu . [CODESPLIT] function onControlTableRowContextClick ( node , event ) { event . preventDefault ( ) ; // Prevents default browser context menu from showing. onNodeContextClick ( node , { x : event . pageX , y : event . pageY } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles a context click on a table row showing the related node context menu . Defers to onNodeMouseOverOut . [CODESPLIT] function onControlTableRowMouseOver ( nodes , links , node , enter ) { // Hide the node context menu if currently showing when a new table row / node is moused over. if ( node !== selectedContextNode ) { hideNodeContextMenu ( event ) ; } onNodeMouseOverOut ( nodes , links , enter , node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles clicks on zoom control buttons and invokes centerGraph with new scale value . [CODESPLIT] function onControlZoomClicked ( ) { var newScale = 1 ; var scalePercentile = 0.20 ; // Add or subtract scale percentile from current scale value. switch ( $ ( this ) . data ( 'action' ) ) { case 'zoom_in' : newScale = Math . max ( Math . min ( zoom . scale ( ) * ( 1 + scalePercentile ) , maxScaleExtent ) , minScaleExtent ) ; break ; case 'zoom_out' : newScale = Math . max ( zoom . scale ( ) * ( 1 - scalePercentile ) , minScaleExtent ) ; break ; case 'zoom_all_out' : newScale = zoomFit ( ) ; break ; } centerGraph ( newScale ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles clicks on the node context menu invoking any active actions . [CODESPLIT] function onNodeContextMenuClick ( ) { // When a context menu is selected remove node highlighting. hideNodeContextMenu ( ) ; console . log ( '!! action: ' + $ ( this ) . data ( 'action' ) + '; link: ' + $ ( this ) . data ( 'link' ) ) ; switch ( $ ( this ) . data ( 'action' ) ) { case 'openLink' : var link = $ ( this ) . data ( 'link' ) ; if ( typeof link === 'string' ) { window . open ( link , '_blank' , 'location=yes,menubar=yes,scrollbars=yes,status=yes' ) ; } break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shows the node context menu [CODESPLIT] function onNodeContextClick ( targetNode , coords ) { // Hides any existing node context menu. hideNodeContextMenu ( ) ; if ( typeof coords !== 'object' ) { coords = getElementCoords ( this ) ; } var popupmenu = $ ( '#contextpopup .mdl-menu__container' ) ; var packageData = targetNode . packageData ; var packageLink , packageType , scmLink , scmType ; if ( packageData ) { if ( packageData . packageLink ) { packageLink = packageData . packageLink . link ; packageType = packageData . packageLink . type ; // Create proper name for package type. switch ( packageType ) { case 'npm' : packageType = 'NPM' ; break ; } } if ( packageData . scmLink ) { scmLink = packageData . scmLink . link ; scmType = packageData . scmLink . type ; // Create proper name for SCM type. switch ( scmType ) { case 'github' : scmType = 'Github' ; break ; } } } // Populate data for the context menu. popupmenu . find ( 'li' ) . each ( function ( index ) { var liTarget = $ ( this ) ; switch ( index ) { case 0 : if ( scmLink && scmType ) { liTarget . text ( 'Open on ' + scmType ) ; liTarget . data ( 'link' , scmLink ) ; liTarget . removeClass ( 'hidden' ) ; } else { liTarget . addClass ( 'hidden' ) ; } break ; case 1 : if ( packageLink && packageType ) { liTarget . text ( 'Open on ' + packageType ) ; liTarget . data ( 'link' , packageLink ) ; liTarget . removeClass ( 'hidden' ) ; } else { liTarget . addClass ( 'hidden' ) ; } break ; case 2 : if ( packageData && packageData . version ) { liTarget . text ( 'Version: ' + packageData . version ) ; liTarget . removeClass ( 'hidden' ) ; } else { liTarget . addClass ( 'hidden' ) ; } break ; } } ) ; // Wrapping in a 100ms timeout allows MDL to draw animation when showing a context menu after one has been hidden. setTimeout ( function ( ) { // Assign new selected context node and highlight related nodes. selectedContextNode = targetNode ; fadeRelatedNodes ( selectedContextNode , true , nodes , links ) ; // For MDL a programmatic click of the hidden context menu. var contextMenuButton = $ ( \"#context-menu\" ) ; contextMenuButton . click ( ) ; // Necessary to defer reposition of the context menu. setTimeout ( function ( ) { popupmenu . parent ( ) . css ( { position : 'relative' } ) ; popupmenu . css ( { left : coords . x , top : coords . y , position : 'absolute' } ) ; } , 0 ) ; } , 100 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles a mouse down action on a graph node . Hides any showing context menu . For left clicks the selected node becomes the drag target and related nodes are faded . Any other mouse button is ignored . [CODESPLIT] function onNodeMouseDown ( nodes , links , targetNode ) { hideNodeContextMenu ( ) ; // Only select / drag nodes with left clicked otherwise stop propagation of event. if ( d3 . event . button === 0 ) { selectedDragNode = targetNode ; // Select / highlight related nodes or remove attributes based on enter state. fadeRelatedNodes ( targetNode , true , nodes , links ) ; } else { d3 . event . stopPropagation ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles fading related nodes to the given targetNode if there is no currently selected node . [CODESPLIT] function onNodeMouseOverOut ( nodes , links , enter , targetNode ) { // If there is an existing selected node then exit early. if ( isNodeSelected ( ) ) { return ; } // Select / highlight related nodes or remove attributes based on enter state. fadeRelatedNodes ( targetNode , enter , nodes , links ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the window resize event . [CODESPLIT] function onResize ( ) { // Update graph parameters. graphWidth = window . innerWidth ; graphHeight = window . innerHeight ; graph . attr ( 'width' , graphWidth ) . attr ( 'height' , graphHeight ) ; layout . size ( [ graphWidth , graphHeight ] ) . resume ( ) ; updateMenuUI ( ) ; updateTableUIExtent ( ) ; // Hides any existing node context menu. hideNodeContextMenu ( ) ; centerGraph ( zoomFit , 1000 , data . allNodesFixed ? 0 : 2000 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "D3 tick handler for the forced graph layout . [CODESPLIT] function onTick ( ) { nodes . attr ( 'cx' , function ( node ) { return node . x ; } ) . attr ( 'cy' , function ( node ) { return node . y ; } ) . attr ( 'transform' , function ( node ) { return 'translate(' + node . x + ',' + node . y + ')' ; } ) ; // Pull data from data.nodes array. Provides a curve to the links. links . attr ( 'd' , function ( link ) { var sourceX = data . nodes [ link . source . index ] . x ; var sourceY = data . nodes [ link . source . index ] . y ; var targetX = data . nodes [ link . target . index ] . x ; var targetY = data . nodes [ link . target . index ] . y ; var dx = targetX - sourceX , dy = targetY - sourceY , dr = Math . sqrt ( dx * dx + dy * dy ) ; return 'M' + sourceX + ',' + sourceY + 'A' + dr + ',' + dr + ' 0 0,1 ' + targetX + ',' + targetY ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the D3 zoom / scale event . [CODESPLIT] function onZoomChanged ( ) { var newScale = Math . max ( d3 . event . scale , minScaleExtent ) ; zoom . scale ( newScale ) ; graph . attr ( 'transform' , 'translate(' + d3 . event . translate + ')' + ' scale(' + newScale + ')' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recycles all SVG elements above the top level SVGGElement defining the graph . [CODESPLIT] function recycleGraph ( ) { var childNodes = graph . selectAll ( 'g > *' ) . remove ( ) ; if ( ! Array . isArray ( childNodes ) && ! Array . isArray ( childNodes [ '0' ] ) ) { return ; } // Get the child nodes group from selection. childNodes = childNodes [ '0' ] ; for ( var cntr = 0 ; cntr < childNodes . length ; cntr ++ ) { var childNode = childNodes [ cntr ] ; if ( childNode instanceof SVGPathElement ) { svgElementMap [ 'path' ] . push ( childNode ) ; } else if ( childNode instanceof SVGCircleElement ) { svgElementMap [ 'circle' ] . push ( childNode ) ; } else if ( childNode instanceof SVGTextElement ) { svgElementMap [ 'text' ] . push ( childNode ) ; } else if ( childNode instanceof SVGGElement ) { childNode . removeAttribute ( 'transform' ) ; // Must remove current transform. svgElementMap [ 'g' ] . push ( childNode ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders the graph after recycling any nodes above the top level g SVGGElement . [CODESPLIT] function renderGraph ( options ) { options = typeof options === 'object' ? options : { } ; options . redrawOnly = typeof options . redrawOnly === 'boolean' ? options . redrawOnly : false ; // Recycle all SVG elements above the first SVGGElement. recycleGraph ( ) ; // Lines // Note: on second render link.source / target will be an object instead of a number. links = graph . append ( getSVG ( 'g' ) ) . selectAll ( 'line' ) . data ( data . links ) . enter ( ) . append ( getSVG ( 'path' ) ) . attr ( 'class' , 'link' ) . attr ( 'marker-end' , function ( ) { return 'url(#regular)' ; } ) . attr ( 'data-source' , function ( link ) { return typeof link . source === 'number' ? link . source : link . source . index ; } ) . attr ( 'data-target' , function ( link ) { return typeof link . target === 'number' ? link . target : link . target . index ; } ) ; // Nodes nodes = graph . append ( getSVG ( 'g' ) ) . selectAll ( 'node' ) . data ( data . nodes ) . enter ( ) . append ( getSVG ( 'g' ) ) . call ( layout . drag ) . attr ( 'class' , 'node' ) ; // Circles nodes . attr ( 'class' , function ( node ) { return formatClassName ( 'node' , node ) ; } ) ; nodes . append ( getSVG ( 'circle' ) ) . attr ( 'id' , function ( node ) { return formatClassName ( 'id' , node ) ; } ) . attr ( 'class' , function ( node ) { return formatClassName ( 'circle' , node ) + ' ' + node . packageData . jspmType ; } ) . attr ( 'r' , circleRadius ) . on ( 'contextmenu' , onNodeContextClick ) . on ( 'mousedown' , onNodeMouseDown . bind ( this , nodes , links ) ) . on ( 'mouseover' , onNodeMouseOverOut . bind ( this , nodes , links , true ) ) . on ( 'mouseout' , onNodeMouseOverOut . bind ( this , nodes , links , false ) ) . on ( 'dblclick.zoom' , function ( node ) // Centers view on node. { d3 . event . stopPropagation ( ) ; var dcx = ( window . innerWidth / 2 - node . x * zoom . scale ( ) ) ; var dcy = ( window . innerHeight / 2 - node . y * zoom . scale ( ) ) ; zoom . translate ( [ dcx , dcy ] ) ; graph . transition ( ) . duration ( 500 ) . attr ( 'transform' , 'translate(' + dcx + ',' + dcy + ')scale(' + zoom . scale ( ) + ')' ) ; } ) ; // A copy of the text with a thick white stroke for legibility. nodes . append ( getSVG ( 'text' ) ) . attr ( 'x' , 15 ) . attr ( 'y' , '.31em' ) . attr ( 'class' , function ( node ) { return 'shadow ' + formatClassName ( 'text' , node ) ; } ) . text ( function ( node ) { return ( appOptions . showFullNames ? node . packageData . actualPackageName : node . packageData . packageName ) + ' (' + node . minLevel + ')' ; } ) ; nodes . append ( getSVG ( 'text' ) ) . attr ( 'class' , function ( node ) { return node . packageData . isAlias ? 'isAliased ' : '' + formatClassName ( 'text' , node ) ; } ) . attr ( 'x' , 15 ) . attr ( 'y' , '.31em' ) . text ( function ( node ) { return ( appOptions . showFullNames ? node . packageData . actualPackageName : node . packageData . packageName ) + ' (' + node . minLevel + ')' ; } ) ; // Set the force layout nodes / links and start the bounce. layout . nodes ( data . nodes ) ; layout . links ( data . links ) ; layout . start ( ) ; linkedByIndex = { } ; // Build linked index data . links . forEach ( function ( node ) { linkedByIndex [ node . source . index + ',' + node . target . index ] = true ; } ) ; // Set a low alpha to provide minimal bounce when just redrawing. if ( options . redrawOnly ) { layout . alpha ( 0.01 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reverses all graph links . [CODESPLIT] function reverseGraphLinks ( ) { for ( var key in dataPackageMap ) { var graphData = dataPackageMap [ key ] ; graphData . links . forEach ( function ( link ) { var linkSource = link . source ; link . source = link . target ; link . target = linkSource ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets all nodes fixed ( freeze ) or unfixed ( unfreeze ) . [CODESPLIT] function setNodesFixed ( fixed ) { // Resets any fixed node state. if ( nodes ) { nodes . each ( function ( node ) { d3 . select ( this ) . classed ( 'fixed' , node . fixed = fixed ) ; } ) ; } // Copy existing sim data to any package scope that contains the same node ID. for ( var key in dataPackageMap ) { dataPackageMap [ key ] . nodes . forEach ( function ( node ) { node . fixed = fixed ; } ) ; } if ( data ) { data . allNodesFixed = fixed ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters graph data based on current app option parameters : currentScope and currentLevel . [CODESPLIT] function updateGraphData ( ) { // Copy existing data / node parameters to new filtered data; if ( data ) { var existingNodeSimMap = { } ; // Collect existing simulation data. data . nodes . forEach ( function ( node ) { existingNodeSimMap [ node . id ] = { weight : node . weight , x : node . x , y : node . y , px : node . px , py : node . py , fixed : node . fixed ? node . fixed : false } ; } ) ; // Copy existing sim data to any package scope that contains the same node ID. for ( var mapKey in dataPackageMap ) { var graphData = dataPackageMap [ mapKey ] ; graphData . nodes . forEach ( function ( node ) { if ( existingNodeSimMap [ node . id ] ) { for ( var key in existingNodeSimMap [ node . id ] ) { node [ key ] = existingNodeSimMap [ node . id ] [ key ] ; } } } ) ; } } var allNodesFixed = true ; // Set new data data = { directed : dataPackageMap [ appOptions . currentScope ] . directed , multigraph : dataPackageMap [ appOptions . currentScope ] . multigraph , graph : dataPackageMap [ appOptions . currentScope ] . graph , links : dataPackageMap [ appOptions . currentScope ] . links . filter ( function ( link ) { return link . minLevel <= appOptions . currentLevel ; } ) , nodes : dataPackageMap [ appOptions . currentScope ] . nodes . filter ( function ( node ) { if ( typeof node . fixed === 'undefined' || node . fixed === false ) { allNodesFixed = false ; } return node . minLevel <= appOptions . currentLevel ; } ) } ; data . allNodesFixed = allNodesFixed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides handling of changing menu text & material icons based on current state . [CODESPLIT] function updateMenuUI ( ) { if ( data ) { $ ( '.control-menu li[data-action=toggleFreezeAllNodes]' ) . html ( data . allNodesFixed ? 'Unfreeze nodes' : 'Freeze nodes' ) ; } appMenuToggleOptions . forEach ( function ( key ) { var icon = appOptions [ key ] ? 'check_box' : 'check_box_outline_blank' ; $ ( '.control-menu li[data-action=' + key + '] i' ) . html ( icon ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the table UI with all current node data and associates the active events on each row . [CODESPLIT] function updateTableUI ( ) { var table = $ ( '.control-table tbody' ) ; table . off ( 'mouseenter' , 'tr' , onControlTableRowMouseOver ) ; table . off ( 'mouseleave' , 'tr' , onControlTableRowMouseOver ) ; table . off ( 'contextmenu' , 'tr' , onControlTableRowContextClick ) ; table . empty ( ) ; if ( data ) { data . nodes . forEach ( function ( node ) { var nd = node . packageData ; var name = appOptions . showFullNames ? nd . actualPackageName : nd . packageName ; var isAliased = nd . isAlias ? ' isAliased' : '' ; var tr = $ ( '<tr>' + '<td class=\"mdl-data-table__cell--non-numeric' + isAliased + '\">' + name + '</td>' + '<td class=\"mdl-data-table__cell--non-numeric\">' + nd . jspmType + '</td>' + '<td class=\"mdl-data-table__cell--non-numeric\">' + nd . version + '</td>' + '<td class=\"mdl-data-table__cell--non-numeric\">' + node . minLevel + '</td>' + '</tr>' ) ; table . append ( tr ) ; tr . on ( 'mouseenter' , onControlTableRowMouseOver . bind ( this , nodes , links , node , true ) ) ; tr . on ( 'mouseleave' , onControlTableRowMouseOver . bind ( this , nodes , links , node , false ) ) ; tr . on ( 'contextmenu' , onControlTableRowContextClick . bind ( this , node ) ) ; } ) ; // Removes sort order for any header and signals update for new data $ ( '#nodeTable th' ) . removeClass ( 'headerSortDown' ) ; $ ( '#nodeTable th' ) . removeClass ( 'headerSortUp' ) ; $ ( '#nodeTable' ) . trigger ( 'update' ) ; updateTableUIExtent ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the node table max - height enabling scrolling as necessary . [CODESPLIT] function updateTableUIExtent ( ) { var tableDiv = $ ( '.control-table-inner' ) ; var nodeTable = $ ( '#nodeTable' ) ; var tableHeight = nodeTable . height ( ) ; var offset = tableDiv . offset ( ) ; var maxTableHeight = window . innerHeight - offset . top - 20 ; tableDiv . css ( 'max-height' , maxTableHeight ) ; nodeTable . css ( 'margin-right' , tableHeight > maxTableHeight ? '10px' : '0px' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines a new scale that fits the entire graph into view . [CODESPLIT] function zoomFit ( ) { var bounds = graph . node ( ) . getBBox ( ) ; var parent = graph . node ( ) . parentElement ; var fullWidth = parent . clientWidth , fullHeight = parent . clientHeight ; var width = bounds . width , height = bounds . height ; if ( width === 0 || height === 0 ) { return 1 ; } // nothing to fit var scale = 0.75 / Math . max ( width / fullWidth , height / fullHeight ) ; scale = Math . max ( Math . min ( scale , maxScaleExtent ) , minScaleExtent ) ; return scale ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the the inner width of the browser window [CODESPLIT] function getWindowWidth ( ) { if ( window . innerWidth ) { return window . innerWidth ; } else if ( document . documentElement . clientWidth ) { return document . documentElement . clientWidth ; } else if ( document . body . clientWidth ) { return document . body . clientWidth ; } else { return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds link to CSS in the head if no CSS is loaded [CODESPLIT] function ( cssScreen , cssHandheld , mobileMaxWidth ) { // Set config values\r if ( typeof ( cssScreen ) != \"undefined\" ) { config . cssScreen = cssScreen ; } if ( typeof ( cssHandheld ) != \"undefined\" ) { config . cssHandheld = cssHandheld ; } if ( typeof ( mobileMaxWidth ) != \"undefined\" ) { config . mobileMaxWidth = mobileMaxWidth ; } // Check if CSS is loaded\r var cssloadCheckNode = document . createElement ( 'div' ) ; cssloadCheckNode . className = config . testDivClass ; document . getElementsByTagName ( \"body\" ) [ 0 ] . appendChild ( cssloadCheckNode ) ; if ( cssloadCheckNode . offsetWidth != 100 && noMediaQuery == false ) { noMediaQuery = true ; } cssloadCheckNode . parentNode . removeChild ( cssloadCheckNode ) if ( noMediaQuery == true ) { // Browser does not support Media Queries, so JavaScript will supply a fallback \r var cssHref = \"\" ; // Determines what CSS file to load\r if ( getWindowWidth ( ) <= config . mobileMaxWidth ) { cssHref = config . cssHandheld ; newCssMediaType = \"handheld\" ; } else { cssHref = config . cssScreen ; newCssMediaType = \"screen\" ; } // Add CSS link to <head> of page\r if ( cssHref != \"\" && currentCssMediaType != newCssMediaType ) { var currentCssLinks = document . styleSheets for ( var i = 0 ; i < currentCssLinks . length ; i ++ ) { for ( var ii = 0 ; ii < currentCssLinks [ i ] . media . length ; ii ++ ) { if ( typeof ( currentCssLinks [ i ] . media ) == \"object\" ) { if ( currentCssLinks [ i ] . media . item ( ii ) == \"fallback\" ) { currentCssLinks [ i ] . ownerNode . parentNode . removeChild ( currentCssLinks [ i ] . ownerNode ) i -- break ; } } else { if ( currentCssLinks [ i ] . media . indexOf ( \"fallback\" ) >= 0 ) { currentCssLinks [ i ] . owningElement . parentNode . removeChild ( currentCssLinks [ i ] . owningElement ) i -- break ; } } } } if ( typeof ( cssHref ) == \"object\" ) { for ( var i = 0 ; i < cssHref . length ; i ++ ) { addCssLink ( cssHref [ i ] ) } } else { addCssLink ( cssHref ) } currentCssMediaType = newCssMediaType ; } // Check screen size again if user resizes window \r addEvent ( window , wbos . CssTools . MediaQueryFallBack . LoadCssDelayed , 'onresize' ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Plugin level function ( dealing with files ) [CODESPLIT] function gulpRebound ( options ) { options || ( options = { } ) ; // Creating a stream through which each file will pass return through . obj ( function ( file , enc , cb ) { // return empty file if ( file . isNull ( ) ) return cb ( null , file ) ; if ( file . isStream ( ) ) { throw new PluginError ( PLUGIN_NAME , \"Gulp Rebound doesn't handle streams!\" ) ; } // Compile try { file . contents = new Buffer ( rebound ( file . contents . toString ( enc ) , { name : file . path , baseDest : options . baseUrl || '' } ) . src , enc ) ; gutil . log ( gutil . colors . green ( 'File ' + file . relative + ' compiled' ) ) ; file . path = file . path . replace ( '.html' , '.js' ) ; } catch ( err ) { gutil . log ( gutil . colors . red ( 'Error in ' + file . relative ) ) ; gutil . log ( err ) ; } cb ( null , file ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Utils . clear () If folder exist clear files inside Else create it [CODESPLIT] function clearFile ( obj ) { if ( Utils . tools . isArray ( obj ) ) obj . forEach ( _clearFile ) ; else _clearFile ( obj ) ; return Utils ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function Item ( source , file ) { this . source = source ; this . file = file ; this . dirname = path . dirname ( this . file ) ; this . basename = path . basename ( this . file , '.yml' ) ; this . relPath = path . relative ( this . source , this . dirname ) ; this . yaml = yaml . load ( fs . readFileSync ( this . file , 'utf8' ) ) ; this [ \"package\" ] = path . dirname ( this . relPath ) ; this . module = path . basename ( this . relPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends successful HTTP reply [CODESPLIT] function do_success ( req , res , msg ) { res . writeHead ( 200 , { 'Content-Type' : ( ( typeof msg === 'string' ) ? 'text/plain' : 'application/json' ) } ) ; msg = ( typeof msg === 'string' ) ? msg : helpers . stringify ( msg ) ; res . end ( msg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends failed HTTP reply [CODESPLIT] function do_failure ( req , res , opts ) { opts = opts || { } ; var obj = { 'type' : opts . type || 'error' , 'code' : opts . code || 501 , 'desc' : opts . desc || ( '' + opts ) } ; res . writeHead ( obj . code , { 'Content-Type' : 'application/json' } ) ; res . end ( helpers . stringify ( obj ) + '\\n' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builder for generic HTTP Request Handler [CODESPLIT] function do_create_req ( config , routes ) { routes = routes || { } ; var version = routes . version || { } ; if ( version && ( typeof version === 'object' ) ) { } else { version = { 'self' : routes . version || config . pkg . version } ; } if ( ! version . api ) { version . api = api_config . pkg . version ; } routes . version = version ; var router = new RequestRouter ( routes ) ; var req_counter = 0 ; /* Inner Request handler */ function do_req ( req , res ) { req_counter += 1 ; return router . resolve ( req , res ) ; } // do_req return do_req ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "HTTP Server Creation [CODESPLIT] function do_create_server ( config , do_req ) { var http = require ( 'http' ) ; if ( config . host ) { http . createServer ( do_req ) . listen ( config . port , config . host ) ; //console.log(\"Server running at http://\"+config.host+\":\"+config.port+\"/\"); } else { http . createServer ( do_req ) . listen ( config . port ) ; //console.log(\"Server running at http://0.0.0.0:\"+config.port); } return http ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "API server builder [CODESPLIT] function setup_server ( config , opts ) { config . _def ( 'port' , 3000 ) ; var req_handler = do_create_req ( config , opts ) ; var server = do_create_server ( config , function ( req , res ) { req_handler ( req , res ) . then ( function ( obj ) { if ( obj === api . replySent ) { // Silently return since reply has been handler already. return ; } else if ( obj === api . notFound ) { do_failure ( req , res , { 'verb' : 'notFound' , 'desc' : 'The requested resource could not be found.' , 'code' : 404 } ) ; } else { do_success ( req , res , obj ) ; } } ) . fail ( function ( err ) { do_failure ( req , res , err ) ; if ( ! ( err instanceof errors . HTTPError ) ) { require ( 'prettified' ) . errors . print ( err ) ; } } ) . done ( ) ; } ) ; return server ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cross - browser event listener [CODESPLIT] function ( element , ev , fn ) { if ( element . addEventListener ) element . addEventListener ( ev , fn , false ) ; else element . attachEvent ( \"on\" + ev , fn ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "// FIXME : make SuggestBox work for multiple documents . [CODESPLIT] function ( ) { if ( this . visible ( ) ) return ; this . _bodyElement = document . body ; this . _bodyElement . addEventListener ( \"mousedown\" , this . _maybeHideBound , true ) ; this . _overlay = new WebInspector . SuggestBox . Overlay ( ) ; this . _overlay . setContentElement ( this . _container ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new Reply with the given parent and definition . [CODESPLIT] function Reply ( parent , definition ) { var key ; for ( key in updateMixin ) { this [ key ] = updateMixin [ key ] ; } Reply . super_ . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--- class / interfaces ---------------------------------- --- implements ------------------------------------------ [CODESPLIT] function WMURL_decode ( source ) { // @arg String - percent encoded string. // @ret String - decode string. // @throws Error(\"invalid WMURL.decode\") // @desc decodeURIComponent impl. //{@dev $valid ( $type ( source , \"String\" ) , WMURL_decode , \"source\" ) ; //}@dev return source . replace ( / (%[\\da-f][\\da-f])+ / g , function ( match ) { var rv = [ ] ; var ary = match . split ( \"%\" ) . slice ( 1 ) , i = 0 , iz = ary . length ; var a = 0 , b = 0 , c = 0 ; // UTF-8 bytes for ( ; i < iz ; ++ i ) { a = parseInt ( ary [ i ] , 16 ) ; if ( a !== a ) { // isNaN(a) throw new Error ( \"invalid WMURL.decode\" ) ; } // decode UTF-8 if ( a < 0x80 ) { // ASCII(0x00 ~ 0x7f) rv . push ( a ) ; } else if ( a < 0xE0 ) { b = parseInt ( ary [ ++ i ] , 16 ) ; rv . push ( ( a & 0x1f ) << 6 | ( b & 0x3f ) ) ; } else if ( a < 0xF0 ) { b = parseInt ( ary [ ++ i ] , 16 ) ; c = parseInt ( ary [ ++ i ] , 16 ) ; rv . push ( ( a & 0x0f ) << 12 | ( b & 0x3f ) << 6 | ( c & 0x3f ) ) ; } } return String . fromCharCode . apply ( null , rv ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Buffer of the specified file from the specified repo and commit reference . Recursively gets the tree instances until the last part which is gets the rawObject for and serves back over HTTP . [CODESPLIT] function serveGitFile ( repo , tree , parts , res , next ) { //console.log(\"Serving git file: \" + parts); var thisPart = parts . shift ( ) ; var isLastPart = parts . length === 0 ; var entryIndex = - 1 ; for ( var i = 0 ; i < tree . entries . length ; i ++ ) { if ( tree . entries [ i ] . name === thisPart ) { entryIndex = i ; break ; } } if ( entryIndex < 0 ) return next ( ) ; var entry = tree . entries [ entryIndex ] ; if ( isLastPart ) { repo . getBlob ( entry . id , function ( err , buf ) { if ( err ) return next ( err ) ; if ( ! buf . data ) return next ( ) ; serveBuffer ( buf . data , res , thisPart ) ; } ) ; } else { repo . getTree ( entry . id , function ( err , entryTree ) { if ( err ) return next ( err ) ; serveGitFile ( repo , entryTree , parts , res , next ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////// [CODESPLIT] function buildAndStart ( ) { if ( / ^https?:\\/\\/ / . test ( Program . file ) ) { var url = Program . file . replace ( / ^(https?:\\/\\/)([^/:]+)(?=:\\d+|\\/) / , function ( m , a , b ) { if ( ! / \\d+\\.\\d+\\.\\d+\\.\\d+ / . test ( a ) ) { return a + Hosts . findRealHost ( b ) ; } else { return m ; } } ) ; Config . entryBundleUrl = url ; startServerAndLaunchDevtool ( ) ; } else { var filePath = Path . resolve ( Program . file ) ; var ext = Path . extname ( filePath ) ; if ( ! Fs . existsSync ( filePath ) ) { console . error ( filePath + ': No such file or directory' ) ; return Exit ( 0 ) ; } if ( ext == '.ju' || ext == '.vue' ) { console . log ( 'building...' ) ; console . time ( 'Build completed!' ) ; buildFileAndWatchIt ( Program . mode , filePath ) . then ( function ( ) { console . timeEnd ( 'Build completed!' ) ; startServerAndLaunchDevtool ( Program . file ) ; } , function ( err ) { if ( err ) { console . log ( err , err . stack ) ; } Exit ( 0 ) ; } ) } else if ( ext == '.js' ) { buildFileAndWatchIt ( 'copy' , filePath ) . then ( function ( ) { startServerAndLaunchDevtool ( Program . file ) ; } ) } else if ( ! ext ) { //处理目录 if ( Fs . statSync ( filePath ) . isDirectory ( ) ) { Config . root = filePath ; startServerAndLaunchDevtool ( Program . entry ) } else { console . error ( Program . file + ' is not a directory!' ) ; Exit ( 0 ) ; } } else { console . error ( 'Error:unsupported file type: ' , ext ) ; return Exit ( 0 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@function randomUniqueId [CODESPLIT] function randomUniqueId ( ) { // increment count of generated ids randomUniqueId . count ++ // get timestamp var timestamp = microTimestamp ( ) // create unique id randomUniqueId . id = crypto . createHash ( 'sha256' ) // process id, microsec timestamp, and counter . update ( randomUniqueId . processId + randomUniqueId . id + timestamp + randomUniqueId . count ) // get hash as hex . digest ( 'hex' ) // only get 128 bits . substring ( 0 , 32 ) // return object with id and timestamp return { id : randomUniqueId . id , timestamp , } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Callback to start editing the next / previous property / selector . [CODESPLIT] function moveToNextCallback ( alreadyNew , valueChanged , section ) { if ( ! moveDirection ) return ; // User just tabbed through without changes. if ( moveTo && moveTo . parent ) { moveTo . startEditing ( ! isEditingName ? moveTo . nameElement : moveTo . valueElement ) ; return ; } // User has made a change then tabbed, wiping all the original treeElements. // Recalculate the new treeElement for the same property we were going to edit next. if ( moveTo && ! moveTo . parent ) { var rootElement = section . propertiesTreeOutline . rootElement ( ) ; if ( moveDirection === \"forward\" && blankInput && ! isEditingName ) -- moveToIndex ; if ( moveToIndex >= rootElement . childCount ( ) && ! this . _newProperty ) createNewProperty = true ; else { var treeElement = moveToIndex >= 0 ? rootElement . childAt ( moveToIndex ) : null ; if ( treeElement ) { var elementToEdit = ! isEditingName || isPropertySplitPaste ? treeElement . nameElement : treeElement . valueElement ; if ( alreadyNew && blankInput ) elementToEdit = moveDirection === \"forward\" ? treeElement . nameElement : treeElement . valueElement ; treeElement . startEditing ( elementToEdit ) ; return ; } else if ( ! alreadyNew ) moveToSelector = true ; } } // Create a new attribute in this section (or move to next editable selector if possible). if ( createNewProperty ) { if ( alreadyNew && ! valueChanged && ( isEditingName ^ ( moveDirection === \"backward\" ) ) ) return ; section . addNewBlankProperty ( ) . startEditing ( ) ; return ; } if ( abandonNewProperty ) { moveTo = this . _findSibling ( moveDirection ) ; var sectionToEdit = ( moveTo || moveDirection === \"backward\" ) ? section : section . nextEditableSibling ( ) ; if ( sectionToEdit ) { if ( sectionToEdit . style ( ) . parentRule ) sectionToEdit . startEditingSelector ( ) ; else sectionToEdit . _moveEditorFromSelector ( moveDirection ) ; } return ; } if ( moveToSelector ) { if ( section . style ( ) . parentRule ) section . startEditingSelector ( ) ; else section . _moveEditorFromSelector ( moveDirection ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes a list of files and produces the api routing for them [CODESPLIT] function processFileList ( files , base , settings , state ) { for ( var i = 0 ; i < files . length ; i ++ ) { var modulePath = path . join ( base , files [ i ] ) ; var stats = fs . statSync ( modulePath ) ; if ( stats . isFile ( ) ) { // Try to load the module var module = require ( modulePath ) ; var relative = path . relative ( settings . source , modulePath ) ; __log ( 'Relative path: %s' , relative ) ; var pathWithoutExtension = relative . substr ( 0 , relative . lastIndexOf ( '.' ) ) ; var routeName = pathWithoutExtension . replace ( / \\\\ / g , '/' ) . replace ( / \\. / g , '_' ) ; var isRoot = new RegExp ( settings . rootModule + '/?$' , 'g' ) . test ( routeName ) ; var routePath = routeName ; // Special case for an index file - put these in the root of the api             if ( isRoot ) { if ( routePath . lastIndexOf ( '/' ) > - 1 ) routePath = routePath . substr ( 0 , routePath . lastIndexOf ( '/' ) ) ; else routePath = undefined ; } __log ( '%s (%s)' , routeName , routePath ) ; var apiPath = utils . combineApiPath ( settings . root , routePath ) ; state . endpoints [ routeName ] = { baseUrl : apiPath , filename : modulePath , routeName : routeName } ; __log ( state . endpoints [ routeName ] ) ; settings . app . use ( apiPath , module ) ; } else if ( stats . isDirectory ( ) ) { var dirFiles = fs . readdirSync ( modulePath ) ; processFileList ( dirFiles , modulePath , settings , state ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package module for different environments [CODESPLIT] function packageModule ( global , name , api ) { if ( global . define && global . define . amd ) { define ( [ ] , api ) ; } else if ( typeof exports !== \"undefined\" ) { module . exports = api ; } else { global [ name ] = api ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * frameworkEventListeners fetcher functions should produce following output : { framework event listeners eventListeners : [ { handler : function () useCapture : true passive : false type : change remove : function ( type handler useCapture passive ) } ... ] internal framework event handlers internalHandlers : [ function () function () ... ] } [CODESPLIT] function frameworkEventListeners ( ) { var errorLines = [ ] ; var eventListeners = [ ] ; var internalHandlers = [ ] ; var fetchers = [ jQueryFetcher ] ; try { if ( self . devtoolsFrameworkEventListeners && isArrayLike ( self . devtoolsFrameworkEventListeners ) ) fetchers = fetchers . concat ( self . devtoolsFrameworkEventListeners ) ; } catch ( e ) { errorLines . push ( \"devtoolsFrameworkEventListeners call produced error: \" + toString ( e ) ) ; } for ( var i = 0 ; i < fetchers . length ; ++ i ) { try { var fetcherResult = fetchers [ i ] ( this ) ; if ( fetcherResult . eventListeners && isArrayLike ( fetcherResult . eventListeners ) ) { eventListeners = eventListeners . concat ( fetcherResult . eventListeners . map ( checkEventListener ) . filter ( nonEmptyObject ) ) ; } if ( fetcherResult . internalHandlers && isArrayLike ( fetcherResult . internalHandlers ) ) internalHandlers = internalHandlers . concat ( fetcherResult . internalHandlers . map ( checkInternalHandler ) . filter ( nonEmptyObject ) ) ; } catch ( e ) { errorLines . push ( \"fetcher call produced error: \" + toString ( e ) ) ; } } var result = { eventListeners : eventListeners } ; if ( internalHandlers . length ) result . internalHandlers = internalHandlers ; if ( errorLines . length ) { var errorString = \"Framework Event Listeners API Errors:\\n\\t\" + errorLines . join ( \"\\n\\t\" ) ; errorString = errorString . substr ( 0 , errorString . length - 1 ) ; result . errorString = errorString ; } return result ; /**\n         * @param {?Object} obj\n         * @return {boolean}\n         */ function isArrayLike ( obj ) { if ( ! obj || typeof obj !== \"object\" ) return false ; try { if ( typeof obj . splice === \"function\" ) { var len = obj . length ; return typeof len === \"number\" && ( len >>> 0 === len && ( len > 0 || 1 / len > 0 ) ) ; } } catch ( e ) { } return false ; } /**\n         * @param {*} eventListener\n         * @return {?WebInspector.EventListenerObjectInInspectedPage}\n         */ function checkEventListener ( eventListener ) { try { var errorString = \"\" ; if ( ! eventListener ) errorString += \"empty event listener, \" ; var type = eventListener . type ; if ( ! type || ( typeof type !== \"string\" ) ) errorString += \"event listener's type isn't string or empty, \" ; var useCapture = eventListener . useCapture ; if ( typeof useCapture !== \"boolean\" ) errorString += \"event listener's useCapture isn't boolean or undefined, \" ; var passive = eventListener . passive ; if ( typeof passive !== \"boolean\" ) errorString += \"event listener's passive isn't boolean or undefined, \" ; var handler = eventListener . handler ; if ( ! handler || ( typeof handler !== \"function\" ) ) errorString += \"event listener's handler isn't a function or empty, \" ; var remove = eventListener . remove ; if ( remove && ( typeof remove !== \"function\" ) ) errorString += \"event listener's remove isn't a function, \" ; if ( ! errorString ) { return { type : type , useCapture : useCapture , passive : passive , handler : handler , remove : remove } ; } else { errorLines . push ( errorString . substr ( 0 , errorString . length - 2 ) ) ; return null ; } } catch ( e ) { errorLines . push ( toString ( e ) ) ; return null ; } } /**\n         * @param {*} handler\n         * @return {function()|null}\n         */ function checkInternalHandler ( handler ) { if ( handler && ( typeof handler === \"function\" ) ) return handler ; errorLines . push ( \"internal handler isn't a function or empty\" ) ; return null ; } /**\n         * @param {*} obj\n         * @return {string}\n         * @suppress {uselessCode}\n         */ function toString ( obj ) { try { return \"\" + obj ; } catch ( e ) { return \"<error>\" ; } } /**\n         * @param {*} obj\n         * @return {boolean}\n         */ function nonEmptyObject ( obj ) { return ! ! obj ; } function jQueryFetcher ( node ) { if ( ! node || ! ( node instanceof Node ) ) return { eventListeners : [ ] } ; var jQuery = /** @type {?{fn,data,_data}}*/ ( window [ \"jQuery\" ] ) ; if ( ! jQuery || ! jQuery . fn ) return { eventListeners : [ ] } ; var jQueryFunction = /** @type {function(!Node)} */ ( jQuery ) ; var data = jQuery . _data || jQuery . data ; var eventListeners = [ ] ; var internalHandlers = [ ] ; if ( typeof data === \"function\" ) { var events = data ( node , \"events\" ) ; for ( var type in events ) { for ( var key in events [ type ] ) { var frameworkListener = events [ type ] [ key ] ; if ( typeof frameworkListener === \"object\" || typeof frameworkListener === \"function\" ) { var listener = { handler : frameworkListener . handler || frameworkListener , useCapture : true , passive : false , type : type } ; listener . remove = jQueryRemove . bind ( node , frameworkListener . selector ) ; eventListeners . push ( listener ) ; } } } var nodeData = data ( node ) ; if ( nodeData && typeof nodeData . handle === \"function\" ) internalHandlers . push ( nodeData . handle ) ; } var entry = jQueryFunction ( node ) [ 0 ] ; if ( entry ) { var entryEvents = entry [ \"$events\" ] ; for ( var type in entryEvents ) { var events = entryEvents [ type ] ; for ( var key in events ) { if ( typeof events [ key ] === \"function\" ) { var listener = { handler : events [ key ] , useCapture : true , passive : false , type : type } ; // We don't support removing for old version < 1.4 of jQuery because it doesn't provide API for getting \"selector\". eventListeners . push ( listener ) ; } } } if ( entry && entry [ \"$handle\" ] ) internalHandlers . push ( entry [ \"$handle\" ] ) ; } return { eventListeners : eventListeners , internalHandlers : internalHandlers } ; } /**\n         * @param {string} selector\n         * @param {string} type\n         * @param {function()} handler\n         * @this {?Object}\n         */ function jQueryRemove ( selector , type , handler ) { if ( ! this || ! ( this instanceof Node ) ) return ; var node = /** @type {!Node} */ ( this ) ; var jQuery = /** @type {?{fn,data,_data}}*/ ( window [ \"jQuery\" ] ) ; if ( ! jQuery || ! jQuery . fn ) return ; var jQueryFunction = /** @type {function(!Node)} */ ( jQuery ) ; jQueryFunction ( node ) . off ( type , selector , handler ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a proxy for the given { [CODESPLIT] function proxify ( api ) { if ( ! api || typeof api !== \"object\" ) throw new TypeError ( \"Only objects can be proxified.\" ) ; if ( typeof api . route !== \"function\" || typeof api . close !== \"function\" ) throw new TypeError ( \"Only objects that offer an owe Api interface can be proxified.\" ) ; const passthroughSet = api [ passthrough ] ; const proxy = new Proxy ( target , { get ( target , property ) { if ( typeof property === \"symbol\" || passthroughSet && passthroughSet . has ( property ) && property in api ) return typeof api [ property ] === \"function\" ? api [ property ] . bind ( api ) : api [ property ] ; return proxify ( api . route ( property ) ) ; } , apply ( target , context , args ) { return api . close ( args [ 0 ] ) ; } , deleteProperty ( ) { return false ; } } ) ; proxyMap . set ( proxy , api ) ; return proxy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "polyfills the global setImmediate [CODESPLIT] function Ebus ( p ) { \"use strict\" ; this . debug = false ; this . yields = false ; this . handlers = { } ; if ( p ) { this . priorities = p ; } else { this . priorities = { } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Common entry point for all API models [CODESPLIT] function ApiClient ( config ) { var self = this this . config = _ . extend ( { } , config , { client : this } ) config . headers = _ . extend ( { } , config . headers , { Accept : 'application/json' } ) this . auth = config . auth models . sync = require ( './sync' ) models . Model = require ( './modelbase' ) models . NginModel = require ( './nginModel' ) // add each model to the ApiClient Object . keys ( models ) . forEach ( function ( modelName ) { Object . defineProperty ( self , modelName , { get : function ( ) { return models [ modelName ] ( self ) } , enumerable : true , configurable : true } ) } ) _ . extend ( this , models ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns - 1 if value being searched for isn t found . value cannot be object . [CODESPLIT] function getFirstIndexOf ( value , array ) { error_if_not_primitive_or_array_1 . errorIfNotPrimitiveOrArray ( value ) ; if ( isArray_notArray_1 . isArray ( value ) ) { return getFirstIndexOfArray_1 . getFirstIndexOfArray ( value , array ) ; } else { // if primitive... return getIndexOfPrimitive_1 . getIndexOfPrimitive ( value , array ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * js / src / isinstance . js [CODESPLIT] function ( type , obj ) { return obj !== null && obj !== undefined && obj . constructor . prototype === type . prototype ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "breakStringList [CODESPLIT] function breakRoleList ( matcher , list ) { const pieces = [ ] const roleBreaker = XRegExp ( ` \\\\ ${ matcher . roleMatcher } \\\\ ` ) for ( let m = list . match ( roleBreaker ) ; m !== null ; m = list . match ( roleBreaker ) ) { const [ consumed , matched ] = m pieces . push ( matched ) list = list . substring ( consumed . length ) } const altFinder = XRegExp ( ` \\\\ \\\\ \\\\ ${ matcher . roleMatcher } ` ) const altMatch = list . match ( altFinder ) if ( altMatch ) { pieces . push ( altMatch [ 2 ] ) } // if ... return pieces }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes the url to the season [CODESPLIT] function scopeUrl ( options , inst ) { options = _ . extend ( { } , inst , options ) if ( ! options . season_id ) throw new Error ( 'season_id required to make division instance api calls' ) return ngin . Season . urlRoot ( ) + '/' + options . season_id + Division . urlRoot ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "main function [CODESPLIT] function process ( ast , scope ) { ast . scope = scope ; ast . names = [ ] ; ast . scopes = [ ] ; var varWalker = function ( token , scope ) { scope . declarations . push ( { type : 'var' , name : token . id . name , parent : this . top ( 1 ) , loc : token . loc . start } ) ; scope . put ( token . id . name , { type : 'var' , token : token . init , loc : token . loc . start } ) ; } ; return walker . walk ( ast , { VariableDeclarator : varWalker , FunctionDeclaration : fnWalker , FunctionExpression : fnWalker , ArrowFunctionExpression : fnWalker , ExpressionStatement : function ( token ) { if ( token . directive && token . directive . toLowerCase ( ) === 'use strict' ) scope . strict = true ; } , CatchClause : function ( token , scope ) { var newScope = new Scope ( 'catch' , scope ) ; scope . put ( token . param . name , { type : 'catch' , token : null } ) ; token . body . scope = newScope ; this . scopes . push ( scope ) ; } , Identifier : function ( token , scope ) { var parent = this . top ( 1 ) ; // let insane begin! // todo implement more efficient solution in a future version var isLabel = parent . type === 'LabeledStatement' || parent . type === 'ContinueStatement' || parent . type === 'BreakStatement' ; var isFunctionName = parent . type === 'FunctionDeclaration' || parent . type === 'FunctionExpression' || parent . type === 'ClassDeclaration' || parent . type === 'ClassExpression' ; var isProperty = parent . type === 'Property' ; var isMemberExpression = parent . type === 'MemberExpression' ; var isAssignmentExpression = parent . type === 'AssignmentExpression' ; var isVariableDeclarator = parent . type === 'VariableDeclarator' ; if ( isLabel || isFunctionName || isProperty || isMemberExpression || isAssignmentExpression || isVariableDeclarator ) { var isObjectKey = isProperty && parent . key === token && parent . computed ; var isObjectValue = isProperty && parent . value === token ; var isMemberExpressionProperty = isMemberExpression && parent . property === token && parent . computed ; var isMemberExpressionObject = isMemberExpression && parent . object === token ; var isVariableInit = isVariableDeclarator && parent . init === token ; var isLeftOfAssignment = isAssignmentExpression && parent . left === token && parent . operator !== '=' ; var isRightOfAssignment = isAssignmentExpression && parent . right === token ; // is it for..in variable? (mark its name as used) var isVarInForIn = false ; if ( isVariableDeclarator ) { var declarationParent = this . top ( 3 ) ; isVarInForIn = declarationParent && declarationParent . type === 'ForInStatement' ; } if ( isFunctionName || isLabel || ! isObjectKey && ! isObjectValue && ! isMemberExpressionProperty && ! isMemberExpressionObject && ! isLeftOfAssignment && ! isRightOfAssignment && ! isVariableInit && ! isVarInForIn ) return ; } this . names . push ( { scope : scope , token : token } ) ; } } , { names : ast . names , scopes : ast . scopes } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scope class [CODESPLIT] function Scope ( type , parentScope , thisObject ) { this . type = type || 'unknown' ; this . thisObject = thisObject || utils . createIdentifier ( 'undefined' ) ; this . subscopes = [ ] ; this . names = { } ; this . declarations = [ ] ; if ( parentScope ) { this . parent = parentScope ; this . root = parentScope . root ; this . strict = parentScope . strict ; parentScope . subscopes . push ( this ) ; } else { this . root = this ; } this . put ( 'this' , { type : 'readonly' , token : this . thisObject } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new Customer with the given parent and definition . [CODESPLIT] function Customer ( parent , definition ) { var key ; for ( key in updateMixin ) { this [ key ] = updateMixin [ key ] ; } Customer . super_ . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This does a shallow copy of objects . This is needed for objects such as Errors Otherwise some properties may not be available . [CODESPLIT] function copy ( obj ) { return Object . getOwnPropertyNames ( obj || { } ) . reduce ( ( a , c ) => { a [ c ] = obj [ c ] ; return a ; } , { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats a message using the specified options . [CODESPLIT] function formatWith ( options ) { options = Object . assign ( { } , DEFAULTS , options ) ; return ( message , ... args ) => { return _formatter ( options , message , ... args ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// * Prevents errors on console methods when no console present . * Exposes a global debug function that preserves line numbering and formatting . [CODESPLIT] function ( obj ) { var that = { } ; that . obj = obj ; var method ; var con ; if ( typeof window !== 'undefined' ) { window . console = window . console || { } ; con = window . console ; } else { con = console || { } ; } if ( ! con [ 'debug' ] ) { con . debug = con . log ; } // IE does not support debug. var length = methods . length ; while ( length -- ) { method = methods [ length ] ; // Only stub undefined methods. if ( ! con [ method ] ) { // .hasOwnProperty(method) ) { // !con[method] ) { con [ method ] = noop ; // Disable for con that [ method ] = noop ; // and for this object too } else { if ( Function . prototype . bind ) { that [ method ] = Function . prototype . bind . call ( con [ method ] , con , '%s' ) ; // '%s' does not works for group } else { that [ method ] = Function . prototype . apply . call ( con [ method ] , con , 'xyz' , arguments ) ; } } } //if(that.obj) { //  con.log('>>>>>>>>>>>>', that.obj.debugId, that.obj); // } //  if (!con.debug) { // IE does not support con.debug //    that.debug = Function.prototype.bind.call(con.log,   con, pref + ' **** debug:   %s');; //  } else { //    that.debug = Function.prototype.bind.call(con.debug, con, pref + ' **** debug: %s'); //  } /** Rewrite specific methods **/ if ( Function . prototype . bind ) { // con.log('_debug(): if (Function.prototype.bind) '); var pref = '[' + ( ( that . obj && that . obj . debugId ) ? that . obj . debugId : 'null' ) + ']' ; that . error = Function . prototype . bind . call ( con . error , con , pref + ' * error: %s' ) ; that . warn = Function . prototype . bind . call ( con . warn , con , pref + ' ** warn:  %s' ) ; that . info = Function . prototype . bind . call ( con . info , con , pref + ' *** info:  %s' ) ; if ( ! con . debug ) { // IE does not support con.debug that . debug = Function . prototype . bind . call ( con . log , con ) ; //pref + ' **** debug:   %s');; } else { that . debug = Function . prototype . bind . call ( con . debug , con ) ; //pref + ' **** debug: %s'); } that . log = Function . prototype . bind . call ( con . log , con , pref + ' ***** log:   %s' ) ; //    that.group = Function.prototype.bind.call(con.group, con, '%s'); that . group = Function . prototype . bind . call ( con . log , con , pref + ' GROUP:   %s' ) ; //    that.groupCollapsed = Function.prototype.bind.call(con.groupCollapsed, con, '%s'); that . groupCollapsed = Function . prototype . bind . call ( con . log , con , pref + ' GROUP: %s' ) ; //    if (!that.assert) { that.assert = Function.prototype.bind.call(con.error, con, '* assert: %s'); } //  } else { //    that.error = function() { Function.prototype.apply.call(con.error, con, arguments); }; //    that.warn  = function() { Function.prototype.apply.call(con.warn , con, arguments); }; //    that.info  = function() { Function.prototype.apply.call(con.info,  con, arguments); }; //    that.debug = function() { Function.prototype.apply.call(con.debug, con, arguments); }; //    that.log   = function() { Function.prototype.apply.call(con.log,   con, arguments); }; } return that ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Zips up a directory . [CODESPLIT] function ( sourceDir , destFile , opts ) { opts = opts || { archive_path : '/' } ; return new Promise ( function ( resolve , reject ) { try { var archive = archiver . create ( 'zip' , { zlib : { level : 9 } } ) ; var output = fs . createWriteStream ( destFile ) ; output . on ( 'finish' , function ( ) { resolve ( destFile ) ; } ) ; archive . pipe ( output ) ; archive . directory ( sourceDir , opts . archive_path ) ; archive . finalize ( ) ; } catch ( err ) { reject ( err ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts a zip to a directory . This will fail if the destination already exists . [CODESPLIT] function ( sourceFile , destDir ) { return new Promise ( function ( resolve , reject ) { var zip = new AdmZip ( sourceFile ) ; try { zip . extractAllTo ( destDir ) ; resolve ( destDir ) ; } catch ( err ) { reject ( err ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Bzip2 compressed tar of a directory . [CODESPLIT] function ( sourceDir , destFile , opts ) { opts = opts || { archive_path : '/' } ; return new Promise ( function ( resolve , reject ) { // pack var tempFile = destFile + '.tmp.tar' ; try { var archive = archiver . create ( 'tar' ) ; var output = fs . createWriteStream ( tempFile ) ; output . on ( 'finish' , function ( ) { resolve ( tempFile ) ; } ) ; archive . pipe ( output ) ; archive . directory ( sourceDir , opts . archive_path ) ; archive . finalize ( ) ; } catch ( err ) { reject ( err ) ; } } ) . then ( function ( tempFile ) { // compress try { var data = new Buffer ( fs . readFileSync ( tempFile ) , 'utf8' ) ; var compressed = new Buffer ( Bzip2 . compressFile ( data ) ) ; fs . writeFileSync ( destFile , compressed ) ; return destFile ; } catch ( err ) { throw err ; } finally { rimraf . sync ( tempFile ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts a tar to a directory . [CODESPLIT] function ( sourceFile , destDir ) { return new Promise ( function ( resolve , reject ) { // expand var tempFile = sourceFile + '.tmp.tar' ; try { var data = new Buffer ( fs . readFileSync ( sourceFile ) ) ; var expanded = Bzip2 . decompressFile ( data ) ; fs . writeFileSync ( tempFile , new Buffer ( expanded ) ) ; resolve ( tempFile ) ; } catch ( err ) { reject ( err ) ; } } ) . then ( function ( tempFile ) { // un-pack return new Promise ( function ( resolve , reject ) { try { var rs = fs . createReadStream ( tempFile ) ; rs . pipe ( tar . extract ( destDir ) . on ( 'finish' , function ( ) { rimraf . sync ( tempFile ) ; resolve ( destDir ) ; } ) ) ; } catch ( err ) { rimraf . sync ( tempFile ) ; reject ( err ) ; } } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为负数 [CODESPLIT] function _isNegativeNumber ( val , options ) { var opts = _isObject ( options ) ? options : { } ; if ( opts . isStrict === true ) { return _isNumber ( val ) && REGEX_ENUM . NEGATIVE_NUMBER_REX . test ( val ) ; } return REGEX_ENUM . NEGATIVE_NUMBER_REX . test ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive promise - based mkdir . [CODESPLIT] async function make ( dir ) { try { await makePromise ( mkdir , dir ) } catch ( err ) { if ( err . code == 'ENOENT' ) { const parentDir = dirname ( dir ) await make ( parentDir ) await make ( dir ) } else if ( err . code != 'EEXIST' ) { // created in parallel throw err } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expose small fabrication helper . [CODESPLIT] function fabricator ( stack , options ) { options = options || { } ; // // Empty strings, arrays or objects should not be processed, return early. // if ( empty ( stack ) ) return [ ] ; switch ( is ( stack ) ) { case 'string' : stack = read ( stack , options ) ; break ; case 'object' : stack = Object . keys ( stack ) . reduce ( iterator ( read , stack , options ) , [ ] ) ; break ; case 'array' : stack = stack . reduce ( iterator ( read , null , options ) , [ ] ) ; break ; default : if ( 'function' !== typeof stack ) { throw new Error ( 'Unsupported type, cannot fabricate an: ' + is ( stack ) ) ; } stack = [ init ( stack , undefined , options ) ] ; } return ( stack || [ ] ) . filter ( Boolean ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read directory and initialize JavaScript files . [CODESPLIT] function read ( filepath , options ) { if ( 'string' !== is ( filepath ) ) return fabricator ( filepath , options ) ; if ( options . source ) filepath = path . resolve ( options . source , filepath ) ; // // Check if the provided string is a JS file or when recursion is not allowed. // if ( js ( filepath ) || options . recursive === false ) return [ init ( filepath , path . basename ( filepath , '.js' ) , options ) ] ; // // Read the directory, only process files. // if ( ! fs . existsSync ( filepath ) ) return false ; return fs . readdirSync ( filepath ) . map ( function locate ( file ) { file = path . resolve ( filepath , file ) ; var stat = fs . statSync ( file ) ; if ( stat . isDirectory ( ) && fs . existsSync ( path . join ( file , 'index.js' ) ) ) { // // Use the directory name instead of `index` for name as it probably has // more meaning then just `index` as a name. // return init ( path . join ( file , 'index.js' ) , path . basename ( file , '.js' ) , options ) ; } // // Only allow JS files, init determines if it is a constructible instance. // if ( ! stat . isFile ( ) || ! js ( file ) ) return ; return init ( file , path . basename ( file , '.js' ) , options ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return iterator for array or object . [CODESPLIT] function iterator ( traverse , obj , options ) { return function reduce ( stack , entity ) { var base = obj ? obj [ entity ] : entity , name = options . name || entity ; // // Fabricated objects should provide each constructor with the name // of its property on the original object. // if ( obj ) options . name = entity ; // // Run the functions, traverse will handle init. // if ( js ( base ) ) { return stack . concat ( init ( base , 'string' === is ( name ) ? name : '' , options ) ) ; } // // When we've been supplied with an array as base assume we want to keep it // as array and do not want it to be merged. // if ( Array . isArray ( base ) ) { options . name = name ; // Force the name of the entry for all items in array. stack . push ( traverse ( base , options ) ) ; return stack ; } return stack . concat ( traverse ( base , options ) ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make sure only valid JavaScript files are used as source . Ignore other files like . log files . Also allow constructors . [CODESPLIT] function js ( file ) { var type = is ( file ) ; return 'function' === type || 'string' === type && path . extname ( file ) === '.js' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simple check to see if the provided stack is empty or falsy . [CODESPLIT] function empty ( value ) { if ( ! value ) return true ; switch ( is ( value ) ) { case \"object\" : return ! Object . keys ( value ) . length ; case \"array\" : return ! value . length ; default : return ! value ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It s not required to supply resolve with instances we can just automatically require them if they are using the : [CODESPLIT] function init ( constructor , name , options ) { constructor = ( 'string' === is ( constructor ) ) ? require ( constructor ) : constructor ; // // We really want to have a function/class here. Make sure that we can // construct it using `new constructor` // if ( ! constructor . prototype ) return ; name = constructor . prototype . name || name || constructor . name ; if ( options . name ) name = options . name ; // // Sets the name on the prototype to a string. // if ( 'name' in constructor . prototype ) { constructor . prototype . name = name . toString ( ) ; } return constructor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "menu link is a toggle sidebar links are close - only [CODESPLIT] function click ( e ) { var op = 'remove' ; if ( this . className === 'menuLink' ) { op = document . body . classList . contains ( 'menu-open' ) ? 'remove' : 'add' ; e . preventDefault ( ) ; } document . body . classList [ op ] ( 'menu-open' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main function for creating a shellstream [CODESPLIT] function ShellStream ( args ) { if ( this instanceof ShellStream === false ) { return new ShellStream ( args ) ; } this . _command = args ; this . _events = [ ] ; var self = this ; // Create holders for events to be added streams . forEach ( function ( stream ) { self [ stream ] = { on : this . on , _events : [ ] } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read path with options with callback ( err str ) . When options . cache is true the template string will be cached . [CODESPLIT] function read ( path , options , callback ) { var str = readCache [ path ] ; var cached = options . cache && str && ( 'string' === typeof str ) ; // cached (only if cached is a string and not a compiled template function) if ( cached ) { return callback ( null , str ) ; } // read fs . readFile ( path , 'utf8' , function ( err , str ) { if ( err ) { return callback ( err ) ; } // remove extraneous utf8 BOM marker str = str . replace ( / ^\\uFEFF / , '' ) ; if ( options . cache ) { readCache [ path ] = str ; } callback ( null , str ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A representation of an object in the profile [CODESPLIT] function ( name , specs ) { this . name = name ; this . id = 0 ; this . properties = specs . properties || [ ] ; this . extends = specs . extends || null ; this . depends = specs . depends || null ; this . factory = specs . factory || \"new\" ; this . init = specs . init || \"default\" ; this . frequent = false ; this . keepUsedProperties = false ; this . initProperties = true ; this . initConstructorArgs = [ ] ; this . propCustomAssign = { } ; this . propAssign = \"\" ; this . propCustomGet = { } ; this . propGet = \"\" ; this . postInit = specs . postInit || \"\" ; this . embed = specs . embed || [ ] ; if ( this . postInit ) this . postInit += \"\\n\" ; // Calculate a safe name this . safeName = name . replace ( / [,\\.\\- \\_] / g , '_' ) ; // Change init to 'constructor' if init is array if ( this . init instanceof Array ) { this . initConstructorArgs = this . init ; this . init = \"constructor\" ; this . factory = \"create\" } else if ( this . init instanceof { } . constructor ) { this . propCustomAssign = this . init ; this . init = \"default\" ; // Extract default if ( this . propCustomAssign [ 'default' ] ) { this . propAssign = this . propCustomAssign [ 'default' ] ; delete this . propCustomAssign [ 'default' ] ; } } else if ( this . init !== \"default\" ) { // Custom user init function if ( this . factory === \"new\" ) this . factory = \"create\" ; } // Check if we have custom property getters if ( specs . getter ) { if ( typeof specs == 'object' ) { this . propCustomGet = specs . getter ; // Extract default if ( this . propCustomGet [ 'default' ] ) { this . propGet = this . propCustomGet [ 'default' ] ; delete this . propCustomGet [ 'default' ] ; } } else { this . propGet = specs . getter ; } } // Initialize boolean fields if ( specs . frequent !== undefined ) { this . frequent = ( [ \"yes\" , \"true\" , \"1\" ] . indexOf ( specs . frequent . toString ( ) . toLowerCase ( ) ) >= 0 ) ; } if ( specs . initProperties !== undefined ) { this . initProperties = ( [ \"yes\" , \"true\" , \"1\" ] . indexOf ( specs . initProperties . toString ( ) . toLowerCase ( ) ) >= 0 ) ; } if ( specs . keepUsedProperties !== undefined ) { this . keepUsedProperties = ( [ \"yes\" , \"true\" , \"1\" ] . indexOf ( specs . keepUsedProperties . toString ( ) . toLowerCase ( ) ) >= 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extend our properties based on specified object [CODESPLIT] function ( o ) { // Don't extend 'depends', extend only 'extends' if ( this . extends ) { this . embed = o . embed . concat ( this . embed ) ; this . properties = o . properties . concat ( this . properties ) ; this . postInit = o . postInit + this . postInit ; // Replace init & Factory if different if ( this . init === \"default\" ) this . init = o . init ; if ( this . factory === \"new\" ) this . factory = o . factory ; // Replace default property assigned if not defined if ( ! this . propAssign ) this . propAssign = o . propAssign ; // Implement undefined extended property assigners for ( var k in o . propCustomAssign ) { if ( ! this . propCustomAssign [ k ] ) { this . propCustomAssign [ k ] = o . propCustomAssign [ k ] ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the property getter [CODESPLIT] function ( instVar , prefix ) { var code = \"[\" , getCode = \"\" , prop = \"\" , defaultGet = \"$inst.$prop\" ; if ( this . defaultGet ) defaultGet = defaultGet ; for ( var i = 0 , l = this . properties . length ; i < l ; ++ i ) { prop = this . properties [ i ] ; if ( i > 0 ) code += \",\" ; if ( this . propCustomGet [ prop ] ) { getCode = this . propCustomGet [ prop ] . replace ( / \\$inst / g , instVar ) . replace ( / \\$prop / g , prop ) ; } else { getCode = defaultGet . replace ( / \\$inst / g , instVar ) . replace ( / \\$prop / g , prop ) ; } // Check if we should embed this property if ( this . embed . indexOf ( prop ) === - 1 ) { code += \"\\n\" + prefix + getCode ; } else { code += \"\\n\" + prefix + \"new BinaryEncoder.FileResource( \" + getCode + \" )\" ; } } code += \"]\" ; return code ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the name of the property initialization function . This is used to de - duplicate init functions for the same properties [CODESPLIT] function ( ) { var props = this . properties . slice ( ) . sort ( ) ; return 'init' + crypto . createHash ( 'md5' ) . update ( props . join ( \",\" ) ) . digest ( \"hex\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the piece of code that initializes an instance of the object [CODESPLIT] function ( instVar , valVar , pageszVar , offsetVar , prefix , indent ) { var code = \"\" , usedProps = { } , defaultAssign = \"$inst.$prop = $value\" , replaceVariableMacro = ( function ( s , v ) { var i = this . properties . indexOf ( v ) ; if ( i >= 0 ) { usedProps [ v ] = true ; } else { throw \"Macro \" + s + \" refers to a property not part of property table!\" ; } } ) . bind ( this ) ; // // [default] - Default empty constructor // if ( this . init == \"default\" ) { // // [constructor] - Call constructor // } else if ( this . init == 'constructor' ) { code += prefix + this . name + \".call(\" + instVar ; for ( var i = 0 , l = this . initConstructorArgs . length ; i < l ; i ++ ) { var arg = this . initConstructorArgs [ i ] , partIdx = arg . search ( / [\\.\\[] / ) , part = \"\" , found = false ; // Try to translate constructor arguments to components of the value // array when possivle if ( partIdx == - 1 ) partIdx = arg . length ; part = arg . substr ( 0 , partIdx ) ; for ( var j = 0 , jl = this . properties . length ; j < jl ; ++ j ) { if ( this . properties [ j ] == part ) { arg = valVar + \"[\" + offsetVar + '+' + pageszVar + '*' + j + \"]\" + arg . substr ( partIdx ) ; usedProps [ part ] = true ; found = true ; break ; } } // Warn user if not found if ( ! found ) { console . warn ( \"Could not find property '\" + arg + \"' in \" + this . name + \". Assuming literal\" ) ; } // Update constructor call code += \",\\n\" + prefix + indent + arg ; } code += \");\\n\" ; // // [other] - Custom user function // } else { console . warn ( \"Using custom init function for \" + this . name ) ; code += prefix + this . init + \"(\" + instVar + \", \" + valVar + \");\\n\" ; } // Replace variable macros in the property assigners & track handled properties for ( var k in this . propCustomAssign ) { this . propCustomAssign [ k ] = this . propCustomAssign [ k ] . replace ( / \\$\\$(\\w+) / g , replaceVariableMacro ) ; } // Get default assign function if ( this . propAssign ) defaultAssign = this . propAssign ; defaultAssign = defaultAssign . replace ( / \\$\\$(\\w+) / g , replaceVariableMacro ) ; // Call property initializer (might be shared with other instances) if ( this . initProperties ) { for ( var i = 0 , l = this . properties . length ; i < l ; ++ i ) { var prop = this . properties [ i ] ; // Skip properties used in the constructor if ( usedProps [ prop ] && ! this . keepUsedProperties ) continue ; if ( this . propCustomAssign [ prop ] ) { code += prefix + this . propCustomAssign [ prop ] . replace ( / \\$inst / g , instVar ) . replace ( / \\$prop / g , prop ) . replace ( / \\$values / g , valVar ) . replace ( / \\$value / g , valVar + \"[\" + offsetVar + '+' + pageszVar + '*' + i + \"]\" ) + \";\\n\" ; } else { code += prefix + defaultAssign . replace ( / \\$inst / g , instVar ) . replace ( / \\$prop / g , prop ) . replace ( / \\$values / g , valVar ) . replace ( / \\$value / g , valVar + \"[\" + offsetVar + '+' + pageszVar + '*' + i + \"]\" ) + \";\\n\" ; } } } // Call post-init if ( this . postInit ) { code += \"\\n\" + prefix + \"// Custom init function\\n\" ; code += prefix + this . postInit . replace ( / \\n / g , \"\\n\" + prefix ) . replace ( / \\$inst / g , instVar ) . replace ( / \\$values / g , valVar ) . replace ( / \\$\\$(\\w+) / g , replaceVariableMacro ) ; } return code ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read entire buffer and compile [CODESPLIT] function bufferMode ( contents , options , callback ) { ProfileCompiler ( contents . toString ( 'utf-8' ) , options , function ( err , encBuf , decBuf ) { if ( err ) { callback ( err ) ; return ; } // Callback buffers callback ( null , new Buffer ( encBuf , 'utf8' ) , new Buffer ( decBuf , 'utf8' ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read entire stream and process [CODESPLIT] function streamMode ( contents , options , callback ) { toArray ( contents , function ( err , chunks ) { if ( err ) { callback ( err ) ; return ; } bufferMode ( Buffer . concat ( chunks ) , options , function ( err , encBuf , decBuf ) { if ( err ) { callback ( err ) ; return ; } var encStream = new Readable ( ) ; encStream . push ( encBuf ) ; encStream . push ( null ) ; var decStream = new Readable ( ) ; decStream . push ( decBuf ) ; decStream . push ( null ) ; // Callback streams callback ( null , encStream , decStream ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call when finished with compression [CODESPLIT] function ( err , encContents , decContents ) { // Emmit errors if ( err ) { var error = new PluginError ( PLUGIN_NAME , err , { showStack : true } ) ; self . emit ( 'error' , error ) ; done ( ) ; return ; } // Get base name var dir = path . dirname ( originalFile . path ) ; var name = path . basename ( originalFile . path ) ; var parts = name . split ( \".\" ) ; parts . pop ( ) ; var baseName = self . config . name || parts . join ( \".\" ) ; // The encode file var f = originalFile . clone ( ) ; f . contents = encContents ; f . path = path . join ( dir , baseName + '-encode.js' ) ; self . push ( f ) ; // The decode file var f = originalFile . clone ( ) ; f . contents = decContents ; f . path = path . join ( dir , baseName + '-decode.js' ) ; self . push ( f ) ; // We are done done ( ) ; return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "journal . js [CODESPLIT] function journal ( ) { 'use strict' ; var fs = require ( 'fs' ) ; // private properties var eventList = { 'creationEvents' : { } , 'executionEvents' : { } } ; var logMode ; // sets the log method: 'q', 'v' or 'l' // exposed by the agency constructor function setLogMode ( mode ) { logMode = mode ; } // records the agent's validation and creation events in a temporary structure if log method is 'l' or  // outputs the same events to the console if method is 'v'  function logCreationEvent ( id , type , message , time ) { if ( logMode === 'l' ) { if ( ! eventList . creationEvents [ id ] ) { eventList . creationEvents [ id ] = [ ] ; } eventList . creationEvents [ id ] . push ( { 'type' : type , 'event' : message , \"timestamp\" : time } ) ; } else if ( logMode === 'v' ) { console . log ( type + ': Agent ' + id + ' ' + message + ' on ' + time ) ; } } // records the agent's execution events in a temporary structure if log method is 'l' or  // outputs the same events to the console if method is 'v'  function logExecutionEvent ( id , type , message , time ) { if ( logMode === 'l' ) { if ( ! eventList . executionEvents [ id ] ) { eventList . executionEvents [ id ] = [ ] ; } eventList . executionEvents [ id ] . push ( { 'type' : type , 'event' : message , \"timestamp\" : time } ) ; } else if ( logMode === 'v' ) { console . log ( type + ': Agent ' + id + ' ' + message + ' on ' + time ) ; } } // outputs the contents of the temporary creation and execution structure to a specific file // defined by the user; if file is not defined outputs to a default file; otherwise outputs error to the console function report ( logFile ) { var defaultLogFile = ( new Date ( ) ) . toJSON ( ) + '.log' ; var data = JSON . stringify ( eventList , null , 3 ) ; if ( logFile ) { fs . writeFile ( logFile , data , function ( err ) { if ( err ) { console . log ( '\\nCould not write log to file \"' + logFile + '\"\\n' + err ) ; fs . writeFile ( defaultLogFile , data , function ( err ) { if ( err ) { console . log ( 'Could not write log file: ' + err ) ; } else { console . log ( 'Log was written on default file \"' + defaultLogFile + '\"' ) ; } } ) ; } } ) ; } else { fs . writeFile ( defaultLogFile , data , function ( err ) { if ( err ) { console . log ( 'Could not write log file: ' + err ) ; } } ) ; } } //public interface return { setLogMode : setLogMode , logCreationEvent : logCreationEvent , logExecutionEvent : logExecutionEvent , report : report } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "records the agent s validation and creation events in a temporary structure if log method is l or outputs the same events to the console if method is v [CODESPLIT] function logCreationEvent ( id , type , message , time ) { if ( logMode === 'l' ) { if ( ! eventList . creationEvents [ id ] ) { eventList . creationEvents [ id ] = [ ] ; } eventList . creationEvents [ id ] . push ( { 'type' : type , 'event' : message , \"timestamp\" : time } ) ; } else if ( logMode === 'v' ) { console . log ( type + ': Agent ' + id + ' ' + message + ' on ' + time ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "records the agent s execution events in a temporary structure if log method is l or outputs the same events to the console if method is v [CODESPLIT] function logExecutionEvent ( id , type , message , time ) { if ( logMode === 'l' ) { if ( ! eventList . executionEvents [ id ] ) { eventList . executionEvents [ id ] = [ ] ; } eventList . executionEvents [ id ] . push ( { 'type' : type , 'event' : message , \"timestamp\" : time } ) ; } else if ( logMode === 'v' ) { console . log ( type + ': Agent ' + id + ' ' + message + ' on ' + time ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "outputs the contents of the temporary creation and execution structure to a specific file defined by the user ; if file is not defined outputs to a default file ; otherwise outputs error to the console [CODESPLIT] function report ( logFile ) { var defaultLogFile = ( new Date ( ) ) . toJSON ( ) + '.log' ; var data = JSON . stringify ( eventList , null , 3 ) ; if ( logFile ) { fs . writeFile ( logFile , data , function ( err ) { if ( err ) { console . log ( '\\nCould not write log to file \"' + logFile + '\"\\n' + err ) ; fs . writeFile ( defaultLogFile , data , function ( err ) { if ( err ) { console . log ( 'Could not write log file: ' + err ) ; } else { console . log ( 'Log was written on default file \"' + defaultLogFile + '\"' ) ; } } ) ; } } ) ; } else { fs . writeFile ( defaultLogFile , data , function ( err ) { if ( err ) { console . log ( 'Could not write log file: ' + err ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes the url to the team and member [CODESPLIT] function scopeUrl ( options , inst ) { options = _ . extend ( { } , inst , options ) if ( ! options . teamcenter_team_id ) throw new Error ( 'teamcenter_team_id required to make TeamCenterContact instance api calls' ) if ( ! options . teamcenter_member_id ) throw new Error ( 'teamcenter_member_id require to make TeamCenterContact instance api calls' ) return ngin . TeamCenterTeam . urlRoot ( ) + '/' + options . teamcenter_team_id + ngin . TeamCenterMember . urlRoot ( ) + '/' + options . teamcenter_member_id + TeamCenterContact . urlRoot ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DevToolsApp --------------------------------------------------------------- [CODESPLIT] function installObjectObserve ( ) { var properties = [ \"advancedSearchConfig\" , \"auditsPanelSplitViewState\" , \"auditsSidebarWidth\" , \"blockedURLs\" , \"breakpoints\" , \"cacheDisabled\" , \"colorFormat\" , \"consoleHistory\" , \"consoleTimestampsEnabled\" , \"cpuProfilerView\" , \"cssSourceMapsEnabled\" , \"currentDockState\" , \"customColorPalette\" , \"customDevicePresets\" , \"customEmulatedDeviceList\" , \"customFormatters\" , \"customUserAgent\" , \"databaseTableViewVisibleColumns\" , \"dataGrid-cookiesTable\" , \"dataGrid-DOMStorageItemsView\" , \"debuggerSidebarHidden\" , \"disableDataSaverInfobar\" , \"disablePausedStateOverlay\" , \"domBreakpoints\" , \"domWordWrap\" , \"elementsPanelSplitViewState\" , \"elementsSidebarWidth\" , \"emulation.deviceHeight\" , \"emulation.deviceModeValue\" , \"emulation.deviceOrientationOverride\" , \"emulation.deviceScale\" , \"emulation.deviceScaleFactor\" , \"emulation.deviceUA\" , \"emulation.deviceWidth\" , \"emulation.geolocationOverride\" , \"emulation.showDeviceMode\" , \"emulation.showRulers\" , \"enableAsyncStackTraces\" , \"eventListenerBreakpoints\" , \"fileMappingEntries\" , \"fileSystemMapping\" , \"FileSystemViewSidebarWidth\" , \"fileSystemViewSplitViewState\" , \"filterBar-consoleView\" , \"filterBar-networkPanel\" , \"filterBar-promisePane\" , \"filterBar-timelinePanel\" , \"frameViewerHideChromeWindow\" , \"heapSnapshotRetainersViewSize\" , \"heapSnapshotSplitViewState\" , \"hideCollectedPromises\" , \"hideNetworkMessages\" , \"highlightNodeOnHoverInOverlay\" , \"highResolutionCpuProfiling\" , \"inlineVariableValues\" , \"Inspector.drawerSplitView\" , \"Inspector.drawerSplitViewState\" , \"InspectorView.panelOrder\" , \"InspectorView.screencastSplitView\" , \"InspectorView.screencastSplitViewState\" , \"InspectorView.splitView\" , \"InspectorView.splitViewState\" , \"javaScriptDisabled\" , \"jsSourceMapsEnabled\" , \"lastActivePanel\" , \"lastDockState\" , \"lastSelectedSourcesSidebarPaneTab\" , \"lastSnippetEvaluationIndex\" , \"layerDetailsSplitView\" , \"layerDetailsSplitViewState\" , \"layersPanelSplitViewState\" , \"layersShowInternalLayers\" , \"layersSidebarWidth\" , \"messageLevelFilters\" , \"messageURLFilters\" , \"monitoringXHREnabled\" , \"navigatorGroupByFolder\" , \"navigatorHidden\" , \"networkColorCodeResourceTypes\" , \"networkConditions\" , \"networkConditionsCustomProfiles\" , \"networkHideDataURL\" , \"networkLogColumnsVisibility\" , \"networkLogLargeRows\" , \"networkLogShowOverview\" , \"networkPanelSplitViewState\" , \"networkRecordFilmStripSetting\" , \"networkResourceTypeFilters\" , \"networkShowPrimaryLoadWaterfall\" , \"networkSidebarWidth\" , \"openLinkHandler\" , \"pauseOnCaughtException\" , \"pauseOnExceptionEnabled\" , \"preserveConsoleLog\" , \"prettyPrintInfobarDisabled\" , \"previouslyViewedFiles\" , \"profilesPanelSplitViewState\" , \"profilesSidebarWidth\" , \"promiseStatusFilters\" , \"recordAllocationStacks\" , \"requestHeaderFilterSetting\" , \"request-info-formData-category-expanded\" , \"request-info-general-category-expanded\" , \"request-info-queryString-category-expanded\" , \"request-info-requestHeaders-category-expanded\" , \"request-info-requestPayload-category-expanded\" , \"request-info-responseHeaders-category-expanded\" , \"resources\" , \"resourcesLastSelectedItem\" , \"resourcesPanelSplitViewState\" , \"resourcesSidebarWidth\" , \"resourceViewTab\" , \"savedURLs\" , \"screencastEnabled\" , \"scriptsPanelNavigatorSidebarWidth\" , \"searchInContentScripts\" , \"selectedAuditCategories\" , \"selectedColorPalette\" , \"selectedProfileType\" , \"shortcutPanelSwitch\" , \"showAdvancedHeapSnapshotProperties\" , \"showEventListenersForAncestors\" , \"showFrameowkrListeners\" , \"showHeaSnapshotObjectsHiddenProperties\" , \"showInheritedComputedStyleProperties\" , \"showMediaQueryInspector\" , \"showNativeFunctionsInJSProfile\" , \"showUAShadowDOM\" , \"showWhitespacesInEditor\" , \"sidebarPosition\" , \"skipContentScripts\" , \"skipStackFramesPattern\" , \"sourceMapInfobarDisabled\" , \"sourcesPanelDebuggerSidebarSplitViewState\" , \"sourcesPanelNavigatorSplitViewState\" , \"sourcesPanelSplitSidebarRatio\" , \"sourcesPanelSplitViewState\" , \"sourcesSidebarWidth\" , \"standardEmulatedDeviceList\" , \"StylesPaneSplitRatio\" , \"stylesPaneSplitViewState\" , \"textEditorAutocompletion\" , \"textEditorAutoDetectIndent\" , \"textEditorBracketMatching\" , \"textEditorIndent\" , \"timelineCaptureFilmStrip\" , \"timelineCaptureLayersAndPictures\" , \"timelineCaptureMemory\" , \"timelineCaptureNetwork\" , \"timeline-details\" , \"timelineEnableJSSampling\" , \"timelineOverviewMode\" , \"timelinePanelDetailsSplitViewState\" , \"timelinePanelRecorsSplitViewState\" , \"timelinePanelTimelineStackSplitViewState\" , \"timelinePerspective\" , \"timeline-split\" , \"timelineTreeGroupBy\" , \"timeline-view\" , \"timelineViewMode\" , \"uiTheme\" , \"watchExpressions\" , \"WebInspector.Drawer.lastSelectedView\" , \"WebInspector.Drawer.showOnLoad\" , \"workspaceExcludedFolders\" , \"workspaceFolderExcludePattern\" , \"workspaceInfobarDisabled\" , \"workspaceMappingInfobarDisabled\" , \"xhrBreakpoints\" ] ; /**\n     * @this {!{_storage: Object, _name: string}}\n     */ function settingRemove ( ) { this . _storage [ this . _name ] = undefined ; } function objectObserve ( object , observer ) { if ( window [ \"WebInspector\" ] ) { var settingPrototype = window [ \"WebInspector\" ] [ \"Setting\" ] [ \"prototype\" ] ; if ( typeof settingPrototype [ \"remove\" ] === \"function\" ) settingPrototype [ \"remove\" ] = settingRemove ; } var changedProperties = new Set ( ) ; var scheduled = false ; function scheduleObserver ( ) { if ( ! scheduled ) { scheduled = true ; setImmediate ( callObserver ) ; } } function callObserver ( ) { scheduled = false ; var changes = [ ] ; changedProperties . forEach ( function ( name ) { changes . push ( { name : name } ) ; } ) ; changedProperties . clear ( ) ; observer . call ( null , changes ) ; } var storage = new Map ( ) ; function defineProperty ( property ) { if ( property in object ) { storage . set ( property , object [ property ] ) ; delete object [ property ] ; } Object . defineProperty ( object , property , { get : function ( ) { return storage . get ( property ) ; } , set : function ( value ) { storage . set ( property , value ) ; changedProperties . add ( property ) ; scheduleObserver ( ) ; } } ) ; } for ( var i = 0 ; i < properties . length ; ++ i ) defineProperty ( properties [ i ] ) ; } window . Object . observe = objectObserve ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new ArticleTranslation with the given parent and definition . [CODESPLIT] function ArticleTranslation ( parent , definition ) { var key ; for ( key in updateMixin ) { this [ key ] = updateMixin [ key ] ; } ArticleTranslation . super_ . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "=== Define the Main Function ================================================= A function for converting lists into human - friendly joined stings e . g . [ A B C ] into A B & C . [CODESPLIT] function ( list , options ) { // short-circuit non-arrays if ( ! Array . isArray ( list ) || Object . prototype . toString . call ( list ) === '[object Arguments]' ) { return String ( list ) ; } // short-circuit empty lists if ( list . length === 0 ) { return '' ; } // make sure we have a sane options object if ( typeof options === 'string' ) { var newOptions = { } ; newOptions [ options ] = true ; options = newOptions ; } if ( typeof options !== 'object' ) { options = { } ; } // set up configuration var def = humanJoin . optionDefaults ; // a local reference to make the code more readable var separator = typeof def . separator === 'string' || typeof def . separator === 'number' ? def . separator : ', ' ; if ( typeof options . separator === 'string' || typeof options . separator === 'number' ) { separator = options . separator ; } separator = '' + separator ; // force to string var conjunction = typeof def . conjunction === 'string' || typeof def . conjunction === 'number' || typeof def . conjunction === 'boolean' ? def . conjunction : ' & ' ; if ( typeof options . conjunction === 'string' || typeof options . conjunction === 'number' || typeof options . conjunction === 'boolean' ) { conjunction = options . conjunction ; } if ( typeof conjunction === 'number' ) { conjunction = '' + conjunction ; // force to string } if ( options . noConjunction ) { conjunction = false ; } var quoteWith = typeof def . quoteWith === 'string' || typeof def . quoteWith === 'number' || typeof def . quoteWith === 'boolean' ? def . quoteWith : false ; if ( typeof options . quoteWith === 'string' || typeof options . quoteWith === 'number' || typeof options . quoteWith === 'boolean' ) { quoteWith = options . quoteWith ; } if ( typeof quoteWith === 'number' ) { quoteWith = '' + quoteWith ; // force to string } var mirrorQuote = typeof def . mirrorQuote === 'boolean' ? def . mirrorQuote : true ; if ( typeof options . mirrorQuote !== 'undefined' ) { mirrorQuote = options . mirrorQuote ? true : false ; } // apply any shortcuts specified if ( options . and ) { conjunction = ' and ' ; } if ( options . or ) { conjunction = ' or ' ; } if ( options . oxford || options . oxfordAnd ) { conjunction = ', and ' ; } if ( options . oxfordOr ) { conjunction = ', or ' ; } // process the array to quote and stringify as needed var stringList = [ ] ; for ( var i = 0 ; i < list . length ; i ++ ) { // for loop rather than forEach to support Arguments objects // force to string stringList [ i ] = '' + list [ i ] ; // quote if needed if ( quoteWith ) { if ( mirrorQuote ) { stringList [ i ] = quoteWith + stringList [ i ] + humanJoin . mirrorString ( quoteWith ) ; } else { stringList [ i ] = quoteWith + stringList [ i ] + quoteWith ; } } } // generate the human-friendly string var ans = stringList . shift ( ) ; while ( stringList . length ) { if ( stringList . length === 1 && conjunction !== false ) { ans += conjunction ; } else { ans += separator ; } ans += stringList . shift ( ) ; } // return the generated string return ans ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Blatantly stolen from the fantastic node - obfuscator project by Stephen Mathieson https : // github . com / stephenmathieson / node - obfuscator / blob / master / lib / require . js based on TJ Holowaychuk s commonjs require binding [CODESPLIT] function require ( p , root ) { // third-party module?  use native require if ( '.' != p [ 0 ] && '/' != p [ 0 ] ) { return native_require ( p ) ; } root = root || 'root' ; var path = require . resolve ( p ) ; // if it's a non-registered json file, it // must be at the root of the project if ( ! path && / \\.json$ / i . test ( p ) ) { return native_require ( './' + require . basename ( p ) ) ; } var module = require . cache [ path ] ; if ( ! module ) { try { return native_require ( p ) ; } catch ( err ) { throw new Error ( 'failed to require \"' + p + '\" from ' + root + '\\n' + err . message + '\\n' + err . stack ) ; } } if ( ! module . exports ) { module . exports = { } ; module . call ( module . exports , module , module . exports , require . relative ( path ) ) ; } return module . exports ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new MacroAction with the given parent and definition . [CODESPLIT] function MacroAction ( parent , definition ) { var key ; for ( key in updateMixin ) { this [ key ] = updateMixin [ key ] ; } MacroAction . super_ . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts one JSON object to another using maps specified with from - > to array [CODESPLIT] function map ( obj , source , target , isRecursive = true ) { // Check if parameters have invalid types if ( ( typeof obj ) != \"object\" ) throw new TypeError ( \"The object should be JSON\" ) ; if ( ( typeof source ) != \"string\" && ( typeof source ) != \"array\" ) throw new TypeError ( \"Source should be aither string or array\" ) ; if ( ( typeof target ) != \"string\" && ( typeof target ) != \"array\" ) throw new TypeError ( \"Target should be aither string or array\" ) ; // result object init let res = { } ; // get array of properties need to be converted let propS = ( typeof source == \"string\" ) ? source . replace ( /   / g , '' ) . split ( \",\" ) : source ; let propT = ( typeof target == \"string\" ) ? target . replace ( /   / g , '' ) . split ( \",\" ) : target ; // each property is checked ... for ( let propertyName in obj ) { // ... if need be converted or not let propIndexInSource = propS . indexOf ( propertyName ) ; let newName = ( propIndexInSource != - 1 ) ? propT [ propIndexInSource ] : propertyName ; // take into account that property could be an array if ( isRecursive && obj [ propertyName ] instanceof Array ) { res [ newName ] = [ ] ; for ( var i = 0 ; i < obj [ propertyName ] . length ; i ++ ) { let mappedItem = map ( obj [ propertyName ] [ i ] , source , target , isRecursive ) res [ newName ] . push ( mappedItem ) ; } continue ; } // take into account that JSON object can have nested objects if ( isRecursive && ( ( typeof obj [ propertyName ] ) == \"object\" ) ) res [ newName ] = map ( obj [ propertyName ] , source , target , isRecursive ) ; else res [ newName ] = obj [ propertyName ] ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a function as a promise for every item in a list . [CODESPLIT] function ( visit , onFail , opts ) { var fail = onFail ? onFail : utils . ret ( false ) , config = opts || { compact : true } ; return function ( list ) { var p = Promise . resolve ( false ) , results = [ ] ; list . forEach ( function ( l , i ) { p = p . then ( visit . bind ( null , l ) ) . catch ( function ( err ) { return fail ( err , l ) ; } ) . then ( function ( result ) { results . push ( result ) ; if ( config . onProgress ) config . onProgress ( list . length , i + 1 , l ) ; } ) ; } ) ; return p . then ( function ( ) { return config . compact ? results . filter ( Boolean ) : results ; } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turns a standard callback method into a promise - style method . Assumes standard node . js style : someFunction ( arg1 arg2 function ( err data ) { ... } ) [CODESPLIT] function ( module , fn ) { var hasModule = typeof module !== 'function' , f = hasModule ? module [ fn ] : module , mod = hasModule ? module : null ; return function ( ) { var args = [ ] , i = arguments . length - 1 ; /**\n             *  Don't pass an arguments list that has undefined values at the end.\n             *      This is so the callback for function gets passed in the right slot.\n             *\n             *      If the function gets passed:\n             *          f(arg1, arg2, undefined, cb)\n             *\n             *      ...it will think it got an undefined cb.\n             *\n             *      We instead want it to get passed:\n             *          f(arg1, arg2, cb)\n             *\n             *      Before:    [arg1, null, undefined, arg2, undefined, undefined]\n             *      After:     [arg1, null, undefined, arg2]\n             */ while ( i >= 0 && typeof arguments [ i ] === 'undefined' ) { -- i ; } while ( i >= 0 ) { args . unshift ( arguments [ i ] ) ; -- i ; } return new Promise ( function ( resolve , reject ) { try { resolve ( f . apply ( mod , args ) ) ; } catch ( err ) { reject ( err ) ; } } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls promisify on all valid functions on a module . Ignores certain properties on a modules so the return values is not polluted . ( This can be configured by passing in a filter function via opts . isValid . ) [CODESPLIT] function ( module , opts ) { var config = opts || { } , isValid = config . isValid || function ( f , fn , mod ) { /**\n                     * Filter out functions that aren't 'public' and aren't 'methods' and aren't asynchronous.\n                     *  This is mostly educated guess work based on de facto naming standards for js.\n                     *\n                     * e.g.\n                     *      valid:        'someFunctionName' or 'some_function_name' or 'someFunctionAsync'\n                     *      not valid:    'SomeConstructor' or '_someFunctionName' or 'someFunctionSync'\n                     *\n                     *  As there may be exceptions to these rules for certain modules,\n                     *   you can pass in a function via opts.isValid which will override this.\n                     */ return typeof f === 'function' && fn [ 0 ] !== '_' && fn [ 0 ] . toUpperCase ( ) !== fn [ 0 ] && ! fn . endsWith ( 'Sync' ) ; } ; return utils . mapObject ( module , function ( f , fn , mod ) { return utils . promisify ( mod , fn ) ; } , isValid ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attaches resource data to a given object . The resource data is usually used to store metadata ( e . g . a content type ) for an object . [CODESPLIT] function resource ( object , data ) { if ( data === undefined ) return resourceMap . get ( object ) || { } ; if ( ! object || typeof object !== \"object\" && typeof object !== \"function\" || resourceMap . has ( object ) ) throw new TypeError ( \"Could not transform given object into a resource.\" ) ; if ( ! data || typeof data !== \"object\" ) throw new TypeError ( \"Resource data has to be an object.\" ) ; resourceMap . set ( object , data ) ; return object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes the url to the tournament or flight [CODESPLIT] function scopeUrl ( options , inst ) { options = _ . extend ( _ . clone ( options || { } ) , inst ) if ( typeof options !== 'object' && ! options . flight_id ) throw new Error ( 'flight_id required to make flight defaults api calls' ) return ngin . Flight . urlRoot ( ) + '/' + options . flight_id + FlightStage . urlRoot ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Old snake_case method [CODESPLIT] function ( ) { console . warn ( 'Code is using deprecated teams_advancing, switch to teamsAdvancing' ) var where = ( new Error ( ) . stack || '' ) . split ( '\\n' , 3 ) [ 2 ] if ( where ) console . warn ( where ) this . teamsAdvancing . apply ( this , arguments ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "According to tests this error - checking does not slow down execution . It s not necessary to worry about repetitive error - checking slowing down execution when this function is called inside a loop . [CODESPLIT] function getIndexOfPrimitive ( primitive , array , startingPosition ) { if ( startingPosition === void 0 ) { startingPosition = 0 ; } errorIfNotPrimitive_1 . errorIfNotPrimitive ( primitive ) ; error_if_not_populated_array_1 . errorIfNotPopulatedArray ( array ) ; errorIfNotInteger_1 . errorIfNotInteger ( startingPosition ) ; return array . indexOf ( primitive , startingPosition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attach various of event listeners to a given XHR request . [CODESPLIT] function loads ( xhr , ee ) { var onreadystatechange , onprogress , ontimeout , onabort , onerror , onload , timer ; /**\n   * Error listener.\n   *\n   * @param {Event} evt Triggered error event.\n   * @api private\n   */ onerror = xhr . onerror = one ( function onerror ( evt ) { var status = statuscode ( xhr ) , err = fail ( new Error ( 'Network request failed' ) , status ) ; ee . emit ( 'error' , err ) ; ee . emit ( 'end' , err , status ) ; } ) ; /**\n   * Fix for FireFox's odd abort handling behaviour. When you press ESC on an\n   * active request it triggers `error` instead of abort. The same is called\n   * when an HTTP request is canceled onunload.\n   *\n   * @see https://bugzilla.mozilla.org/show_bug.cgi?id=768596\n   * @see https://bugzilla.mozilla.org/show_bug.cgi?id=880200\n   * @see https://code.google.com/p/chromium/issues/detail?id=153570\n   * @param {Event} evt Triggerd abort event\n   * @api private\n   */ onabort = xhr . onabort = function onabort ( evt ) { onerror ( evt ) ; } ; /**\n   * ReadyStateChange listener.\n   *\n   * @param {Event} evt Triggered readyState change event.\n   * @api private\n   */ onreadystatechange = xhr . onreadystatechange = function change ( evt ) { var target = evt . target ; if ( 4 === target . readyState ) return onload ( evt ) ; } ; /**\n   * The connection has timed out.\n   *\n   * @api private\n   */ ontimeout = xhr . ontimeout = one ( function timeout ( evt ) { ee . emit ( 'timeout' , evt ) ; // // Make sure that the request is aborted when there is a timeout. If this // doesn't trigger an error, the next call will. // if ( xhr . abort ) xhr . abort ( ) ; onerror ( evt ) ; } ) ; // // Fallback for implementations that did not ship with timer support yet. // Microsoft's XDomainRequest was one of the first to ship with `.timeout` // support so we all XHR implementations before that require a polyfill. // // @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816 // if ( xhr . timeout ) timer = setTimeout ( ontimeout , + xhr . timeout ) ; /**\n   * IE needs have it's `onprogress` function assigned to a unique function. So,\n   * no touchy touchy here!\n   *\n   * @param {Event} evt Triggered progress event.\n   * @api private\n   */ onprogress = xhr . onprogress = function progress ( evt ) { var status = statuscode ( xhr ) , data ; ee . emit ( 'progress' , evt , status ) ; if ( xhr . readyState >= 3 && status . code === 200 && ( data = response ( xhr ) ) ) { ee . emit ( 'stream' , data , status ) ; } } ; /**\n   * Handle load events an potential data events for when there was no streaming\n   * data.\n   *\n   * @param {Event} evt Triggered load event.\n   * @api private\n   */ onload = xhr . onload = one ( function load ( evt ) { var status = statuscode ( xhr ) , data = response ( xhr ) ; if ( status . code < 100 || status . code > 599 ) return onerror ( evt ) ; // // There is a bug in FireFox's XHR2 implementation where status code 204 // triggers a \"no element found\" error and bad data. So to be save here, // we're just **never** going to emit a `stream` event as for 204's there // shouldn't be any content. // // @see https://bugzilla.mozilla.org/show_bug.cgi?id=521301 // if ( data && status . code !== 204 ) { ee . emit ( 'stream' , data , status ) ; } ee . emit ( 'end' , undefined , status ) ; } ) ; // // Properly clean up the previously assigned event listeners and timers to // prevent potential data leaks and unwanted `stream` events. // ee . once ( 'end' , function cleanup ( ) { xhr . onreadystatechange = onreadystatechange = xhr . onprogress = onprogress = xhr . ontimeout = ontimeout = xhr . onerror = onerror = xhr . onabort = onabort = xhr . onload = onload = nope ; if ( timer ) clearTimeout ( timer ) ; } ) ; return xhr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SASS plugin for Sheetify ( str str obj fn ) - > null [CODESPLIT] function sheetifyNest ( filename , source , opts , done ) { var processor = postcss ( [ nest ( opts ) ] ) processor . process ( source ) . then ( function ( res ) { done ( null , res . css ) } ) . catch ( done ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * var cache = require ( cachewatch ) ; var watch = cache () ; watch . setToken ( -- My key -- ) ; [CODESPLIT] function Cache ( key , opt ) { if ( ! ( this instanceof Cache ) ) return new Cache ( key , opt ) ; if ( key ) this . setToken ( key ) ; this . config = _ . defaults ( opt || { } , { protocol : 'https' , fragment : '_escaped_fragment_' , service : 'service.cache.watch' , path : '/' , sender : { method : 'get' , headers : { 'User-Agent' : 'CacheWatch Client' } , } , auth : 'x-cache-watch' , lengths : 150 , useragent : pack . config . useragent , url : pack . config . extencion } ) ; var that = this ; that . watch = function CacheWatch ( req , res , next ) { var query = querystring . parse ( url . parse ( req . url ) . query ) ; if ( that . isNot ( req , query ) || ! that . key ) return next ( ) ; that . get ( that . createUrl ( req , query ) , function ( err , resp , body ) { if ( err || that . res ( resp ) ) return next ( ) ; res . setHeader ( 'CacheWatch' , Cache . version ) ; res . setHeader ( 'last-modified' , resp . headers [ 'last-modified' ] ) ; res . setHeader ( 'content-type' , resp . headers [ 'content-type' ] ) ; res . send ( body ) ; } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a filename to the list with its dependencies first [CODESPLIT] function addWithDependencies ( allFiles , newFile , dependencies , currentFiles , cycleCheck ) { if ( cycleCheck . indexOf ( newFile ) >= 0 ) { throw new Error ( 'Dependency cycle found ' + JSON . stringify ( cycleCheck ) ) } cycleCheck . push ( newFile ) try { // Add dependencies first if ( dependencies [ newFile ] ) { dependencies [ newFile ] . forEach ( function ( dependency ) { if ( allFiles . indexOf ( dependency ) < 0 ) { throw new Error ( 'Dependency \"' + dependency + '\" of file \"' + newFile + '\" is not part of ' + JSON . stringify ( allFiles ) ) } addWithDependencies ( allFiles , dependency , dependencies , currentFiles , cycleCheck ) } ) } if ( currentFiles . indexOf ( newFile ) < 0 ) { currentFiles . push ( newFile ) } } finally { cycleCheck . pop ( ) } return currentFiles }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Order files by their dependencies ( insert dependencies first ) [CODESPLIT] function orderFiles ( allFiles , dependencies ) { var result = [ ] allFiles . forEach ( function ( newFile ) { addWithDependencies ( allFiles , newFile , dependencies , result , [ ] ) } ) return result }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a new LevelUp chain - style batch a denormalized Common Form and the output of commonform - merkleize for that Common Form add LevelUp put operations to the batch for the Common Form and each of its children . [CODESPLIT] function batchForms ( batch , form , merkle ) { // Use commonform-stringify to produce the text to be stored. var stringified = stringify ( form ) var digest = merkle . digest batch . put ( digest , stringified ) // Recurse children. form . content . forEach ( function ( element , index ) { if ( isChild ( element ) ) { var childForm = element . form var childMerkle = merkle . content [ index ] batchForms ( batch , childForm , childMerkle ) } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JSON . parse wrapped to take an errback . [CODESPLIT] function parseJSON ( input , callback ) { var error var result try { result = JSON . parse ( input ) } catch ( e ) { error = e } callback ( error , result ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Utils . create . folder () ; Utils . create . file () ; Create folder if needed Then create file [CODESPLIT] function createFile ( filePath , fileContent ) { var folderPath = filePath . split ( '/' ) ; folderPath . pop ( ) ; folderPath = folderPath . join ( '/' ) ; if ( ! Utils . exist ( folderPath ) ) createFolder ( folderPath ) ; fs . writeFileSync ( filePath , fileContent ) ; Utils . log ( 'Created file: ' + filePath ) ; return Utils ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the url based on crazy [CODESPLIT] function scopeUrl ( options , inst ) { options = _ . extend ( _ . clone ( options || { } ) , inst ) var route = [ ] if ( options . season_id ) route . push ( 'seasons' , options . season_id ) if ( options . flight_stage_id ) route . push ( 'flight_stages' , options . flight_stage_id ) else if ( options . division_id ) route . push ( 'divisions' , options . division_id ) else if ( options . pool_id ) route . push ( 'pools' , options . pool_id ) route . push ( 'standings' ) var base = config . urls && config . urls . sports || config . url return Url . resolve ( base , route . join ( '/' ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format number [CODESPLIT] function formatNum ( value , type ) { const conv = { scientific : \".3e\" , si : \".3s\" , rounded : \".3r\" } ; if ( type === 'raw' ) return value ; if ( value === undefined || value === null || Number . isNaN ( value ) ) return '' ; return value == parseFloat ( value ) ? d3 . format ( conv [ type ] ) ( value ) : value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extend WebSocket to automatically reconnect [CODESPLIT] function ReconnectingWebSocket ( url , opts ) { if ( ! ( this instanceof ReconnectingWebSocket ) ) { throw new TypeError ( 'Cannot call a constructor as a function' ) ; } opts = opts || { } ; var self = this ; function getOpt ( name , def ) { return opts . hasOwnProperty ( name ) ? opts [ name ] : def ; } var timeout = getOpt ( 'timeout' , 100 ) ; var maxRetries = getOpt ( 'maxRetries' , 5 ) ; var curRetries = 0 ; // External event callbacks self . onmessage = noop ; self . onopen = noop ; self . onclose = noop ; function unreliableOnOpen ( e ) { self . onopen ( e ) ; curRetries = 0 ; } function unreliableOnClose ( e ) { self . onclose ( e ) ; if ( curRetries < maxRetries ) { ++ curRetries ; setTimeout ( connect , timeout ) ; } } function unreliableOnMessage ( e ) { self . onmessage ( e ) ; } function connect ( ) { // Constructing a WebSocket() with opts.protocols === undefined // does NOT behave the same as calling it with only one argument // (specifically, it throws security errors). if ( opts . protocols ) { self . ws = new WebSocket ( url , opts . protocols ) ; } else { self . ws = new WebSocket ( url ) ; } // onerror isn't necessary: it is always accompanied by onclose self . ws . onopen = unreliableOnOpen ; self . ws . onclose = unreliableOnClose ; self . ws . onmessage = unreliableOnMessage ; } connect ( ) ; this . connect = connect ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns - 1 if array being searched for isn t found . if arrayToSearchFor contains objects this will always return - 1 . [CODESPLIT] function getFirstIndexOfArray ( arrayToSearchFor , arrayToSearchInside ) { errorIfNotArray_1 . errorIfNotArray ( arrayToSearchFor ) ; error_if_not_populated_array_1 . errorIfNotPopulatedArray ( arrayToSearchInside ) ; return arrayToSearchInside . findIndex ( function ( value ) { return ( isArray_notArray_1 . isArray ( value ) && arrays_match_1 . arraysMatch ( value , arrayToSearchFor ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为 正整数 [CODESPLIT] function _isPositiveInteger ( val , options ) { var opts = _isObject ( options ) ? options : { } ; if ( opts . isStrict === true ) { return _isNumber ( val ) && REGEX_ENUM . POSITIVE_INTEGER_REX . test ( val ) ; } return REGEX_ENUM . POSITIVE_INTEGER_REX . test ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] function client ( protocol ) { if ( ! protocol || typeof protocol !== \"object\" ) throw new TypeError ( \"owe ClientApi protocols have to be objects.\" ) ; if ( typeof protocol . closer !== \"function\" ) throw new TypeError ( \"owe ClientApi proctols have to offer a closer function.\" ) ; if ( protocol . init && typeof protocol . init !== \"function\" ) throw new TypeError ( \"owe ClientApi protocols have to offer an init function.\" ) ; let connected = false ; const observers = new Set ( ) ; protocol = Object . assign ( { get connected ( ) { return connected ; } , set connected ( value ) { if ( typeof value !== \"boolean\" ) throw new TypeError ( \"Protocol connection state has to be boolean.\" ) ; if ( value === connected ) return ; connected = value ; for ( const observer of observers ) observer ( connected ) ; } , observe ( observer ) { if ( typeof observer !== \"function\" ) throw new TypeError ( \"Protocol connection state observers have to be functions.\" ) ; observers . add ( observer ) ; } , unobserve ( observer ) { observers . delete ( observer ) ; } } , protocol ) ; if ( protocol . init ) protocol . init ( ) ; return new ClientApi ( protocol ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively creates a file [CODESPLIT] function writePath ( parentDir , path , data ) { let files = path . split ( '/' ) ; let file = files . shift ( ) ; // init file if ( ! parentDir [ file ] ) parentDir [ file ] = { content : undefined , tree : { } } ; if ( files . length > 0 ) { writePath ( parentDir [ file ] . tree , files . join ( '/' ) , data ) ; } else if ( data ) { parentDir [ file ] . content = data . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is set by the task _read_overrides_and_resolutions [CODESPLIT] function ( mainFiles /*, component*/ ) { for ( var i = 0 ; i < mainFiles . length ; i ++ ) { //Use no-minified version if available var parts = mainFiles [ i ] . split ( '.' ) , ext = parts . pop ( ) , min = parts . pop ( ) , fName ; if ( min == 'min' ) { parts . push ( ext ) ; fName = parts . join ( '.' ) ; if ( grunt . file . exists ( fName ) ) mainFiles [ i ] = fName ; } } return mainFiles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "class RoleFinder [CODESPLIT] function descendantRoles ( roles , fieldName , allDescendants ) { return roles . map ( role => allDescendants . get ( role ) ) . filter ( descendants => ! ! descendants ) . map ( descendants => descendants . get ( fieldName ) ) . filter ( fieldRoles => ! ! fieldRoles ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "descendantRoles [CODESPLIT] function mapOfMaps ( ) { const m = new Map ( ) m . getOrCreate = function ( key ) { if ( ! this . has ( key ) ) this . set ( key , mapOfMaps ( ) ) return this . get ( key ) } return m }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "mapOfMaps [CODESPLIT] function mapOfArrays ( ) { const m = new Map ( ) m . getOrCreate = function ( key ) { if ( ! this . has ( key ) ) this . set ( key , [ ] ) return this . get ( key ) } return m }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The profile index where profile objects are contained . [CODESPLIT] function ( ) { this . objects = { } ; this . index = [ ] ; this . _objTree = [ ] ; this . _objList = [ ] ; this . _properties = { } ; this . _propID = 0 ; this . _decodeIndex = [ ] ; this . _objFreq = [ ] ; this . _objInfeq = [ ] ; this . shortNames = true ; this . indent = \"\\t\" ; this . hasEmbed = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a profile object on the index [CODESPLIT] function ( po ) { this . objects [ po . name ] = po ; if ( po . extends ) { this . _objTree . push ( [ po . extends , po . name ] ) ; } else if ( po . depends ) { this . _objTree . push ( [ po . depends , po . name ] ) ; } else { this . _objList . push ( po . name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a divide - and - conquer nested if - statements up to maximum depth steps deep . After that it performs equality testing using a switch - case statement . [CODESPLIT] function ( index_offset , size , depth , prefix , testVar , callback ) { if ( size == 0 ) return prefix + this . indent + \"/* No items */\\n\" ; var code = \"\" ; genChunk = ( function ( s , e , d , pf ) { if ( d === 0 ) { code += pf + \"switch (\" + testVar + \") {\\n\" ; for ( var i = s ; i < e ; ++ i ) { code += pf + this . indent + \"case \" + ( index_offset + i ) + \": return \" + callback ( i ) ; } code += pf + \"}\\n\" ; } else { // No items if ( e == s ) { // Only 1 item } else if ( e == s + 1 ) { code += pf + \"if (\" + testVar + \" === \" + ( index_offset + s ) + \")\\n\" ; code += pf + this . indent + \"return \" + callback ( s ) ; } else { var mid = Math . round ( ( s + e ) / 2 ) ; code += pf + \"if (\" + testVar + \" < \" + ( index_offset + mid ) + \") {\\n\" ; genChunk ( s , mid , d - 1 , pf + this . indent ) ; code += pf + \"} else {\\n\" ; genChunk ( mid , e , d - 1 , pf + this . indent ) ; code += pf + \"}\\n\" ; } } } ) . bind ( this ) ; genChunk ( 0 , size , depth , prefix + this . indent ) ; return code ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the property variable name used to optimize for size the minified result . [CODESPLIT] function ( name ) { var id = this . _properties [ name ] ; if ( id === undefined ) { if ( this . shortNames ) { id = this . _properties [ name ] = 'p' + ( this . _propID ++ ) . toString ( ) } else { id = this . _properties [ name ] = 'p' + name [ 0 ] . toUpperCase ( ) + name . substr ( 1 ) . toLowerCase ( ) . replace ( / [,\\.\\- \\_] / g , '_' ) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve dependencies and arrange objects accoridng to priority and priority . [CODESPLIT] function ( ) { // Reset index this . index = [ ] ; // Apply extends to the objects for ( var i = 0 , l = this . _objTree . length ; i < l ; ++ i ) { if ( this . objects [ this . _objTree [ i ] [ 0 ] ] === undefined ) { throw \"Extending unknown object \" + this . _objTree [ i ] [ 0 ] ; } // Apply this . objects [ this . _objTree [ i ] [ 1 ] ] . applyExtend ( this . objects [ this . _objTree [ i ] [ 0 ] ] ) ; } // Resolve dependencies var deps = toposort ( this . _objTree ) . reverse ( ) , used = { } ; for ( var i = 0 , l = deps . length ; i < l ; ++ i ) { used [ deps [ i ] ] = 1 ; this . objects [ deps [ i ] ] . id = this . index . length ; this . index . push ( this . objects [ deps [ i ] ] ) ; } // Then include objects not part of dependency tree for ( var i = 0 , l = this . _objList . length ; i < l ; ++ i ) { // Skip objects already used in the dependency resolution if ( ! used [ this . _objList [ i ] ] ) { this . index . push ( this . objects [ this . _objList [ i ] ] ) ; } } // Then pre-cache property IDs for all the propeties // and check if any of the objects has embeds for ( var i = 0 , l = this . index . length ; i < l ; ++ i ) { var pp = this . index [ i ] . properties ; for ( var j = 0 , jl = pp . length ; j < jl ; ++ j ) { this . propertyVar ( pp [ j ] ) ; } if ( this . index [ i ] . embed . length > 0 ) { this . hasEmbed = true ; } } // Separate to frequent and infrequent objects for ( var i = 0 , l = this . index . length ; i < l ; ++ i ) { var obj = this . index [ i ] , isFreq = obj . frequent ; // Make sure we only register 5-bit objects if ( isFreq ) { if ( this . _objFreq . length >= MAX_FREQ_ITEMS ) { isFreq = false ; } } // Put on frequent or infrequent table if ( isFreq ) { obj . id = this . _objFreq . length ; this . _objFreq . push ( obj ) ; } else { obj . id = this . _objInfeq . length + MAX_FREQ_ITEMS ; this . _objInfeq . push ( obj ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a table with all the property constants [CODESPLIT] function ( ) { var pn = Object . keys ( this . _properties ) ; var code = \"var \" ; for ( var i = 0 , l = pn . length ; i < l ; ++ i ) { if ( i !== 0 ) code += \",\\n\" ; code += this . indent + this . _properties [ pn [ i ] ] + \" = '\" + pn [ i ] + \"'\" ; } code += \";\\n\" ; return code ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the list of init functions used by the lookup fcatory to generate the items [CODESPLIT] function ( ) { var code = \"\" ; // Collect object initializers for ( var i = 0 , l = this . index . length ; i < l ; ++ i ) { var o = this . index [ i ] ; code += \"/**\\n * Factory & Initializer of \" + o . name + \"\\n */\\n\" ; code += \"var factory_\" + o . safeName + \" = {\\n\" ; code += this . indent + \"props: \" + o . properties . length + \",\\n\" ; code += this . indent + \"create: function() {\\n\" ; code += this . indent + this . indent + \"return \" + o . generateFactory ( ) + \";\\n\" ; code += this . indent + \"},\\n\" ; code += this . indent + \"init: function(inst, props, pagesize, offset) {\\n\" ; code += o . generateInitializer ( 'inst' , 'props' , 'pagesize' , 'offset' , this . indent + this . indent , this . indent ) ; code += this . indent + \"}\\n\" ; code += \"}\\n\\n\" ; } return code ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the lookup factory by ID [CODESPLIT] function ( prefix ) { var code = \"function( id ) {\\n\" ; code += prefix + this . indent + \"if (id < \" + MAX_FREQ_ITEMS + \") {\\n\" ; code += this . generateDnCif ( 0 , this . _objFreq . length , 3 , prefix + this . indent , 'id' , ( function ( i ) { return \"factory_\" + this . _objFreq [ i ] . safeName + \";\\n\" } ) . bind ( this ) ) ; code += prefix + this . indent + \"} else {\\n\" ; code += this . generateDnCif ( MAX_FREQ_ITEMS , this . _objInfeq . length , 3 , prefix + this . indent , 'id' , ( function ( i ) { return \"factory_\" + this . _objInfeq [ i ] . safeName + \";\\n\" } ) . bind ( this ) ) ; code += prefix + this . indent + \"}\\n\" ; code += prefix + \"}\\n\" ; return code ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the function to use for identifying an object [CODESPLIT] function ( prefix ) { var code = \"function( inst ) {\\n\" ; for ( var i = 0 , l = this . index . length ; i < l ; ++ i ) { var o = this . index [ i ] ; if ( i === 0 ) code += prefix + this . indent + \"if\" ; else code += prefix + this . indent + \"} else if\" ; code += \" (inst instanceof \" + o . name + \") {\\n\" ; code += prefix + this . indent + this . indent + \"return [\" + o . id + \", getter_\" + o . safeName + \"];\\n\" ; } code += prefix + this . indent + \"}\\n\" ; code += prefix + \"}\\n\" return code ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the function that is used to encode an object [CODESPLIT] function ( ) { var code = \"\" ; // Collect object initializers for ( var i = 0 , l = this . index . length ; i < l ; ++ i ) { var o = this . index [ i ] ; code += \"/**\\n * Property getter \" + o . name + \"\\n */\\n\" ; code += \"function getter_\" + o . safeName + \"(inst) {\\n\" ; code += this . indent + \"return \" + o . generatePropertyGetter ( 'inst' , this . indent + this . indent ) + \";\\n\" ; code += \"}\\n\\n\" ; } code += \"\\n\" return code ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new Client with the given options . [CODESPLIT] function Client ( options ) { options = options || { } ; this . isClient = true ; this . subdomain = options . subdomain ; this . endpoint = options . endpoint ; if ( ! this . subdomain && ! this . endpoint ) throw new Error ( 'No subdomain was specified.' ) ; // Determine if we construct a URL from the subdomain or use a custom one if ( this . endpoint && typeof this . endpoint !== 'undefined' ) { this . baseUrl = this . endpoint ; } else { this . baseUrl = 'https://' + this . subdomain + '.desk.com' ; } if ( options . username && options . password ) { this . auth = { username : options . username , password : options . password , sendImmediately : true } ; } else if ( options . consumerKey && options . consumerSecret && options . token && options . tokenSecret ) { this . auth = { consumer_key : options . consumerKey , consumer_secret : options . consumerSecret , token : options . token , token_secret : options . tokenSecret } ; } else { throw new Error ( 'No authentication specified, use either Basic Authentication or OAuth.' ) ; } this . retry = options . retry || false ; this . maxRetry = options . maxRetry || 3 ; this . timeout = options . timeout ; this . logger = options . logger || null ; this . queue = async . queue ( this . request . bind ( this ) , 60 ) ; linkMixin . call ( this , JSON . parse ( fs . readFileSync ( __dirname + '/resources.json' , 'utf-8' ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为 正数 [CODESPLIT] function _isPositiveNumber ( val , options ) { var opts = _isObject ( options ) ? options : { } ; if ( opts . isStrict === true ) { return _isNumber ( val ) && REGEX_ENUM . POSITIVE_NUMBER_REX . test ( val ) ; } return REGEX_ENUM . POSITIVE_NUMBER_REX . test ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes the url to the tournament or flight [CODESPLIT] function scopeUrl ( options , inst ) { options = _ . extend ( { } , inst , options ) if ( ! options . season_id && ! options . team_id && ! ( options . flight_stage_id && options . flight_id ) ) throw new Error ( 'flight_stage_id+flight_id, season_id and/or team_id required to make team instance api calls' ) if ( options . flight_stage_id && options . flight_id ) { var url = ngin . Flight . urlRoot ( ) + '/' + options . flight_id + '/flight_stages/' + options . flight_stage_id + '/teams' return options . team_id ? url + '/' + options . team_id : url } else if ( options . season_id ) { var url = ngin . Season . urlRoot ( ) + '/' + options . season_id + '/teams' return options . team_id ? url + '/' + options . team_id : url } else { return ngin . Team . urlRoot ( ) + '/' + options . team_id + ngin . TeamInstance . urlRoot ( ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Image collection loader [CODESPLIT] function Imagesloader ( opts ) { /**\n     * @define {object} Collection of public methods.\n     */ var self = { } ; /**\n     * @define {object} Options for the constructor \n     */ var opts = opts || { } ; /**\n\t * @define {object} A image loader object\n\t */ var imageloader = Imageloader ( ) ; /**\n     * @define {array} A holder for when an image is loaded\n     */ var imgs = [ ] ; /**\n\t * @define {array} A holder for the image src that should be loaded\n\t */ var srcs = [ ] ; /**\n\t * @define {object} A promise container for promises\n\t */ var def ; /**\n\t * Load a collection of images\n\t * @example imageloader.load(['img1.jpg', 'img2.jpg', 'img3.jpg']).success(function(){ // Do something });\n\t * @param {array} images A collection of img object or img.src (paths)\n\t * @config {object} def Create a promise object\n\t * @return {object} Return the promise object\n\t */ function load ( images ) { def = Deferred ( ) ; /**\n\t\t * Check if the images is img objects or image src\n\t\t * return string of src\n\t\t */ srcs = convertImagesToSrc ( images ) ; /**\n\t\t * Loop through src's and load image\n\t\t */ for ( var i = 0 ; i < srcs . length ; i ++ ) { imageloader . load ( srcs [ i ] ) . success ( function ( img ) { /** call imageloaded a pass the img that is loaded */ imageLoaded ( img ) ; } ) . error ( function ( msg ) { def . reject ( msg + ' couldn\\'t be loaded' ) ; } ) ; } ; return def . promise ; } /**\n\t * Image loaded checker\n\t * @param {img} img The loaded image\n\t */ function imageLoaded ( img ) { /** Notify the promise */ def . notify ( \"notify\" ) ; /** Add the image to the imgs array */ imgs . push ( img ) ; /** If the imgs array size is the same as the src's */ if ( imgs . length == srcs . length ) { /** First sort images, to have the same order as src's */ sortImages ( ) ; /** Resolve the promise with the images */ def . resolve ( imgs ) ; } } /**\n\t * Convert img to src\n\t * @param {array} imgs A collection og img/img paths\n\t * @config {array} src A temporally array for storing img path/src\n\t * @return {array} Return an array of img src's\n\t */ function convertImagesToSrc ( imgs ) { var src = [ ] ; for ( var i = 0 ; i < imgs . length ; i ++ ) { /** If the img is an object (img) get the src  */ if ( typeof imgs [ i ] == 'object' ) { src . push ( imgs [ i ] . src ) ; } } ; /** If the src array is null return the original imgs array */ return src . length ? src : imgs ; } /**\n\t * Sort images after the originally order\n\t * @config {array} arr A temporally array for sorting images\n\t */ function sortImages ( ) { var arr = [ ] ; /**\n\t\t * Create a double loop\n\t\t * And match the order of the srcs array\n\t\t */ for ( var i = 0 ; i < srcs . length ; i ++ ) { for ( var j = 0 ; j < imgs . length ; j ++ ) { var str = imgs [ j ] . src . toString ( ) ; var reg = new RegExp ( srcs [ i ] ) /** If srcs matches the imgs add it the the new array */ if ( str . match ( reg ) ) arr . push ( imgs [ j ] ) ; } ; } ; /** Override imgs array with the new sorted arr */ imgs = arr ; } /**\n\t * Public methods\n\t * @public {function}\n\t */ self . load = load ; /**\n\t * @return {object} Public methods\n\t */ return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load a collection of images [CODESPLIT] function load ( images ) { def = Deferred ( ) ; /**\n\t\t * Check if the images is img objects or image src\n\t\t * return string of src\n\t\t */ srcs = convertImagesToSrc ( images ) ; /**\n\t\t * Loop through src's and load image\n\t\t */ for ( var i = 0 ; i < srcs . length ; i ++ ) { imageloader . load ( srcs [ i ] ) . success ( function ( img ) { /** call imageloaded a pass the img that is loaded */ imageLoaded ( img ) ; } ) . error ( function ( msg ) { def . reject ( msg + ' couldn\\'t be loaded' ) ; } ) ; } ; return def . promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Image loaded checker [CODESPLIT] function imageLoaded ( img ) { /** Notify the promise */ def . notify ( \"notify\" ) ; /** Add the image to the imgs array */ imgs . push ( img ) ; /** If the imgs array size is the same as the src's */ if ( imgs . length == srcs . length ) { /** First sort images, to have the same order as src's */ sortImages ( ) ; /** Resolve the promise with the images */ def . resolve ( imgs ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert img to src [CODESPLIT] function convertImagesToSrc ( imgs ) { var src = [ ] ; for ( var i = 0 ; i < imgs . length ; i ++ ) { /** If the img is an object (img) get the src  */ if ( typeof imgs [ i ] == 'object' ) { src . push ( imgs [ i ] . src ) ; } } ; /** If the src array is null return the original imgs array */ return src . length ? src : imgs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort images after the originally order [CODESPLIT] function sortImages ( ) { var arr = [ ] ; /**\n\t\t * Create a double loop\n\t\t * And match the order of the srcs array\n\t\t */ for ( var i = 0 ; i < srcs . length ; i ++ ) { for ( var j = 0 ; j < imgs . length ; j ++ ) { var str = imgs [ j ] . src . toString ( ) ; var reg = new RegExp ( srcs [ i ] ) /** If srcs matches the imgs add it the the new array */ if ( str . match ( reg ) ) arr . push ( imgs [ j ] ) ; } ; } ; /** Override imgs array with the new sorted arr */ imgs = arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a default value getter . [CODESPLIT] function builder ( envList , envName ) { if ( envList == null ) { envList = DEFAULT_ENV_LIST ; } if ( envName == null ) { envName = DEFAULT_ENV_NAME ; } if ( ! Array . isArray ( envList ) ) { throw new Error ( 'envList must be an array' ) ; } if ( typeof envName !== 'string' ) { throw new Error ( 'envName must be a string' ) ; } // . const index = envList . indexOf ( env . get ( envName , DEFAULT_ENV ) . required ( ) . asString ( ) ) ; /**\n   * .\n   */ // return function defaults(obj) { //   return 'object' !== typeof obj ? obj : obj[index]; // }; let body ; if ( index < 0 ) { body = 'return function defaults() {}' ; } else { body = ` ${ index } ` ; } return new Function ( body ) ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--- implements ------------------------------------------ [CODESPLIT] function DataType_Array_toString ( source ) { // @arg IntegerArray(= undefined): [0xff, ...] // @ret BinaryString: //{@dev $valid ( $type ( source , \"IntegerArray|omit\" ) , DataType_Array_toString , \"source\" ) ; //}@dev if ( ! source ) { return \"\" ; } var rv = [ ] , i = 0 , iz = source . length , bulkSize = 32000 ; // Avoid String.fromCharCode.apply(null, BigArray) exception if ( iz < bulkSize ) { return String . fromCharCode . apply ( null , source ) ; } for ( ; i < iz ; i += bulkSize ) { rv . push ( String . fromCharCode . apply ( null , source . slice ( i , i + bulkSize ) ) ) ; } return rv . join ( \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "agent . js [CODESPLIT] function agent ( agency , jn ) { 'use strict' ; // private properties var id ; var expression ; var tokenizedExpression ; var dependencies ; var func ; var callback ; var canExecute ; var executed ; var result ; var waitingExec ; var deffDepCheck ; var haltsExecution ; var err = new Error ( ) ; // getter for the id property function getId ( ) { return id ; } // setter for the id property function setId ( identifier ) { id = identifier ; } // validates the agent's id according to the validity of the symbols used // and the possibility of duplication inside the same agency  function validateId ( id ) { if ( id && id . trim ( ) && / ^[a-zA-Z0-9_]+$ / . test ( id ) ) { if ( agency . isIdInUse ( id ) ) { err . name = 'DuplicateIdError' ; err . message = 'duplication (use a different id)' ; return err ; } else { return id ; } } else { err . name = 'ValidateIdError' ; err . message = 'failed id validation (please use alphanumeric characters and underscore)' ; return err ; } } // returns a list of unique dependency agents function arrayGetUniques ( arr ) { var a = [ ] ; for ( var i = 0 , l = arr . length ; i < l ; i ++ ) { if ( a . indexOf ( arr [ i ] ) === - 1 && arr [ i ] !== '' ) a . push ( arr [ i ] ) ; } return a ; } // parses the dependency logical expression of each agent and populates // the auxiliary structures used by the agency to control the flow of execution function parseExpression ( expr ) { var parentList = [ ] ; var parsedTokenizedExpression = [ ] ; var parsedExpression = '' ; var testInvalidChar ; if ( expr && expr . trim ( ) ) { parsedExpression = expr . replace ( / \\040 / g , '' ) ; testInvalidChar = / [^a-zA-Z0-9_&|!()_] / . test ( parsedExpression ) ; //valid characters if ( ! testInvalidChar ) { var pos = '0' ; var prevprev = '?' ; var prev = '?' ; var head = '' ; var key = '' ; var rbrackets = 0 ; var tmpparent = '' ; var tmpexpression = '' ; // parser rules: // // left hand side of rule determines the rule to apply to the current element of the expression: // //   first element of key indicates the position of the expression element being evaluated: //    1 - first position //    n - other position //   second element of key represents the position before the previous position: //    ? - don't care //    & - logical AND //    | - logical OR //   third element of key represents the previous position on the expression: //    ? - don't care //    ( - opening parenthesis //    # - alpha numeric characters and underscore //    ) - closing parenthesis //    ! - logical NOT // // right hand side of rule represents valid symbols for that key // // example: // //  parsing expression 'a&&b' (one position at a time): //   //  - 'a' element is evaluated by first rule: //    key: 1st position, before previous and previous positions elements don't care //    validation: any alpha numeric character or open parenthesis or underscore or NOT  //  - '&' element is evaluated by the third rule: //    key: (any position but first, indiferent before previous element, any valid previous element) //    validation: any alpha numeric character or closing parenthesis or underscore or AND or OR  //  - '&' element is evaluated by sixth rule: //    key: any position but first, indiferent before previous element, OR previous element //    validation: value has to be '&' //  - 'b' element is evaluated by the seventh rule: //    key: any position but first, '&' before previous element, '&' previous element //    validation: any alpha numeric character or open parenthesis or underscore or NOT or opening parenthesis //   var rules = { '1??' : / [a-zA-Z0-9_(!] / , 'n?(' : / [a-zA-Z0-9_(!] / , 'n?#' : / [a-zA-Z0-9_)&|] / , 'n?!' : / [a-zA-Z0-9_(] / , 'n?)' : / [&|)] / , 'n?&' : / [&] / , 'n&&' : / [a-zA-Z0-9_(!] / , 'n&#' : / [a-zA-Z0-9_)&|] / , 'n&(' : / [a-zA-Z0-9_(!] / , 'n?|' : / [|] / , 'n||' : / [a-zA-Z0-9_(!] / , 'n|(' : / [a-zA-Z0-9_(!] / , 'n|#' : / [a-zA-Z0-9_)&|] / , 'n|&' : / [] / , 'n&|' : / [] / , } ; for ( var i = 0 ; i < parsedExpression . length ; i += 1 ) { pos = ( i === 0 ? '1' : 'n' ) ; head = parsedExpression . charAt ( i ) ; key = pos + prevprev + prev ; if ( ! rules [ key ] . test ( head ) ) { err . code = 'InvalidCharacter' ; err . message = 'failed dependency expression validation (invalid character at position ' + ( i + 1 ) + ')' ; return err ; } if ( head === '(' ) { rbrackets += 1 ; } if ( head === ')' ) { if ( rbrackets <= 0 ) { err . code = 'UnopenedParentheses' ; err . message = 'failed dependency expression validation (unopened parenthesis)' ; return err ; } else { rbrackets -= 1 ; } } // last character if ( i === parsedExpression . length - 1 ) { // ), # -> expression terminators if ( / [a-zA-Z0-9)] / . test ( head ) ) { if ( rbrackets !== 0 ) { err . code = 'UnclosedParentheses' ; err . message = 'failed dependency expression validation (unclosed parenthesis)' ; return err ; } } else { err . code = 'InvalidTerminator' ; err . message = 'failed dependency expression validation (invalid expression terminator)' ; return err ; } } else { if ( prev === '&' || prev === '|' ) { prevprev = prev ; } else { prevprev = '?' ; // ? -> don't care } if ( / [a-zA-Z0-9_] / . test ( head ) ) { prev = '#' ; // # -> valid identifier character } else { prev = head ; } } // handle parent list and tokenized expression if ( / [a-zA-Z0-9_] / . test ( head ) ) { if ( tmpexpression !== '' ) { parsedTokenizedExpression . push ( tmpexpression ) ; tmpexpression = '' ; } if ( parsedExpression . length === 1 ) { if ( id === head ) { err . name = 'SelfDependency' ; err . message = 'failed dependency expression validation (agent self dependency)' ; return err ; } else { parentList . push ( head ) ; parsedTokenizedExpression . push ( head ) ; } } else { if ( i === parsedExpression . length - 1 ) { tmpparent = tmpparent + head ; if ( id === tmpparent ) { err . name = 'SelfDependency' ; err . message = 'failed dependency expression validation (agent self dependency)' ; return err ; } else { parentList . push ( tmpparent ) ; parsedTokenizedExpression . push ( tmpparent ) ; } } else { tmpparent = tmpparent + head ; } } } else { if ( tmpparent !== '' ) { if ( id === tmpparent ) { err . name = 'SelfDependency' ; err . message = 'failed dependency expression validation (agent self dependency)' ; return err ; } else { parentList . push ( tmpparent ) ; parsedTokenizedExpression . push ( tmpparent ) ; tmpparent = '' ; } } tmpexpression = tmpexpression + head ; if ( i === parsedExpression . length - 1 ) { parsedTokenizedExpression . push ( tmpexpression ) ; } } } expression = parsedExpression ; tokenizedExpression = parsedTokenizedExpression ; dependencies = arrayGetUniques ( parentList ) ; } else { err . name = 'InvalidExpression' ; err . message = 'failed dependency expression validation (please use underscore, alphanumeric and logical chars)' ; return err ; } } else { expression = '' ; dependencies = [ ] ; tokenizedExpression = [ ] ; } } // getter for dependencies property  function getDependencies ( ) { return dependencies ; } // getter for expression property function getExpression ( ) { return expression ; } // getter for tokenizedExpression property function getTokenizedExpression ( ) { return tokenizedExpression ; } // setter for canExecute flag property function setCanExecute ( flag ) { canExecute = flag ; } // getter for canExecute property function getCanExecute ( ) { return canExecute ; } // setter for function property function setFunction ( f ) { if ( canExecute ) { if ( Object . getPrototypeOf ( f ) === Function . prototype ) { func = f ; jn . logCreationEvent ( id , 'INFO' , 'function definition completed' , ( new Date ( ) ) . toJSON ( ) ) ; } else { setCanExecute ( false ) ; jn . logCreationEvent ( id , 'ERROR' , 'function definition failed' , ( new Date ( ) ) . toJSON ( ) ) ; } } } // setter for callback property function setCallback ( cb ) { if ( canExecute ) { if ( Object . getPrototypeOf ( cb ) === Function . prototype ) { callback = cb ; jn . logCreationEvent ( id , 'INFO' , 'callback definition completed' , ( new Date ( ) ) . toJSON ( ) ) ; } else { setCanExecute ( false ) ; jn . logCreationEvent ( id , 'ERROR' , 'callback definition failed' , ( new Date ( ) ) . toJSON ( ) ) ; } } } // setter for result property function setResult ( res ) { if ( res ) { result = res ; } else { result = null ; } } // getter for result property function getResult ( ) { return result ; } // setter for executed flag property function setExecuted ( flag ) { executed = flag ; } // getter for executed property function getExecuted ( ) { return executed ; } // setter for waitingExec flag property function setWaitingExec ( flag ) { waitingExec = flag ; } // getter for waitingExec property function getWaitingExec ( ) { return waitingExec ; } // setter for deffDepCheck flag property function setDeffDepCheck ( flag ) { deffDepCheck = flag ; } // getter for deffDepCheck property function getDeffDepCheck ( ) { return deffDepCheck ; } // setter for haltsExecution flag property function setHaltExecution ( flag ) { haltsExecution = flag ; } // gets value of a dependency agent's execution (inter agent communication); // wraps a call to the agency method function getValueOfAgent ( dep ) { var len = dependencies . length ; for ( var i = 0 ; i < len ; i ++ ) { if ( dep === dependencies [ i ] ) { return agency . getAgentValue ( dep ) ; } } jn . logExecutionEvent ( id , 'INFO' , 'could not get value of agent ' + dep + ' (not a dependency)' , ( new Date ( ) ) . toJSON ( ) ) ; return null ; } // asynchronously executes the agent's function (wrapper for user defined code) and the optional corresponding callback // following the callback contract: callback(error, data); validates the continuation of the agency in case // of error during execution of current agent  function execute ( ) { var res ; var functionInterface = { getValueOfAgent : getValueOfAgent } ; if ( func ) { setWaitingExec ( true ) ; setTimeout ( function ( ) { var errorOnExecution = false ; jn . logExecutionEvent ( id , 'INFO' , 'began function execution' , ( new Date ( ) ) . toJSON ( ) ) ; try { res = func ( functionInterface ) ; setResult ( res ) ; if ( callback ) { callback ( null , res ) ; } jn . logExecutionEvent ( id , 'INFO' , 'function executed whitout errors' , ( new Date ( ) ) . toJSON ( ) ) ; } catch ( err ) { errorOnExecution = true ; setResult ( err ) ; jn . logExecutionEvent ( id , 'ERROR' , 'failed to execute function: ' + err . message , ( new Date ( ) ) . toJSON ( ) ) ; if ( callback ) { callback ( err ) ; } } setExecuted ( true ) ; setWaitingExec ( false ) ; if ( haltsExecution && errorOnExecution ) { jn . logExecutionEvent ( id , 'ERROR' , 'error on execution halted agency execution' , ( new Date ( ) ) . toJSON ( ) ) ; agency . report ( ) ; } else { agency . runAgents ( ) ; } } , 0 ) ; } else { jn . logExecutionEvent ( id , 'INFO' , 'does not have a defined function' , ( new Date ( ) ) . toJSON ( ) ) ; } } // public interface return { getId : getId , validateId : validateId , setId : setId , parseExpression : parseExpression , getDependencies : getDependencies , getExpression : getExpression , getTokenizedExpression : getTokenizedExpression , setFunction : setFunction , setCallback : setCallback , setCanExecute : setCanExecute , getCanExecute : getCanExecute , setResult : setResult , getResult : getResult , setExecuted : setExecuted , getExecuted : getExecuted , setWaitingExec : setWaitingExec , getWaitingExec : getWaitingExec , setDeffDepCheck : setDeffDepCheck , getDeffDepCheck : getDeffDepCheck , setHaltExecution : setHaltExecution , execute : execute } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "validates the agent s id according to the validity of the symbols used and the possibility of duplication inside the same agency [CODESPLIT] function validateId ( id ) { if ( id && id . trim ( ) && / ^[a-zA-Z0-9_]+$ / . test ( id ) ) { if ( agency . isIdInUse ( id ) ) { err . name = 'DuplicateIdError' ; err . message = 'duplication (use a different id)' ; return err ; } else { return id ; } } else { err . name = 'ValidateIdError' ; err . message = 'failed id validation (please use alphanumeric characters and underscore)' ; return err ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns a list of unique dependency agents [CODESPLIT] function arrayGetUniques ( arr ) { var a = [ ] ; for ( var i = 0 , l = arr . length ; i < l ; i ++ ) { if ( a . indexOf ( arr [ i ] ) === - 1 && arr [ i ] !== '' ) a . push ( arr [ i ] ) ; } return a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parses the dependency logical expression of each agent and populates the auxiliary structures used by the agency to control the flow of execution [CODESPLIT] function parseExpression ( expr ) { var parentList = [ ] ; var parsedTokenizedExpression = [ ] ; var parsedExpression = '' ; var testInvalidChar ; if ( expr && expr . trim ( ) ) { parsedExpression = expr . replace ( / \\040 / g , '' ) ; testInvalidChar = / [^a-zA-Z0-9_&|!()_] / . test ( parsedExpression ) ; //valid characters if ( ! testInvalidChar ) { var pos = '0' ; var prevprev = '?' ; var prev = '?' ; var head = '' ; var key = '' ; var rbrackets = 0 ; var tmpparent = '' ; var tmpexpression = '' ; // parser rules: // // left hand side of rule determines the rule to apply to the current element of the expression: // //   first element of key indicates the position of the expression element being evaluated: //    1 - first position //    n - other position //   second element of key represents the position before the previous position: //    ? - don't care //    & - logical AND //    | - logical OR //   third element of key represents the previous position on the expression: //    ? - don't care //    ( - opening parenthesis //    # - alpha numeric characters and underscore //    ) - closing parenthesis //    ! - logical NOT // // right hand side of rule represents valid symbols for that key // // example: // //  parsing expression 'a&&b' (one position at a time): //   //  - 'a' element is evaluated by first rule: //    key: 1st position, before previous and previous positions elements don't care //    validation: any alpha numeric character or open parenthesis or underscore or NOT  //  - '&' element is evaluated by the third rule: //    key: (any position but first, indiferent before previous element, any valid previous element) //    validation: any alpha numeric character or closing parenthesis or underscore or AND or OR  //  - '&' element is evaluated by sixth rule: //    key: any position but first, indiferent before previous element, OR previous element //    validation: value has to be '&' //  - 'b' element is evaluated by the seventh rule: //    key: any position but first, '&' before previous element, '&' previous element //    validation: any alpha numeric character or open parenthesis or underscore or NOT or opening parenthesis //   var rules = { '1??' : / [a-zA-Z0-9_(!] / , 'n?(' : / [a-zA-Z0-9_(!] / , 'n?#' : / [a-zA-Z0-9_)&|] / , 'n?!' : / [a-zA-Z0-9_(] / , 'n?)' : / [&|)] / , 'n?&' : / [&] / , 'n&&' : / [a-zA-Z0-9_(!] / , 'n&#' : / [a-zA-Z0-9_)&|] / , 'n&(' : / [a-zA-Z0-9_(!] / , 'n?|' : / [|] / , 'n||' : / [a-zA-Z0-9_(!] / , 'n|(' : / [a-zA-Z0-9_(!] / , 'n|#' : / [a-zA-Z0-9_)&|] / , 'n|&' : / [] / , 'n&|' : / [] / , } ; for ( var i = 0 ; i < parsedExpression . length ; i += 1 ) { pos = ( i === 0 ? '1' : 'n' ) ; head = parsedExpression . charAt ( i ) ; key = pos + prevprev + prev ; if ( ! rules [ key ] . test ( head ) ) { err . code = 'InvalidCharacter' ; err . message = 'failed dependency expression validation (invalid character at position ' + ( i + 1 ) + ')' ; return err ; } if ( head === '(' ) { rbrackets += 1 ; } if ( head === ')' ) { if ( rbrackets <= 0 ) { err . code = 'UnopenedParentheses' ; err . message = 'failed dependency expression validation (unopened parenthesis)' ; return err ; } else { rbrackets -= 1 ; } } // last character if ( i === parsedExpression . length - 1 ) { // ), # -> expression terminators if ( / [a-zA-Z0-9)] / . test ( head ) ) { if ( rbrackets !== 0 ) { err . code = 'UnclosedParentheses' ; err . message = 'failed dependency expression validation (unclosed parenthesis)' ; return err ; } } else { err . code = 'InvalidTerminator' ; err . message = 'failed dependency expression validation (invalid expression terminator)' ; return err ; } } else { if ( prev === '&' || prev === '|' ) { prevprev = prev ; } else { prevprev = '?' ; // ? -> don't care } if ( / [a-zA-Z0-9_] / . test ( head ) ) { prev = '#' ; // # -> valid identifier character } else { prev = head ; } } // handle parent list and tokenized expression if ( / [a-zA-Z0-9_] / . test ( head ) ) { if ( tmpexpression !== '' ) { parsedTokenizedExpression . push ( tmpexpression ) ; tmpexpression = '' ; } if ( parsedExpression . length === 1 ) { if ( id === head ) { err . name = 'SelfDependency' ; err . message = 'failed dependency expression validation (agent self dependency)' ; return err ; } else { parentList . push ( head ) ; parsedTokenizedExpression . push ( head ) ; } } else { if ( i === parsedExpression . length - 1 ) { tmpparent = tmpparent + head ; if ( id === tmpparent ) { err . name = 'SelfDependency' ; err . message = 'failed dependency expression validation (agent self dependency)' ; return err ; } else { parentList . push ( tmpparent ) ; parsedTokenizedExpression . push ( tmpparent ) ; } } else { tmpparent = tmpparent + head ; } } } else { if ( tmpparent !== '' ) { if ( id === tmpparent ) { err . name = 'SelfDependency' ; err . message = 'failed dependency expression validation (agent self dependency)' ; return err ; } else { parentList . push ( tmpparent ) ; parsedTokenizedExpression . push ( tmpparent ) ; tmpparent = '' ; } } tmpexpression = tmpexpression + head ; if ( i === parsedExpression . length - 1 ) { parsedTokenizedExpression . push ( tmpexpression ) ; } } } expression = parsedExpression ; tokenizedExpression = parsedTokenizedExpression ; dependencies = arrayGetUniques ( parentList ) ; } else { err . name = 'InvalidExpression' ; err . message = 'failed dependency expression validation (please use underscore, alphanumeric and logical chars)' ; return err ; } } else { expression = '' ; dependencies = [ ] ; tokenizedExpression = [ ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for function property [CODESPLIT] function setFunction ( f ) { if ( canExecute ) { if ( Object . getPrototypeOf ( f ) === Function . prototype ) { func = f ; jn . logCreationEvent ( id , 'INFO' , 'function definition completed' , ( new Date ( ) ) . toJSON ( ) ) ; } else { setCanExecute ( false ) ; jn . logCreationEvent ( id , 'ERROR' , 'function definition failed' , ( new Date ( ) ) . toJSON ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for callback property [CODESPLIT] function setCallback ( cb ) { if ( canExecute ) { if ( Object . getPrototypeOf ( cb ) === Function . prototype ) { callback = cb ; jn . logCreationEvent ( id , 'INFO' , 'callback definition completed' , ( new Date ( ) ) . toJSON ( ) ) ; } else { setCanExecute ( false ) ; jn . logCreationEvent ( id , 'ERROR' , 'callback definition failed' , ( new Date ( ) ) . toJSON ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets value of a dependency agent s execution ( inter agent communication ) ; wraps a call to the agency method [CODESPLIT] function getValueOfAgent ( dep ) { var len = dependencies . length ; for ( var i = 0 ; i < len ; i ++ ) { if ( dep === dependencies [ i ] ) { return agency . getAgentValue ( dep ) ; } } jn . logExecutionEvent ( id , 'INFO' , 'could not get value of agent ' + dep + ' (not a dependency)' , ( new Date ( ) ) . toJSON ( ) ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "asynchronously executes the agent s function ( wrapper for user defined code ) and the optional corresponding callback following the callback contract : callback ( error data ) ; validates the continuation of the agency in case of error during execution of current agent [CODESPLIT] function execute ( ) { var res ; var functionInterface = { getValueOfAgent : getValueOfAgent } ; if ( func ) { setWaitingExec ( true ) ; setTimeout ( function ( ) { var errorOnExecution = false ; jn . logExecutionEvent ( id , 'INFO' , 'began function execution' , ( new Date ( ) ) . toJSON ( ) ) ; try { res = func ( functionInterface ) ; setResult ( res ) ; if ( callback ) { callback ( null , res ) ; } jn . logExecutionEvent ( id , 'INFO' , 'function executed whitout errors' , ( new Date ( ) ) . toJSON ( ) ) ; } catch ( err ) { errorOnExecution = true ; setResult ( err ) ; jn . logExecutionEvent ( id , 'ERROR' , 'failed to execute function: ' + err . message , ( new Date ( ) ) . toJSON ( ) ) ; if ( callback ) { callback ( err ) ; } } setExecuted ( true ) ; setWaitingExec ( false ) ; if ( haltsExecution && errorOnExecution ) { jn . logExecutionEvent ( id , 'ERROR' , 'error on execution halted agency execution' , ( new Date ( ) ) . toJSON ( ) ) ; agency . report ( ) ; } else { agency . runAgents ( ) ; } } , 0 ) ; } else { jn . logExecutionEvent ( id , 'INFO' , 'does not have a defined function' , ( new Date ( ) ) . toJSON ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new Case with the given parent and definition . [CODESPLIT] function Case ( parent , definition ) { var key ; for ( key in updateMixin ) { this [ key ] = updateMixin [ key ] ; } Case . super_ . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The returned Promise is resolved with null if another showPanel () gets called while this . panel ( panelName ) Promise is in flight . [CODESPLIT] function ( panelName ) { if ( this . _currentPanelLocked ) { if ( this . _currentPanel !== this . _panels [ panelName ] ) return Promise . reject ( new Error ( \"Current panel locked\" ) ) ; return Promise . resolve ( this . _currentPanel ) ; } this . _panelForShowPromise = this . panel ( panelName ) ; return this . _panelForShowPromise . then ( setCurrentPanelIfNecessary . bind ( this , this . _panelForShowPromise ) ) ; /**\n         * @param {!Promise.<!WebInspector.Panel>} panelPromise\n         * @param {!WebInspector.Panel} panel\n         * @return {?WebInspector.Panel}\n         * @this {WebInspector.InspectorView}\n         */ function setCurrentPanelIfNecessary ( panelPromise , panel ) { if ( this . _panelForShowPromise !== panelPromise ) return null ; this . setCurrentPanel ( panel ) ; return panel ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new Resource with the given parent and definition . [CODESPLIT] function Resource ( parent , definition ) { this . parent = parent ; this . definition = definition ; // add mixins this . _link = linkMixin ; this . _setup ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes the url to the tournament or flight [CODESPLIT] function scopeUrl ( options , inst ) { options = _ . extend ( _ . clone ( options || { } ) , inst ) var url = config . urls && config . urls . sports || config . url url = ngin . Season . urlRoot ( ) + '/' + options . season_id + '/teams/' + options . team_id + '/rosters' if ( options . id ) url += '/' + options . id return url }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "from d - m - y h : i : s [CODESPLIT] function ( ctx ) { var DMYRegex = / ^([0-9]{1,2})[\\.\\-\\/]([0-9]{1,2})[\\.\\-\\/]([0-9]{4,4})\\s([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}) / gi ; var regexmatch = DMYRegex . exec ( ctx . value ) ; if ( ! regexmatch || regexmatch . length !== 7 ) { return console . log ( 'valdiation error -- not DMY' , ctx ) ; } var datetime = [ [ regexmatch [ 3 ] , regexmatch [ 2 ] , regexmatch [ 1 ] ] . join ( '-' ) , [ regexmatch [ 4 ] , regexmatch [ 5 ] , regexmatch [ 6 ] ] . join ( ':' ) ] . join ( ' ' ) ; var date = new Date ( datetime ) ; ctx . value = date . getTime ( ) ; return ctx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OK . [CODESPLIT] function ( result ) { var body = JSON . parse ( result . body ) ; // console.log(body); return exits . success ( inputs . id ? { item : body [ inputs . model ] } : { items : body [ inputs . model ] , count : body . listcount } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns empty [] if arrayToSearchFor isn t found . if arrayToSearchFor contains objects this will always return empty array . [CODESPLIT] function getIndexesOfArray ( arrayToSearchFor , arrayToSearchInside ) { errorIfNotArray_1 . errorIfNotArray ( arrayToSearchFor ) ; error_if_not_populated_array_1 . errorIfNotPopulatedArray ( arrayToSearchInside ) ; var indexes = [ ] ; arrayToSearchInside . filter ( function ( value , index ) { if ( isArray_notArray_1 . isArray ( value ) && arrays_match_1 . arraysMatch ( value , arrayToSearchFor ) ) { indexes . push ( index ) ; return true ; } else return false ; } ) ; return indexes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为零 [CODESPLIT] function _isZero ( val , options ) { var opts = _isObject ( options ) ? options : { } ; if ( _isNumber ( val ) ) { return val - 0 === 0 ; } if ( opts . isStrict !== true ) { return _isRealNumber ( val ) && val - 0 === 0 ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a properly formatted container slug . [CODESPLIT] function containerSlug ( language_slug , project_slug , resource_slug ) { if ( ! language_slug || ! project_slug || ! resource_slug ) throw new Error ( 'Invalid resource container slug parameters' ) ; return language_slug + '_' + project_slug + '_' + resource_slug ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents an instance of a resource container . [CODESPLIT] function Container ( container_directory , package_json ) { let config_yaml = { } ; let toc_yaml = { } ; assert ( container_directory , 'resource-container: missing container_directory' ) ; assert . equal ( typeof container_directory , 'string' , 'resource-container: container_directory should be a string' ) ; try { let configFile = path . join ( container_directory , content_dir , 'config.yml' ) ; if ( fileUtils . fileExists ( configFile ) ) config_yaml = YAML . parse ( fs . readFileSync ( configFile , { encoding : 'utf8' } ) ) ; } catch ( err ) { console . warn ( err ) ; } try { let tocFile = path . join ( container_directory , content_dir , 'toc.yml' ) ; if ( fileUtils . fileExists ( tocFile ) ) toc_yaml = YAML . parse ( fs . readFileSync ( tocFile , { encoding : 'utf8' } ) ) ; } catch ( err ) { console . warn ( err ) ; } assert ( package_json , 'resource-container: missing package json' ) ; assert ( package_json . language , 'resource-container: missing language' ) ; assert ( package_json . project , 'resource-container: missing project' ) ; assert ( package_json . resource , 'resource-container: missing resource' ) ; assert ( package_json . resource . type , 'resource-container: missing resource type' ) ; return { get language ( ) { return package_json . language ; } , get project ( ) { return package_json . project ; } , get resource ( ) { return package_json . resource ; } , /**\n         * Returns an array of chapters in this resource container\n         */ chapters : function ( ) { let dir = path . join ( container_directory , content_dir ) ; return fs . readdirSync ( dir ) . filter ( function ( file ) { try { return fs . statSync ( file ) . isDirectory ( ) ; } catch ( err ) { console . log ( err ) ; return false ; } } ) ; } , /**\n         * Returns an array of chunks in the chapter\n         */ chunks : function ( chapterSlug ) { let dir = path . join ( container_directory , content_dir , chapterSlug ) ; return fs . readdirSync ( dir ) . filter ( function ( file ) { try { return fs . statSync ( file ) . isFile ( ) ; } catch ( err ) { console . log ( err ) ; return false ; } } ) ; } , /**\n         * Returns the contents of a chunk.\n         * If the chunk does not exist or there is an exception an empty string will be returned.\n         * @param chapterSlug\n         * @param chunkSlug\n         * @returns string the contents of the chunk\n         */ readChunk : function ( chapterSlug , chunkSlug ) { let file = path . join ( container_directory , content_dir , chapterSlug , chunkSlug + '.' + this . chunkExt ) ; return fs . readFileSync ( file , { encoding : 'utf8' } ) ; } , /**\n         * Returns the file extension to use for content files (chunks)\n         * @returns {*}\n         */ get chunkExt ( ) { switch ( package_json [ 'content_mime_type' ] ) { case 'text/usx' : return 'usx' ; case 'text/usfm' : return 'usfm' ; case 'text/markdown' : return 'md' ; default : return 'txt' ; } } , /**\n         * Returns the path to the resource container directory\n         * @returns {string}\n         */ get path ( ) { return container_directory ; } , /**\n         * Returns the slug of the resource container\n         * @returns {string}\n         */ get slug ( ) { return containerSlug ( package_json . language . slug , package_json . project . slug , package_json . resource . slug ) ; } , /**\n         * Returns the type of the resource container.\n         * Shorthand for info.resource.type\n         * @returns {string}\n         */ get type ( ) { return package_json . resource . type ; } , /**\n         * Returns the resource container package information.\n         * This is the package.json file\n         * @returns {{}}\n         */ get info ( ) { return package_json ; } , /**\n         * Returns the resource container data configuration.\n         * This is the config.yml file under the content/ directory\n         *\n         * @returns {{}}\n         */ get config ( ) { return config_yaml ; } , /**\n         * Returns the table of contents.\n         * This is the toc.yml file under the content/ directory\n         *\n         * @returns {{}|[]}\n         */ get toc ( ) { return toc_yaml ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of chapters in this resource container [CODESPLIT] function ( ) { let dir = path . join ( container_directory , content_dir ) ; return fs . readdirSync ( dir ) . filter ( function ( file ) { try { return fs . statSync ( file ) . isDirectory ( ) ; } catch ( err ) { console . log ( err ) ; return false ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the contents of a chunk . If the chunk does not exist or there is an exception an empty string will be returned . [CODESPLIT] function ( chapterSlug , chunkSlug ) { let file = path . join ( container_directory , content_dir , chapterSlug , chunkSlug + '.' + this . chunkExt ) ; return fs . readFileSync ( file , { encoding : 'utf8' } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new resource container . Rejects with an error if the container exists . [CODESPLIT] function makeContainer ( container_directory , opts ) { return new Promise ( function ( resolve , reject ) { if ( fileUtils . fileExists ( container_directory ) ) { reject ( new Error ( 'Container already exists' ) ) ; return ; } let package_json = { } ; // TODO: build the container reject ( new Error ( 'Not implemented yet.' ) ) ; // resolve(new Container(container_directory, package_json)); } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens an archived resource container . If the container is already opened it will be loaded [CODESPLIT] function openContainer ( container_archive , container_directory , opts ) { opts = opts || { compression_method : 'tar' } ; if ( fileUtils . fileExists ( container_directory ) ) { return loadContainer ( container_directory ) ; } if ( ! fileUtils . fileExists ( container_archive ) ) return Promise . reject ( new Error ( 'Missing resource container' ) ) ; if ( opts . compression_method === 'zip' ) { return compressionUtils . unzip ( container_archive , container_directory ) . then ( function ( dir ) { return loadContainer ( dir ) ; } ) ; } else { return compressionUtils . untar ( container_archive , container_directory ) . then ( function ( dir ) { return loadContainer ( dir ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes ( archives ) a resource container . [CODESPLIT] function closeContainer ( container_directory , opts ) { opts = opts || { compression_method : 'tar' , clean : true } ; if ( ! fileUtils . fileExists ( container_directory ) ) return Promise . reject ( new Error ( 'Missing resource container' ) ) ; var container_archive = container_directory + '.' + spec . file_ext ; var compressPromise = Promise . resolve ( container_archive ) ; // create archive if it's missing if ( ! fileUtils . fileExists ( container_archive ) ) { if ( opts . compression_method === 'zip' ) { compressPromise = compressionUtils . zip ( container_directory , container_archive ) ; } else { compressPromise = compressionUtils . tar ( container_directory , container_archive ) ; } } return compressPromise . then ( function ( path ) { // remove directory if ( opts . clean ) rimraf . sync ( container_directory ) ; return Promise . resolve ( path ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a localized chapter title . e . g . Chapter 1 If the language does not have a match a default localization will be used . [CODESPLIT] function localizeChapterTitle ( language_slug , chapter_number ) { var translations = { 'ar' : 'الفصل %',  'en' : 'Chapter %' , 'ru' : 'Глава %',  'hu' : '%. fejezet' , 'sr-Latin' : 'Поглавље %',  'default' : 'Chapter %' } ; var title = translations [ language_slug ] ; if ( ! title ) title = translations [ 'default' ] ; var num = parseInt ( chapter_number ) ; if ( isNaN ( num ) ) num = chapter_number ; return title . replace ( '%' , num ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pads a slug to 2 significant digits . Examples : 1 - > 01 001 - > 01 12 - > 12 123 - > 123 0123 - > 123 Words are not padded : a - > a 0word - > 0word And as a matter of consistency : 0 - > 00 00 - > 00 [CODESPLIT] function normalizeSlug ( slug ) { if ( typeof slug !== 'string' ) throw new Error ( 'slug must be a string' ) ; if ( slug === '' ) throw new Error ( 'slug cannot be an empty string' ) ; if ( isNaN ( Number ( slug ) ) ) return slug ; slug = slug . replace ( / ^(0+) / , '' ) . trim ( ) ; while ( slug . length < 2 ) { slug = '0' + slug ; } return slug ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the resource container info without opening it . This will however work on containers that are both open and closed . [CODESPLIT] function inspectContainer ( container_path , opts ) { return new Promise ( function ( resolve , reject ) { if ( path . extname ( container_path ) !== '.' + spec . file_ext ) { reject ( new Error ( 'Invalid resource container file extension' ) ) ; return ; } try { resolve ( fs . statSync ( container_path ) . isFile ( ) ) ; } catch ( err ) { reject ( new Error ( 'The resource container does not exist at' , container_path ) ) ; } } ) . then ( function ( isFile ) { if ( isFile ) { // TODO: For now we are just opening the container then closing it. // Eventually it would be nice if we can inspect the archive without extracting everything. let containerDir = path . join ( path . dirname ( container_path ) , path . basename ( container_path , '.' + spec . file_ext ) ) ; return openContainer ( container_path , containerDir , opts ) . then ( function ( container ) { return closeContainer ( containerDir , opts ) . then ( function ( ) { return Promise . resolve ( container . info ) ; } ) ; } ) ; } else { loadContainer ( container_path ) . then ( function ( container ) { return Promise . resolve ( container . info ) ; } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes the url to the tournament or flight [CODESPLIT] function scopeUrl ( options , inst , action ) { var opts = _ . extend ( { } , inst , options ) if ( ! opts . id && ! opts . tournament_id && ! opts . league_id && ! opts . season_id ) throw new Error ( 'id, season_id, tournament_id or league_id required to make survey api calls' ) return Survey . urlRoot ( ) + '/' + action + ( opts . id ? '/' + opts . id : '' ) + '.json' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the widths of the table including the positions of the column resizers . IMPORTANT : This function MUST be called once after the element of the DataGrid is attached to its parent element and every subsequent time the width of the parent element is changed in order to make it possible to resize the columns . If this function is not called after the DataGrid is attached to its parent element then the DataGrid s columns will not be resizable . [CODESPLIT] function ( ) { var headerTableColumns = this . _headerTableColumnGroup . children ; // Use container size to avoid changes of table width caused by change of column widths. var tableWidth = this . element . offsetWidth - this . _cornerWidth ; var numColumns = headerTableColumns . length - 1 ; // Do not process corner column. // Do not attempt to use offsetes if we're not attached to the document tree yet. if ( ! this . _columnWidthsInitialized && this . element . offsetWidth ) { // Give all the columns initial widths now so that during a resize, // when the two columns that get resized get a percent value for // their widths, all the other columns already have percent values // for their widths. for ( var i = 0 ; i < numColumns ; i ++ ) { var columnWidth = this . headerTableBody . rows [ 0 ] . cells [ i ] . offsetWidth ; var column = this . _visibleColumnsArray [ i ] ; if ( ! column . weight ) column . weight = 100 * columnWidth / tableWidth ; } this . _columnWidthsInitialized = true ; } this . _applyColumnWeights ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new UserPreference with the given parent and definition . [CODESPLIT] function UserPreference ( parent , definition ) { var key ; for ( key in updateMixin ) { this [ key ] = updateMixin [ key ] ; } UserPreference . super_ . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a Crafty server instance with net features enabled . <br / > Each server instance shall have an unique <code > room< / code > name . Only client and server instances within the same <code > room< / code > can talk to each other . <br / > This method also set s the server instance s [ label ] { @link module : npm_crafty . net #PeerLabel } to <code > SERVER < / code > . [CODESPLIT] function ( room , sockets ) { // create a new crafty instance var Crafty = craftyLib ( ) ; // add net features to crafty craftyNet . __addNet ( Crafty , \"SERVER\" , room ) ; // initialize server send list craftyNet . __setServerOutputSockets ( Crafty , sockets ) ; return Crafty ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a client <code > socket< / code > to the Crafty server instance . The Crafty net features will use this <code > socket< / code > to communicate with the client . [CODESPLIT] function ( Crafty , socket ) { // add client to receive list craftyNet . __setInputSocket ( Crafty , socket ) ; // add client to send list craftyNet . __addOutputSocket ( Crafty , socket ) ; return Crafty ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a client <code > socket< / code > from the Crafty server instance . The Crafty net features will no longer use this <code > socket< / code > to communicate with the client . [CODESPLIT] function ( Crafty , socket ) { // add client to receive list craftyNet . __unsetInputSocket ( Crafty , socket ) ; // add client to send list craftyNet . __removeOutputSocket ( Crafty , socket ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Server API . <br / > Can be constructed with this constructor or by calling the [ default setup method ] { @link module : npm_crafty . server ~Server . setupDefault } . After construction various methods are available for creating a crafty server instance with net features and for connecting these net features to socket . io . <br / > Also offers a static method for [ automatic matchmaking ] ( module : npm_crafty . server ~Server . MatchMaker ) . <br / > The <code > sockets< / code > parameter contains the Socket . IO namespace to use for all Crafty related data . [CODESPLIT] function Server ( sockets ) { return { createInstance : function ( room ) { return createInstance ( room , sockets ) ; } , addClient : addClient , removeClient : removeClient } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup a default node server which will serve npm_crafty s required files ( it will reply to GET requests ) . <br / > Each callback will be called at the appropriate times . Communication will be set to the default <code > / < / code > namespace . [CODESPLIT] function ( immediateFN , connectFN , disconnectFN , port ) { var app = require ( 'express' ) ( ) , server = require ( 'http' ) . createServer ( app ) , io = require ( 'socket.io' ) . listen ( server ) , path = require ( 'path' ) , browserify = require ( 'browserify-middleware' ) ; io . set ( 'log level' , 2 ) ; server . listen ( port || process . env . PORT || 80 ) ; var browserifyOptions = { } ; browserifyOptions [ path . join ( __dirname + '/npm_crafty.client.js' ) ] = { expose : 'npm_crafty' } ; app . get ( '/npm_crafty.js' , browserify ( [ browserifyOptions ] ) ) ; app . get ( '/crafty_client.js' , function ( req , res ) { res . sendfile ( path . join ( __dirname + '/crafty_client.js' ) ) ; } ) ; io . sockets . on ( 'connection' , function ( socket ) { console . log ( \"Connected \" , socket . id ) ; connectFN ( socket ) ; socket . on ( 'disconnect' , function ( arg ) { console . log ( \"Disconnected \" , socket . id ) ; disconnectFN ( socket ) ; } ) ; } ) ; process . nextTick ( immediateFN ) ; var _server = new Server ( io . sockets ) ; _server . app = app ; _server . server = server ; _server . io = io ; return _server ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CRUD Aliases [CODESPLIT] function _create ( crud , schema , data ) { if ( data . _id ) delete data . _id ; //This is a mongodb thing. if ( data [ schema . primaryKey ] ) delete data [ schema . primaryKey ] ; if ( schema . storageType !== \"gcs\" ) { data = _scrubDatum ( schema , data ) ; } return crud . execute ( schema , crud . operations . CREATE , data ) . then ( function ( result ) { if ( schema . storageType === \"gcs\" ) { return result ; } else { data [ schema . primaryKey ] = result . insertId ; var r = _transformDatum ( schema , data ) ; return r ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "replaces { id } tokens [CODESPLIT] function replace ( format , data ) { return format . replace ( / {(\\w+)} / g , ( m , name ) => ( data [ name ] ? data [ name ] : '' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eslint - disable - line [CODESPLIT] function highlight ( code , lang ) { const g = Prism . languages [ lang ] ; if ( g ) { return Prism . highlight ( code , g , lang ) ; } return code ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an updater function for the esprima transform with the given error handler [CODESPLIT] function getUpdater ( errorFn ) { errorFn = errorFn || new Function ( ) ; return updater ; /**\n   * The updater function for the esprima transform\n   * @param {string} file The filename for the Browserify transform\n   * @param {object} ast The esprima syntax tree\n   * @returns {object} The transformed esprima syntax tree\n   */ function updater ( file , ast ) { if ( ast . comments ) { ast . comments . filter ( testDocTag ) . map ( getAnnotatedNode ) . concat ( inferAngular ( ast ) ) // find the items that are not explicitly annotated . filter ( testFirstOccurrence ) // ensure unique values . forEach ( processNode ) ; } else { errorFn ( 'Esprima AST is required to have top-level comments array' ) ; } return ast ; } /**\n   * Get the node that is annotated by the comment or throw if not present.\n   * @throws {Error} Where comment does not annotate a node\n   * @param {object} comment The comment node\n   */ function getAnnotatedNode ( comment ) { // find the first function declaration or expression following the annotation var result ; if ( comment . annotates ) { var candidateTrees ; // consider the context the block is in (i.e. what is its parent) var parent = comment . annotates . parent ; // consider nodes from the annotated node forward //  include the first non-generated node and all generated nodes preceding it if ( testNode . isBlockOrProgram ( parent ) ) { var body = parent . body ; var index = body . indexOf ( comment . annotates ) ; var candidates = body . slice ( index ) ; var length = candidates . map ( testNode . isGeneratedCode ) . indexOf ( false ) + 1 ; candidateTrees = candidates . slice ( 0 , length || candidates . length ) ; } // otherwise we can only consider the given node else { candidateTrees = [ comment . annotates ] ; } // try the nodes while ( ! result && candidateTrees . length ) { result = esprimaTools . orderNodes ( candidateTrees . shift ( ) ) . filter ( testNode . isFunctionNotIFFE ) . shift ( ) ; } } // throw where not valid if ( result ) { return result ; } else { errorFn ( 'Doc-tag @ngInject does not annotate anything' ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The updater function for the esprima transform [CODESPLIT] function updater ( file , ast ) { if ( ast . comments ) { ast . comments . filter ( testDocTag ) . map ( getAnnotatedNode ) . concat ( inferAngular ( ast ) ) // find the items that are not explicitly annotated . filter ( testFirstOccurrence ) // ensure unique values . forEach ( processNode ) ; } else { errorFn ( 'Esprima AST is required to have top-level comments array' ) ; } return ast ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the node that is annotated by the comment or throw if not present . [CODESPLIT] function getAnnotatedNode ( comment ) { // find the first function declaration or expression following the annotation var result ; if ( comment . annotates ) { var candidateTrees ; // consider the context the block is in (i.e. what is its parent) var parent = comment . annotates . parent ; // consider nodes from the annotated node forward //  include the first non-generated node and all generated nodes preceding it if ( testNode . isBlockOrProgram ( parent ) ) { var body = parent . body ; var index = body . indexOf ( comment . annotates ) ; var candidates = body . slice ( index ) ; var length = candidates . map ( testNode . isGeneratedCode ) . indexOf ( false ) + 1 ; candidateTrees = candidates . slice ( 0 , length || candidates . length ) ; } // otherwise we can only consider the given node else { candidateTrees = [ comment . annotates ] ; } // try the nodes while ( ! result && candidateTrees . length ) { result = esprimaTools . orderNodes ( candidateTrees . shift ( ) ) . filter ( testNode . isFunctionNotIFFE ) . shift ( ) ; } } // throw where not valid if ( result ) { return result ; } else { errorFn ( 'Doc-tag @ngInject does not annotate anything' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to report errors [CODESPLIT] function locationStr ( runtime , line ) { var loc ; loc = 'line: ' + ( line !== undefined ? line : runtime . lineNumber ) ; if ( runtime . file ) { loc += ' -- file: ' + runtime . file ; } return loc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为座机号码 [CODESPLIT] function _isTelephone ( val , locale ) { var key = _isString ( locale ) ? locale : LOCALE_ENUM . ZHCN ; var rex = REGEX_ENUM . TELEPHONE_REX [ key ] ; if ( ! rex ) { return false ; } if ( ! _isString ( val ) ) { return false ; } return rex . test ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new Macro with the given parent and definition . [CODESPLIT] function Macro ( parent , definition ) { var key ; for ( key in updateMixin ) { this [ key ] = updateMixin [ key ] ; } this . destroy = destroyMixin ; Macro . super_ . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Quick sort an array . [CODESPLIT] function quickSort ( a , l , h , k , c ) { const s = [ ] ; let t = 0 ; s [ t ++ ] = l ; s [ t ++ ] = h ; while ( t > 0 ) { h = s [ -- t ] ; l = s [ -- t ] ; if ( h - l > k ) { const p = partition ( a , l , h , c ) ; if ( p > l ) { s [ t ++ ] = l ; s [ t ++ ] = p ; } if ( p + 1 < h ) { s [ t ++ ] = p + 1 ; s [ t ++ ] = h ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Select the pivot element using the median - of - three rule . [CODESPLIT] function pivot ( a , l , h , c ) { const p = ( l + ( ( h - l ) / 2 ) ) | 0 ; if ( c ( a [ h ] , a [ l ] ) < 0 ) { [ a [ l ] , a [ h ] ] = [ a [ h ] , a [ l ] ] ; } if ( c ( a [ p ] , a [ l ] ) < 0 ) { [ a [ l ] , a [ p ] ] = [ a [ p ] , a [ l ] ] ; } if ( c ( a [ h ] , a [ p ] ) < 0 ) { [ a [ h ] , a [ p ] ] = [ a [ p ] , a [ h ] ] ; } return p ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Partition a subarray according to the Hoare partitioning scheme . [CODESPLIT] function partition ( a , l , h , c ) { const p = a [ pivot ( a , l , h , c ) ] ; let i = l - 1 ; let j = h + 1 ; for ( ; ; ) { do { i ++ ; } while ( c ( a [ i ] , p ) < 0 ) ; do { j -- ; } while ( c ( a [ j ] , p ) > 0 ) ; if ( i < j ) { [ a [ i ] , a [ j ] ] = [ a [ j ] , a [ i ] ] ; } else { return j ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insertion sort an array . [CODESPLIT] function insertionSort ( a , l , h , c ) { for ( let i = l + 1 ; i <= h ; i ++ ) { const x = a [ i ] ; let j = i - 1 ; while ( j >= 0 && c ( a [ j ] , x ) > 0 ) { a [ j + 1 ] = a [ j ] ; j -- ; } a [ j + 1 ] = x ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches a resource . [CODESPLIT] function search ( parent , baseUrl , callback ) { var resource = new ( getResource ( 'page' ) ) ( parent , { _links : { self : { href : baseUrl , 'class' : 'page' } } } ) ; if ( typeof callback == 'function' ) return resource . exec ( callback ) ; return resource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main entrance function will create PipeStream or joined pipe based on input [CODESPLIT] function createPipeStream ( cmd /*, args, opts*/ ) { var proc ; var command ; if ( Array . isArray ( cmd ) ) { // We have an array so create a pipe from all elements var firstCmd = cmd . shift ( ) ; var open = Array . isArray ( firstCmd ) ? createPipeStream . apply ( { } , firstCmd ) : createPipeStream ( firstCmd ) ; cmd . forEach ( function ( p ) { open = open . pipe ( p ) ; } ) ; return open ; } else if ( cmd instanceof EventEmitter ) { // Take the eventemitter as base proc = cmd ; command = 'pre-defined' ; } else if ( typeof cmd === 'object' ) { throw new TypeError ( 'Invalid input, expected object type -> EventEmitter' ) ; } else { // We have input for Spawn command, normalize the input and create spawn var input = utils . normalizeInput . apply ( this , arguments ) ; command = utils . getCommand ( input ) ; proc = spawn . apply ( { } , input ) ; } // Create inner pointer for command proc . _command = command ; // Check if process is still alive if ( proc . exitCode ) { throw new Error ( 'Process already dead' ) ; } return PipeStream ( proc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function for adding PipeStream functionality to an EventEmitter @param { EventEmitter } self [CODESPLIT] function PipeStream ( self ) { // Inner pipeline handle self . _pipeline = [ self ] ; // Inner position handle self . _nr = 0 ; // Modify object wrapMethods ( self ) ; addFunctions ( self ) ; connectEvents ( self ) ; addEventHandlers ( self ) ; return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function for wrapping default EventEmitter functions to return itself [CODESPLIT] function wrapMethods ( self ) { var methods = [ 'on' ] ; var childObjects = [ 'stdin' , 'stdout' , 'stderr' ] ; // Wrap on method methods . forEach ( function ( m ) { var old = self [ m ] ; self [ m ] = function ( ) { old . apply ( self , arguments ) ; return self ; } ; } ) ; // If its a spawn object then wrap child EventEmitters if ( utils . isSpawn ( self ) ) { childObjects . forEach ( function ( child ) { methods . forEach ( function ( m ) { var old = self [ child ] [ m ] ; self [ child ] [ m ] = function ( ) { old . apply ( self [ child ] , arguments ) ; return self ; } ; } ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds extra functionality to EventEmitter [CODESPLIT] function addFunctions ( self ) { // Function for assigning a process to run after the end of this PipeStream self . and = function ( ) { self . _and = new ShellStream ( arguments ) ; self . on ( 'exit' , function ( code ) { if ( code !== 0 ) { self . emit ( 'error' , code ) ; return ; } self . _and = self . _and . run ( ) ; } ) ; return self . _and ; } ; var oldPipe = self . pipe ? self . pipe . bind ( self ) : false ; // Function for adding a new pipe to the pipeline self . pipe = function ( ) { // Create pipe and add it to the pipeline hierarchy self . _pipe = createPipeStream . apply ( { } , arguments ) ; self . _pipe . _parent = self ; self . _addPipe ( self . _pipe ) ; self . _pipe . _pipeline = self . _pipeline ; // Pipe the necessary data events to the new PipeStream if ( utils . isSpawn ( self ) ) { self . stdout . pipe ( utils . isSpawn ( self . _pipe ) ? self . _pipe . stdin : self . _pipe ) ; self . stderr . on ( 'data' , function ( d ) { self . _pipe . emit ( 'error' , d ) ; } ) ; } else { if ( utils . isSpawn ( self . _pipe ) ) { oldPipe ( self . _pipe . stdin ) ; self . on ( 'error' , function ( d ) { self . _pipe . stderr . emit ( 'data' , d ) ; } ) ; } else { oldPipe ( self . _pipe ) ; self . on ( 'error' , function ( d ) { self . _pipe . emit ( 'error' , d ) ; } ) ; } } // return new PipeStream return self . _pipe ; } ; // Internal function for appending a PipeStream to pipeline Object . defineProperty ( self , '_addPipe' , { value : function ( pipe ) { self . _pipeline . push ( pipe ) ; pipe . _nr = self . _pipeline . length - 1 ; pipe . _error = self . _error ; } } ) ; // Internal function for destroying the whole pipeline Object . defineProperty ( self , '_cleanUp' , { value : function ( ) { this . _pipeline . forEach ( function ( p ) { p . _error = null ; // Make sure error is called only once. if ( p . kill ) { p . kill ( ) ; } else if ( p . destroy ) { p . destroy ( ) ; } } ) ; } } ) ; // Function for retrieving the pipeline beginning self . first = function ( ) { return self . get ( 0 ) ; } ; // Function for retrieving the pipeline end self . last = function ( ) { return self . get ( self . _pipeline . length - 1 ) ; } ; // Function for retrieving the nth element in pipeline self . get = function ( n ) { return self . _pipeline [ n ] || false ; } ; // Function for appending an error handler for all elements in pipeline self . error = function ( fn ) { self . _pipeline . forEach ( function ( section ) { section . _error = fn ; } ) ; return self ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function for connecting some events [CODESPLIT] function connectEvents ( self ) { if ( self . stdout ) { self . stdout . on ( 'data' , function ( d ) { self . emit ( 'data' , d ) ; } ) ; self . stderr . on ( 'data' , function ( d ) { self . emit ( 'error' , d ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function for adding internal event handlers [CODESPLIT] function addEventHandlers ( self ) { self . on ( 'error' , function ( d ) { var fn = self . _error ; self . _cleanUp ( ) ; if ( fn ) { fn ( 'pipeline[' + self . _nr + ']:\"' + self . _command + '\" failed with: ' + d . toString ( ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal target resolver [CODESPLIT] function _resolve ( routes , path , req , res ) { return Q . fcall ( function ( ) { path = path || [ ] ; var obj = routes ; // Resolve promises first if ( IS . obj ( obj ) && IS . fun ( obj . then ) ) { var p = obj . then ( function ( ret ) { return _resolve ( ret , path , req , res ) ; } ) ; return p ; } // Resolve functions first if ( IS . fun ( obj ) ) { var p2 = Q . when ( obj ( req , res ) ) . then ( function ( ret ) { return _resolve ( ret , path , req , res ) ; } ) ; return p2 ; } // If the resource is undefined, return flags.notFound (resulting to a HTTP error 404). if ( obj === undefined ) { return flags . notFound ; } // If path is at the end, then return the current resource. if ( path . length === 0 ) { return obj ; } // Handle arrays if ( IS . array ( obj ) ) { var k = path [ 0 ] , n = parseInt ( path . shift ( ) , 10 ) ; if ( k === \"length\" ) { return _resolve ( obj . length , path . shift ( ) , req , res ) ; } if ( k !== \"\" + n ) { return Q . fcall ( function ( ) { throw new errors . HTTPError ( { 'code' : 400 , 'desc' : 'Bad Request' } ) ; } ) ; } return _resolve ( obj [ n ] , path . shift ( ) , req , res ) ; } // Handle objects if ( IS . obj ( obj ) ) { var k2 = path [ 0 ] ; if ( obj [ k2 ] === undefined ) { return flags . notFound ; } if ( ! obj . hasOwnProperty ( k2 ) ) { return Q . fcall ( function ( ) { throw new errors . HTTPError ( { 'code' : 403 , 'desc' : 'Forbidden' } ) ; } ) ; } return _resolve ( obj [ path . shift ( ) ] , path , req , res ) ; } // Returns notFound because we still have keys in the path but nowhere to go. return flags . notFound ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse target [CODESPLIT] function do_parse_url ( url ) { var s = require ( 'url' ) . parse ( url ) . pathname . replace ( / [^a-zA-Z0-9_\\-\\+\\.]+ / g , \"/\" ) . replace ( / ^\\/+ / , \"\" ) ; if ( s . length === 0 ) { return [ ] ; } return s . split ( \"/\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Link handles the _links part of the HAL response and sets up the associations . It is used by the client to setup the initial resources like users cases and so on as well as by the resource object itself for sub resources ( cases () . replies () ) . [CODESPLIT] function link ( definition ) { var key , link , newResource , Resource ; if ( '_links' in definition ) { for ( key in definition . _links ) { if ( key === 'self' ) continue ; link = definition . _links [ key ] ; key = key . charAt ( 0 ) + inflection . camelize ( key ) . slice ( 1 ) ; // resources like next, previous can be null if ( link === null ) { this [ key ] = _buildFunction ( null ) ; continue ; } // this is a really ugly hack but necessary for sub resources which aren't declared consistently if ( inflection . singularize ( key ) !== key && link [ 'class' ] === inflection . singularize ( key ) ) link [ 'class' ] = 'page' newResource = new ( getResource ( link [ 'class' ] ) ) ( this , { _links : { self : link } } ) ; this [ key ] = _buildFunction ( newResource ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the function for the resource . [CODESPLIT] function _buildFunction ( resource ) { return function ( callback ) { if ( typeof callback == 'function' ) { if ( resource !== null ) return resource . exec . call ( resource , callback ) ; else return callback ( null , null ) ; } return resource ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为 负整数 [CODESPLIT] function _isNegativeInteger ( val , options ) { var opts = _isObject ( options ) ? options : { } ; if ( opts . isStrict === true ) { return _isNumber ( val ) && REGEX_ENUM . NEGATIVE_INTEGER_REX . test ( val ) ; } return REGEX_ENUM . NEGATIVE_INTEGER_REX . test ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "see : http : // 115 . 236 . 113 . 201 / doc / nos_user_manual / _build / html / accessControl . html#head generate signature [CODESPLIT] function generateSignature ( secretKey , method , contentMd5 , contentType , date , canonicalizedHeaders , canonicalizedResource ) { var hmac = _crypto2 . default . createHmac ( SHA256 , secretKey ) ; var headers = canonicalizedHeaders . map ( function ( header ) { return header . toLowerCase ( ) ; } ) . sort ( ) . join ( '\\n' ) ; var data = method + '\\n' + contentMd5 + '\\n' + contentType + '\\n' + date + '\\n' ; if ( headers && headers . length ) { data += headers + '\\n' ; } data += canonicalizedResource ; hmac . update ( data ) ; return hmac . digest ( ENCODING ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "读取对象内容 [CODESPLIT] function getObject ( host , accessKey , secretKey , bucket , objectKey ) { var expires = arguments . length <= 5 || arguments [ 5 ] === undefined ? 0 : arguments [ 5 ] ; var opts = arguments . length <= 6 || arguments [ 6 ] === undefined ? { } : arguments [ 6 ] ; var date = utcDate ( ) ; if ( opts . versionId ) url += '?versionId=' + opts . versionId ; var resource = genResource ( bucket , objectKey , ( 0 , _lodash . pick ) ( opts , [ 'versionId' ] ) ) ; var signature = encodeURIComponent ( generateSignature ( secretKey , 'GET' , '' , '' , expires , [ ] , resource ) ) ; var url = pub ? 'http://' + bucket + '.' + host + '/' + objectKey : 'http://' + host + '/' + bucket + '/' + objectKey + '?NOSAccessKeyId=' + accessKey + '&Expires=' + expires + '&Signature=' + signature ; var headers = { Date : date } ; if ( opts . range ) headers . Range = opts . range ; if ( opts . modifiedSince ) headers [ 'If-Modified-Since' ] = opts . modifiedSince ; headers [ 'url' ] = url ; return nosRequest ( { method : 'get' , headers : headers , uri : url } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取对象相关元数据信息 [CODESPLIT] function getMeta ( host , accessKey , secretKey , bucket , objectKey ) { var expires = arguments . length <= 5 || arguments [ 5 ] === undefined ? 0 : arguments [ 5 ] ; var opts = arguments . length <= 6 || arguments [ 6 ] === undefined ? { } : arguments [ 6 ] ; var date = utcDate ( ) ; if ( opts . versionId ) url += '?versionId=' + opts . versionId ; var resource = genResource ( bucket , objectKey , ( 0 , _lodash . pick ) ( opts , [ 'versionId' ] ) ) ; var authorization = authorize ( accessKey , secretKey , 'HEAD' , '' , '' , date , [ ] , resource ) ; var signature = ( 0 , _urlencode2 . default ) ( generateSignature ( secretKey , 'HEAD' , '' , '' , date , [ ] , resource ) ) ; var url = pub ? 'http://' + bucket + '.' + host + '/' + objectKey : 'http://' + host + '/' + bucket + '/' + objectKey + '?NOSAccessKeyId=' + accessKey + '&Expires=' + expires + '&Signature=' + signature ; var headers = { Date : date } ; if ( opts . modifiedSince ) headers [ 'If-Modified-Since' ] = opts . modifiedSince ; headers [ 'url' ] = url ; return nosRequest ( { method : 'head' , uri : url , headers : headers } ) . then ( function ( res ) { var contentType = res [ 'content-type' ] ; var lastModified = res [ 'last-modified' ] ; var etag = res [ 'etag' ] ; var requestId = res [ 'x-nos-request-id' ] ; return { contentType : contentType , lastModified : lastModified , etag : etag , requestId : requestId } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "上传对象 @param { String } accessKey @param { String } secretKey @param { String } bucket @param { String } objectKey @param { String } file @param { Object } nosHeader [CODESPLIT] function upload ( host , accessKey , secretKey , bucket , objectKey , file ) { var nosHeader = arguments . length <= 6 || arguments [ 6 ] === undefined ? { } : arguments [ 6 ] ; nosHeader [ 'x-nos-storage-class' ] = nosHeader [ 'x-nos-storage-class' ] || 'standard' ; var date = utcDate ( ) ; var content = _fs2 . default . readFileSync ( file ) ; var contentLength = content . length ; var contentMd5 = ( 0 , _md2 . default ) ( content ) ; var resource = genResource ( bucket , objectKey ) ; var canonicalizedHeaders = Object . keys ( nosHeader ) . map ( function ( key ) { return key + ':' + nosHeader [ key ] ; } ) ; var authorization = authorize ( accessKey , secretKey , 'PUT' , contentMd5 , '' , date , canonicalizedHeaders , resource ) ; var url = 'http://' + bucket + '.' + host + '/' + objectKey ; var headers = ( 0 , _lodash . assign ) ( { Date : date , 'Content-Length' : contentLength , 'Content-MD5' : contentMd5 , Authorization : authorization , 'url' : url } , nosHeader ) ; return nosRequest ( { method : 'put' , uri : url , body : content , headers : headers } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为 非负整数 即正整数和零 [CODESPLIT] function _isUnNegativeInteger ( val , options ) { var opts = _isObject ( options ) ? options : { } ; if ( opts . isStrict === true ) { return _isNumber ( val ) && REGEX_ENUM . UN_NEGATIVE_INTEGER_REX . test ( val ) ; } return REGEX_ENUM . UN_NEGATIVE_INTEGER_REX . test ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find all * . md files and create list of { cwd src } in result [CODESPLIT] function getFileList ( ) { var result = [ ] , fileNameList = [ 'da.md' , 'en.md' ] , cwd , fileName ; for ( var i = 0 ; i < dirList . length ; i ++ ) { cwd = paths . temp_dist + dirList [ i ] ; for ( var f in fileNameList ) { fileName = fileNameList [ f ] ; if ( grunt . file . isFile ( cwd + '/' + fileName ) ) result . push ( { cwd : cwd , src : fileName } ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#### mixin This is the mixin function available on an object with advice added to it . Takes a mixin or array of mixins and options Adds the given mixins to the to on the target object . [CODESPLIT] function ( mixins , options ) { // used to saved applied mixins this . mixedIn = _ . clone ( this . mixedIn ) || [ ] ; if ( ! this . __super__ || this . mixedOptions == this . __super__ . constructor . mixedOptions ) { this . mixedOptions = _ . clone ( this . mixedOptions ) || { } ; } _ . extend ( this . mixedOptions , options ) ; // if only one passed in make it an array if ( ! _ . isArray ( mixins ) ) mixins = [ mixins ] ; // if an array then run each mixin and save to mixedIn array mixins = _ ( mixins ) . map ( function ( mixin ) { if ( ! Boolean ( mixin ) ) console . error ( 'Missing mixin at ' , this . prototype . className , this . prototype ) ; if ( ! _ . isFunction ( mixin ) ) return mixin ; if ( ! _ . contains ( this . mixedIn , mixin ) ) { this . mixedIn . push ( mixin ) ; if ( mixin ) return mixin . call ( this , this . mixedOptions ) ; } } , this ) ; // if we have an object (can be returned by functions) - use them _ ( mixins ) . each ( function ( mixin ) { if ( ! mixin ) return ; mixin = _ . clone ( mixin ) ; // call the reserved keywords _ ( [ 'mixin' , 'around' , 'after' , 'before' , 'clobber' , 'addToObj' , 'setDefaults' ] ) . each ( function ( key ) { if ( mixin [ key ] ) { if ( key == 'mixin' ) this [ key ] ( mixin [ key ] , this . mixedOptions ) ; else this [ key ] ( mixin [ key ] ) ; delete mixin [ key ] ; } } , this ) ; // on the remaining keywords, guess how to add them in _ . each ( _ . keys ( mixin ) , function ( key ) { // if it's a function then put it after if ( _ . isFunction ( mixin [ key ] ) ) { this . after ( key , mixin [ key ] ) ; // if it's an object then add it to any existing one } else if ( _ . isObject ( mixin [ key ] ) && ! _ . isArray ( mixin [ key ] ) ) { var obj = { } ; obj [ key ] = mixin [ key ] ; this . addToObj ( obj ) ; //else change the value } else { this . clobber ( key , mixin [ key ] ) ; } } , this ) ; } , this ) ; // chaining return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#### around calls the wrapped function with base function as first argument on the target object . [CODESPLIT] function ( base , wrapped ) { return function ( ) { var args = [ ] . slice . call ( arguments , 0 ) ; return wrapped . apply ( this , [ _ . bind ( base , this ) ] . concat ( args ) ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#### before will call the new function before the old one with same arguments on the target object . [CODESPLIT] function ( base , before ) { return Advice . around ( base , function ( ) { var args = [ ] . slice . call ( arguments , 0 ) , orig = args . shift ( ) , beforeFn ; beforeFn = ( typeof before == 'function' ) ? before : before . obj [ before . fnName ] ; beforeFn . apply ( this , args ) ; return ( orig ) . apply ( this , args ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#### after will call the new function after the old one with same arguments on the target object . [CODESPLIT] function ( base , after ) { return Advice . around ( base , function ( ) { var args = [ ] . slice . call ( arguments , 0 ) , orig = args . shift ( ) , afterFn ; // this is a separate statement for debugging purposes. var res = ( orig . unbound || orig ) . apply ( this , args ) ; afterFn = ( typeof after == 'function' ) ? after : after . obj [ after . fnName ] ; var result = afterFn . apply ( this , args ) ; return result ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#### clobber Extend an object with a key - value pair or another object . on the target object . [CODESPLIT] function ( base , key , value ) { var extBase = base ; if ( typeof extBase == 'function' ) extBase = base . prototype ; if ( _ . isString ( key ) ) { var temp = key ; key = { } ; key [ temp ] = value ; } _ . extend ( extBase , key ) ; return base ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#### addToObj will extend all key - values in a base object given another objects key - values ( good for events ) on the target object . [CODESPLIT] function ( base , obj ) { var extBase = base ; if ( typeof extBase == 'function' ) extBase = base . prototype ; _ . each ( obj , function ( val , key ) { extBase [ key ] = _ . extend ( _ . clone ( Advice . findVal ( extBase , key ) ) || { } , val ) ; } ) ; return base ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#### findVal find a value in a prototype chain [CODESPLIT] function ( obj , name ) { while ( ! obj [ name ] && obj . prototype ) obj = obj . prototype ; return obj [ name ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#### addAdvice adds advice functions to an object [CODESPLIT] function ( obj ) { var addApi = function ( ) { // adds before, after and around [ 'before' , 'after' , 'around' ] . forEach ( function ( m ) { obj [ m ] = function ( method , fn ) { // if an object is passed in then split that in to individual calls if ( typeof method == 'object' ) { _ . each ( _ . keys ( method ) , function ( key ) { this [ m ] ( key , method [ key ] ) ; } , this ) ; return this ; } // functions should go on a prototype if a constructor passed in var base = this ; if ( typeof base == 'function' ) base = this . prototype ; // find original function in the prototype chain var orig = Advice . findVal ( base , method ) ; // use an identity function if none found if ( typeof orig != 'function' ) { if ( m != 'around' ) { base [ method ] = fn ; return this } orig = _ . identity ; } base [ method ] = Advice [ m ] ( orig , fn ) ; // chaining return this ; } ; } ) ; var callWithThis = function ( fn ) { return fn . apply ( this , [ this ] . concat ( _ . toArray ( arguments ) . slice ( 1 ) ) ) ; } ; // add in other functions obj . addMixin = addMixin ; obj . mixin = mixInto ; obj . hasMixin = obj . prototype . hasMixin = hasMixin ; obj . addToObj = _ . partial ( callWithThis , Advice . addToObj ) ; obj . setDefaults = _ . partial ( callWithThis , Advice . setDefaults ) ; obj . findVal = _ . partial ( callWithThis , Advice . findVal ) ; obj . clobber = _ . partial ( callWithThis , Advice . clobber ) ; } addApi ( obj ) ; addApi ( obj . prototype ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes the url to the tournament or flight [CODESPLIT] function scopeUrl ( options , inst ) { options = _ . extend ( _ . clone ( options || { } ) , inst ) if ( options && options . flight_id ) { var route = ngin . Flight . urlRoot ( ) + '/' + options . flight_id + StandingsPreference . urlRoot ( ) } else if ( options && ( options . division_id && options . game_type ) ) { var route = ngin . Division . urlRoot ( ) + '/' + options . division_id + StandingsPreference . urlRoot ( ) + '/' + options . game_type } else { throw new Error ( 'flight_id or division_id and game_type required to make standings preference api calls' ) } var base = config . urls && config . urls . sports || config . url return Url . resolve ( base , route ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exposes objects as another value when serialized . expose uses the expose property of object [ resources ] { [CODESPLIT] function expose ( obj , val ) { if ( arguments . length === 1 ) { if ( obj instanceof Error ) Object . defineProperty ( obj , \"message\" , { enumerable : true , value : obj . message } ) ; val = obj ; } return resource ( obj , { expose : val } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the app api key required to make a service request [CODESPLIT] function getApiKey ( ) { if ( isLocal ( ) && pkg . apiKey ) { log . trace ( 'using apiKey in fhconfig' ) ; return pkg . apiKey ; } else { log . trace ( 'using api key in FH_APP_API_KEY env var' ) ; return env ( 'FH_APP_API_KEY' ) . asString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FieldValueConstraint [CODESPLIT] function strMapToObj ( strMap ) { const obj = { } for ( const [ k , v ] of strMap ) { // We don’t escape the key '__proto__' // which can cause problems on older engines obj [ k ] = v } return obj }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get or require the resource based on the class name . [CODESPLIT] function getResource ( name ) { if ( name in resources ) return resources [ name ] ; try { return resources [ name ] = require ( '../resource/' + name ) ; } catch ( err ) { return resources [ name ] = require ( '../resource' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为纯粹的 object [CODESPLIT] function _isPlainObject ( val ) { if ( ! _isObject ( val ) ) { return false ; } var proto = Object . getPrototypeOf ( val ) ; if ( proto === null ) { return true ; } var ctor = proto . constructor ; return _isFunction ( ctor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * putil - stringify ------------------------ ( c ) 2017 - present Panates SQB may be freely distributed under the MIT license . For details and documentation : https : // panates . github . io / putil - stringify / [CODESPLIT] function stringify ( obj , replacer , space ) { if ( typeof replacer === 'string' || typeof replacer === 'number' ) { // noinspection JSValidateTypes space = replacer ; // noinspection JSValidateTypes replacer = undefined ; } const replacerArgs = replacer ? replacer . length : 0 ; if ( space && typeof space === 'number' ) { var i = space ; space = ' ' ; while ( i -- > 1 ) space += ' ' ; } const toString = function ( o , k , v ) { var z ; if ( replacerArgs === 2 ) { z = replacer ( k , v ) ; return z === undefined ? z : JSON . stringify ( z ) ; } if ( replacerArgs === 3 ) { z = replacer ( o , k , v ) ; return z === undefined ? z : JSON . stringify ( z ) ; } return JSON . stringify ( v ) ; } ; var result = '' ; var indent = 0 ; const refs = [ ] ; const doStringify = function ( obj , key , value ) { // Check circular references const arrayOfObject = Array . isArray ( value ) || isPlainObject ( value ) ; if ( arrayOfObject && refs . indexOf ( value ) >= 0 ) { result += '\"[Circular]\"' ; return ; } const getIndent = function ( n ) { if ( ! space ) return '' ; indent += ( n || 0 ) ; var s = '\\n' ; var k = indent ; while ( k -- > 0 ) s += space ; return s ; } ; var i ; // serialize array if ( Array . isArray ( value ) ) { refs . push ( value ) ; result += '[' + getIndent ( 1 ) ; i = 0 ; value . forEach ( function ( v , k ) { if ( Array . isArray ( v ) || isPlainObject ( v ) ) { result += ( i ? ',' + getIndent ( ) : '' ) ; doStringify ( value , k , v ) ; i ++ ; } else { const s = toString ( value , k , v ) ; if ( s !== undefined ) { result += ( i ? ',' + getIndent ( ) : '' ) + s ; i ++ ; } } } ) ; result += getIndent ( - 1 ) + ']' ; refs [ refs . indexOf ( value ) ] = undefined ; return ; } // serialize object if ( isPlainObject ( value ) ) { refs . push ( value ) ; result += '{' + getIndent ( 1 ) ; i = 0 ; Object . getOwnPropertyNames ( value ) . forEach ( function ( k ) { const v = value [ k ] ; if ( Array . isArray ( v ) || isPlainObject ( v ) ) { result += ( i ? ',' + getIndent ( ) : '' ) + JSON . stringify ( k ) + ':' + ( space ? ' ' : '' ) ; doStringify ( value , k , v ) ; i ++ ; } else { const s = toString ( value , k , v ) ; if ( s !== undefined ) { result += ( i ? ',' + getIndent ( ) : '' ) + JSON . stringify ( k ) + ':' + ( space ? ' ' : '' ) + s ; i ++ ; } } } ) ; result += getIndent ( - 1 ) + '}' ; refs [ refs . indexOf ( value ) ] = undefined ; return ; } // serialize values result += toString ( obj , key , value ) ; } ; doStringify ( undefined , undefined , obj ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the navigation sidebar . [CODESPLIT] function buildNav ( members , opts ) { var nav = '' , seen = { } , list = { Modules : 'modules' , Externals : 'externals' , Classes : 'classes' , Events : 'events' , Namespaces : 'namespaces' , Mixins : 'mixins' } , hasClassList = false , classNav = '' , globalNav = '' ; nav += '<h2><a href=\"index.html\">' + ( opts . indexName || 'Index' ) + '</a></h2>' ; for ( var name in list ) { if ( members [ list [ name ] ] . length ) { nav += '<div class=\"nav-' + list [ name ] + '\">' ; nav += '<h3>' + name + '</h3><ul>' ; members [ list [ name ] ] . forEach ( function ( m ) { if ( ! hasOwnProp . call ( seen , m . longname ) ) { nav += '<li title=\"' + m . longname + '\">' + linkto ( m . longname , m . name ) + '</li>' ; } seen [ m . longname ] = true ; var funcs = find ( { kind : 'function' , memberof : m . longname === 'Global' ? { isUndefined : true } : m . longname } ) ; if ( funcs . length ) { nav += '<div class=\"navinner nav-methods\"><h4>Methods</h4><ul>' ; funcs . forEach ( function ( f ) { if ( ! hasOwnProp . call ( seen , f . longname ) ) { nav += '<li title=\"' + f . longname + '\">' + linkto ( f . longname , f . name ) + '</li>' ; } seen [ m . longname ] = true ; } ) ; nav += '</ul></div>' ; } } ) ; nav += '</ul>' ; } } /*\n    if (members.modules.length) {\n        nav += '<h3>Modules</h3><ul>';\n        members.modules.forEach(function(m) {\n            if ( !hasOwnProp.call(seen, m.longname) ) {\n                nav += '<li title=\"'+m.longname+'\">'+linkto(m.longname, m.name)+'</li>';\n            }\n            seen[m.longname] = true;\n\n            methods(m);\n        });\n\n        nav += '</ul>';\n    }\n\n    if (members.externals.length) {\n        nav += '<h3>Externals</h3><ul>';\n        members.externals.forEach(function(e) {\n            if ( !hasOwnProp.call(seen, e.longname) ) {\n                nav += '<li title=\"'+e.longname+'\">'+linkto( e.longname, e.name.replace(/(^\"|\"$)/g, '') )+'</li>';\n            }\n            seen[e.longname] = true;\n        });\n\n        nav += '</ul>';\n    }\n\n    if (members.classes.length) {\n        nav += '<h3>Classes</h3><ul>';\n        members.classes.forEach(function(c) {\n            if ( !hasOwnProp.call(seen, c.longname) ) {\n                nav += '<li title=\"'+c.longname+'\">'+linkto(c.longname, c.name)+'</li>';\n            }\n            seen[c.longname] = true;\n\n            methods(c);\n        });\n        nav += '</ul>';\n    }\n\n    if (members.events.length) {\n        nav += '<h3>Events</h3><ul>';\n        members.events.forEach(function(e) {\n            if ( !hasOwnProp.call(seen, e.longname) ) {\n                nav += '<li title=\"'+e.longname+'\">'+linkto(e.longname, e.name)+'</li>';\n            }\n            seen[e.longname] = true;\n        });\n\n        nav += '</ul>';\n    }\n\n    if (members.namespaces.length) {\n        nav += '<h3>Namespaces</h3><ul>';\n        members.namespaces.forEach(function(n) {\n            if ( !hasOwnProp.call(seen, n.longname) ) {\n                nav += '<li title=\"'+n.longname+'\">'+linkto(n.longname, n.name)+'</li>';\n            }\n            seen[n.longname] = true;\n\n            methods(n);\n        });\n\n        nav += '</ul>';\n    }\n\n    if (members.mixins.length) {\n        nav += '<h3>Mixins</h3><ul>';\n        members.mixins.forEach(function(m) {\n            if ( !hasOwnProp.call(seen, m.longname) ) {\n                nav += '<li title=\"'+m.longname+'\">'+linkto(m.longname, m.name)+'</li>';\n            }\n            seen[m.longname] = true;\n        });\n\n        nav += '</ul>';\n    }\n    */ if ( members . tutorials . length ) { nav += '<h3>Tutorials</h3><ul>' ; members . tutorials . forEach ( function ( t ) { nav += '<li>' + tutoriallink ( t . name ) + '</li>' ; } ) ; nav += '</ul>' ; } if ( members . globals . length ) { members . globals . forEach ( function ( g ) { if ( g . kind !== 'typedef' && ! hasOwnProp . call ( seen , g . longname ) ) { globalNav += '<li title=\"' + g . longname + '\">' + linkto ( g . longname , g . name ) + '</li>' ; } seen [ g . longname ] = true ; } ) ; if ( ! globalNav ) { // turn the heading into a link so you can actually get to the global page nav += '<h3>' + linkto ( 'global' , 'Global' ) + '</h3>' ; } else { nav += '<h3>Global</h3><ul>' + globalNav + '</ul>' ; } } return nav ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--- class / interfaces ---------------------------------- --- implements ------------------------------------------ [CODESPLIT] function WMURL_encode ( source ) { // @arg String // @ret String - percent encoded string // @desc encodeURIComponent impl //{@dev $valid ( $type ( source , \"String\" ) , WMURL_encode , \"source\" ) ; //}@dev function _hex ( num ) { return ( num < 16 ) ? \"0\" + num . toString ( 16 ) // 0x00 ~ 0x0f : num . toString ( 16 ) ; // 0x10 ~ 0xff } var rv = [ ] , i = 0 , iz = source . length , c = 0 , safe ; for ( ; i < iz ; ++ i ) { c = source . charCodeAt ( i ) ; if ( c < 0x80 ) { // encode ASCII(0x00 ~ 0x7f) safe = c === 95 || // _ ( c >= 48 && c <= 57 ) || // 0~9 ( c >= 65 && c <= 90 ) || // A~Z ( c >= 97 && c <= 122 ) ; // a~z if ( ! safe ) { safe = c === 33 || // ! c === 45 || // - c === 46 || // . c === 126 || // ~ ( c >= 39 && c <= 42 ) ; // '()* } if ( safe ) { rv . push ( source . charAt ( i ) ) ; } else { rv . push ( \"%\" , _hex ( c ) ) ; } } else if ( c < 0x0800 ) { // encode UTF-8 rv . push ( \"%\" , _hex ( ( ( c >>> 6 ) & 0x1f ) | 0xc0 ) , \"%\" , _hex ( ( c & 0x3f ) | 0x80 ) ) ; } else if ( c < 0x10000 ) { // encode UTF-8 rv . push ( \"%\" , _hex ( ( ( c >>> 12 ) & 0x0f ) | 0xe0 ) , \"%\" , _hex ( ( ( c >>> 6 ) & 0x3f ) | 0x80 ) , \"%\" , _hex ( ( c & 0x3f ) | 0x80 ) ) ; } } return rv . join ( \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### updateSubscribers [CODESPLIT] function updateSubscribers ( ) { lastUpdate = Date . now ( ) ; updateRequested = false ; var accessMap = new immutable . Map ( ) ; for ( var path of dirtyState ) { accessMap = setIn ( accessMap , path , true ) ; } dirtyState . clear ( ) ; for ( var subscriber of subscribers . values ( ) ) { var needsUpdate = false ; for ( path of subscriber . accessed ) { if ( accessMap . getIn ( path ) ) { needsUpdate = true ; break ; } } if ( needsUpdate ) { updateSubscriber ( subscriber ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### updateSubscriber [CODESPLIT] function updateSubscriber ( subscriber ) { stateAccessed . clear ( ) ; subscriber . fn ( ) ; subscriber . accessed = Array . from ( stateAccessed ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### setIn [CODESPLIT] function setIn ( o , path , value ) { if ( path . length ) { var key = path [ 0 ] ; var rest = path . slice ( 1 ) ; if ( typeof key === 'number' && ! ( o instanceof immutable . List ) ) { o = new immutable . List ( ) ; } else if ( ! ( o instanceof immutable . Map ) ) { o = new immutable . Map ( ) ; } return o . set ( key , setIn ( o . get ( path [ 0 ] ) , path . slice ( 1 ) , value ) ) ; } else { return immutable . fromJS ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### toJS [CODESPLIT] function toJS ( o ) { if ( typeof o === 'object' && o !== null && typeof o . toJS === 'function' ) { o = o . toJS ( ) ; } return o ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### toPath [CODESPLIT] function toPath ( arr ) { if ( typeof arr === 'string' ) { arr = arr . split ( '.' ) ; } else if ( ! Array . isArray ( arr ) ) { arr = [ arr ] ; } return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sign msg with the given key and alg [CODESPLIT] function signMsg ( msg , key , alg ) { var signer = crypto . createSign ( alg ) ; signer . update ( msg ) ; return signer . sign ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "hash the msg with the msg and alg [CODESPLIT] function hashMsg ( msg , alg ) { var hash = crypto . createHash ( alg ) ; hash . update ( msg ) ; return hash . digest ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function decrypts and parses an encrypted response body sent by APIM The body must be in the following format : [CODESPLIT] function decryptAPIMResponse ( body , private_key ) { if ( ! body . key || ! body . cipher ) { throw new Error ( 'bad handshake response from APIm' ) ; } var key = crypto . privateDecrypt ( { key : private_key , padding : constants . RSA_PKCS1_PADDING } , new Buffer ( body . key , 'base64' ) ) ; var iv = new Buffer ( 16 ) ; iv . fill ( 0 ) ; var decipher = crypto . createDecipheriv ( 'aes-256-cbc' , key , iv ) ; var plainText = decipher . update ( body . cipher , 'base64' , 'utf8' ) ; plainText += decipher . final ( 'utf8' ) ; log . debug ( 'handshake response payload:' , plainText ) ; return JSON . parse ( plainText ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the signature headers date digest and authorization headers according to IETF I - D draft - cavage - http - signatures - 05 using rsa - sha256 algorithm [CODESPLIT] function addSignatureHeaders ( body , headers , keyId , key ) { if ( ! headers ) { headers = { } ; } if ( ! headers . date ) { headers . date = ( new Date ( ) ) . toUTCString ( ) ; } if ( ! headers . digest ) { headers . digest = 'SHA256=' + hashMsg ( JSON . stringify ( body ) , 'sha256' ) . toString ( 'base64' ) ; } var combine = function ( names , headers ) { var parts = [ ] ; names . forEach ( function ( e ) { parts . push ( e + ': ' + headers [ e ] ) ; } ) ; return parts . join ( '\\n' ) ; } ; headers . authorization = 'Signature ' + 'keyId=\"' + keyId + '\", ' + 'headers=\"date digest\", ' + 'algorithm=\"rsa-sha256\", ' + 'signature=\"' + signMsg ( combine ( [ 'date' , 'digest' ] , headers ) , key , 'RSA-SHA256' ) . toString ( 'base64' ) + '\"' ; return headers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : support OZW security API [CODESPLIT] function OZWManager ( ) { this . ozw = new OZW ( { Logging : true , // enable logging to OZW_Log.txt ConsoleOutput : false , // copy logging to the console } ) ; this . ozw . on ( 'driver ready' , this . onDriverReady . bind ( this ) ) ; this . ozw . on ( 'driver failed' , this . onDriverFailed . bind ( this ) ) ; this . ozw . on ( 'node added' , this . onNodeAdded . bind ( this ) ) ; this . ozw . on ( 'node ready' , this . onNodeReady . bind ( this ) ) ; this . ozw . on ( 'node naming' , this . onNodeNaming . bind ( this ) ) ; this . ozw . on ( 'node available' , this . onNodeAvailable . bind ( this ) ) ; this . ozw . on ( 'value added' , this . onValueAdded . bind ( this ) ) ; this . ozw . on ( 'value changed' , this . onValueChanged . bind ( this ) ) ; this . ozw . on ( 'value removed' , this . onValueRemoved . bind ( this ) ) ; this . ozw . on ( 'scan complete' , this . onScanComplete . bind ( this ) ) ; this . ozw . on ( 'notification' , this . onNotification . bind ( this ) ) ; this . deviceList = { } ; this . discoverState = 'stopped' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "File name for saving original vesion of bower . json copyORIGINALToBowerJson : copy _ORIGINAL_bower . json - > bower . json [CODESPLIT] function copyORIGINALToBowerJson ( ) { if ( grunt . file . exists ( ORIGINALFileName ) ) { grunt . file . copy ( ORIGINALFileName , 'bower.json' ) ; grunt . file . delete ( ORIGINALFileName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eachDependencies ( packageFunc options ) Visit each dependencies and dependencies of dependencies and ... in bower . json packageFunc : function ( packageName bwr options firstlevel dotBowerJson ) - function to process bower . json bwr : json - object ( = the contents of the current bower . json ) firstlevel : boolean - true when bwr is the packages own bower . json dotBowerJson : json - object ( = the contents of the current . bower . json ) options : user - defined . Passed on to packageFunc [CODESPLIT] function eachDependencies ( packageFunc , options ) { var bwr = common . readJSONFile ( 'bower.json' ) ; _eachDependencies ( bwr . name , bwr , packageFunc , options , [ ] , true , common . readJSONFile ( '.bower.json' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_eachDependencies ( bwr packageFunc options packageList firstLevel ) Internal version with additional parametre packageList = [ PACKAGENAME ] of boolean [CODESPLIT] function _eachDependencies ( packageName , bowerJson , packageFunc , options , packageList , firstLevel , dotBowerJson ) { bowerJson = bowerJson || { } ; dotBowerJson = dotBowerJson || { } ; var dependenciesPackageName , dependencies = bowerJson . dependencies || dotBowerJson . dependencies || { } ; packageFunc ( packageName , bowerJson , options , firstLevel , dotBowerJson ) ; //Find dependencies for ( dependenciesPackageName in dependencies ) if ( dependencies . hasOwnProperty ( dependenciesPackageName ) ) { //If the package already has been check => continue if ( packageList [ dependenciesPackageName ] ) continue ; packageList [ dependenciesPackageName ] = true ; //Read the dependences of the package _eachDependencies ( dependenciesPackageName , common . readJSONFile ( paths . bower_components + dependenciesPackageName + '/bower.json' ) , packageFunc , options , packageList , false , common . readJSONFile ( paths . bower_components + dependenciesPackageName + '/.bower.json' ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait variable expression matches value [CODESPLIT] async function waitVariableToBe ( variableExpression , value , timeout ) { return await this . waitUntil ( async ( ) => { const result = await this . execute ( ` ${ variableExpression } ${ JSON . stringify ( value ) } ` ) return result . value } , timeout , ` \\` ${ variableExpression } \\` \\` ${ JSON . stringify ( value ) } \\` ` ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait attribute matches value [CODESPLIT] async function waitAttributeToBe ( selector , key , value , timeout ) { return await this . waitUntil ( async ( ) => { const got = await this . element ( selector ) . getAttribute ( key ) return [ ] . concat ( value ) . some ( ( value ) => got === value || String ( got ) === String ( value ) ) } , timeout , ` ${ key } \\` ${ selector } \\` \\` ${ JSON . stringify ( value ) } \\` ` ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Realiza un unmount y renderiza la nueva vista . [CODESPLIT] function ( view ) { this . unmount ( ) ; this . currentView = view ; var renderReturnsView = this . currentView . render ( ) ; if ( renderReturnsView ) { $ ( SpecialK . mainContainer ) . empty ( ) . append ( renderReturnsView . el ) . fadeIn ( 'slow' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Elimina la vista actual y sus eventos en DOM . [CODESPLIT] function ( ) { if ( ! this . currentView ) return false ; $ ( SpecialK . container ) . hide ( ) ; this . currentView . unbind ( ) ; this . currentView . remove ( ) ; this . currentView = null ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Utils . check . value () ; Utils . check . fn () ; Test typeof of a returned value or of a single value [CODESPLIT] function checkValue ( val , expectedType , name ) { if ( typeof val !== expectedType ) { throw new Error ( name + ' must return ' + expectedType ) ; } return Utils ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "keeping it DRY [CODESPLIT] function mergeAll ( safe , obj ) { let args = toArray ( arguments ) . slice ( 2 ) ; for ( let i = 0 ; i < args . length ; i ++ ) { obj = merge ( obj , args [ i ] , safe ) ; } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param { Boolean } condition - Condition used to determine whether to call end return the result of func or undefined . @param { Function } func - Function to be called if condition evaluates to true . @param { ... ? * } funcParams - Parameters to be passed to func if called . [CODESPLIT] function callIf ( condition , func ) { return ( condition ? func . apply ( undefined , Array . prototype . slice . call ( arguments , 2 ) ) : undefined ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Supports instance numbers ( 11 ) or object types ( 1 . 2 . 11 ) . Object type Validation is enforced when an object type is used . [CODESPLIT] function ( reserved_spaces , object_type ) { v . required ( reserved_spaces , \"reserved_spaces\" ) ; v . required ( object_type , \"object_type\" ) ; return { fromByteBuffer ( b ) { return b . readVarint32 ( ) ; } , appendByteBuffer ( b , object ) { v . required ( object ) ; if ( object . resolve !== undefined ) { object = object . resolve ; } // convert 1.2.n into just n if ( / ^[0-9]+\\.[0-9]+\\.[0-9]+$ / . test ( object ) ) { object = v . get_instance ( reserved_spaces , object_type , object ) ; } b . writeVarint32 ( v . to_number ( object ) ) ; return ; } , fromObject ( object ) { v . required ( object ) ; if ( object . resolve !== undefined ) { object = object . resolve ; } if ( v . is_digits ( object ) ) { return v . to_number ( object ) ; } return v . get_instance ( reserved_spaces , object_type , object ) ; } , toObject ( object , debug = { } ) { var object_type_id = ChainTypes . object_type [ object_type ] ; if ( debug . use_default && object === undefined ) { return ` ${ reserved_spaces } ${ object_type_id } ` ; } v . required ( object ) ; if ( object . resolve !== undefined ) { object = object . resolve ; } if ( / ^[0-9]+\\.[0-9]+\\.[0-9]+$ / . test ( object ) ) { object = v . get_instance ( reserved_spaces , object_type , object ) ; } return ` ${ reserved_spaces } ${ object_type_id } ` + object ; } , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse quality str returning an object with . value and . quality . [CODESPLIT] function quality ( str ) { var parts = str . split ( /  *; * / ) , val = parts [ 0 ] ; var q = parts [ 1 ] ? parseFloat ( parts [ 1 ] . split ( /  *= * / ) [ 1 ] ) : 1 ; return { value : val , quality : q } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CAST // FUNCTION : cast ( x type ) Casts an input array or array - like object to a specified type . [CODESPLIT] function cast ( x , type ) { /* jshint newcap:false */ var ctor , len , d , i ; if ( ! arrayLike ( x ) ) { throw new TypeError ( 'invalid input argument. First argument must be an array-like object. Value: `' + x + '`.' ) ; } if ( typeof type === 'string' ) { ctor = getCtor ( type ) ; } else { ctor = getCtor ( dtype ( typeName ( type ) ) ) ; } if ( ctor === null ) { throw new Error ( 'invalid input argument. Unrecognized/unsupported type to which to cast. Value: `' + type + '`.' ) ; } len = x . length ; // Ensure fast elements (contiguous memory)... if ( type === 'generic' && len > 64000 ) { d = new ctor ( 64000 ) ; for ( i = 0 ; i < 64000 ; i ++ ) { d [ i ] = x [ i ] ; } for ( i = 64000 ; i < len ; i ++ ) { d . push ( x [ i ] ) ; } } else { d = new ctor ( len ) ; for ( i = 0 ; i < len ; i ++ ) { d [ i ] = x [ i ] ; } } return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] function parse_by_content_type ( type , body ) { if ( type === 'application/json' ) { return JSON . parse ( body ) ; } if ( type === 'text/plain' ) { return '' + body ; } throw new Error ( \"Unknown Content-Type \" + type + \" -- don't know how to parse!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * _resolveFilter [CODESPLIT] function _resolveFilter ( req ) { function __isReqObject ( req ) { return ! ! req . url ; } function __hasQueryString ( req ) { return __isReqObject ( req ) && ( Object . keys ( req . query || { } ) . length > 0 ) ; } function __hasRouteParams ( req ) { return __isReqObject ( req ) && ( Object . keys ( req . params || { } ) . length > 0 ) ; } function __hasODATA ( req ) { return __isReqObject ( req ) && ( Object . keys ( req . odata || { } ) . length > 0 ) ; } if ( ! req ) { return { type : \"none\" , filter : null } ; } else if ( __hasODATA ( req ) ) { return { type : \"odata\" , filter : req . odata } ; } else if ( __hasQueryString ( req ) ) { return { type : \"queryString\" , filter : req . query } ; } else if ( __hasRouteParams ( req ) ) { return { type : \"routeParams\" , filter : req . params } ; } else { if ( __isReqObject ( req ) ) { return req ; } else { if ( typeof ( req ) === \"object\" ) { return { type : \"plainObject\" , filter : req } ; } else { return { type : \"routeParams\" , filter : { \"id\" : req } } ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Functions to calculate brightness [CODESPLIT] function getBrightness ( hex ) { var r = parseInt ( hex . substr ( 2 + 0 * 2 , 2 ) , 16 ) , g = parseInt ( hex . substr ( 2 + 1 * 2 , 2 ) , 16 ) , b = parseInt ( hex . substr ( 2 + 2 * 2 , 2 ) , 16 ) ; function lin2log ( n ) { return n <= 0.0031308 ? n * 12.92 : 1.055 * Math . pow ( n , 1 / 2.4 ) - 0.055 ; } function log2lin ( n ) { return n <= 0.04045 ? n / 12.92 : Math . pow ( ( ( n + 0.055 ) / 1.055 ) , 2.4 ) ; } r = log2lin ( r / 255 ) ; g = log2lin ( g / 255 ) ; b = log2lin ( b / 255 ) ; return lin2log ( 0.2126 * r + 0.7152 * g + 0.0722 * b ) * 100 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Route ===== constructor ----------- create a route that can be used for matching ### required arguments ** name ** : name for this route ** pattern ** : pattern for this route ### optional arguments ** method ** : specify HTTP method for this route [CODESPLIT] function Route ( args ) { this . name = args . name ; this . method = args . method ; var pattern = args . pattern ; this . pattern = RoutePattern . fromString ( pattern ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Telepathy constructor [CODESPLIT] function Telepathy ( options ) { 'use strict' ; options = options || { } ; if ( typeof options == 'string' ) options = { secret : options } ; /** Private variable shared secret */ var _secret = options . secret || '' ; delete options . secret ; this . user = options . user || '' ; this . alphabet = options . alphabet || Telepathy . alphabet . base62 ; this . length = options . length || 10 ; this . domain = options . domain || '' ; this . algorithm = options . algorithm || 'SHA256' ; /**\n   * Set the private secret we'll be using in generating passwords\n   * @param {string} secret\n   */ this . setSecret = function ( secret ) { _secret = secret || '' ; } ; /**\n   * Generate a password\n   * @param {object|string|number} [options]\n   * @returns {string} Generated password\n   * @example\n   * var telepathy = new Telepathy('secret');\n   * console.log(telepathy.password('google.com'));\n   */ this . password = function ( options ) { return this . _password ( _secret , options ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "readFile ( filename isJSON stripComments defaultContents ) [CODESPLIT] function readFile ( filename , isJSON , stripComments , defaultContents ) { if ( grunt . file . exists ( filename ) ) { var contents = grunt . file . read ( filename ) ; if ( isJSON || stripComments ) contents = stripJsonComments ( contents ) ; return isJSON ? JSON . parse ( contents ) : contents ; } else return defaultContents ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "readJSONFile ( filename defaultContents ) [CODESPLIT] function readJSONFile ( filename , defaultContents ) { return readFile ( filename , true , true , defaultContents === null ? { } : defaultContents ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writeJSONFile ( fileName contents ) [CODESPLIT] function writeJSONFile ( fileName , contents ) { var obj = JSON . parse ( JSON . stringify ( contents ) ) ; grunt . file . write ( fileName , JSON . stringify ( obj , null , 4 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writeFile ( fileName isJSON contents ) [CODESPLIT] function writeFile ( fileName , isJSON , contents ) { if ( isJSON ) contents = JSON . stringify ( contents ) ; grunt . file . write ( fileName , contents ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "updateOptions : Update options with missing id / values from defaultOptions [CODESPLIT] function updateOptions ( options , defaultOptions ) { for ( var id in defaultOptions ) if ( defaultOptions . hasOwnProperty ( id ) && ( ! options . hasOwnProperty ( id ) ) || ( options [ id ] === '' ) || ( options [ id ] === null ) ) options [ id ] = defaultOptions [ id ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "merge : Merge all the options given into a new object [CODESPLIT] function merge ( ) { var result = { } ; for ( var i = 0 ; i < arguments . length ; i ++ ) for ( var key in arguments [ i ] ) if ( arguments [ i ] . hasOwnProperty ( key ) ) result [ key ] = arguments [ i ] [ key ] ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "runCmd ( cmd useCmdOutput ) useCmdOutput = true = > the command output direct to std [CODESPLIT] function runCmd ( cmd , useCmdOutput ) { if ( ! useCmdOutput ) grunt . log . writeln ( cmd [ 'grey' ] ) ; var shell = require ( 'shelljs' ) , result = shell . exec ( cmd , { silent : ! useCmdOutput } ) ; if ( result . code === 0 ) { if ( ! useCmdOutput ) grunt . log . writeln ( result . stdout [ 'white' ] ) ; } else { if ( ! useCmdOutput ) { grunt . log . writeln ( ) ; grunt . log . writeln ( result . stderr [ 'yellow' ] ) ; } grunt . fail . warn ( '\"' + cmd + '\" failed.' ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "~~~ Second Call in the API createTransition ( glslSource [ uniforms ] ) Creates a GLSL Transition for the current canvas context . [CODESPLIT] function createTransition ( glsl ) { // Second level variables var buffer , shader , textureUnits , textures ; function load ( ) { if ( ! gl ) return ; buffer = gl . createBuffer ( ) ; shader = createShader ( gl , VERTEX_SHADER , glsl ) ; textureUnits = { } ; textures = { } ; var i = 0 ; for ( var name in shader . types . uniforms ) { var t = shader . types . uniforms [ name ] ; if ( t === \"sampler2D\" ) { textureUnits [ name ] = i ; i ++ ; } } } function onContextLost ( ) { if ( shader ) shader . dispose ( ) ; shader = null ; } function onContextRestored ( ) { load ( ) ; } function syncViewport ( ) { var w = canvas . width , h = canvas . height ; var x1 = 0 , x2 = w , y1 = 0 , y2 = h ; if ( currentShader ) { currentShader . uniforms [ RESOLUTION_UNIFORM ] = new Float32Array ( [ w , h ] ) ; } gl . bindBuffer ( gl . ARRAY_BUFFER , buffer ) ; shader . attributes . position . pointer ( ) ; gl . bufferData ( gl . ARRAY_BUFFER , new Float32Array ( [ x1 , y1 , x2 , y1 , x1 , y2 , x1 , y2 , x2 , y1 , x2 , y2 ] ) , gl . STATIC_DRAW ) ; gl . viewport ( x1 , y1 , x2 , y2 ) ; } function setProgress ( p ) { shader . uniforms [ PROGRESS_UNIFORM ] = p ; } function setUniform ( name , value ) { if ( name in textureUnits ) { var i = textureUnits [ name ] ; gl . activeTexture ( gl . TEXTURE0 + i ) ; var texture = textures [ name ] ; // Destroy the previous texture if ( texture ) texture . dispose ( ) ; if ( value === null ) { // Texture is now a black texture textures [ name ] = texture = createTexture ( gl , 2 , 2 ) ; } else { gl . pixelStorei ( gl . UNPACK_FLIP_Y_WEBGL , true ) ; // Create a new texture textures [ name ] = texture = createTexture ( gl , value ) ; } shader . uniforms [ name ] = texture . bind ( i ) ; } else { shader . uniforms [ name ] = value ; } } function reset ( ) { var hasChanged = false ; if ( ! shader ) { load ( ) ; // Possibly shader was not loaded. hasChanged = true ; } if ( currentShader !== shader ) { currentShader = shader ; shader . bind ( ) ; hasChanged = true ; } syncViewport ( ) ; return hasChanged ; } function destroy ( ) { if ( currentShader === shader ) { currentShader = null ; } if ( shader ) { for ( var t in textures ) { textures [ t ] . dispose ( ) ; } textures = null ; shader . dispose ( ) ; shader = null ; } } function getUniforms ( ) { if ( ! shader ) load ( ) ; return extend ( { } , shader . types . uniforms ) ; } var transition = { getGL : function ( ) { return gl ; } , load : function ( ) { // Possibly shader was not loaded. if ( ! shader ) load ( ) ; } , bind : function ( ) { // If shader has changed, we need to bind it if ( currentShader !== shader ) { currentShader = shader ; if ( ! shader ) load ( ) ; shader . bind ( ) ; } } , isCurrentTransition : function ( ) { return currentShader === shader ; } , onContextLost : onContextLost , onContextRestored : onContextRestored , syncViewport : syncViewport , setProgress : setProgress , setUniform : setUniform , reset : reset , draw : draw , destroy : destroy , getUniforms : getUniforms } ; transitions . push ( transition ) ; return transition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search command from PATH [CODESPLIT] function command_exists ( paths , name ) { if ( is . string ( paths ) ) { paths = paths . split ( ':' ) ; } debug . assert ( paths ) . is ( 'array' ) ; return paths . some ( dir => fs . existsSync ( PATH . join ( dir , name ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug . log ( pg_ctl detected as PG_CTL ) ; Return promise of a spawned command [CODESPLIT] function spawnProcess ( command , args , { env = { } } = { } ) { return Async . Promise ( ( resolve , reject ) => { //debug.log('command = ', command); //debug.log('args = ', args); //debug.log('options = ', options); // NOTE! If you set stdout to be captured instead of ignored (the postgres log is there), // pgctl start will fail to exit. const options = { env : merge ( process . env , env || { } ) , detached : true , stdio : [ \"ignore\" , \"ignore\" , \"pipe\" ] } ; let stderr = '' ; // Run the process //debug.log('Executing command ', command, args); let proc = child_process . spawn ( command , args , options ) ; // Handle exit proc . on ( 'close' , retval => { //debug.log('Command ', command, args, ' closed with ', retval); if ( retval === 0 ) { resolve ( retval ) ; } else { reject ( { retval , stderr } ) ; } } ) ; // Handle error proc . on ( 'error' , err => { reject ( err ) ; } ) ; //proc.stdout.setEncoding('utf8'); //proc.stdout.on('data', data => { //\tprocess.stderr.write(data); //}); proc . stderr . setEncoding ( 'utf8' ) ; proc . stderr . on ( 'data' , data => { stderr += data ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes the current ( uncommitted ) text into the history . [CODESPLIT] function ( ) { if ( this . _uncommittedIsTop ) this . _data . pop ( ) ; // Throw away obsolete uncommitted text. this . _uncommittedIsTop = true ; this . clearAutoComplete ( true ) ; this . _data . push ( this . text ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Node 0 . 10 - 0 . 12 does not supports Object . assign () Instead of modifying Object with polyfill we define private function object_assign () [CODESPLIT] function completeAssign ( target /*..sources*/ ) { for ( var index = 1 ; index < arguments . length ; index ++ ) { var source = arguments [ index ] ; //sources.forEach(source => { //let descriptors = Object.keys(source).reduce((descriptors, key) => { var descriptors = Object . keys ( source ) . reduce ( function ( descriptors , key ) { descriptors [ key ] = Object . getOwnPropertyDescriptor ( source , key ) ; return descriptors ; } , { } ) ; // by default, Object.assign copies enumerable Symbols too Object . getOwnPropertySymbols ( source ) . forEach ( function ( sym ) { var descriptor = Object . getOwnPropertyDescriptor ( source , sym ) ; if ( descriptor . enumerable ) { descriptors [ sym ] = descriptor ; } } ) ; Object . defineProperties ( target , descriptors ) ; //}); } return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为 整数 [CODESPLIT] function _isInteger ( val , options ) { var opts = _isObject ( options ) ? options : { } ; if ( opts . isStrict === true ) { return _isNumber ( val ) && REGEX_ENUM . INTEGER_REX . test ( val ) ; } return REGEX_ENUM . INTEGER_REX . test ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- Coretags -- name : willHandle description : array of tags that the coretags plugin will handle [CODESPLIT] function ( Template ) { return [ Template . language . tag ( 'set' ) , Template . language . tag ( 'setalist' ) , Template . language . tag ( 'setahash' ) , Template . language . tag ( 'addtolist' ) , Template . language . tag ( 'setaregex' ) ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- Coretags -- name : handleToken description : executed when any tag in willHandle is found [CODESPLIT] function ( Template , expression , tag ) { switch ( tag ) { case Template . language . tag ( 'set' ) : return new Set ( Template , expression ) ; case Template . language . tag ( 'setalist' ) : return new SetList ( Template , expression ) ; case Template . language . tag ( 'setahash' ) : return new SetHash ( Template , expression ) ; case Template . language . tag ( 'addtolist' ) : return new AddToList ( Template , expression ) ; case Template . language . tag ( 'setaregex' ) : return new SetARegEx ( Template , expression ) ; default : return { skip : true } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- module -- name : Set description : Set execution [CODESPLIT] function ( Template , expression ) { this . needs = { } ; expression = expression . split ( ' ' ) ; if ( expression . length < 4 ) { this . skip = true ; Noodles . Utilities . warning ( Template , 'Set tag has bad syntax' ) ; return ; } var temp = Noodles . Utilities . parseType ( Template , expression [ 1 ] ) ; if ( temp . type !== \"object\" ) { this . skip = true ; Noodles . Utilities . warning ( Template , 'Set tag has bad syntax, the variable must be an identifier or object' ) ; return ; } this . key = temp ; if ( this . key . order . length > 1 ) { this . needs = Noodles . Utilities . mergeObjectWith ( this . needs , this . key . needs ) ; } else { this . sets = { } ; this . sets [ this . key . order [ 0 ] ] = true ; } this . modifies = { } ; this . modifies [ this . key . order [ 0 ] ] = true ; this . value = Noodles . Utilities . parseType ( Template , expression [ 3 ] ) ; this . needs = Noodles . Utilities . mergeObjectWith ( this . needs , this . value . needs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- module -- name : SetList description : List object set method [CODESPLIT] function ( Template , expression ) { this . needs = { } ; var reListSplit = new RegExp ( '^' + Template . language . tag ( 'setalist' ) + '\\\\s+([^=]+)\\\\s*=\\\\s*(.+)' ) , obj , list , item ; if ( ! reListSplit . test ( expression ) ) { this . skip = true ; Noodles . Utilities . warning ( Template , 'Setalist tag has bad syntax' ) ; return ; } expression = reListSplit . exec ( expression ) obj = Noodles . Utilities . parseType ( Template , expression [ 1 ] ) ; if ( obj . type !== \"object\" ) { this . skip = true ; Noodles . Utilities . warning ( Template , 'Setalist tag has bad syntax, the variable must be an identifier or object' ) ; return ; } this . key = obj ; if ( this . key . order . length > 1 ) { this . needs = Noodles . Utilities . mergeObjectWith ( this . needs , this . key . needs ) ; } else { this . sets = { } ; this . sets [ this . key . order [ 0 ] ] = true ; } this . modifies = { } ; this . modifies [ this . key . order [ 0 ] ] = true ; list = expression [ 2 ] . split ( ',' ) ; for ( var i = 0 , l = list . length ; i < l ; i ++ ) { list [ i ] = Noodles . Utilities . parseType ( Template , list [ i ] . trim ( ) ) ; this . needs = Noodles . Utilities . mergeObjectWith ( this . needs , list [ i ] . needs ) ; } this . value = list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- module -- name : SetHash description : Hash object set method [CODESPLIT] function ( Template , expression ) { this . needs = { } ; var reHashSplit = new RegExp ( '^' + Template . language . tag ( 'setahash' ) + '\\\\s+([^=]+)\\\\s*=\\\\s*(.+)' ) , hashObject = { } , obj , hash , value ; if ( ! reHashSplit . test ( expression ) ) { this . skip = true ; Noodles . Utilities . warning ( Template , 'Setahash tag has bad syntax' ) ; return ; } expression = reHashSplit . exec ( expression ) obj = Noodles . Utilities . parseType ( Template , expression [ 1 ] ) ; if ( obj . type !== \"object\" ) { this . skip = true ; Noodles . Utilities . warning ( Template , 'Setahash tag has bad syntax, the variable must be an identifier or object' ) ; return ; } this . key = obj ; if ( this . key . order . length > 1 ) { this . needs = Noodles . Utilities . mergeObjectWith ( this . needs , this . key . needs ) ; } else { this . sets = { } ; this . sets [ this . key . order [ 0 ] ] = true ; } this . modifies = { } ; this . modifies [ this . key . order [ 0 ] ] = true ; hash = expression [ 2 ] . split ( ',' ) ; for ( var i = 0 , l = hash . length ; i < l ; i ++ ) { hash [ i ] = hash [ i ] . split ( ':' ) ; value = hash [ i ] [ 0 ] . trim ( ) . toLowerCase ( ) ; hashObject [ value ] = Noodles . Utilities . parseType ( Template , hash [ i ] [ 1 ] . trim ( ) ) this . needs = Noodles . Utilities . mergeObjectWith ( this . needs , hashObject [ value ] . needs ) ; } this . value = hashObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- module -- name : AddToList description : AddToList object set method [CODESPLIT] function ( Template , expression ) { this . needs = { } ; var reAddToList = new RegExp ( '^' + Template . language . tag ( 'addtolist' ) + '\\\\s+([^=]+)\\\\s+to\\\\s+(.+)' ) ; if ( ! reAddToList . test ( expression ) ) { this . skip = true ; Noodles . Utilities . warning ( Template , 'Addtolist tag has bad syntax' ) ; return ; } expression = reAddToList . exec ( expression ) this . value = Noodles . Utilities . parseType ( Template , expression [ 1 ] ) ; this . list = Noodles . Utilities . parseType ( Template , expression [ 2 ] ) ; if ( this . list . type !== \"object\" ) { this . skip = true ; Noodles . Utilities . warning ( Template , 'Addtolist tag has bad syntax, the list must be an identifier or object' ) ; return ; } this . needs = Noodles . Utilities . mergeObjectWith ( this . needs , this . value . needs ) ; this . needs = Noodles . Utilities . mergeObjectWith ( this . needs , this . list . needs ) ; this . modifies = { } ; this . modifies [ this . list . order [ 0 ] ] = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- module -- name : SetARegEx description : SetRegexp method [CODESPLIT] function ( Template , expression ) { this . needs = { } ; expression = expression . split ( / \\s+ / ) ; this . name = Noodles . Utilities . parseType ( Template , expression [ 0 ] ) ; if ( this . name . type !== \"object\" ) { Noodles . Utilities . warning ( Template , 'SetARegEx tag has bad syntax, the name must be an identifier' ) ; this . skip = true ; return ; } this . value = Noodles . Utilities . parseType ( Template , expression [ 2 ] ) ; this . options = typeof expression [ 3 ] === \"string\" && expression [ 3 ] . length > 0 ? expression [ 3 ] . toLowerCase ( ) : false ; if ( this . value . type === \"string\" ) { this . regex = this . options ? new RegExp ( this . value . execute ( ) , this . options ) : new RegExp ( this . value . execute ( ) ) ; } else if ( this . value . type === \"object\" ) { this . regex = false ; this . needs = Noodles . Utilities . mergeObjectWith ( this . needs , this . value . needs ) ; this . modifies = { } ; this . modifies [ this . value . order [ 0 ] ] = true ; } else { this . skip = true ; Noodles . Utilities . warning ( Template , 'SetARegEx tag has bad syntax, the value must receive a string or object' ) ; return ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- module -- name : sortFunc description : sort function for sortloop . [CODESPLIT] function ( obj , keys , key , Template , Context , desc ) { var name = key === Template . language . other ( 'name' ) , value = key === null || key === Template . language . other ( 'value' ) ; keys = keys . sort ( function ( a , b ) { if ( value ) { a = obj [ a ] ; b = obj [ b ] ; if ( typeof a === \"object\" && typeof a . execute !== \"undefined\" ) a = a . execute ( Template , Context ) ; if ( typeof b === \"object\" && typeof b . execute !== \"undefined\" ) b = b . execute ( Template , Context ) ; } else if ( ! name ) { a = obj [ a ] ; b = obj [ b ] ; if ( typeof a === \"object\" && typeof a . execute !== \"undefined\" ) a = a . execute ( Template , Context ) ; if ( typeof b === \"object\" && typeof b . execute !== \"undefined\" ) b = b . execute ( Template , Context ) ; a = a [ key ] ; b = b [ key ] ; if ( typeof a === \"object\" && typeof a . execute !== \"undefined\" ) a = a . execute ( Template , Context ) ; if ( typeof b === \"object\" && typeof b . execute !== \"undefined\" ) b = b . execute ( Template , Context ) ; } if ( desc ) { return b - a ; } else { return a - b ; } } ) ; return keys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- Coretags -- name : onTemplateExecute description : executed when template is run [CODESPLIT] function ( Template ) { Template . endTags = Template . endTags || { } ; Template . endTags [ Template . language . tag ( 'loop' ) ] = true ; Template . endTags [ Template . language . tag ( 'sortloop' ) ] = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- Coretags -- name : handleToken description : executed when any tag in willHandle is found [CODESPLIT] function ( Template , expression , tag ) { switch ( tag ) { case Template . language . tag ( 'loop' ) : return new Loop ( Template , expression ) ; case Template . language . tag ( 'sortloop' ) : return new Loop ( Template , expression , true ) ; default : return { skip : true } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- module -- name : Loop description : Loop object [CODESPLIT] function ( Template , expression , sort ) { var name , set , index ; this . rawString = Noodles . Utilities . grabToEndSliceRaw ( Template , expression , Template . language . tag ( 'Loop' ) ) ; this . needs = { } ; expression = expression . split ( / \\s+ / g ) ; if ( expression . length < 2 ) { this . skip = true ; Noodles . Utilities . warning ( Template , 'Loop tag has bad syntax' ) ; return ; } this . object = Noodles . Utilities . parseType ( Template , expression [ 1 ] ) ; if ( ! ( this . object instanceof Noodles . Object ) ) { this . skip = true ; Noodles . Utilities . warning ( Template , 'Loop must have an object to loop over' ) ; delete this . object ; return ; } this . needs = Noodles . Utilities . mergeObjectWith ( this . needs , this . object . needs ) ; this . template = Noodles . Utilities . createSubTemplate ( Template , this . rawString , this ) ; if ( this . template . needsCallback ) { this . skip = true ; Noodles . Utilities . warning ( Template , 'Loop cannot contain any tags that will take a long time to run' ) ; delete this . template ; return ; } Template . _leftCount ++ ; //the end tag we sliced above this . sets = { } ; this . modifies = { } ; name = Template . language . other ( 'name' ) this . name = new Noodles . Object ( this . template , name ) ; this . sets [ name ] ; this . modifies [ name ] ; value = Template . language . other ( 'value' ) ; this . value = new Noodles . Object ( this . template , value ) ; index = '__' + Template . language . other ( 'index' ) this . index = new Noodles . Object ( this . template , index ) ; this . sets [ index ] ; this . modifies [ index ] ; this . setExists = false ; //<{loop foo as bar}> this . sort = ! ! sort ; if ( expression . length > 3 && ( ! this . sort || expression [ 2 ] . toLowerCase ( ) === Template . language . other ( 'as' ) ) ) { this . setObject = new Noodles . Object ( this . template , expression [ 3 ] ) ; if ( this . setObject . order . length > 1 ) { Noodles . Utilities . warning ( Template , 'Loop cannot set an object with multiple levels' ) ; this . skip = true ; delete this . setObjet ; return ; } this . setExists = true ; } if ( this . sort ) { //<{sortloop foo as bar on baz}> if ( expression . length > 5 ) { this . sortKey = expression [ 5 ] ; } //<{sortloop foo on bar}> else if ( expression . length > 3 && expression [ 2 ] . toLowerCase ( ) === Template . language . other ( 'on' ) ) { this . sortKey = expression [ 3 ] ; } else { this . sortKey = Template . language . other ( 'value' ) ; } //<{sortloop foo as bar on baz descending}> if ( expression . length > 6 ) { this . descending = expression [ 6 ] . toLowerCase ( ) === Template . language . other ( \"descending\" ) ; } //<{sortloop foo on bar descending}> or <{sortloop foo as bar descending}> else if ( expression . length > 4 && expression [ 4 ] . toLowerCase ( ) === Template . language . other ( \"descending\" ) ) { this . descending = true ; } //<{sortloop foo descending}> else if ( expression . length > 2 && expression [ 2 ] . toLowerCase ( ) === Template . language . other ( \"descending\" ) ) { this . descending = true ; } else { this . descending = false ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- module -- name : Language description : Language Class . [CODESPLIT] function ( lang , language ) { this . language = lang ; if ( this . language !== 'english' ) { var keys = Object . keys ( language ) , i = keys . length ; while ( i -- !== 0 ) { this [ keys [ i ] ] = language [ keys [ i ] ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- module -- name : _registerMaster - private method description : starts the creation process for master templates [CODESPLIT] function ( objArg ) { var _self = this ; this . _id = 'master-' + Date . now ( ) ; objArg . language = typeof objArg . language !== \"undefined\" ? objArg . language : 'english' ; Globalization . language ( objArg . language , function ( lang ) { _instantiateMetas . call ( _self , objArg , lang ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- module -- name : _instantiateMetas description : instantiates meta data for template then registers plugins . [CODESPLIT] function ( objArg , language ) { this . language = language ; this . _plugins = this . language . coreTags . slice ( ) ; var metaData = objArg . metaData , metaArr = metaData . split ( / \\n+ / ) , i = metaArr . length , reMeta = / ([^=]+)(={1})(.*) / , meta , name , value , keys , l ; if ( metaData . length > 0 ) { while ( i -- ) { if ( / ^\\s+$ / . test ( metaArr [ i ] ) ) continue ; meta = reMeta . exec ( metaArr [ i ] . trim ( ) ) ; name = meta [ 1 ] . toLowerCase ( ) . trim ( ) ; value = meta [ 3 ] . trim ( ) ; if ( _Object . reIdentifier . test ( name ) && meta [ 2 ] === '=' ) { if ( name === this . language . other ( \"plugins\" ) ) { this . _plugins = this . _plugins . concat ( value . toLowerCase ( ) . split ( ',' ) ) ; continue ; } switch ( name [ 0 ] ) { case '\\\\' : this . _metaData [ name . slice ( 1 ) ] = new _Template ( { rawString : value , executeOnce : true , metaKey : name . slice ( 1 ) } , this ) ; break ; case '#' : break ; default : this . _metaData [ name ] = new _Template ( { rawString : value , executeOnce : false } , this ) ; } } } } this . _master = true ; this . onFinishCompiling = objArg . onFinishCompiling ; _registerPlugins . call ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- module -- name : _create - private method description : creates the document list of the Template Class [CODESPLIT] function ( ) { var leftIndex = this . _rawString . indexOf ( '<{' ) , rightIndex = this . _rawString . indexOf ( '}>' ) , expression , tag , lineStart , tagSplit ; if ( leftIndex > - 1 ) { this . _leftCount ++ ; if ( rightIndex > - 1 ) { expression = this . _rawString . slice ( leftIndex + 2 , rightIndex ) ; this . _document . push ( new _String ( this , this . _rawString . slice ( 0 , leftIndex ) ) ) ; this . _rawString = this . _rawString . slice ( rightIndex + 2 ) ; if ( expression . charAt ( 0 ) === ' ' ) { Utilities . warning ( this , 'Invalid whitespace at the start of expression' ) ; } else { tag = expression . split ( ' ' ) [ 0 ] . toLowerCase ( ) ; lineStart = Utilities . getLineCount ( this ) ; tagSplit = tag . split ( '.' ) [ 0 ] ; expression = typeof allPlugins [ this . _tagDelegation [ tagSplit ] ] !== \"undefined\" ? allPlugins [ this . _tagDelegation [ tagSplit ] ] . handleToken ( this , expression , tag ) : Utilities . parseType ( this , expression ) ; if ( typeof expression . skip === \"undefined\" || expression . skip === false ) { expression . lineStart = lineStart ; this . _document . push ( expression ) ; expression . needs = expression . needs || { } ; } } } else { this . _rawString = this . _rawString . slice ( leftIndex + 2 ) ; Utilities . warning ( this , 'Open ended expression' ) ; } } else { if ( this . _rawString . length > 0 ) { this . _document . push ( new _String ( this , this . _rawString ) ) ; } this . _documentLength = this . _document . length ; delete this . _rawString ; tag = Utilities . stringOnly ( this . _document ) ; if ( tag . stringOnly ) { this . _stringOnly = true ; this . _document = [ new _String ( this , tag . string ) ] ; this . _documentLength = 1 ; this . needs = { } ; } this . _templating = false ; _createExecutionOrder . call ( this , this . _master ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- module -- name : _createExecutionOrder - private method description : creates the execution order for a template based on its needs . [CODESPLIT] function ( master ) { _reduceNeeds . call ( this , master ) ; //Rules for out of order execution: //Goal: We want to get anything that is ambiguous or requires a callback //to execute ASAP because they will be our bottlenecks. //Ambiguity means that we don't know if the element will affect anything after it, // so it's safest to assume that it will affect everything after it. //Something that needs a callback is an element that either has a lot of //\tprocess time around it and so should tell the template to wait for it. //\tOr, it is something that needs to make a call to another service, and will, //\titself, be idling for a response, that the template needs. //We want to execute or callbacks, stop processing, and wait for them to get back to us.  //1. Anything that modifies or sets something needs to execute in //\torder against anything that needs that thing (go it! :). //2. Anything that is ambiguous acts as a break point, nothing after it //\tcan render until it's done, ambiguity trumps callbacks. But //\tambiguous things can have callbacks. //3. Anything that doesn't need anything can render at anytime, but, //\tideally, should render as close to the order it is in, when possible. //Note: Contrary to intuition, going in order is actually ideal, save for // our bottlenecks, because the more we can do in order the more we // can buffer to the server in the appropriate order. this . _executionOrders = [ ] ; this . _inAlready = { } ; var i = this . callBackDocs . length , index , l ; //figure ambiguity out while ( i -- ) { if ( this . _inAlready [ index . toString ( ) ] ) continue ; this . _executionOrders . unshift ( [ ] ) ; index = this . callBackDocs [ i ] ; this . _inAlready [ index . toString ( ) ] = true ; _orderNeedsByObject . call ( this , index ) ; this . _executionOrders [ 0 ] . push ( index ) ; } //put everything else in this . _executionOrders . push ( [ ] ) ; l = this . _executionStack . length ; i = 0 ; while ( i < l ) { if ( this . _inAlready [ i . toString ] ) continue ; this . _inAlready [ i . toString ( ) ] = true ; _orderNeedsByObject . call ( this , i ) ; this . _executionOrders [ 0 ] . push ( i ) ; i ++ ; } this . _executionThreadLength = this . _executionOrders . length }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- module -- name : _orderNeedsByObject - private method description : orders the execution stack based on where the current object is . [CODESPLIT] function ( index ) { var obj = this . _executionStack [ index ] , i = index + 1 , temp , t , setsOrModifies ; while ( i -- ) { if ( this . _inAlready [ i . toString ( ) ] ) continue ; temp = this . _executionStack [ i ] ; if ( temp . isAmbiguous ) { if ( typeof temp . needs !== \"undefined\" && Object . keys ( temp . needs ) . length !== 0 ) _orderNeedsByObject . call ( this , i ) ; this . _executionOrders [ 0 ] . unshift ( i ) ; this . _inAlready [ i . toString ( ) ] = true ; continue ; } setsOrModifies = [ ] ; if ( typeof temp . modifies !== \"undefined\" ) { setsOrModifies = setsOrModifies . concat ( Object . keys ( temp . modifies ) ) ; } if ( typeof temp . sets !== \"undefined\" ) { setsOrModifies = setsOrModifies . concat ( Object . keys ( temp . sets ) ) ; } t = setsOrModifies . length ; while ( t -- ) { if ( typeof obj . needs !== \"undefined\" && obj . needs [ setsOrModifies [ t ] ] ) { //We need this object if ( typeof temp . needs !== \"undefined\" && Object . keys ( temp . needs ) . length !== 0 ) _orderNeedsByObject . call ( this , i ) ; this . _executionOrders [ 0 ] . unshift ( i ) ; this . _inAlready [ i . toString ( ) ] = true ; break ; } } } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- module -- name : _reduceNeeds - private method description : reduces the needs sets and modifies objects of all the objects to what they ought to be . [CODESPLIT] function ( master ) { this . needs = { } ; this . sets = { } ; this . modifies = { } ; this . callBackDocs = [ ] ; var docs = this . _document , l = docs . length , i = 0 , arr = [ ] , count = - 1 , doc , needs , sets , modifies , t , key ; //actually figure out what Template needs and sets. Modifies is always correct (even when it isn't :) while ( i < l ) { doc = docs [ i ] ; if ( doc . skip ) { i ++ ; continue ; } //get rid of empty strings; if ( doc instanceof _String && doc . string . length === 0 ) { i ++ ; continue ; } count ++ ; arr . push ( doc ) ; if ( doc . isAmbiguous ) { this . isAmbiguous = true ; } else if ( doc . needsCallback ) { this . needsCallback = true ; this . callBackDocs . push ( count ) ; } if ( typeof doc . sets !== \"undefined\" ) { sets = Object . keys ( doc . sets ) ; t = sets . length ; while ( t -- ) { key = sets [ t ] . toLowerCase ( ) ; if ( typeof this . sets [ key ] === \"undefined\" ) { this . sets [ key ] = true ; } else { delete doc . sets [ sets [ t ] ] ; } } } if ( typeof doc . needs !== \"undefined\" ) { needs = Object . keys ( doc . needs ) ; t = needs . length ; while ( t -- ) { key = needs [ t ] . toLowerCase ( ) ; if ( typeof this . sets [ key ] === \"undefined\" ) { this . needs [ key ] = true ; } } } if ( typeof doc . modifies !== \"undefined\" ) { modifies = Object . keys ( doc . modifies ) ; t = modifies . length ; while ( t -- ) { key = modifies [ t ] . toLowerCase ( ) ; this . modifies [ key ] = true ; } } i ++ ; } this . _executionStack = arr ; this . _executionLength = this . _executionStack . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- Noodles . Template -- name : subExecute - private method [CODESPLIT] function ( Context , first , localObj , callback ) { var i = 0 , arr = first ? this . _executionOrders : localObj . threads [ i ] , l = arr . length , executing = false , _self = this , tempColl = [ ] , buffer = this . _master && Context . bufferMode , exit = false ; while ( i < l && ! Context . exitNow ) { localObj . threads [ i ] = arr [ i ] . reduce ( function ( previous , current ) { if ( executing || Context . exitNow ) { return previous . concat ( current ) ; } if ( typeof localObj . status [ current ] === \"undefined\" ) { if ( _self . _executionStack [ current ] . needsCallback ) { localObj . status [ current ] = 'executing' ; if ( Context . debugMode ) Context . _current = current ; _self . _executionStack [ current ] . execute ( _self , Context , function ( _string ) { localObj . collected [ current ] = _string ; localObj . status [ current ] = 'done' ; _subExecute . call ( _self , Context , false , localObj , callback ) ; } ) ; executing = true ; return previous ; } else { if ( Context . debugMode ) Context . _current = current ; localObj . collected [ current ] = _self . _executionStack [ current ] . execute ( _self , Context ) ; localObj . status [ current ] = 'done' ; return previous ; } } if ( localObj . status [ current ] === 'executing' ) { executing = true ; return previous } if ( localObj . status [ current ] === \"done\" ) { return previous ; } } , [ ] ) ; if ( localObj . threads [ i ] . length === 0 ) { localObj . threads . splice ( i , 1 ) ; l -- ; } executing = false ; i ++ ; } //render and stuff return _finish . call ( this , Context , localObj , callback , tempColl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- Noodles . Template -- name : finish - private method description : finish up everything [CODESPLIT] function ( Context , localObj , callback , tempColl ) { var buffer = this . _master && Context . bufferMode , i , l ; if ( Context . onRender && this . _master ) { i = localObj . startFrom ; l = this . _executionLength ; while ( i < l ) { if ( typeof localObj . status [ i ] === \"undefined\" ) break ; if ( localObj . status [ i ] === \"done\" ) { tempColl . push ( localObj . collected [ i ] ) ; } else { break ; } i ++ ; } tempColl = buffer && this . _master ? new Buffer ( tempColl . join ( '' ) ) : tempColl . join ( '' ) ; if ( this . _master ) Context . onRender ( tempColl , Context ) ; localObj . startFrom = i ; } //finish up. if ( localObj . threads . length === 0 || Context . exitNow ) { tempColl = buffer && this . _master ? new Buffer ( localObj . collected . join ( '' ) ) : localObj . collected . join ( '' ) ; if ( this . _master ) { if ( Context . onRenderAll ) Context . onRenderAll ( tempColl , Context ) ; Context . onFinish ( Date . now ( ) - Context . time , Context ) ; } else { if ( typeof callback === \"function\" ) { callback ( tempColl ) ; } else { if ( this . _executeOnce ) { Context . _metaSkip [ this . _metaKey ] = true ; Context . setObject ( this , this . _metaKey , tempColl ) } return tempColl ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- Noodles -- name : _registerPlugins - private method description : registers the plugins of the Template Class [CODESPLIT] function ( ) { var i = this . _plugins . length , num = i , _self = this , key , value , t , plugin ; while ( i -- ) { key = this . language . plugin ( this . _plugins [ i ] ) ; if ( typeof allPlugins [ key ] !== \"undefined\" ) { plugin = allPlugins [ key ] ; if ( BrowserEnvironment && ! plugin . browserFriendly ) Utilities . warning ( this , [ \"The following plugin will not work for the browser: \" , _self . language . others ( plugin . pluginName ) ] ) ; if ( typeof plugin . onTemplateCreate !== \"undefined\" ) plugin . onTemplateCreate ( this , function ( ) { num -- ; if ( typeof plugin . willHandle !== \"undefined\" && plugin . handleToken !== \"undefined\" ) { var handle = plugin . willHandle ( _self ) , t = handle . length ; while ( t -- ) { _self . _tagDelegation [ handle [ t ] ] = plugin . pluginName ; } if ( num === 0 ) { num = - 1 ; _startCreate . call ( _self ) ; } } } ) ; } else { _grabPlugin . call ( this , key , function ( ) { num -- ; if ( num === 0 ) { num = - 1 ; _startCreate . call ( _self ) ; } } ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- Noodles -- name : _grabPlugin - private method description : grabs the actual plugin files for the browser though . [CODESPLIT] function ( pluginName , callback , deep ) { var file = ( deep ? './../../../noodles_plugins/' : './../plugins/' ) + pluginName + '/' + pluginName , _self = this ; require ( [ file ] , function ( plugin ) { if ( typeof plugin === \"undefined\" || typeof plugin . Plugin === \"undefined\" ) { if ( deep ) throw pluginName + \" does not exist as a plugin.\" ; else return _grabPlugin . call ( _self , pluginName , callback , true ) ; } plugin = plugin . Plugin ; if ( typeof plugin . getNoodles !== \"undefined\" ) { plugin . getNoodles ( _Noodles ) ; } plugin = new _Noodles . Plugin ( plugin ) ; if ( typeof plugin . pluginName === \"undefined\" ) { throw \"The following plugin needs a plugin name: \" + plugin . toString ( ) ; } if ( BrowserEnvironment && ! plugin . browserFriendly ) Utilities . warning ( _self , [ \"The following plugin will not work for the browser: \" , _self . language . others ( plugin . pluginName ) ] ) ; if ( typeof plugin . onTemplateCreate !== \"undefined\" ) { plugin . onTemplateCreate ( _self , function ( ) { allPlugins [ plugin . pluginName ] = plugin ; if ( typeof plugin . willHandle !== \"undefined\" && plugin . handleToken !== \"undefined\" ) { var handle = plugin . willHandle ( _self ) , t = handle . length ; while ( t -- ) { _self . _tagDelegation [ handle [ t ] ] = plugin . pluginName ; } } callback ( ) ; } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse string [CODESPLIT] function parse ( str ) { var args = [ ] . slice . call ( arguments , 1 ) ; var i = 0 ; return str . replace ( / %s / g , function ( ) { return args [ i ++ ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute with promises [CODESPLIT] function qExec ( command , options ) { var d = Q . defer ( ) ; exec ( command , options , function ( err , stdout , stderr ) { if ( err ) { err . stdout = stdout ; err . stderr = stderr ; return d . reject ( err ) ; } return d . resolve ( stdout , stderr ) ; } ) ; return d . promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--- implements ------------------------------------------ [CODESPLIT] function DataType_Object_clone ( source , // @arg Any             - source object. depth , // @arg Integer = 0     - max depth, 0 is infinity. hook ) { // @arg Function = null - handle the unknown object. // @ret Any             - copied object. // @throw TypeError(\"DataCloneError: ...\") // @desc Object with the reference -> deep copy //       Object without the reference -> shallow copy //       do not look prototype chain. //{@dev $valid ( $type ( depth , \"Number|omit\" ) , DataType_Object_clone , \"depth\" ) ; $valid ( $type ( hook , \"Function|omit\" ) , DataType_Object_clone , \"hook\" ) ; //}@dev return _clone ( source , depth || 0 , hook , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "function _getConstructorName ( value ) { // [CODESPLIT] function _cloneArray ( source , depth , hook , nest ) { var result = [ ] ; result . length = source . length ; for ( var i = 0 , iz = source . length ; i < iz ; ++ i ) { if ( i in source ) { result [ i ] = _clone ( source [ i ] , depth , hook , nest + 1 ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eslint - disable - line indent ----------- [CODESPLIT] function parse_query_string ( query_string ) { const query_object = { } ; const query_pairs = query_string . split ( / &+ / ) ; for ( const pair of query_pairs ) { let separator_index = pair . indexOf ( '=' ) ; if ( 0 === separator_index ) { separator_index = pair . indexOf ( '=' , 1 ) ; } /* eslint-disable indent */ const key = decode ( pair . substring ( 0 , - 1 === separator_index ? undefined : separator_index , ) ) ; const value = - 1 === separator_index ? true : pair . length === separator_index + 1 ? null : decode ( pair . substring ( separator_index + 1 ) ) ; /* eslint-enable indent */ if ( is_composite_key ( key ) ) { add_composite_value ( key , value ) ; } else { query_object [ decode ( key ) ] = value ; } } return query_object ; // ----------- function is_composite_key ( key ) { const open_brack_i = key . indexOf ( '[' , 1 ) ; return open_brack_i > 0 && key . includes ( ']' , open_brack_i ) ; } function add_composite_value ( key , value ) { const path_keys = get_path_keys ( key ) ; let query_object_value = query_object ; for ( let i = 0 , n = path_keys . length - 1 ; i <= n ; i ++ ) { const path_key = path_keys [ i ] ; if ( i === n ) { if ( null === path_key && query_object_value instanceof Set ) { // eslint-disable-line indent query_object_value . add ( value ) ; } else { /* eslint-disable indent */ const real_path_key = Array . isArray ( query_object_value ) ? path_key : null === path_key ? '' : String ( path_key ) ; /* eslint-enable indent */ query_object_value [ real_path_key ] = value ; } } else { ensure_query_object_value ( path_key , path_keys [ i + 1 ] ) ; } } return true ; // ----------- function ensure_query_object_value ( path_key , next_path_key ) { if ( ! query_object_value [ path_key ] ) { /* eslint-disable indent */ query_object_value [ path_key ] = 'number' === typeof next_path_key ? [ ] : null === next_path_key ? new Set : { } ; /* eslint-enable indent */ } else if ( 'string' === typeof next_path_key && Array . isArray ( query_object_value [ path_key ] ) ) { // eslint-disable-line indent query_object_value [ path_key ] = convert_to_object ( query_object_value [ path_key ] , ) ; // eslint-disable-line indent } else if ( 'string' === typeof next_path_key && query_object_value [ path_key ] instanceof Set ) { // eslint-disable-line indent query_object_value [ path_key ] = convert_to_object ( Array . from ( query_object_value [ path_key ] ) , ) ; // eslint-disable-line indent } query_object_value = query_object_value [ path_key ] ; return true ; } function convert_to_object ( arr ) { const obj = { } ; const indices = Object . keys ( arr ) ; for ( const index of indices ) { obj [ String ( index ) ] = arr [ index ] ; } return obj ; } } function get_path_keys ( path_string ) { const path_keys = [ ] ; let unparsed_path = path_string ; while ( unparsed_path ) { const open_brack_i = unparsed_path . indexOf ( '[' ) ; if ( 0 === open_brack_i ) { const close_brack_i = unparsed_path . indexOf ( ']' , open_brack_i ) ; // eslint-disable-line indent path_keys . push ( unparsed_path . substring ( 1 , close_brack_i ) , ) ; // eslint-disable-line indent unparsed_path = unparsed_path . substring ( close_brack_i + 1 ) ; } else { const path_key = - 1 === open_brack_i ? unparsed_path : unparsed_path . substring ( 0 , open_brack_i ) ; // eslint-disable-line indent path_keys . push ( path_key ) ; unparsed_path = - 1 === open_brack_i ? '' : unparsed_path . substring ( open_brack_i ) ; // eslint-disable-line indent } } return path_keys . map ( coerce_numbers ) ; // ----------- function coerce_numbers ( item ) { return '' === item ? null : ! isNaN ( item ) && 'Infinity' !== item ? Number ( item ) : item // eslint-disable-line indent ; // eslint-disable-line indent } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------- [CODESPLIT] function ensure_query_object_value ( path_key , next_path_key ) { if ( ! query_object_value [ path_key ] ) { /* eslint-disable indent */ query_object_value [ path_key ] = 'number' === typeof next_path_key ? [ ] : null === next_path_key ? new Set : { } ; /* eslint-enable indent */ } else if ( 'string' === typeof next_path_key && Array . isArray ( query_object_value [ path_key ] ) ) { // eslint-disable-line indent query_object_value [ path_key ] = convert_to_object ( query_object_value [ path_key ] , ) ; // eslint-disable-line indent } else if ( 'string' === typeof next_path_key && query_object_value [ path_key ] instanceof Set ) { // eslint-disable-line indent query_object_value [ path_key ] = convert_to_object ( Array . from ( query_object_value [ path_key ] ) , ) ; // eslint-disable-line indent } query_object_value = query_object_value [ path_key ] ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------- [CODESPLIT] function coerce_numbers ( item ) { return '' === item ? null : ! isNaN ( item ) && 'Infinity' !== item ? Number ( item ) : item // eslint-disable-line indent ; // eslint-disable-line indent }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if Parameter ( sub ) List has a type Field . Example : @apiSuccess varname1 No type . @apiSuccess { String } varname2 With type . [CODESPLIT] function _hasTypeInFields ( fields ) { var result = false ; $ . each ( fields , function ( name ) { if ( _ . any ( fields [ name ] , function ( item ) { return item . type ; } ) ) result = true ; } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "On Template changes recall plugins . [CODESPLIT] function initDynamic ( ) { // bootstrap popover $ ( 'a[data-toggle=popover]' ) . popover ( ) . click ( function ( e ) { e . preventDefault ( ) ; } ) ; var version = $ ( '#version strong' ) . html ( ) ; $ ( '#sidenav li' ) . removeClass ( 'is-new' ) ; if ( apiProject . template . withCompare ) { $ ( '#sidenav li[data-version=\\'' + version + '\\']' ) . each ( function ( ) { var group = $ ( this ) . data ( 'group' ) ; var name = $ ( this ) . data ( 'name' ) ; var length = $ ( '#sidenav li[data-group=\\'' + group + '\\'][data-name=\\'' + name + '\\']' ) . length ; var index = $ ( '#sidenav li[data-group=\\'' + group + '\\'][data-name=\\'' + name + '\\']' ) . index ( $ ( this ) ) ; if ( length === 1 || index === ( length - 1 ) ) $ ( this ) . addClass ( 'is-new' ) ; } ) ; } // tabs $ ( '.nav-tabs-examples a' ) . click ( function ( e ) { e . preventDefault ( ) ; $ ( this ) . tab ( 'show' ) ; } ) ; $ ( '.nav-tabs-examples' ) . find ( 'a:first' ) . tab ( 'show' ) ; // sample request switch $ ( '.sample-request-switch' ) . click ( function ( e ) { var name = '.' + $ ( this ) . attr ( 'name' ) + '-fields' ; $ ( name ) . addClass ( 'hide' ) ; $ ( this ) . parent ( ) . next ( name ) . removeClass ( 'hide' ) ; } ) ; // init modules sampleRequest . initDynamic ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change version of an article to compare it to an other version . [CODESPLIT] function changeVersionCompareTo ( e ) { e . preventDefault ( ) ; var $root = $ ( this ) . parents ( 'article' ) ; var selectedVersion = $ ( this ) . html ( ) ; var $button = $root . find ( '.version' ) ; var currentVersion = $button . find ( 'strong' ) . html ( ) ; $button . find ( 'strong' ) . html ( selectedVersion ) ; var group = $root . data ( 'group' ) ; var name = $root . data ( 'name' ) ; var version = $root . data ( 'version' ) ; var compareVersion = $root . data ( 'compare-version' ) ; if ( compareVersion === selectedVersion ) return ; if ( ! compareVersion && version == selectedVersion ) return ; if ( compareVersion && articleVersions [ group ] [ name ] [ 0 ] === selectedVersion || version === selectedVersion ) { // the version of the entry is set to the highest version (reset) resetArticle ( group , name , version ) ; } else { var $compareToArticle = $ ( 'article[data-group=\\'' + group + '\\'][data-name=\\'' + name + '\\'][data-version=\\'' + selectedVersion + '\\']' ) ; var sourceEntry = { } ; var compareEntry = { } ; $ . each ( apiByGroupAndName [ group ] [ name ] , function ( index , entry ) { if ( entry . version === version ) sourceEntry = entry ; if ( entry . version === selectedVersion ) compareEntry = entry ; } ) ; var fields = { article : sourceEntry , compare : compareEntry , versions : articleVersions [ group ] [ name ] } ; // add unique id // TODO: replace all group-name-version in template with id. fields . article . id = fields . article . group + '-' + fields . article . name + '-' + fields . article . version ; fields . article . id = fields . article . id . replace ( / \\. / g , '_' ) ; fields . compare . id = fields . compare . group + '-' + fields . compare . name + '-' + fields . compare . version ; fields . compare . id = fields . compare . id . replace ( / \\. / g , '_' ) ; var entry = sourceEntry ; if ( entry . parameter && entry . parameter . fields ) fields . _hasTypeInParameterFields = _hasTypeInFields ( entry . parameter . fields ) ; if ( entry . error && entry . error . fields ) fields . _hasTypeInErrorFields = _hasTypeInFields ( entry . error . fields ) ; if ( entry . success && entry . success . fields ) fields . _hasTypeInSuccessFields = _hasTypeInFields ( entry . success . fields ) ; if ( entry . info && entry . info . fields ) fields . _hasTypeInInfoFields = _hasTypeInFields ( entry . info . fields ) ; var entry = compareEntry ; if ( fields . _hasTypeInParameterFields !== true && entry . parameter && entry . parameter . fields ) fields . _hasTypeInParameterFields = _hasTypeInFields ( entry . parameter . fields ) ; if ( fields . _hasTypeInErrorFields !== true && entry . error && entry . error . fields ) fields . _hasTypeInErrorFields = _hasTypeInFields ( entry . error . fields ) ; if ( fields . _hasTypeInSuccessFields !== true && entry . success && entry . success . fields ) fields . _hasTypeInSuccessFields = _hasTypeInFields ( entry . success . fields ) ; if ( fields . _hasTypeInInfoFields !== true && entry . info && entry . info . fields ) fields . _hasTypeInInfoFields = _hasTypeInFields ( entry . info . fields ) ; var content = templateCompareArticle ( fields ) ; $root . after ( content ) ; var $content = $root . next ( ) ; // Event on.click re-assign $content . find ( '.versions li.version a' ) . on ( 'click' , changeVersionCompareTo ) ; // select navigation $ ( '#sidenav li[data-group=\\'' + group + '\\'][data-name=\\'' + name + '\\'][data-version=\\'' + currentVersion + '\\']' ) . addClass ( 'has-modifications' ) ; $root . remove ( ) ; // TODO: on change main version or select the highest version re-render } initDynamic ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare all currently selected Versions with their predecessor . [CODESPLIT] function changeAllVersionCompareTo ( e ) { e . preventDefault ( ) ; $ ( 'article:visible .versions' ) . each ( function ( ) { var $root = $ ( this ) . parents ( 'article' ) ; var currentVersion = $root . data ( 'version' ) ; var $foundElement = null ; $ ( this ) . find ( 'li.version a' ) . each ( function ( ) { var selectVersion = $ ( this ) . html ( ) ; if ( selectVersion < currentVersion && ! $foundElement ) $foundElement = $ ( this ) ; } ) ; if ( $foundElement ) $foundElement . trigger ( 'click' ) ; } ) ; initDynamic ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add article settings . [CODESPLIT] function addArticleSettings ( fields , entry ) { // add unique id // TODO: replace all group-name-version in template with id. fields . id = fields . article . group + '-' + fields . article . name + '-' + fields . article . version ; fields . id = fields . id . replace ( / \\. / g , '_' ) ; if ( entry . header && entry . header . fields ) fields . _hasTypeInHeaderFields = _hasTypeInFields ( entry . header . fields ) ; if ( entry . parameter && entry . parameter . fields ) fields . _hasTypeInParameterFields = _hasTypeInFields ( entry . parameter . fields ) ; if ( entry . error && entry . error . fields ) fields . _hasTypeInErrorFields = _hasTypeInFields ( entry . error . fields ) ; if ( entry . success && entry . success . fields ) fields . _hasTypeInSuccessFields = _hasTypeInFields ( entry . success . fields ) ; if ( entry . info && entry . info . fields ) fields . _hasTypeInInfoFields = _hasTypeInFields ( entry . info . fields ) ; // add template settings fields . template = apiProject . template ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render Article . [CODESPLIT] function renderArticle ( group , name , version ) { var entry = { } ; $ . each ( apiByGroupAndName [ group ] [ name ] , function ( index , currentEntry ) { if ( currentEntry . version === version ) entry = currentEntry ; } ) ; var fields = { article : entry , versions : articleVersions [ group ] [ name ] } ; addArticleSettings ( fields , entry ) ; return templateArticle ( fields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render original Article and remove the current visible Article . [CODESPLIT] function resetArticle ( group , name , version ) { var $root = $ ( 'article[data-group=\\'' + group + '\\'][data-name=\\'' + name + '\\']:visible' ) ; var content = renderArticle ( group , name , version ) ; $root . after ( content ) ; var $content = $root . next ( ) ; // Event on.click muss neu zugewiesen werden (sollte eigentlich mit on automatisch funktionieren... sollte) $content . find ( '.versions li.version a' ) . on ( 'click' , changeVersionCompareTo ) ; $ ( '#sidenav li[data-group=\\'' + group + '\\'][data-name=\\'' + name + '\\'][data-version=\\'' + version + '\\']' ) . removeClass ( 'has-modifications' ) ; $root . remove ( ) ; return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load google fonts . [CODESPLIT] function loadGoogleFontCss ( ) { var host = document . location . hostname . toLowerCase ( ) ; var protocol = document . location . protocol . toLowerCase ( ) ; var googleCss = '//fonts.googleapis.com/css?family=Source+Code+Pro|Source+Sans+Pro:400,600,700' ; if ( host == 'localhost' || ! host . length || protocol === 'file:' ) googleCss = 'http:' + googleCss ; $ ( '<link/>' , { rel : 'stylesheet' , type : 'text/css' , href : googleCss } ) . appendTo ( 'head' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return ordered entries by custom order and append not defined entries to the end . [CODESPLIT] function sortByOrder ( elements , order , splitBy ) { var results = [ ] ; order . forEach ( function ( name ) { if ( splitBy ) elements . forEach ( function ( element ) { var parts = element . split ( splitBy ) ; var key = parts [ 1 ] ; // reference keep for sorting if ( key == name ) results . push ( element ) ; } ) ; else elements . forEach ( function ( key ) { if ( key == name ) results . push ( name ) ; } ) ; } ) ; // Append all other entries that ar not defined in order elements . forEach ( function ( element ) { if ( results . indexOf ( element ) === - 1 ) results . push ( element ) ; } ) ; return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************** writeGithubActionList : write all selected action ************************************************** [CODESPLIT] function writeGithubActionList ( ) { var newVersion , tagMessage ; _console . writelnYellow ( '**************************************************' ) ; _console . writelnYellow ( 'ACTIONS:' ) ; if ( grunt . config ( 'build' ) ) _console . writelnYellow ( '- Build/compile the ' + ( options . isApplication ? 'application' : 'packages' ) ) ; if ( grunt . config ( 'newVersion' ) != 'none' ) { newVersion = semver . inc ( options . currentVersion , grunt . config ( 'newVersion' ) ) ; _console . writelnYellow ( '- Bump \\'version: \"' + newVersion + '\"\\' to bower.json and package.json' ) ; } if ( grunt . config ( 'commit' ) == 'commit' ) _console . writelnYellow ( '- Commit staged changes to a new snapshot. Message=\"' + grunt . config ( 'commitMessage' ) + '\"' ) ; else _console . writelnYellow ( '- Amend/combine staged changes with the previous commit' ) ; if ( grunt . config ( 'newVersion' ) != 'none' ) { tagMessage = grunt . config ( 'tagMessage' ) ; _console . writelnYellow ( '- Create new tag=\"' + newVersion + ( tagMessage ? ': ' + tagMessage : '' ) + '\"' ) ; } if ( options . haveGhPages ) _console . writelnYellow ( '- Merge \"master\" branch into \"gh-pages\" branch' ) ; else grunt . config . set ( 'release.options.afterRelease' , [ ] ) ; //Remove all git merge commands if ( grunt . config ( 'newVersion' ) == 'none' ) _console . writelnYellow ( '- Push all branches to GitHub' ) ; else _console . writelnYellow ( '- Push all branches and tags to GitHub' ) ; _console . writelnYellow ( '**************************************************' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "******************************************************* runGithubTasks : Run all the needed github - commands ******************************************************* [CODESPLIT] function runGithubTasks ( ) { function writeHeader ( header ) { grunt . log . writeln ( '' ) ; _console . writelnYellow ( '**************************************************' ) ; _console . writelnYellow ( header . toUpperCase ( ) ) ; } if ( ! grunt . config ( 'continue' ) ) return 0 ; //Get new version and commit ang tag messages var newVersion = grunt . config ( 'newVersion' ) == 'none' ? '' : semver . inc ( options . currentVersion , grunt . config ( 'newVersion' ) ) , commitMessage = grunt . config ( 'commitMessage' ) || 'No message' , tagMessage = grunt . config ( 'tagMessage' ) || '' , userName ; if ( newVersion ) { //Create tagMessage userName = grunt . config ( 'gitinfo' ) . userName || grunt . fcoo . bowerJson . authors ; //grunt.fcoo.bowerJson.authors is fall-back tagMessage = ' -m \"Version ' + newVersion + '\"' + ' -m \"Released ' + grunt . fcoo . todayStr + ' by ' + userName + ' (https://github.com/orgs/FCOO/people)\"' + ( tagMessage ? ' -m \"' + tagMessage + '\"' : '' ) ; //Update grunt.fcoo.bowerJson grunt . fcoo . bowerJson . version = newVersion ; } //Build application/packages if ( grunt . config ( 'build' ) ) { writeHeader ( 'Build/compile the ' + ( options . isApplication ? 'application' : 'packages' ) ) ; common . runCmd ( 'grunt build' , true ) ; } //Bump bower.json and packages.json if ( newVersion ) { writeHeader ( 'Bump \\'version: \"' + newVersion + '\"\\' to bower.json and package.json' ) ; var files = [ 'bower.json' , 'package.json' ] , file , json ; for ( var i = 0 ; i < files . length ; i ++ ) { file = files [ i ] ; json = grunt . file . readJSON ( file ) ; json . version = newVersion ; grunt . file . write ( file , JSON . stringify ( json , null , '  ' ) + '\\n' ) ; grunt . log . writeln ( file + '-OK' ) ; } //Replace {VERSION] with newVersion in all js in dist if ( options . isPackage ) { common . runCmd ( 'grunt replace:Dist_js_version' ) ; } } //git add all common . runCmd ( 'git add -A' ) ; //commit or amend if ( grunt . config ( 'commit' ) == 'commit' ) { //commit writeHeader ( 'Commit staged changes to a new snapshot' ) ; common . runCmd ( 'git commit  -m \"' + commitMessage + '\"' ) ; } else { writeHeader ( 'Combine/amend staged changes with the previous commit' ) ; common . runCmd ( 'git commit --amend --no-edit' ) ; } //git tag if ( newVersion ) { writeHeader ( 'Create new tag=\"' + newVersion + '\"' ) ; common . runCmd ( 'git tag ' + newVersion + tagMessage ) ; } //git push (and push tag) writeHeader ( 'Push all branches ' + ( newVersion ? 'and tags ' : '' ) + 'to GitHub' ) ; common . runCmd ( 'git push \"origin\" HEAD' ) ; if ( newVersion ) common . runCmd ( 'git push \"origin\" ' + newVersion ) ; //Merge \"master\" into \"gh-pages\" if ( options . haveGhPages ) { writeHeader ( 'Merge \"master\" branch into \"gh-pages\" branch' ) ; common . runCmd ( 'git checkout -B \"gh-pages\"' ) ; common . runCmd ( 'git merge master' ) ; common . runCmd ( 'git checkout master' ) ; common . runCmd ( 'git push \"origin\" gh-pages' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create merge function @funtion mergeArgs [CODESPLIT] function mergeArgs ( target , args ) { // require target object assert . ok ( target && typeof target === 'object' , 'target must be object' ) // if args is undefined then nothing to do if ( args === undefined ) { return } // require args to be object assert . ok ( args && typeof args === 'object' , 'args must be object' ) // check it target is empty var targetIsEmpty = _ . keys ( target ) . length === 0 ? true : false // iterate over args properties _ . each ( args , ( val , key ) => { // only validate against target if target has properties if ( ! targetIsEmpty ) { // require key to exist in target assert . ok ( target . hasOwnProperty ( key ) , 'invalid argument ' + key ) // if target property has type then type must match if ( target [ key ] !== undefined ) { assert . ok ( typeof target [ key ] === typeof args [ key ] , 'invalid type ' + typeof args [ key ] + ' for ' + key + ' ' + typeof target [ key ] + ' required' ) } } // if property is an array then either concat or replace if ( Array . isArray ( target [ key ] ) ) { // concat arrays if ( config . concatArrays ) { target [ key ] = target [ key ] . concat ( args [ key ] ) } // otherwise replace else { target [ key ] = args [ key ] } } // if property is an object then do recursive merge else if ( typeof target [ key ] === 'object' ) { mergeArgs ( target [ key ] , args [ key ] ) } // all other values overwrite else { target [ key ] = args [ key ] } } ) // convert empty strings to undefined if ( config . emptyStringUndefined ) { _ . each ( target , ( val , key ) => { if ( typeof val === 'string' && val . length === 0 ) { target [ key ] = undefined } } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "******************************************************************************** 3 : Create list of all packages used by the application in dist / log / packages . md and dist / log / packages . txt ******************************************************************************** [CODESPLIT] function _addPackage ( pname , bowerJson , depOptions , firstLevel , dotBowerJson ) { if ( ! firstLevel ) depOptions . list . push ( { name : bowerJson . name || dotBowerJson . name || pname , homepage : bowerJson . homepage || dotBowerJson . homepage || '' , version : bowerJson . version || dotBowerJson . version || '' } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search constructor [CODESPLIT] function Search ( document , tree ) { this . document = document ; this . tree = tree ; this . onlyFlag = false ; this . onlySearch = false ; this . searchFilled = false ; this . searchList = { 'id' : null , 'tag' : null , 'attr' : [ ] } ; this . nodeList = [ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Node constructor [CODESPLIT] function Node ( document , elem ) { this . document = document ; this . elem = elem ; // precalculate these, since they in any case will be used this . _isRoot = elem . nodeType === 9 ; if ( this . _isRoot === false ) { this . _tagName = elem . tagName . toLowerCase ( ) ; this . _isSingleton = NO_ENDING_TAG . indexOf ( this . _tagName ) !== - 1 ; } else { this . _tagName = '' ; this . _isSingleton = false ; } this . isChunked = false ; this . isContainer = false ; // allow node object to be reused document . elemCache . push ( elem ) ; document . nodeCache . push ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- Main Type and Public API -- / * QB - The primary type of the qb package [CODESPLIT] function QB ( options ) { if ( ! ( this instanceof QB ) ) { return new QB ( options ) ; } // Super constructor MiddlewareProvider . call ( this ) ; var qb = this ; // Init qb . _options = defaults ( options , default_options ) qb . _types = { } qb . _aliases = { } qb . name = qb . _options . name // TODO process this into .alias _processAliasOptions ( qb , qb . _options . aliases ) qb . log = book . default ( ) ; if ( qb . _options . catch_sigterm_end ) handleSigterm ( qb ) ; _listen ( qb ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- Helpers -- [CODESPLIT] function _listen ( qb ) { qb . on ( 'error' , function ( err , next ) { qb . log . error ( err ) next ( ) } ) qb . on ( 'process' , function ( type , task , next ) { try { qb . _types [ type ] ( task , callback ) ; } catch ( err ) { callback ( err ) ; } function callback ( err ) { next ( err ) // We don't pass errors through because that is not for \"task failure\" errors if ( err ) { qb . emit ( 'fail' , err , type , task , errcallback ( qb ) ) ; } else { qb . emit ( 'finish' , type , task , errcallback ( qb ) ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "MatchedRoute ============ constructor ----------- create a matched route that can construct a path using the matched params and route pattern ### required arguments ** name ** : name for this route ** params ** : params for this route ** pattern ** : pattern for this route [CODESPLIT] function MatchedRoute ( args ) { this . name = args . name ; this . params = args . params ; this . pattern = args . pattern ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为 非空字符串 [CODESPLIT] function _isUnEmptyString ( val , options ) { var opts = _isObject ( options ) ? options : { } ; if ( ! _isString ( val ) ) { return false ; } if ( opts . isStrict === false ) { return val !== '' ; } // @TODO // 引用: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim // String.prototype.trim, 在 ECMAScript 5.1 定义, 在 JavaScript 1.8.1 实现 // return val.replace(REGEX_ENUM.LEFT_WHITE_SPACE_REX, '').replace(REGEX_ENUM.RIGHT_WHITE_SPACE_REX, '') !== ''; return val . trim ( ) !== '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- Coretags -- name : onTemplateCreate description : executed on template creation [CODESPLIT] function ( Template ) { Template . endTags = Template . endTags || { } ; Template . endTags [ Template . language . tag ( 'if' ) ] = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- Coretags -- name : handleToken description : executed when any tag in willHandle is found [CODESPLIT] function ( Template , expression , tag ) { switch ( tag ) { case Template . language . tag ( 'if' ) : return new Conditional ( Template , expression ) ; default : return { skip : true } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- module -- name : Conditional description : Conditional execution [CODESPLIT] function ( Template , expression ) { this . rawString = Noodles . Utilities . grabToEndSliceRaw ( Template , expression , Template . language . tag ( 'If' ) ) ; this . needs = { } ; this . conditions = [ { condition : _parseCondtions . call ( this , Template , expression , true ) } ] ; _parseConditional . call ( this , Template ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- module -- name : Condition description : Condition [CODESPLIT] function ( condition , Conditional , Template ) { this . leftSide = Noodles . Utilities . parseType ( Template , condition [ 2 ] ) ; Conditional . needs = Noodles . Utilities . mergeObjectWith ( Conditional . needs , this . leftSide . needs ) ; this . leftNegate = condition [ 1 ] . length > 0 ; this . super = false ; if ( typeof condition [ 3 ] !== \"undefined\" && condition [ 5 ] . length > 0 ) { switch ( condition [ 3 ] ) { case Template . language . other ( 'contains' ) : this . expression = 'contains' ; break ; case Template . language . other ( 'startswith' ) : this . expression = 'startswith' ; break ; case Template . language . other ( 'endswith' ) : this . expression = 'endswith' ; break ; case Template . language . other ( 'matches' ) : this . expression = 'matches' ; default : this . expression = condition [ 3 ] . toLowerCase ( ) ; } this . rightSide = Noodles . Utilities . parseType ( Template , condition [ 5 ] ) ; this . rightNegate = condition [ 4 ] . length > 0 Conditional . needs = Noodles . Utilities . mergeObjectWith ( Conditional . needs , this . rightSide . needs ) ; } else { this . expression = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Esprima based explicitly [CODESPLIT] function browserifyNgInject ( opt ) { var options = defaults ( opt , { filter : defaultFilter // remove files that cannot be parsed by esprima } ) , updater = getUpdater ( throwError ) ; return esprimaTools . createTransform ( updater , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a ) ngModel compares by reference not value . This is important when binding to an array of objects . b ) Regardless of data type also check whether the given model exists within the options - data [CODESPLIT] function ( scope ) { if ( scope . model ) { var modelInData = false ; for ( var i = 0 ; i < scope . data . length ; i ++ ) { if ( angular . equals ( scope . data [ i ] , scope . model ) ) { scope . model = scope . data [ i ] ; modelInData = true ; break ; } } if ( ! modelInData ) { scope . model = null ; } } if ( ! scope . model && ! scope . chooseText && scope . data . length ) { scope . model = scope . data [ 0 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns monad definitions suitable for @mfjs / compiler from bind and pure implementation for it . [CODESPLIT] function makeMonad ( ibind , ipure , check ) { return generate ( { inner : { bind : ibind , pure : ipure , check : check } , coerce : check != null } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ tagname : str } [CODESPLIT] function getTagInfo ( buff ) { let robj = { } ; let pos = 0 ; let bi = - 1 ; let ckey = '' ; let cinfo = '' ; do { bi = buff . indexOf ( '//<--' , pos ) ; if ( bi >= 0 ) { let kbi = buff . indexOf ( ' Begin' , bi ) ; if ( kbi < 0 ) { return robj ; } ckey = buff . substr ( bi , kbi - bi ) ; let ei = buff . indexOf ( '//<--' + ckey + ' End' , kbi ) ; if ( ei < 0 ) { return robj ; } cinfo = buff . substr ( kbi + 6 , ei - kbi - 6 ) ; robj [ ckey ] = cinfo ; pos = kbi + 5 + ckey . length + 4 ; } } while ( bi >= 0 ) ; return robj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes the url to a user group or persona [CODESPLIT] function scopeUrl ( options , inst ) { options = _ . extend ( options || { } , inst ) if ( ! options . url && ! options . user_id && ! options . group_id && ! ( options . query || options . query . owner_type && options . query . owner_id ) ) { return callback ( new Error ( 'user_id or group_id or (owner_type and owner_id) are required' ) ) } if ( options . user_id ) { return ngin . User . urlRoot ( ) + '/' + options . user_id + '/personas' } if ( options . group_id ) { return ngin . Group . urlRoot ( ) + '/' + options . group_id + '/personas' } if ( options . url || options . query . owner_type && options . query . owner_id ) { return Persona . urlRoot ( ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wrap request [CODESPLIT] function nosRequest ( { method , uri , body = '' , headers = { } } ) { return new Promise ( ( resolve , reject ) => { request ( { method , uri , body , headers } , function ( err , response , body ) { if ( err ) { return reject ( err ) ; } if ( response . statusCode >= 400 ) { parseString ( body ) . then ( ( { Error } ) => { let e = { code : Error . Code . join ( '' ) , message : Error . Message . join ( '' ) } ; reject ( e ) ; } ) . catch ( reject ) ; } else if ( body ) { if ( typeof body === 'string' && response . headers [ 'content-type' ] . toLowerCase ( ) === XML_MINE ) { parseString ( body ) . then ( json => { resolve ( json ) ; } ) . catch ( reject ) ; } else { resolve ( assign ( { body : body , url : headers . url } ) ) ; } } else { let ret = pick ( response . headers , [ 'content-type' , 'x-nos-request-id' , 'etag' , 'content-range' , 'last-modified' , 'content-length' ] ) ; assign ( ret , { url : headers . url } ) ; resolve ( ret ) ; } } ) ; } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "删除一个对象 [CODESPLIT] function ( host , accessKey , secretKey , bucket , objectKey , opts = { } ) { let date = utcDate ( ) ; let resource = genResource ( bucket , objectKey , opts ) ; let authorization = authorize ( accessKey , secretKey , 'DELETE' , [ ] , \"\" , date , resource ) ; let url = ` ${ bucket } ${ host } ${ objectKey } ` ; let headers = { Date : date , Authorization : authorization } ; return nosRequest ( { method : 'del' , uri : url , headers } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "批量删除对象 [CODESPLIT] function ( host , accessKey , secretKey , bucket , objects , opts = { } ) { if ( ! objects . length ) { return Promise . reject ( new Error ( 'nothing to delete' ) ) ; } let date = utcDate ( ) ; let content = deletePayload ( { objects , quiet : opts . quiet } ) ; let contentLength = content . length ; let url = ` ${ bucket } ${ host } ` ; let authorization = authorize ( accessKey , secretKey , 'POST' , '' , '' , date , [ ] , '' ) ; let headers = { Date : date , Authorization : authorization , 'Content-Length' : contentLength } ; return nosRequest ( { method : 'post' , body : content , headers , uri : url } ) . then ( res => { if ( ! opts . quiet ) { if ( res . DeleteResult ) { let { Error } = res . DeleteResult ; let ret = Error . map ( ( detail ) => { return { key : detail . Key . join ( '' ) , code : detail . Code . join ( '' ) , message : detail . Message . join ( '' ) } } ) ; return { error : ret } } else { return { } ; } } let { Deleted = [ ] , Error = [ ] } = res . DeleteResult ; let deleted = Deleted . map ( detail => { return detail . Key . join ( '' ) ; } ) ; let error = Error . map ( ( detail ) => { return { key : detail . Key . join ( '' ) , code : detail . Code . join ( '' ) , message : detail . Message . join ( '' ) } } ) ; return { deleted , error } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add explicit dependency statements to the node . [CODESPLIT] function processNode ( node ) { // check if the function is part of a variable assignment var isVarAssignment = ( node . parent . type === 'VariableDeclarator' ) ; // the parameters of the function, converted to literal strings var params = node . params . map ( paramToLiteral ) ; // [ 'arg', ..., function(arg) {} ] //  place inline if ( ( node . type === 'FunctionExpression' ) && ! isVarAssignment ) { esprimaTools . nodeSplicer ( node ) ( { parent : node . parent , type : 'ArrayExpression' , elements : params . concat ( node ) } ) ; } // fn.$inject = [ 'arg', ... ] //  hoist before any intervening return statement else { var appendTo = isVarAssignment ? node . parent . parent : node ; esprimaTools . nodeSplicer ( appendTo , offset ) ( { type : 'ExpressionStatement' , expression : { type : 'AssignmentExpression' , operator : '=' , left : { type : 'MemberExpression' , computed : false , object : { type : 'Identifier' , name : node . id . name } , property : { type : 'Identifier' , name : '$inject' } } , right : { type : 'ArrayExpression' , elements : params } } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Offset function for $inject type annotateion . [CODESPLIT] function offset ( array , node ) { var nodeIndex = array . indexOf ( node ) ; var returnIndex = array . map ( test . isReturnStatement ) . indexOf ( true ) ; return ( returnIndex < 0 ) ? + 1 : ( returnIndex > nodeIndex ) ? + 1 : ( returnIndex - nodeIndex - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为手机号码 [CODESPLIT] function _isMobile ( val , locale ) { var key = _isString ( locale ) ? locale : LOCALE_ENUM . ZHCN ; var rex = REGEX_ENUM . MOBILE_REX [ key ] ; if ( ! rex ) { return false ; } if ( ! _isString ( val ) ) { return false ; } return rex . test ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new application . [CODESPLIT] function createApplication ( ) { function app ( req , res ) { app . handle ( req , res ) ; } utils . merge ( app , application ) ; utils . merge ( app , EventEmitter . prototype ) ; app . request = { __proto__ : req } ; app . response = { __proto__ : res } ; app . init ( ) ; return app ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a function that handles the response of an arcgis add / update / delete request . [CODESPLIT] function handleEsriResponse ( callback ) { return function ( err , response , body ) { var error ; if ( err ) { debug ( 'HTTP request resulted in an error:' , err ) ; return callback ( err ) ; } var json = body && JSON . parse ( body ) ; if ( ! json ) { debug ( 'Response body was null or could not be parsed:' , body ) ; return callback ( new Error ( 'Response body was null or could not be parsed' ) ) ; } debug ( 'Response body as JSON:' , json ) ; // Get the results object from the response, which is the first and only object. // Since batch requests aren't implemented, this should be one of addResults, updateResults, or deleteResults. var results = json [ Object . keys ( json ) [ 0 ] ] ; if ( ! results || ! results . length ) { debug ( 'Results object not found or is not as expected:' , results ) ; return callback ( new Error ( 'Results object not found or is not as expected' ) ) ; } // Assume we only get one result back (due to unimplemented batch operations). var result = results [ 0 ] ; if ( result . success ) { debug ( 'Success' ) ; return callback ( null ) ; } else if ( result . error ) { debug ( 'Received error:' , result . error ) ; error = new Error ( result . error . description ) ; error . code = result . error . code ; return callback ( error ) ; } else { debug ( 'Feature service responded with a result that cannot be handled:' , result ) ; error = new Error ( 'Feature service error: unexpected result' ) ; error . result = result ; return callback ( error ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Globally include the chai expect module so each test doesn t need to manually require it [CODESPLIT] function ( ) { var chai = require ( 'chai' ) ; chai . should ( ) ; global . assert = chai . assert ; global . expect = chai . expect ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new Company with the given parent and definition . [CODESPLIT] function Company ( parent , definition ) { var key ; for ( key in updateMixin ) { this [ key ] = updateMixin [ key ] ; } Company . super_ . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find functions that are obvious angular entities . [CODESPLIT] function inferAngular ( ast ) { return esprimaTools . breadthFirst ( ast ) . map ( getAnnotationCandidates ) . filter ( Boolean ) . map ( followReference ) . filter ( Boolean ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find inject candidates [CODESPLIT] function getAnnotationCandidates ( node ) { var callExpression = testNode . isModuleExpression ( node ) && node . parent ; if ( callExpression ) { return callExpression [ 'arguments' ] . filter ( testNode . anyOf ( testNode . isFunction , testNode . isIdentifier ) ) . pop ( ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a function or reference that points to one will resolve to the function node . [CODESPLIT] function followReference ( node ) { var result ; // immediate function if ( testNode . isFunction ( node ) ) { return node ; } // follow identifier else { var name = node . name ; // find the next highest scope and search for declaration while ( node . parent && ! result ) { node = node . parent ; var isBlock = testNode . isBlockOrProgram ( node ) ; if ( isBlock ) { // look at the nodes breadth first and take the first result esprimaTools . breadthFirst ( node ) . some ( function eachNode ( subNode ) { switch ( subNode . type ) { case 'FunctionDeclaration' : if ( subNode . id . name === name ) { result = subNode ; } break ; case 'VariableDeclarator' : if ( subNode . id . name === name ) { result = subNode . init ; } break ; case 'AssignmentExpression' : if ( ( subNode . left . type === 'Identifier' ) && ( subNode . left . name === name ) ) { result = subNode . right ; } break ; } return ! ! result ; } ) ; } } // recurse the result until we find a function return result ? followReference ( result ) : null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manage prepare for shutdown [CODESPLIT] function ( callback ) { // perform all the cleanup and other operations needed prior to shutdown, // but do not actually shutdown. Call the callback function only when // these operations are actually complete. try { TacitServer . app_server . close ( ) ; console . log ( TacitServer . configs . server_prefix + \" - Shutdown app successful.\" ) ; } catch ( ex ) { console . log ( TacitServer . configs . server_prefix + \" - Shutdown app failed.\" ) ; console . log ( ex ) ; } try { TacitServer . api_server . close ( ) ; console . log ( TacitServer . configs . server_prefix + \" - Shutdown api successful.\" ) ; } catch ( ex ) { console . log ( TacitServer . configs . server_prefix + \" - Shutdown api failed.\" ) ; console . log ( ex ) ; } console . log ( TacitServer . configs . server_prefix + \" - All preparations for shutdown completed.\" ) ; callback ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * CMD - The Command [CODESPLIT] function cmd ( request , response ) { var urlpath = url . parse ( request . url ) . pathname ; var param = url . parse ( request . url ) . query ; //    var localpath = path.join(process.cwd(), urlpath); // OLD var localpath = path . join ( __dirname , urlpath ) ; // NEW fs . exists ( localpath , function ( result ) { runScript ( result , localpath , param , response ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * SENDERROR - The Sending of the Error [CODESPLIT] function sendError ( errCode , errString , response ) { console . log ( TacitServer . configs . server_prefix + \" - sendError called\" ) ; response . writeHead ( errCode , { \"Content-Type\" : \"text/plain;charset=utf-8\" } ) ; response . write ( errString + \"\\n\" ) ; response . end ( ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * SENDDATA - The Sending of the Data [CODESPLIT] function sendData ( err , stdout , stderr , response ) { console . log ( TacitServer . configs . server_prefix + \" - sendData called\" ) ; if ( err ) return sendError ( 500 , stderr , response ) ; response . writeHead ( 200 , { \"Content-Type\" : \"text/plain;charset=utf-8\" } ) ; response . write ( stdout ) ; response . end ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * RUNSCRIPT - The Running of the Script [CODESPLIT] function runScript ( exists , file , param , response ) { console . log ( TacitServer . configs . server_prefix + \" - runScript called\" ) ; if ( ! exists ) return sendError ( 404 , 'File not found' , response ) ; var command = '' ; var extension = file . split ( '.' ) . pop ( ) ; switch ( extension ) { case 'php' : command = 'php' ; break ; case 'js' : command = 'node' ; break ; default : // nothing } runner . exec ( command + \" \" + file + \" \" + param , function ( err , stdout , stderr ) { sendData ( err , stdout , stderr , response ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ARGUMENTS - The Arguments [CODESPLIT] function args ( req , res ) { console . log ( TacitServer . configs . server_prefix + \" - args called\" ) ; var urlpath = url . parse ( req . url ) . pathname ; var param = url . parse ( req . url ) . query ; var localpath = path . join ( process . cwd ( ) , urlpath ) ; path . exists ( localpath , function ( result ) { console . log ( TacitServer . configs . server_prefix + \" - Process parameters: %p\" , param ) ; runScript ( result , localpath , param , res ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为实数 ( 有理数和无理数 ) [CODESPLIT] function _isRealNumber ( val , options ) { var opts = _isObject ( options ) ? options : { } ; if ( _isNumber ( val ) ) { return ! _isNaN ( val ) ; } // 若是非严格模式, 则对字符串 '3' 进行判定, 需要排除 '', '   ' 字符串 if ( opts . isStrict !== true && _isUnEmptyString ( val , { isStrict : true } ) ) { var detal = val - 0 ; return ! _isNaN ( detal ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform body into ms - users message [CODESPLIT] function transformBody ( req , input ) { req . log . debug ( 'attempting transformation' , input ) ; const body = input . data ; const { attributes } = body ; const { password , referral } = attributes ; const { autoGeneratePassword } = config ; if ( autoGeneratePassword === true && password ) { throw new Errors . ValidationError ( 'password is auto-generated, do not pass it' , 400 ) ; } if ( autoGeneratePassword === false && ! password ) { throw new Errors . ValidationError ( 'password must be provided' , 400 ) ; } const { country } = body ; if ( country && ! countryData . info ( country , 'ISO3' ) ) { const err = ` ` ; throw new Errors . ValidationError ( err , 400 , 'data.country' ) ; } const message = { username : body . id , metadata : ld . pick ( attributes , WHITE_LIST ) , activate : config . usersRequireActivate !== true || ! password , audience : getAudience ( ) , ipaddress : proxyaddr ( req , config . trustProxy ) , } ; if ( password ) { message . password = password ; } if ( attributes . alias ) { message . alias = attributes . alias . toLowerCase ( ) ; } if ( referral ) { message . referral = referral ; } // BC, remap additionalInformation to longDescription if it is not provided if ( attributes . additionalInformation && ! message . metadata . longDescription ) { message . metadata . longDescription = attributes . additionalInformation ; } return message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "end FUNCTION linspace () FUNCTION : newCounts ( edges ) Initializes a new histogram counts array . [CODESPLIT] function newCounts ( edges ) { var numBins = edges . length + 1 , counts = new Array ( numBins ) ; // The first bin is for all data which is less than the left-most edge: counts [ 0 ] = [ Number . NEGATIVE_INFINITY , 0 , edges [ 0 ] ] ; for ( var i = 1 ; i < numBins - 1 ; i ++ ) { counts [ i ] = [ edges [ i - 1 ] , 0 , edges [ i ] ] ; } // end FOR i // The last bin is for all data which is greater than the right-most edge: counts [ numBins - 1 ] = [ edges [ edges . length - 1 ] , 0 , Number . POSITIVE_INFINITY ] ; return counts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ▄█████ ██████ ██████ ██ ██ █████▄ ▀█▄ ██▄▄ ██ ██ ██ ██▄▄██ ▀█▄ ██▀▀ ██ ██ ██ ██▀▀▀ █████▀ ██████ ██ ▀████▀ ██ [CODESPLIT] function ( table , c ) { // if no thead or tbody, or tablesorter is already present, quit if ( ! table || ! table . tHead || table . tBodies . length === 0 || table . hasInitialized === true ) { if ( c . debug ) { if ( table . hasInitialized ) { console . warn ( 'Stopping initialization. Tablesorter has already been initialized' ) ; } else { console . error ( 'Stopping initialization! No table, thead or tbody' , table ) ; } } return ; } var tmp = '' , $table = $ ( table ) , meta = $ . metadata ; // initialization flag table . hasInitialized = false ; // table is being processed flag table . isProcessing = true ; // make sure to store the config object table . config = c ; // save the settings where they read $ . data ( table , 'tablesorter' , c ) ; if ( c . debug ) { console [ console . group ? 'group' : 'log' ] ( 'Initializing tablesorter' ) ; $ . data ( table , 'startoveralltimer' , new Date ( ) ) ; } // removing this in version 3 (only supports jQuery 1.7+) c . supportsDataObject = ( function ( version ) { version [ 0 ] = parseInt ( version [ 0 ] , 10 ) ; return ( version [ 0 ] > 1 ) || ( version [ 0 ] === 1 && parseInt ( version [ 1 ] , 10 ) >= 4 ) ; } ) ( $ . fn . jquery . split ( '.' ) ) ; // ensure case insensitivity c . emptyTo = c . emptyTo . toLowerCase ( ) ; c . stringTo = c . stringTo . toLowerCase ( ) ; c . last = { sortList : [ ] , clickedIndex : - 1 } ; // add table theme class only if there isn't already one there if ( ! / tablesorter\\- / . test ( $table . attr ( 'class' ) ) ) { tmp = ( c . theme !== '' ? ' tablesorter-' + c . theme : '' ) ; } c . table = table ; c . $table = $table . addClass ( ts . css . table + ' ' + c . tableClass + tmp ) . attr ( 'role' , 'grid' ) ; c . $headers = $table . find ( c . selectorHeaders ) ; // give the table a unique id, which will be used in namespace binding if ( ! c . namespace ) { c . namespace = '.tablesorter' + Math . random ( ) . toString ( 16 ) . slice ( 2 ) ; } else { // make sure namespace starts with a period & doesn't have weird characters c . namespace = '.' + c . namespace . replace ( ts . regex . nonWord , '' ) ; } c . $table . children ( ) . children ( 'tr' ) . attr ( 'role' , 'row' ) ; c . $tbodies = $table . children ( 'tbody:not(.' + c . cssInfoBlock + ')' ) . attr ( { 'aria-live' : 'polite' , 'aria-relevant' : 'all' } ) ; if ( c . $table . children ( 'caption' ) . length ) { tmp = c . $table . children ( 'caption' ) [ 0 ] ; if ( ! tmp . id ) { tmp . id = c . namespace . slice ( 1 ) + 'caption' ; } c . $table . attr ( 'aria-labelledby' , tmp . id ) ; } c . widgetInit = { } ; // keep a list of initialized widgets // change textExtraction via data-attribute c . textExtraction = c . $table . attr ( 'data-text-extraction' ) || c . textExtraction || 'basic' ; // build headers ts . buildHeaders ( c ) ; // fixate columns if the users supplies the fixedWidth option // do this after theme has been applied ts . fixColumnWidth ( table ) ; // add widgets from class name ts . addWidgetFromClass ( table ) ; // add widget options before parsing (e.g. grouping widget has parser settings) ts . applyWidgetOptions ( table ) ; // try to auto detect column type, and store in tables config ts . setupParsers ( c ) ; // start total row count at zero c . totalRows = 0 ; // build the cache for the tbody cells // delayInit will delay building the cache until the user starts a sort if ( ! c . delayInit ) { ts . buildCache ( c ) ; } // bind all header events and methods ts . bindEvents ( table , c . $headers , true ) ; ts . bindMethods ( c ) ; // get sort list from jQuery data or metadata // in jQuery < 1.4, an error occurs when calling $table.data() if ( c . supportsDataObject && typeof $table . data ( ) . sortlist !== 'undefined' ) { c . sortList = $table . data ( ) . sortlist ; } else if ( meta && ( $table . metadata ( ) && $table . metadata ( ) . sortlist ) ) { c . sortList = $table . metadata ( ) . sortlist ; } // apply widget init code ts . applyWidget ( table , true ) ; // if user has supplied a sort list to constructor if ( c . sortList . length > 0 ) { ts . sortOn ( c , c . sortList , { } , ! c . initWidgets ) ; } else { ts . setHeadersCss ( c ) ; if ( c . initWidgets ) { // apply widget format ts . applyWidget ( table , false ) ; } } // show processesing icon if ( c . showProcessing ) { $table . unbind ( 'sortBegin' + c . namespace + ' sortEnd' + c . namespace ) . bind ( 'sortBegin' + c . namespace + ' sortEnd' + c . namespace , function ( e ) { clearTimeout ( c . timerProcessing ) ; ts . isProcessing ( table ) ; if ( e . type === 'sortBegin' ) { c . timerProcessing = setTimeout ( function ( ) { ts . isProcessing ( table , true ) ; } , 500 ) ; } } ) ; } // initialized table . hasInitialized = true ; table . isProcessing = false ; if ( c . debug ) { console . log ( 'Overall initialization time: ' + ts . benchmark ( $ . data ( table , 'startoveralltimer' ) ) ) ; if ( c . debug && console . groupEnd ) { console . groupEnd ( ) ; } } $table . triggerHandler ( 'tablesorter-initialized' , table ) ; if ( typeof c . initialized === 'function' ) { c . initialized ( table ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * █████▄ ▄████▄ █████▄ ▄█████ ██████ █████▄ ▄█████ ██▄▄██ ██▄▄██ ██▄▄██ ▀█▄ ██▄▄ ██▄▄██ ▀█▄ ██▀▀▀ ██▀▀██ ██▀██ ▀█▄ ██▀▀ ██▀██ ▀█▄ ██ ██ ██ ██ ██ █████▀ ██████ ██ ██ █████▀ [CODESPLIT] function ( c , $tbodies ) { var rows , list , span , max , colIndex , indx , header , configHeaders , noParser , parser , extractor , time , tbody , len , table = c . table , tbodyIndex = 0 , debug = { } ; // update table bodies in case we start with an empty table c . $tbodies = c . $table . children ( 'tbody:not(.' + c . cssInfoBlock + ')' ) ; tbody = typeof $tbodies === 'undefined' ? c . $tbodies : $tbodies ; len = tbody . length ; if ( len === 0 ) { return c . debug ? console . warn ( 'Warning: *Empty table!* Not building a parser cache' ) : '' ; } else if ( c . debug ) { time = new Date ( ) ; console [ console . group ? 'group' : 'log' ] ( 'Detecting parsers for each column' ) ; } list = { extractors : [ ] , parsers : [ ] } ; while ( tbodyIndex < len ) { rows = tbody [ tbodyIndex ] . rows ; if ( rows . length ) { colIndex = 0 ; max = c . columns ; for ( indx = 0 ; indx < max ; indx ++ ) { header = c . $headerIndexed [ colIndex ] ; if ( header && header . length ) { // get column indexed table cell configHeaders = ts . getColumnData ( table , c . headers , colIndex ) ; // get column parser/extractor extractor = ts . getParserById ( ts . getData ( header , configHeaders , 'extractor' ) ) ; parser = ts . getParserById ( ts . getData ( header , configHeaders , 'sorter' ) ) ; noParser = ts . getData ( header , configHeaders , 'parser' ) === 'false' ; // empty cells behaviour - keeping emptyToBottom for backwards compatibility c . empties [ colIndex ] = ( ts . getData ( header , configHeaders , 'empty' ) || c . emptyTo || ( c . emptyToBottom ? 'bottom' : 'top' ) ) . toLowerCase ( ) ; // text strings behaviour in numerical sorts c . strings [ colIndex ] = ( ts . getData ( header , configHeaders , 'string' ) || c . stringTo || 'max' ) . toLowerCase ( ) ; if ( noParser ) { parser = ts . getParserById ( 'no-parser' ) ; } if ( ! extractor ) { // For now, maybe detect someday extractor = false ; } if ( ! parser ) { parser = ts . detectParserForColumn ( c , rows , - 1 , colIndex ) ; } if ( c . debug ) { debug [ '(' + colIndex + ') ' + header . text ( ) ] = { parser : parser . id , extractor : extractor ? extractor . id : 'none' , string : c . strings [ colIndex ] , empty : c . empties [ colIndex ] } ; } list . parsers [ colIndex ] = parser ; list . extractors [ colIndex ] = extractor ; span = header [ 0 ] . colSpan - 1 ; if ( span > 0 ) { colIndex += span ; max += span ; while ( span + 1 > 0 ) { // set colspan columns to use the same parsers & extractors list . parsers [ colIndex - span ] = parser ; list . extractors [ colIndex - span ] = extractor ; span -- ; } } } colIndex ++ ; } } tbodyIndex += ( list . parsers . length ) ? len : 1 ; } if ( c . debug ) { if ( ! ts . isEmptyObject ( debug ) ) { console [ console . table ? 'table' : 'log' ] ( debug ) ; } else { console . warn ( '  No parsers detected!' ) ; } console . log ( 'Completed detecting parsers' + ts . benchmark ( time ) ) ; if ( console . groupEnd ) { console . groupEnd ( ) ; } } c . parsers = list . parsers ; c . extractors = list . extractors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "centralized function to extract / parse cell contents [CODESPLIT] function ( c , cell , colIndex , txt ) { if ( typeof txt === 'undefined' ) { txt = ts . getElementText ( c , cell , colIndex ) ; } // if no parser, make sure to return the txt var val = '' + txt , parser = c . parsers [ colIndex ] , extractor = c . extractors [ colIndex ] ; if ( parser ) { // do extract before parsing, if there is one if ( extractor && typeof extractor . format === 'function' ) { txt = extractor . format ( txt , c . table , cell , colIndex ) ; } // allow parsing if the string is empty, previously parsing would change it to zero, // in case the parser needs to extract data from the table cell attributes val = parser . id === 'no-parser' ? '' : // make sure txt is a string (extractor may have converted it) parser . format ( '' + txt , c . table , cell , colIndex ) ; if ( c . ignoreCase && typeof val === 'string' ) { val = val . toLowerCase ( ) ; } } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ▄████▄ ▄████▄ ▄████▄ ██ ██ ██████ ██ ▀▀ ██▄▄██ ██ ▀▀ ██▄▄██ ██▄▄ ██ ▄▄ ██▀▀██ ██ ▄▄ ██▀▀██ ██▀▀ ▀████▀ ██ ██ ▀████▀ ██ ██ ██████ [CODESPLIT] function ( c , callback , $tbodies ) { var cache , val , txt , rowIndex , colIndex , tbodyIndex , $tbody , $row , cols , $cells , cell , cacheTime , totalRows , rowData , prevRowData , colMax , span , cacheIndex , hasParser , max , len , index , table = c . table , parsers = c . parsers ; // update tbody variable c . $tbodies = c . $table . children ( 'tbody:not(.' + c . cssInfoBlock + ')' ) ; $tbody = typeof $tbodies === 'undefined' ? c . $tbodies : $tbodies , c . cache = { } ; c . totalRows = 0 ; // if no parsers found, return - it's an empty table. if ( ! parsers ) { return c . debug ? console . warn ( 'Warning: *Empty table!* Not building a cache' ) : '' ; } if ( c . debug ) { cacheTime = new Date ( ) ; } // processing icon if ( c . showProcessing ) { ts . isProcessing ( table , true ) ; } for ( tbodyIndex = 0 ; tbodyIndex < $tbody . length ; tbodyIndex ++ ) { colMax = [ ] ; // column max value per tbody cache = c . cache [ tbodyIndex ] = { normalized : [ ] // array of normalized row data; last entry contains 'rowData' above // colMax: #   // added at the end } ; totalRows = ( $tbody [ tbodyIndex ] && $tbody [ tbodyIndex ] . rows . length ) || 0 ; for ( rowIndex = 0 ; rowIndex < totalRows ; ++ rowIndex ) { rowData = { // order: original row order # // $row : jQuery Object[] child : [ ] , // child row text (filter widget) raw : [ ] // original row text } ; /** Add the table data to main data array */ $row = $ ( $tbody [ tbodyIndex ] . rows [ rowIndex ] ) ; cols = [ ] ; // if this is a child row, add it to the last row's children and continue to the next row // ignore child row class, if it is the first row if ( $row . hasClass ( c . cssChildRow ) && rowIndex !== 0 ) { len = cache . normalized . length - 1 ; prevRowData = cache . normalized [ len ] [ c . columns ] ; prevRowData . $row = prevRowData . $row . add ( $row ) ; // add 'hasChild' class name to parent row if ( ! $row . prev ( ) . hasClass ( c . cssChildRow ) ) { $row . prev ( ) . addClass ( ts . css . cssHasChild ) ; } // save child row content (un-parsed!) $cells = $row . children ( 'th, td' ) ; len = prevRowData . child . length ; prevRowData . child [ len ] = [ ] ; // child row content does not account for colspans/rowspans; so indexing may be off cacheIndex = 0 ; max = c . columns ; for ( colIndex = 0 ; colIndex < max ; colIndex ++ ) { cell = $cells [ colIndex ] ; if ( cell ) { prevRowData . child [ len ] [ colIndex ] = ts . getParsedText ( c , cell , colIndex ) ; span = $cells [ colIndex ] . colSpan - 1 ; if ( span > 0 ) { cacheIndex += span ; max += span ; } } cacheIndex ++ ; } // go to the next for loop continue ; } rowData . $row = $row ; rowData . order = rowIndex ; // add original row position to rowCache cacheIndex = 0 ; max = c . columns ; for ( colIndex = 0 ; colIndex < max ; ++ colIndex ) { cell = $row [ 0 ] . cells [ colIndex ] ; if ( cell && cacheIndex < c . columns ) { hasParser = typeof parsers [ cacheIndex ] !== 'undefined' ; if ( ! hasParser && c . debug ) { console . warn ( 'No parser found for row: ' + rowIndex + ', column: ' + colIndex + '; cell containing: \"' + $ ( cell ) . text ( ) + '\"; does it have a header?' ) ; } val = ts . getElementText ( c , cell , cacheIndex ) ; rowData . raw [ cacheIndex ] = val ; // save original row text // save raw column text even if there is no parser set txt = ts . getParsedText ( c , cell , cacheIndex , val ) ; cols [ cacheIndex ] = txt ; if ( hasParser && ( parsers [ cacheIndex ] . type || '' ) . toLowerCase ( ) === 'numeric' ) { // determine column max value (ignore sign) colMax [ cacheIndex ] = Math . max ( Math . abs ( txt ) || 0 , colMax [ cacheIndex ] || 0 ) ; } // allow colSpan in tbody span = cell . colSpan - 1 ; if ( span > 0 ) { index = 0 ; while ( index <= span ) { // duplicate text (or not) to spanned columns // instead of setting duplicate span to empty string, use textExtraction to try to get a value // see http://stackoverflow.com/q/36449711/145346 txt = c . duplicateSpan || index === 0 ? val : typeof c . textExtraction !== 'string' ? ts . getElementText ( c , cell , cacheIndex + index ) || '' : '' ; rowData . raw [ cacheIndex + index ] = txt ; cols [ cacheIndex + index ] = txt ; index ++ ; } cacheIndex += span ; max += span ; } } cacheIndex ++ ; } // ensure rowData is always in the same location (after the last column) cols [ c . columns ] = rowData ; cache . normalized [ cache . normalized . length ] = cols ; } cache . colMax = colMax ; // total up rows, not including child rows c . totalRows += cache . normalized . length ; } if ( c . showProcessing ) { ts . isProcessing ( table ) ; // remove processing icon } if ( c . debug ) { len = Math . min ( 5 , c . cache [ 0 ] . normalized . length ) ; console [ console . group ? 'group' : 'log' ] ( 'Building cache for ' + c . totalRows + ' rows (showing ' + len + ' rows in log)' + ts . benchmark ( cacheTime ) ) ; val = { } ; for ( colIndex = 0 ; colIndex < c . columns ; colIndex ++ ) { for ( cacheIndex = 0 ; cacheIndex < len ; cacheIndex ++ ) { if ( ! val [ 'row: ' + cacheIndex ] ) { val [ 'row: ' + cacheIndex ] = { } ; } val [ 'row: ' + cacheIndex ] [ c . $headerIndexed [ colIndex ] . text ( ) ] = c . cache [ 0 ] . normalized [ cacheIndex ] [ colIndex ] ; } } console [ console . table ? 'table' : 'log' ] ( val ) ; if ( console . groupEnd ) { console . groupEnd ( ) ; } } if ( $ . isFunction ( callback ) ) { callback ( table ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ██ ██ █████▄ █████▄ ▄████▄ ██████ ██████ ██ ██ ██▄▄██ ██ ██ ██▄▄██ ██ ██▄▄ ██ ██ ██▀▀▀ ██ ██ ██▀▀██ ██ ██▀▀ ▀████▀ ██ █████▀ ██ ██ ██ ██████ [CODESPLIT] function ( c ) { var $sorted , indx , column , list = c . sortList , len = list . length , none = ts . css . sortNone + ' ' + c . cssNone , css = [ ts . css . sortAsc + ' ' + c . cssAsc , ts . css . sortDesc + ' ' + c . cssDesc ] , cssIcon = [ c . cssIconAsc , c . cssIconDesc , c . cssIconNone ] , aria = [ 'ascending' , 'descending' ] , // find the footer $headers = c . $table . find ( 'tfoot tr' ) . children ( 'td, th' ) . add ( $ ( c . namespace + '_extra_headers' ) ) . removeClass ( css . join ( ' ' ) ) ; // remove all header information c . $headers . removeClass ( css . join ( ' ' ) ) . addClass ( none ) . attr ( 'aria-sort' , 'none' ) . find ( '.' + ts . css . icon ) . removeClass ( cssIcon . join ( ' ' ) ) . addClass ( cssIcon [ 2 ] ) ; for ( indx = 0 ; indx < len ; indx ++ ) { // direction = 2 means reset! if ( list [ indx ] [ 1 ] !== 2 ) { // multicolumn sorting updating - see #1005 // .not(function(){}) needs jQuery 1.4 // filter(function(i, el){}) <- el is undefined in jQuery v1.2.6 $sorted = c . $headers . filter ( function ( i ) { // only include headers that are in the sortList (this includes colspans) var include = true , $el = c . $headers . eq ( i ) , col = parseInt ( $el . attr ( 'data-column' ) , 10 ) , end = col + c . $headers [ i ] . colSpan ; for ( ; col < end ; col ++ ) { include = include ? include || ts . isValueInArray ( col , c . sortList ) > - 1 : false ; } return include ; } ) ; // choose the :last in case there are nested columns $sorted = $sorted . not ( '.sorter-false' ) . filter ( '[data-column=\"' + list [ indx ] [ 0 ] + '\"]' + ( len === 1 ? ':last' : '' ) ) ; if ( $sorted . length ) { for ( column = 0 ; column < $sorted . length ; column ++ ) { if ( ! $sorted [ column ] . sortDisabled ) { $sorted . eq ( column ) . removeClass ( none ) . addClass ( css [ list [ indx ] [ 1 ] ] ) . attr ( 'aria-sort' , aria [ list [ indx ] [ 1 ] ] ) . find ( '.' + ts . css . icon ) . removeClass ( cssIcon [ 2 ] ) . addClass ( cssIcon [ list [ indx ] [ 1 ] ] ) ; } } // add sorted class to footer & extra headers, if they exist if ( $headers . length ) { $headers . filter ( '[data-column=\"' + list [ indx ] [ 0 ] + '\"]' ) . removeClass ( none ) . addClass ( css [ list [ indx ] [ 1 ] ] ) ; } } } } // add verbose aria labels len = c . $headers . length ; for ( indx = 0 ; indx < len ; indx ++ ) { ts . setColumnAriaLabel ( c , c . $headers . eq ( indx ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "nextSort ( optional ) lets you disable next sort text [CODESPLIT] function ( c , $header , nextSort ) { if ( $header . length ) { var column = parseInt ( $header . attr ( 'data-column' ) , 10 ) , tmp = $header . hasClass ( ts . css . sortAsc ) ? 'sortAsc' : $header . hasClass ( ts . css . sortDesc ) ? 'sortDesc' : 'sortNone' , txt = $ . trim ( $header . text ( ) ) + ': ' + ts . language [ tmp ] ; if ( $header . hasClass ( 'sorter-false' ) || nextSort === false ) { txt += ts . language . sortDisabled ; } else { nextSort = c . sortVars [ column ] . order [ ( c . sortVars [ column ] . count + 1 ) % ( c . sortReset ? 3 : 2 ) ] ; // if nextSort txt += ts . language [ nextSort === 0 ? 'nextAsc' : nextSort === 1 ? 'nextDesc' : 'nextNone' ] ; } $header . attr ( 'aria-label' , txt ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "simple header update - see #989 [CODESPLIT] function ( c , callback ) { c . table . isUpdating = true ; ts . buildHeaders ( c ) ; ts . bindEvents ( c . table , c . $headers , true ) ; ts . resortComplete ( c , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "init flag ( true ) used by pager plugin to prevent widget application renamed from appendToTable [CODESPLIT] function ( c , init ) { var parsed , totalRows , $tbody , $curTbody , rowIndex , tbodyIndex , appendTime , table = c . table , wo = c . widgetOptions , $tbodies = c . $tbodies , rows = [ ] , cache = c . cache ; // empty table - fixes #206/#346 if ( ts . isEmptyObject ( cache ) ) { // run pager appender in case the table was just emptied return c . appender ? c . appender ( table , rows ) : table . isUpdating ? c . $table . triggerHandler ( 'updateComplete' , table ) : '' ; // Fixes #532 } if ( c . debug ) { appendTime = new Date ( ) ; } for ( tbodyIndex = 0 ; tbodyIndex < $tbodies . length ; tbodyIndex ++ ) { $tbody = $tbodies . eq ( tbodyIndex ) ; if ( $tbody . length ) { // detach tbody for manipulation $curTbody = ts . processTbody ( table , $tbody , true ) ; parsed = cache [ tbodyIndex ] . normalized ; totalRows = parsed . length ; for ( rowIndex = 0 ; rowIndex < totalRows ; rowIndex ++ ) { rows [ rows . length ] = parsed [ rowIndex ] [ c . columns ] . $row ; // removeRows used by the pager plugin; don't render if using ajax - fixes #411 if ( ! c . appender || ( c . pager && ( ! c . pager . removeRows || ! wo . pager_removeRows ) && ! c . pager . ajax ) ) { $curTbody . append ( parsed [ rowIndex ] [ c . columns ] . $row ) ; } } // restore tbody ts . processTbody ( table , $curTbody , false ) ; } } if ( c . appender ) { c . appender ( table , rows ) ; } if ( c . debug ) { console . log ( 'Rebuilt table' + ts . benchmark ( appendTime ) ) ; } // apply table widgets; but not before ajax completes if ( ! init && ! c . appender ) { ts . applyWidget ( table ) ; } if ( table . isUpdating ) { c . $table . triggerHandler ( 'updateComplete' , table ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ▄█████ ▄████▄ █████▄ ██████ ██ █████▄ ▄████▄ ▀█▄ ██ ██ ██▄▄██ ██ ██ ██ ██ ██ ▄▄▄ ▀█▄ ██ ██ ██▀██ ██ ██ ██ ██ ██ ▀██ █████▀ ▀████▀ ██ ██ ██ ██ ██ ██ ▀████▀ [CODESPLIT] function ( c , cell , event ) { if ( c . table . isUpdating ) { // let any updates complete before initializing a sort return setTimeout ( function ( ) { ts . initSort ( c , cell , event ) ; } , 50 ) ; } var arry , indx , headerIndx , dir , temp , tmp , $header , notMultiSort = ! event [ c . sortMultiSortKey ] , table = c . table , len = c . $headers . length , // get current column index col = parseInt ( $ ( cell ) . attr ( 'data-column' ) , 10 ) , order = c . sortVars [ col ] . order ; // Only call sortStart if sorting is enabled c . $table . triggerHandler ( 'sortStart' , table ) ; // get current column sort order c . sortVars [ col ] . count = event [ c . sortResetKey ] ? 2 : ( c . sortVars [ col ] . count + 1 ) % ( c . sortReset ? 3 : 2 ) ; // reset all sorts on non-current column - issue #30 if ( c . sortRestart ) { for ( headerIndx = 0 ; headerIndx < len ; headerIndx ++ ) { $header = c . $headers . eq ( headerIndx ) ; tmp = parseInt ( $header . attr ( 'data-column' ) , 10 ) ; // only reset counts on columns that weren't just clicked on and if not included in a multisort if ( col !== tmp && ( notMultiSort || $header . hasClass ( ts . css . sortNone ) ) ) { c . sortVars [ tmp ] . count = - 1 ; } } } // user only wants to sort on one column if ( notMultiSort ) { // flush the sort list c . sortList = [ ] ; c . last . sortList = [ ] ; if ( c . sortForce !== null ) { arry = c . sortForce ; for ( indx = 0 ; indx < arry . length ; indx ++ ) { if ( arry [ indx ] [ 0 ] !== col ) { c . sortList [ c . sortList . length ] = arry [ indx ] ; } } } // add column to sort list dir = order [ c . sortVars [ col ] . count ] ; if ( dir < 2 ) { c . sortList [ c . sortList . length ] = [ col , dir ] ; // add other columns if header spans across multiple if ( cell . colSpan > 1 ) { for ( indx = 1 ; indx < cell . colSpan ; indx ++ ) { c . sortList [ c . sortList . length ] = [ col + indx , dir ] ; // update count on columns in colSpan c . sortVars [ col + indx ] . count = $ . inArray ( dir , order ) ; } } } // multi column sorting } else { // get rid of the sortAppend before adding more - fixes issue #115 & #523 c . sortList = $ . extend ( [ ] , c . last . sortList ) ; // the user has clicked on an already sorted column if ( ts . isValueInArray ( col , c . sortList ) >= 0 ) { // reverse the sorting direction for ( indx = 0 ; indx < c . sortList . length ; indx ++ ) { tmp = c . sortList [ indx ] ; if ( tmp [ 0 ] === col ) { // order.count seems to be incorrect when compared to cell.count tmp [ 1 ] = order [ c . sortVars [ col ] . count ] ; if ( tmp [ 1 ] === 2 ) { c . sortList . splice ( indx , 1 ) ; c . sortVars [ col ] . count = - 1 ; } } } } else { // add column to sort list array dir = order [ c . sortVars [ col ] . count ] ; if ( dir < 2 ) { c . sortList [ c . sortList . length ] = [ col , dir ] ; // add other columns if header spans across multiple if ( cell . colSpan > 1 ) { for ( indx = 1 ; indx < cell . colSpan ; indx ++ ) { c . sortList [ c . sortList . length ] = [ col + indx , dir ] ; // update count on columns in colSpan c . sortVars [ col + indx ] . count = $ . inArray ( dir , order ) ; } } } } } // save sort before applying sortAppend c . last . sortList = $ . extend ( [ ] , c . sortList ) ; if ( c . sortList . length && c . sortAppend ) { arry = $ . isArray ( c . sortAppend ) ? c . sortAppend : c . sortAppend [ c . sortList [ 0 ] [ 0 ] ] ; if ( ! ts . isEmptyObject ( arry ) ) { for ( indx = 0 ; indx < arry . length ; indx ++ ) { if ( arry [ indx ] [ 0 ] !== col && ts . isValueInArray ( arry [ indx ] [ 0 ] , c . sortList ) < 0 ) { dir = arry [ indx ] [ 1 ] ; temp = ( '' + dir ) . match ( / ^(a|d|s|o|n) / ) ; if ( temp ) { tmp = c . sortList [ 0 ] [ 1 ] ; switch ( temp [ 0 ] ) { case 'd' : dir = 1 ; break ; case 's' : dir = tmp ; break ; case 'o' : dir = tmp === 0 ? 1 : 0 ; break ; case 'n' : dir = ( tmp + 1 ) % ( c . sortReset ? 3 : 2 ) ; break ; default : dir = 0 ; break ; } } c . sortList [ c . sortList . length ] = [ arry [ indx ] [ 0 ] , dir ] ; } } } } // sortBegin event triggered immediately before the sort c . $table . triggerHandler ( 'sortBegin' , table ) ; // setTimeout needed so the processing icon shows up setTimeout ( function ( ) { // set css for headers ts . setHeadersCss ( c ) ; ts . multisort ( c ) ; ts . appendCache ( c ) ; c . $table . triggerHandler ( 'sortBeforeEnd' , table ) ; c . $table . triggerHandler ( 'sortEnd' , table ) ; } , 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sort multiple columns [CODESPLIT] function ( c ) { /*jshint loopfunc:true */ var tbodyIndex , sortTime , colMax , rows , table = c . table , dir = 0 , textSorter = c . textSorter || '' , sortList = c . sortList , sortLen = sortList . length , len = c . $tbodies . length ; if ( c . serverSideSorting || ts . isEmptyObject ( c . cache ) ) { // empty table - fixes #206/#346 return ; } if ( c . debug ) { sortTime = new Date ( ) ; } for ( tbodyIndex = 0 ; tbodyIndex < len ; tbodyIndex ++ ) { colMax = c . cache [ tbodyIndex ] . colMax ; rows = c . cache [ tbodyIndex ] . normalized ; rows . sort ( function ( a , b ) { var sortIndex , num , col , order , sort , x , y ; // rows is undefined here in IE, so don't use it! for ( sortIndex = 0 ; sortIndex < sortLen ; sortIndex ++ ) { col = sortList [ sortIndex ] [ 0 ] ; order = sortList [ sortIndex ] [ 1 ] ; // sort direction, true = asc, false = desc dir = order === 0 ; if ( c . sortStable && a [ col ] === b [ col ] && sortLen === 1 ) { return a [ c . columns ] . order - b [ c . columns ] . order ; } // fallback to natural sort since it is more robust num = / n / i . test ( ts . getSortType ( c . parsers , col ) ) ; if ( num && c . strings [ col ] ) { // sort strings in numerical columns if ( typeof ( ts . string [ c . strings [ col ] ] ) === 'boolean' ) { num = ( dir ? 1 : - 1 ) * ( ts . string [ c . strings [ col ] ] ? - 1 : 1 ) ; } else { num = ( c . strings [ col ] ) ? ts . string [ c . strings [ col ] ] || 0 : 0 ; } // fall back to built-in numeric sort // var sort = $.tablesorter['sort' + s]( a[col], b[col], dir, colMax[col], table ); sort = c . numberSorter ? c . numberSorter ( a [ col ] , b [ col ] , dir , colMax [ col ] , table ) : ts [ 'sortNumeric' + ( dir ? 'Asc' : 'Desc' ) ] ( a [ col ] , b [ col ] , num , colMax [ col ] , col , c ) ; } else { // set a & b depending on sort direction x = dir ? a : b ; y = dir ? b : a ; // text sort function if ( typeof textSorter === 'function' ) { // custom OVERALL text sorter sort = textSorter ( x [ col ] , y [ col ] , dir , col , table ) ; } else if ( typeof textSorter === 'object' && textSorter . hasOwnProperty ( col ) ) { // custom text sorter for a SPECIFIC COLUMN sort = textSorter [ col ] ( x [ col ] , y [ col ] , dir , col , table ) ; } else { // fall back to natural sort sort = ts [ 'sortNatural' + ( dir ? 'Asc' : 'Desc' ) ] ( a [ col ] , b [ col ] , col , c ) ; } } if ( sort ) { return sort ; } } return a [ c . columns ] . order - b [ c . columns ] . order ; } ) ; } if ( c . debug ) { console . log ( 'Applying sort ' + sortList . toString ( ) + ts . benchmark ( sortTime ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Natural sort - https : // github . com / overset / javascript - natural - sort ( date sorting removed ) this function will only accept strings or you ll see TypeError : undefined is not a function I could add a = a . toString () ; b = b . toString () ; but it ll slow down the sort overall [CODESPLIT] function ( a , b ) { if ( a === b ) { return 0 ; } var aNum , bNum , aFloat , bFloat , indx , max , regex = ts . regex ; // first try and sort Hex codes if ( regex . hex . test ( b ) ) { aNum = parseInt ( a . match ( regex . hex ) , 16 ) ; bNum = parseInt ( b . match ( regex . hex ) , 16 ) ; if ( aNum < bNum ) { return - 1 ; } if ( aNum > bNum ) { return 1 ; } } // chunk/tokenize aNum = a . replace ( regex . chunk , '\\\\0$1\\\\0' ) . replace ( regex . chunks , '' ) . split ( '\\\\0' ) ; bNum = b . replace ( regex . chunk , '\\\\0$1\\\\0' ) . replace ( regex . chunks , '' ) . split ( '\\\\0' ) ; max = Math . max ( aNum . length , bNum . length ) ; // natural sorting through split numeric strings and default strings for ( indx = 0 ; indx < max ; indx ++ ) { // find floats not starting with '0', string or 0 if not defined aFloat = isNaN ( aNum [ indx ] ) ? aNum [ indx ] || 0 : parseFloat ( aNum [ indx ] ) || 0 ; bFloat = isNaN ( bNum [ indx ] ) ? bNum [ indx ] || 0 : parseFloat ( bNum [ indx ] ) || 0 ; // handle numeric vs string comparison - number < string - (Kyle Adams) if ( isNaN ( aFloat ) !== isNaN ( bFloat ) ) { return isNaN ( aFloat ) ? 1 : - 1 ; } // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' if ( typeof aFloat !== typeof bFloat ) { aFloat += '' ; bFloat += '' ; } if ( aFloat < bFloat ) { return - 1 ; } if ( aFloat > bFloat ) { return 1 ; } } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return text string value by adding up ascii value so the text is somewhat sorted when using a digital sort this is NOT an alphanumeric sort [CODESPLIT] function ( val , num , max ) { if ( max ) { // make sure the text value is greater than the max numerical value (max) var indx , len = val ? val . length : 0 , n = max + num ; for ( indx = 0 ; indx < len ; indx ++ ) { n += val . charCodeAt ( indx ) ; } return num * n ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ██ ██ ██ ██ █████▄ ▄████▄ ██████ ██████ ▄█████ ██ ██ ██ ██ ██ ██ ██ ▄▄▄ ██▄▄ ██ ▀█▄ ██ ██ ██ ██ ██ ██ ██ ▀██ ██▀▀ ██ ▀█▄ ███████▀ ██ █████▀ ▀████▀ ██████ ██ █████▀ [CODESPLIT] function ( widget ) { if ( widget . id && ! ts . isEmptyObject ( ts . getWidgetById ( widget . id ) ) ) { console . warn ( '\"' + widget . id + '\" widget was loaded more than once!' ) ; } ts . widgets [ ts . widgets . length ] = widget ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "computeTableHeaderCellIndexes from : http : // www . javascripttoolbox . com / lib / table / examples . php http : // www . javascripttoolbox . com / temp / table_cellindex . html [CODESPLIT] function ( $rows , c ) { var i , j , k , l , cell , cells , rowIndex , rowSpan , colSpan , firstAvailCol , // total columns has been calculated, use it to set the matrixrow columns = c && c . columns || 0 , matrix = [ ] , matrixrow = new Array ( columns ) ; for ( i = 0 ; i < $rows . length ; i ++ ) { cells = $rows [ i ] . cells ; for ( j = 0 ; j < cells . length ; j ++ ) { cell = cells [ j ] ; rowIndex = cell . parentNode . rowIndex ; rowSpan = cell . rowSpan || 1 ; colSpan = cell . colSpan || 1 ; if ( typeof matrix [ rowIndex ] === 'undefined' ) { matrix [ rowIndex ] = [ ] ; } // Find first available column in the first row for ( k = 0 ; k < matrix [ rowIndex ] . length + 1 ; k ++ ) { if ( typeof matrix [ rowIndex ] [ k ] === 'undefined' ) { firstAvailCol = k ; break ; } } // jscs:disable disallowEmptyBlocks if ( columns && cell . cellIndex === firstAvailCol ) { // don't to anything } else if ( cell . setAttribute ) { // jscs:enable disallowEmptyBlocks // add data-column (setAttribute = IE8+) cell . setAttribute ( 'data-column' , firstAvailCol ) ; } else { // remove once we drop support for IE7 - 1/12/2016 $ ( cell ) . attr ( 'data-column' , firstAvailCol ) ; } for ( k = rowIndex ; k < rowIndex + rowSpan ; k ++ ) { if ( typeof matrix [ k ] === 'undefined' ) { matrix [ k ] = [ ] ; } matrixrow = matrix [ k ] ; for ( l = firstAvailCol ; l < firstAvailCol + colSpan ; l ++ ) { matrixrow [ l ] = 'x' ; } } } } return matrixrow . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "automatically add a colgroup with col elements set to a percentage width [CODESPLIT] function ( table ) { table = $ ( table ) [ 0 ] ; var overallWidth , percent , $tbodies , len , index , c = table . config , $colgroup = c . $table . children ( 'colgroup' ) ; // remove plugin-added colgroup, in case we need to refresh the widths if ( $colgroup . length && $colgroup . hasClass ( ts . css . colgroup ) ) { $colgroup . remove ( ) ; } if ( c . widthFixed && c . $table . children ( 'colgroup' ) . length === 0 ) { $colgroup = $ ( '<colgroup class=\"' + ts . css . colgroup + '\">' ) ; overallWidth = c . $table . width ( ) ; // only add col for visible columns - fixes #371 $tbodies = c . $tbodies . find ( 'tr:first' ) . children ( ':visible' ) ; len = $tbodies . length ; for ( index = 0 ; index < len ; index ++ ) { percent = parseInt ( ( $tbodies . eq ( index ) . width ( ) / overallWidth ) * 1000 , 10 ) / 10 + '%' ; $colgroup . append ( $ ( '<col>' ) . css ( 'width' , percent ) ) ; } c . $table . prepend ( $colgroup ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get sorter string empty etc options for each column from jQuery data metadata header option or header class name ( sorter - false ) priority = jQuery data > meta > headers option > header class name [CODESPLIT] function ( header , configHeader , key ) { var meta , cl4ss , val = '' , $header = $ ( header ) ; if ( ! $header . length ) { return '' ; } meta = $ . metadata ? $header . metadata ( ) : false ; cl4ss = ' ' + ( $header . attr ( 'class' ) || '' ) ; if ( typeof $header . data ( key ) !== 'undefined' || typeof $header . data ( key . toLowerCase ( ) ) !== 'undefined' ) { // 'data-lockedOrder' is assigned to 'lockedorder'; but 'data-locked-order' is assigned to 'lockedOrder' // 'data-sort-initial-order' is assigned to 'sortInitialOrder' val += $header . data ( key ) || $header . data ( key . toLowerCase ( ) ) ; } else if ( meta && typeof meta [ key ] !== 'undefined' ) { val += meta [ key ] ; } else if ( configHeader && typeof configHeader [ key ] !== 'undefined' ) { val += configHeader [ key ] ; } else if ( cl4ss !== ' ' && cl4ss . match ( ' ' + key + '-' ) ) { // include sorter class name 'sorter-text', etc; now works with 'sorter-my-custom-parser' val = cl4ss . match ( new RegExp ( '\\\\s' + key + '-([\\\\w-]+)' ) ) [ 1 ] || '' ; } return $ . trim ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "*** Process table *** add processing indicator [CODESPLIT] function ( $table , toggle , $headers ) { $table = $ ( $table ) ; var c = $table [ 0 ] . config , // default to all headers $header = $headers || $table . find ( '.' + ts . css . header ) ; if ( toggle ) { // don't use sortList if custom $headers used if ( typeof $headers !== 'undefined' && c . sortList . length > 0 ) { // get headers from the sortList $header = $header . filter ( function ( ) { // get data-column from attr to keep compatibility with jQuery 1.2.6 return this . sortDisabled ? false : ts . isValueInArray ( parseFloat ( $ ( this ) . attr ( 'data-column' ) ) , c . sortList ) >= 0 ; } ) ; } $table . add ( $header ) . addClass ( ts . css . processing + ' ' + c . cssProcessing ) ; } else { $table . add ( $header ) . removeClass ( ts . css . processing + ' ' + c . cssProcessing ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "detach tbody but save the position don t use tbody because there are portions that look for a tbody index ( updateCell ) [CODESPLIT] function ( table , $tb , getIt ) { table = $ ( table ) [ 0 ] ; if ( getIt ) { table . isProcessing = true ; $tb . before ( '<colgroup class=\"tablesorter-savemyplace\"/>' ) ; return $ . fn . detach ? $tb . detach ( ) : $tb . remove ( ) ; } var holdr = $ ( table ) . find ( 'colgroup.tablesorter-savemyplace' ) ; $tb . insertAfter ( holdr ) ; holdr . remove ( ) ; table . isProcessing = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "restore headers [CODESPLIT] function ( table ) { var index , $cell , c = $ ( table ) [ 0 ] . config , $headers = c . $table . find ( c . selectorHeaders ) , len = $headers . length ; // don't use c.$headers here in case header cells were swapped for ( index = 0 ; index < len ; index ++ ) { $cell = $headers . eq ( index ) ; // only restore header cells if it is wrapped // because this is also used by the updateAll method if ( $cell . find ( '.' + ts . css . headerIn ) . length ) { $cell . html ( c . headerContent [ index ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "mmddyyyy ddmmyyyy or yyyymmdd [CODESPLIT] function ( str ) { str = ( str || '' ) . replace ( ts . regex . spaces , ' ' ) . replace ( ts . regex . shortDateReplace , '/' ) ; return ts . regex . shortDateTest . test ( str ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- Coretags -- name : willHandle description : array of tags that the coretags plugin will handle [CODESPLIT] function ( Template ) { return [ Template . language . tag ( 'exit' ) , Template . language . tag ( 'exitloop' ) , Template . language . tag ( 'continue' ) ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -- Coretags -- name : handleToken description : executed when any tag in willHandle is found [CODESPLIT] function ( Template , expression , tag ) { switch ( tag ) { case Template . language . tag ( 'exit' ) : return new Exit ( Template , expression ) ; case Template . language . tag ( 'continue' ) : return new Continue ( Template , expression ) ; case Template . language . tag ( 'exitloop' ) : return new Exit ( Template , expression , true ) ; default : return { skip : true } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns false if node is a require expression where the module path ends with . js . [CODESPLIT] function checkCallExpression ( node ) { var callee = node . callee ; if ( callee . type === 'Identifier' && callee . name === 'require' ) { var pathNode = node . arguments [ 0 ] ; if ( pathNode . type === 'Literal' ) { var p = pathNode . value ; // Only check relatively-imported modules. if ( startswith ( p , [ '/' , './' , '../' ] ) ) { return ! endswith ( p , '.js' ) ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "校验参数 val 是否为 非正整数 即负整数和零 [CODESPLIT] function _isUnPositiveInteger ( val , options ) { var opts = _isObject ( options ) ? options : { } ; if ( opts . isStrict === true ) { return _isNumber ( val ) && REGEX_ENUM . UN_POSITIVE_INTEGER_REX . test ( val ) ; } return REGEX_ENUM . UN_POSITIVE_INTEGER_REX . test ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Logia module . The returned value of require ( logia ) . [CODESPLIT] function ( name ) { var logger ; if ( LOGGERS [ name ] ) { logger = LOGGERS [ name ] ; } else { ActiveLoggerNameLengthHandler . update ( name ) ; logger = new Logia ( name ) ; LOGGERS [ name ] = logger ; } return logger ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Listens for certain server events . Currently the only supported event is the log event which is triggered when Logia server receives a log . [CODESPLIT] function ( event , listener ) { switch ( event ) { case \"log\" : bus . subscribe ( EVENT_BUSLINE , { onRemoteLogReceived : function ( logObj ) { listener ( logObj ) ; } } ) ; break ; default : console . error ( \"[LOGIA] Unknown event name: '\" + event + \"'\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a instance of a GitCapsule . [CODESPLIT] function createGitRepository ( basePath , options ) { if ( typeof ( options ) === \"undefined\" ) options = defaultRepositoryOptions ; var gitRepository = new GitRepository ( ) ; configureGitRepository ( gitRepository , basePath , options ) ; return gitRepository ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recover a public key from a signature . [CODESPLIT] function recoverPubKey ( curve , e , signature , i ) { assert . strictEqual ( i & 3 , i , 'Recovery param is more than two bits' ) var n = curve . n var G = curve . G var r = signature . r var s = signature . s assert ( r . signum ( ) > 0 && r . compareTo ( n ) < 0 , 'Invalid r value' ) assert ( s . signum ( ) > 0 && s . compareTo ( n ) < 0 , 'Invalid s value' ) // A set LSB signifies that the y-coordinate is odd var isYOdd = i & 1 // The more significant bit specifies whether we should use the // first or second candidate key. var isSecondKey = i >> 1 // 1.1 Let x = r + jn var x = isSecondKey ? r . add ( n ) : r var R = curve . pointFromX ( isYOdd , x ) // 1.4 Check that nR is at infinity var nR = R . multiply ( n ) assert ( curve . isInfinity ( nR ) , 'nR is not a valid curve point' ) // Compute -e from e var eNeg = e . negate ( ) . mod ( n ) // 1.6.1 Compute Q = r^-1 (sR -  eG) //               Q = r^-1 (sR + -eG) var rInv = r . modInverse ( n ) var Q = R . multiplyTwo ( s , G , eNeg ) . multiply ( rInv ) curve . validate ( Q ) return Q }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate pubkey extraction parameter . [CODESPLIT] function calcPubKeyRecoveryParam ( curve , e , signature , Q ) { for ( var i = 0 ; i < 4 ; i ++ ) { var Qprime = recoverPubKey ( curve , e , signature , i ) // 1.6.2 Verify Q if ( Qprime . equals ( Q ) ) { return i } } throw new Error ( 'Unable to find valid recovery factor' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes the url to the tournament or flight [CODESPLIT] function scopeUrl ( options , inst ) { options = _ . extend ( _ . clone ( options || { } ) , inst ) if ( typeof options !== 'object' && ( ! options . tournament_id || ! options . flight_id || ! options . league_id ) ) throw new Error ( 'tournament_id required to make StandingsDefault api calls' ) return options . tournament_id ? tournamentUrl ( options . tournament_id ) : leagueUrl ( options . league_id , options . game_type ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "allows additional permissions for this acl [CODESPLIT] function ( permissions ) { _ . merge ( this . permissions , permissions , function ( a , b ) { return _ . isArray ( a ) ? a . concat ( b ) : undefined ; } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Revoke a role [CODESPLIT] function ( roles ) { if ( ! Array . isArray ( roles ) ) { roles = [ roles ] ; } this . permissions = _ . reduce ( this . permissions , function ( result , actions , key ) { if ( roles . indexOf ( key ) === - 1 ) { result [ key ] = actions ; } return result ; } , { } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assert access to this acl s action with role ( s ) [CODESPLIT] function ( roles , action ) { var self = this ; if ( ! action ) { action = roles ; roles = [ '*' ] ; } if ( ! Array . isArray ( roles ) ) { roles = [ roles ] ; } roles . push ( '*' ) ; var matches = _ . filter ( roles , function ( role ) { var actions = self . permissions [ role ] || self . permissions [ '*' ] ; return actions . indexOf ( action ) !== - 1 || actions . indexOf ( '*' ) !== - 1 ; } ) ; return matches . length > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of actions given role ( s ) have access to [CODESPLIT] function ( roles ) { roles = roles || [ '*' ] ; if ( ! Array . isArray ( roles ) ) { roles = [ roles ] ; } if ( roles . indexOf ( '*' ) === - 1 ) roles . push ( '*' ) ; var actions = [ ] ; _ . each ( roles , function ( role ) { if ( _ . has ( this . permissions , role ) ) { actions = actions . concat ( this . permissions [ role ] ) ; } } , this ) ; return _ . uniq ( actions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------- [CODESPLIT] function construct_uri_query ( parsee , alter_params ) { const this_uri_query = this ; const strategy = DEFAULT_STRATEGY ; Object . defineProperty ( this_uri_query , 'toString' , { value : to_string } ) ; if ( undefined !== parsee && null !== parsee ) { Object . assign ( this_uri_query , parse_parsee ( parsee , strategy , alter_params ) , ) ; // eslint-disable-line indent } return this_uri_query ; // ----------- function to_string ( ) { return compose_query_string ( this_uri_query , strategy , alter_params ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------- [CODESPLIT] function parse_query_string ( raw_query_string , strategy ) { const trimmed_raw_query_string = raw_query_string . trim ( ) ; if ( [ '' , '?' , '#' , '?#' ] . includes ( trimmed_raw_query_string ) ) { return { } ; } const hash_index = trimmed_raw_query_string . indexOf ( '#' ) ; /* eslint-disable indent */ const query_string = trimmed_raw_query_string . substring ( '?' === trimmed_raw_query_string . substring ( 0 , 1 ) ? 1 : 0 , - 1 === hash_index ? undefined : hash_index , ) . replace ( / (?:^[&\\s]+|[&\\s]+$) / g , '' ) // trim white space and &'s . replace ( / [&\\s]*&[&\\s]* / g , '&' ) ; /* eslint-enable indent */ if ( '' === query_string ) { return { } ; } return strategy . parse_query_string ( query_string ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------- [CODESPLIT] function protect_proto ( parsed_query_object ) { const unsafe_keys = Object . getOwnPropertyNames ( Object . prototype ) ; const safe_query_object = Object . assign ( { } , parsed_query_object ) ; for ( const key of unsafe_keys ) { '__proto__' !== key // __proto__ is ignored by javascript && undefined !== safe_query_object [ key ] && safe_query_object [ key ] !== Object . prototype [ key ] && protect_prop ( key ) ; // eslint-disable-line indent } return safe_query_object ; // ----------- function protect_prop ( key ) { safe_query_object [ ` ${ key } ` ] = safe_query_object [ key ] ; delete safe_query_object [ key ] ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------- [CODESPLIT] function unprotect_prop ( unsafe_key , safe_key ) { unsafe_query_object [ unsafe_key ] = unsafe_query_object [ safe_key ] ; delete unsafe_query_object [ safe_key ] ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------- [CODESPLIT] function alter_query_object ( mode , query_object , alter_params ) { const altered_object = Object . assign ( { } , query_object ) ; const query_keys = Object . keys ( query_object ) ; const alter_keys = Object . keys ( alter_params ) ; for ( const key of alter_keys ) { if ( query_keys . includes ( key ) ) { const alter_value = alter_params [ key ] ; /* eslint-disable indent */ const perform_alteration = 'parse' === mode ? 'function' === typeof alter_value ? alter_value : 'function' === typeof alter_value . parse ? alter_value . parse : dont_alter : 'compose' === mode ? 'function' === typeof alter_value . compose ? alter_value . compose : dont_alter : dont_alter ; /* eslint-ensable indent */ altered_object [ key ] = perform_alteration ( altered_object [ key ] ) ; } } return altered_object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Receiver stream [CODESPLIT] function ( options ) { options = options || { } ; this . maxLen = options . maxLen || 20 ; //how many packets can be buffered before stopping acknowledging new packets this . ops = [ ] ; this . seq = 0 ; this . drained = true ; this . _send = function ( op ) { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Sender stream [CODESPLIT] function ( options ) { options = options || { } ; this . retryTimeout = options . retryTimeout || 10000 ; this . maxNotAck = options . maxNotAck || 10 ; //how many unacknowledged packets can be in fly this . ops = [ ] ; this . seq = 0 ; this . sentSeq = 0 ; //the last packet which was sent, but still not acknowledged this . lastSend = 0 ; this . _send = function ( op ) { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * OpStream [CODESPLIT] function ( options ) { var opStream = this ; options = options || { } ; this . pingIntervalMs = options . pingIntervalMs || 5000 ; this . pingTimeoutMs = options . pingTimeoutMs || 3000 ; this . inStream = new InStream ( { maxLen : options . inMaxLen } ) ; this . outStream = new OutStream ( { retryTimeout : options . outRetryTimeout , maxNotAck : options . outMaxNotAck } ) ; this . inStream . _send = this . _send . bind ( this ) ; this . outStream . _send = this . _send . bind ( this ) ; this . inStream . onReadable = function ( ) { if ( opStream . onReadable ) opStream . onReadable ( ) ; } ; this . onReadable = null ; this . onOnline = null ; this . onOffline = null ; this . lastPing = 0 ; this . connectionStatus = 'online' ; this . paused = false ; this . timerInterval = null ; this . pingTimeout = null ; this . initTimer ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DAO implementation . [CODESPLIT] function DAOImplementation ( config ) { let basePath = config . basePath || 'backend/persistence/catalog/' ; let isDBloaded = true ; if ( config . filename ) { config . filename = basePath + config . filename ; } if ( config . schema ) { this . schema = fs . readJSON ( path . join ( appRoot . toString ( ) , basePath , config . schema ) ) ; } else { this . schema = { } ; } let db = new DataStore ( config ) ; if ( config . filename && ! config . autoload ) { isDBloaded = false ; } this . collection = db ; this . isDBloaded = isDBloaded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Model implementation based on Backbone . js Model implementation . [CODESPLIT] function Model ( attributes ) { // Set events hash now to prevent proxy trap this . _events = { } ; // Call super constructor EventEmitter . call ( this ) ; attributes = attributes || { } ; // Separator for change events this . _separator = ':' ; // Internal Object for storing attributes this . attributes = { } ; // Attributes that have changed since the last `change` was called. this . _changed = { } ; // Hash of attributes that have changed silently since the last `change` // was called. this . _silent = { } ; // Hash of changed attributes that have changed since the last `change` // call began. this . _pending = { } ; // Set initial attributes silently this . set ( attributes , { silent : true } ) ; // Reset changes this . _changes = { } ; this . _silent = { } ; this . _pending = { } ; // Keep track of previous values (before the previous change call) this . _previous = _ . clone ( this . attributes ) ; // Call initialize logic this . initialize . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ProxiedModel constructor . This will return a ProxyHandle to act as a Proxy for the created model . [CODESPLIT] function ProxiedModel ( attributes ) { var model ; if ( attributes instanceof Model ) { // Use existing model model = attributes ; } else { // Create a new Model model = new Model ( attributes ) ; } // Return the Proxy handler return createModelProxy ( model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Proxy for a Model . This function will return a new Proxy handle for the given Model . [CODESPLIT] function createModelProxy ( model ) { // Create a Proxy handle var handle = { getOwnPropertyDescriptor : function ( target , name ) { return ObjProto . getOwnPropertyDescriptor . call ( model . attributes , name ) ; } , getOwnPropertyNames : function ( target ) { return ObjProto . getOwnPropertyNames . call ( model . attributes ) ; } , defineProperty : function ( name , propertyDescriptor ) { return Object . defineProperty ( model . attributes , name , propertyDescriptor ) ; } , // Get an attribute from the Model. This will first check for Model properties before // checking the Model's internal attributes map. get : function ( target , name , reciever ) { // Check for direct properties to satisfy internal attribute and function calls if ( model [ name ] ) { return model [ name ] ; } // It's not a property, check for internal attribute value return model . get ( name ) ; } , set : function ( target , name , value , receiver ) { return model . set ( name , value ) ; } , delete : function ( name ) { model . unset ( name ) ; } , has : function ( target , name ) { return model . has ( 'name' ) ; } , hasOwn : function ( target , name ) { return this . has ( target , name ) ; } , enumerate : function ( target ) { return model . attributes ; } , keys : function ( target ) { return Object . keys ( model . attributes ) ; } //protect: function(operation, target) -> boolean //stopTrapping: function(target) -> boolean //iterate: not implemented yet } ; return ProxyCtor . create ( handle , Model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an attribute from the Model . This will first check for Model properties before checking the Model s internal attributes map . [CODESPLIT] function ( target , name , reciever ) { // Check for direct properties to satisfy internal attribute and function calls if ( model [ name ] ) { return model [ name ] ; } // It's not a property, check for internal attribute value return model . get ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private functions . [CODESPLIT] function detectDestType ( dest ) { if ( grunt . util . _ . endsWith ( dest , '/' ) ) { return cnst . directory ; } else { return cnst . file ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "RANDOM // FUNCTION : random ( len mu sigma [ rand ] ) Creates an array of normally distributed random numbers . [CODESPLIT] function random ( len , mu , sigma , rand ) { var out ; var draw ; var i ; draw = partial ( mu , sigma , rand ) ; // Ensure fast elements... if ( len < 64000 ) { out = new Array ( len ) ; for ( i = 0 ; i < len ; i ++ ) { out [ i ] = draw ( ) ; } } else { out = [ ] ; for ( i = 0 ; i < len ; i ++ ) { out . push ( draw ( ) ) ; } } return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FUNCTION : roundn ( x n ) Rounds values to the nearest multiple of 10^n . Notes : if provided an array mutates the array . [CODESPLIT] function roundn ( x , n ) { var isArray = Array . isArray ( x ) , scalar , len ; if ( ! isArray && ( typeof x !== 'number' || x !== x ) ) { throw new TypeError ( 'roundn()::invalid input argument. Must provide either a single numeric value or a numeric array.' ) ; } if ( typeof n !== 'number' || n !== n || n !== ( n | 0 ) ) { throw new TypeError ( 'roundn()::invalid input argument. Power of 10 must be an integer value.' ) ; } n = - n ; scalar = Math . pow ( 10 , n ) ; if ( ! isArray ) { return Math . round ( x * scalar ) / scalar ; } len = x . length ; if ( ! len ) { return null ; } for ( var i = 0 ; i < len ; i ++ ) { x [ i ] = Math . round ( x [ i ] * scalar ) / scalar ; } return x ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a random color [CODESPLIT] function ( ) { return { r : Math . floor ( Math . random ( ) * 256 ) , g : Math . floor ( Math . random ( ) * 256 ) , b : Math . floor ( Math . random ( ) * 256 ) , a : 255 } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pingy constructor [CODESPLIT] function ( width , height ) { width = clamp ( width , 1 ) ; height = clamp ( height , 1 ) ; this . _png = new PNG ( ) ; this . _png . width = width ; this . _png . height = height ; this . _png . data = buffer ( width , height ) ; this . forEachPoint ( function ( x , y , rgba ) { return { r : 0 , g : 0 , b : 0 , a : 255 } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a function on each point in an image [CODESPLIT] function ( fn ) { for ( var y = 0 ; y < this . getHeight ( ) ; y ++ ) { for ( var x = 0 ; x < this . getWidth ( ) ; x ++ ) { var rgba = this . getColor ( x , y ) ; var out = fn . call ( this , x , y , rgba ) ; this . setColor ( x , y , ( out || rgba ) ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the RGBA value of a coordinate [CODESPLIT] function ( x , y ) { var i = this . _getIndex ( x , y ) ; return { r : this . _png . data [ i + 0 ] , g : this . _png . data [ i + 1 ] , b : this . _png . data [ i + 2 ] , a : this . _png . data [ i + 3 ] } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the RGBA value of a coordinate [CODESPLIT] function ( x , y , rgba ) { var i = this . _getIndex ( x , y ) ; var prev = this . getColor ( x , y ) ; this . _png . data [ i + 0 ] = is_num ( rgba . r ) ? to_rgba_int ( rgba . r ) : prev . r ; this . _png . data [ i + 1 ] = is_num ( rgba . g ) ? to_rgba_int ( rgba . g ) : prev . g ; this . _png . data [ i + 2 ] = is_num ( rgba . b ) ? to_rgba_int ( rgba . b ) : prev . b ; this . _png . data [ i + 3 ] = is_num ( rgba . a ) ? to_rgba_int ( rgba . a ) : prev . a ; return this . getColor ( x , y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enlarge by some integer factor [CODESPLIT] function ( factor ) { factor = clamp ( to_int ( factor ) , 1 ) ; var width = this . getWidth ( ) * factor ; var height = this . getHeight ( ) * factor ; var buf = new buffer ( width , height ) ; for ( var y = 0 ; y < height ; y ++ ) { for ( var x = 0 ; x < width ; x ++ ) { var i = get_index ( width , x , y ) ; var rgba = this . getColor ( to_int ( x / factor ) , to_int ( y / factor ) ) ; buf [ i + 0 ] = rgba . r ; buf [ i + 1 ] = rgba . g ; buf [ i + 2 ] = rgba . b ; buf [ i + 3 ] = rgba . a ; } } this . _png . width = width ; this . _png . height = height ; this . _png . data = buf ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the base64 encoding [CODESPLIT] function ( fn ) { fn = fn || console . log . bind ( console ) ; var buffers = [ ] ; var base64 = new Stream ( ) ; base64 . readable = base64 . writable = true ; base64 . write = function ( data ) { buffers . push ( data ) ; } ; base64 . end = function ( ) { fn ( Buffer . concat ( buffers ) . toString ( 'base64' ) ) ; } this . _png . pack ( ) . pipe ( base64 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the base64 encoding as a data URI [CODESPLIT] function ( fn ) { fn = fn || console . log . bind ( console ) ; return this . toBase64 ( function ( str ) { fn ( 'data:image/png;base64,' + str ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a node - specific version of an anal structural equality test modeled on bits and pieces of many other versions of this check most notably deeper which is in turn based on the Node . js source s assert . deepEqual and the Underscore library . It doesn t throw and handles cycles . [CODESPLIT] function deepest ( a , b , ca , cb ) { if ( a === b ) { return true ; } else if ( typeof a !== 'object' || typeof b !== 'object' ) { return false ; } else if ( a === null || b === null ) { return false ; } else if ( Buffer . isBuffer ( a ) && Buffer . isBuffer ( b ) ) { if ( fastEqual ) { return fastEqual . call ( a , b ) ; } else { if ( a . length !== b . length ) return false ; for ( var i = 0 ; i < a . length ; i ++ ) if ( a [ i ] !== b [ i ] ) return false ; return true ; } } else if ( a instanceof Date && b instanceof Date ) { return a . getTime ( ) === b . getTime ( ) ; } else if ( isArguments ( a ) || isArguments ( b ) ) { if ( ! ( isArguments ( a ) && isArguments ( b ) ) ) return false ; var slice = Array . prototype . slice ; return deepest ( slice . call ( a ) , slice . call ( b ) , ca , cb ) ; } else { if ( a . constructor !== b . constructor ) return false ; var pa = Object . getOwnPropertyNames ( a ) ; var pb = Object . getOwnPropertyNames ( b ) ; if ( pa . length !== pb . length ) return false ; var cal = ca . length ; while ( cal -- ) if ( ca [ cal ] === a ) return cb [ cal ] === b ; ca . push ( a ) ; cb . push ( b ) ; pa . sort ( ) ; pb . sort ( ) ; for ( var j = pa . length - 1 ; j >= 0 ; j -- ) if ( pa [ j ] !== pb [ j ] ) return false ; var name , da , db ; for ( var k = pa . length - 1 ; k >= 0 ; k -- ) { name = pa [ k ] ; da = Object . getOwnPropertyDescriptor ( a , name ) ; db = Object . getOwnPropertyDescriptor ( b , name ) ; if ( da . enumerable !== db . enumerable || da . writable !== db . writable || da . configurable !== db . configurable || da . get !== db . get || da . set !== db . set ) { return false ; } if ( ! deepest ( da . value , db . value , ca , cb ) ) return false ; } ca . pop ( ) ; cb . pop ( ) ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copied straight from tap - test . js [CODESPLIT] function assertParasite ( fn ) { return function _deeperAssert ( ) { if ( this . _bailedOut ) return ; var res = fn . apply ( tap . assert , arguments ) ; this . result ( res ) ; return res ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs rot13 encoding / decoding [CODESPLIT] function rot13 ( str ) { return str . replace ( / [a-zA-Z] / g , function ( c ) { return String . fromCharCode ( ( c <= 'Z' ? 90 : 122 ) >= ( c = c . charCodeAt ( 0 ) + 13 ) ? c : c - 26 ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Swaps all tags with a class of obfuscemail with an <a > mailto link [CODESPLIT] function swapTags ( email , text ) { document . querySelectorAll ( '.obfuscemail' ) . forEach ( function ( a ) { var newA = document . createElement ( 'a' ) ; newA . href = 'mailto:' + email ; newA . innerHTML = text ; a . parentNode . replaceChild ( newA , a ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "RANDOM // FUNCTION : random ( dims dt mu sigma [ rand ] ) Creates a matrix of normally distributed random numbers . [CODESPLIT] function random ( dims , dt , mu , sigma , rand ) { var out ; var draw ; var i ; draw = partial ( mu , sigma , rand ) ; out = matrix ( dims , dt ) ; for ( i = 0 ; i < out . length ; i ++ ) { out . data [ i ] = draw ( ) ; } return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates ignore option for given path [CODESPLIT] function getIgnored ( filepath ) { for ( var i in options . ignore ) { if ( filepath . indexOf ( options . ignore [ i ] ) !== - 1 ) { return options . ignore [ i ] ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tells whether or not the given path is a valid directory ( directory which contains a package . json ) [CODESPLIT] function isValidDir ( filepath ) { if ( grunt . file . isDir ( filepath ) ) { return grunt . file . exists ( path . resolve ( filepath , 'package.json' ) ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "utils [CODESPLIT] function bindify ( fn , thisArg , args ) { return fn . bind . apply ( fn , [ thisArg ] . concat ( args ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------------------ [CODESPLIT] function defineGetStageValue ( parts ) { let body ; switch ( parts . length ) { case 0 : body = \"return this.state;\" ; break ; default : const lastIndex = parts . length - 1 ; body = \"var tmp0 = this.state;\" ; for ( let i = 0 ; i < lastIndex ; ++ i ) { body += ` ${ i } ${ i + 1 } ${ i } ${ parts [ i ] } ` ; } body += ` ${ lastIndex } ${ lastIndex } ${ parts [ lastIndex ] } ` ; break ; } return Function ( body ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------------------ [CODESPLIT] function defineSetStageValue ( parts ) { let body = ` ` ; switch ( parts . length ) { case 0 : body += \"\\nthis.setState(value, cb2);\" ; break ; case 1 : body += ` \\n ${ parts [ 0 ] } ` ; break ; default : const lastIndex = parts . length - 1 ; body += ` \\n ` ; for ( let i = 0 ; i < lastIndex ; ++ i ) { body += ` ${ i + 1 } ${ i } ${ parts [ i ] } ${ i + 1 } ${ i + 1 } ${ i } ${ parts [ i ] } ` ; } body += ` ${ lastIndex } ${ parts [ lastIndex ] } ` ; break ; } return Function ( \"value\" , \"cb\" , body ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------------------ [CODESPLIT] function handleSendAction ( event ) { if ( event . defaultPrevented ) { return ; } if ( typeof this . filterAction === \"function\" && ! this . filterAction ( event ) ) { return ; } event . stopPropagation ( ) ; event . applyTo ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@constructor [CODESPLIT] function Mongootils ( ) { if ( arguments [ 0 ] && arguments [ 0 ] . constructor && arguments [ 0 ] . constructor . name === 'NativeConnection' ) { this . connection = arguments [ 0 ] ; this . uri = this . getConnectionURI ( ) ; this . options = this . connection . options ; } else { this . uri = arguments [ 0 ] ; this . options = arguments [ 1 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PARTIAL // FUNCTION : partial ( mu sigma [ rand ] ) Partially applies mu and sigma and returns a function to generate random variables from the normal distribution . Implementation of the Improved Ziggurat Method by J . Doornik . Reference : Doornik J . a . ( 2005 ) . An Improved Ziggurat Method to Generate Normal Random Samples . [CODESPLIT] function partial ( mu , sigma , rand ) { var random ; /* s_adZigX holds coordinates, such that each rectangle has\n\t\tsame area; s_adZigR holds s_adZigX[i + 1] / s_adZigX[i] */ var s_adZigX = new Array ( ZIGNOR_C + 1 ) ; var s_adZigR = new Array ( ZIGNOR_C ) ; var i ; var f ; if ( rand ) { random = rand ; } else { random = Math . random ; } f = exp ( - 0.5 * ZIGNOR_R * ZIGNOR_R ) ; s_adZigX [ 0 ] = ZIGNOR_V / f ; /* [0] is bottom block: V / f(R) */ s_adZigX [ 1 ] = ZIGNOR_R ; s_adZigX [ ZIGNOR_C ] = 0 ; for ( i = 2 ; i < ZIGNOR_C ; i ++ ) { s_adZigX [ i ] = sqrt ( - 2 * log ( ZIGNOR_V / s_adZigX [ i - 1 ] + f ) ) ; f = exp ( - 0.5 * s_adZigX [ i ] * s_adZigX [ i ] ) ; } for ( i = 0 ; i < ZIGNOR_C ; i ++ ) { s_adZigR [ i ] = s_adZigX [ i + 1 ] / s_adZigX [ i ] ; } /**\n\t* FUNCTION: draw( x )\n\t*\tGenerates a random draw for a normal distribution with parameters `mu` and `sigma`.\n\t*\n\t* @private\n\t* @returns {Number} random draw from the specified distribution\n\t*/ return function draw ( ) { var x , u , f0 , f1 ; for ( ; ; ) { u = 2 * random ( ) - 1 ; i = TWO_P_32 * random ( ) & 0x7F ; /* first try the rectangular boxes */ if ( abs ( u ) < s_adZigR [ i ] ) { return mu + sigma * u * s_adZigX [ i ] ; } /* bottom box: sample from the tail */ if ( i === 0 ) { return mu + sigma * dRanNormalTail ( ZIGNOR_R , u < 0 , rand ) ; } /* is this a sample from the wedges? */ x = u * s_adZigX [ i ] ; f0 = exp ( - 0.5 * ( s_adZigX [ i ] * s_adZigX [ i ] - x * x ) ) ; f1 = exp ( - 0.5 * ( s_adZigX [ i + 1 ] * s_adZigX [ i + 1 ] - x * x ) ) ; if ( f1 + random ( ) * ( f0 - f1 ) < 1.0 ) { return mu + sigma * x ; } } } ; // end FUNCTION draw() }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Basic input prompt rendering . [CODESPLIT] function renderInputPrompt ( ) { process . stdout . write ( prefix ) ; process . stdout . write ( textToRender . join ( '' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will return a chalk function based on selected index etc .. [CODESPLIT] function calculateFieldColor ( selectedColor , nonSelectedColor , focusedColor , index , out ) { if ( selected . indexOf ( index ) !== - 1 && focused == index ) return chalk . bold . rgb ( selectedColor . r , selectedColor . g , selectedColor . b ) ( out ) ; if ( selected . indexOf ( index ) !== - 1 ) // this goes before focused so selected color gets priority over focused values return chalk . rgb ( selectedColor . r , selectedColor . g , selectedColor . b ) ( out ) ; if ( focused == index ) return chalk . bold . rgb ( focusedColor . r , focusedColor . g , focusedColor . b ) ( out ) ; return chalk . rgb ( nonSelectedColor . r , nonSelectedColor . g , nonSelectedColor . b ) ( out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FUNCTION randn ( length ) Creates an array of standard normal random variates using the Box - Mueller transform . [CODESPLIT] function randn ( length ) { var urand , vrand , vec = [ ] , numValues = length || 1 ; for ( var i = 0 ; i < numValues ; i ++ ) { urand = Math . random ( ) ; vrand = Math . random ( ) ; vec . push ( Math . sqrt ( - 2 * Math . log ( urand ) ) * Math . cos ( 2 * Math . PI * vrand ) ) ; } if ( numValues === 1 ) { return vec [ 0 ] ; } return vec ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use app . import to add additional libraries to the generated output files . If you need to use different assets in different environments specify an object as the first parameter . That object s keys should be the environment name and the values should be the asset to use in that environment . If the library that you are including contains AMD or ES6 modules that you would like to import into your application please specify an object with the list of modules as keys along with the exports of each module as its value . [CODESPLIT] function render ( errors ) { if ( ! errors ) { return '' ; } ; return errors . map ( function ( error ) { return error . line + ':' + error . column + ' ' + ' - ' + error . message + ' (' + error . ruleId + ')' ; } ) . join ( '\\n' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle GET request . [CODESPLIT] function ( url ) { let request = parseRequest ( url ) ; let resource = getRequestedResource ( request ) ; return resource . get ( request ) . then ( returnGetResponse ) ; function returnGetResponse ( result ) { // eslint-disable-line require-jsdoc return new RESTResponse ( url , \"GET\" , result ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle PUT request . [CODESPLIT] function ( url , data ) { let request = parseRequest ( url , data ) ; let resource = getRequestedResource ( request ) ; return resource . put ( request ) . then ( returnResponse ) ; function returnResponse ( result ) { // eslint-disable-line require-jsdoc return new RESTResponse ( url , \"PUT\" , result ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FUNCTION : recurse ( dims d draw ) Recursively create a multidimensional array of normally distributed random numbers . [CODESPLIT] function recurse ( dims , d , draw ) { var out = [ ] ; var len ; var i ; len = dims [ d ] ; d += 1 ; if ( d < dims . length ) { for ( i = 0 ; i < len ; i ++ ) { out . push ( recurse ( dims , d , draw ) ) ; } } else { for ( i = 0 ; i < len ; i ++ ) { out . push ( draw ( ) ) ; } } return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a copy of the input in which any property that hasn t explicitly been expressed in the schema is stripped . [CODESPLIT] function mapPrune ( input , schema ) { var result = { } ; _ . forOwn ( schema , function ( value , key ) { if ( _ . isPlainObject ( value ) ) { // Recursive. result [ key ] = mapPrune ( input [ key ] || { } , value ) ; } else { // Base. Null is set as the default value. result [ key ] = input [ key ] || null ; } } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a result map of running the schema s tests / transformers against an input object . [CODESPLIT] function mapRun ( input , schema , discrepencies ) { var result = { } ; _ . forOwn ( schema , function ( value , key ) { if ( _ . isPlainObject ( value ) ) { // Recursive. Others are bases. result [ key ] = mapRun ( input [ key ] , value , discrepencies ) ; } else if ( _ . isArray ( value ) ) { try { result [ key ] = value . reduce ( function ( prev , curr , index ) { if ( ! _ . isFunction ( curr ) ) throw 'Index [' + index + ']: Not a function.' ; return curr ( prev ) ; } , input [ key ] ) ; } catch ( e ) { discrepencies . push ( '' + key + ': ' + e ) ; } } else if ( _ . isFunction ( value ) ) { try { result [ key ] = value ( input [ key ] ) ; // Result of running that function against the input. } catch ( e ) { discrepencies . push ( '' + key + ': ' + e ) ; } } else { throw new TypeError ( 'Schemas should be a nested object of functions or function arrays.' ) ; } } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform a given input value using a property spec object . propSpec : an object that defines a Backprop property . Supported keys ( see the README for explanations ) include : coerce choices trim max min inputVal : the value that the caller has assigned to the property fallbackValue ( optional ) : a default value to use if the input is invalid [CODESPLIT] function transformValue ( propSpec , inputVal , fallbackValue ) { var value = inputVal ; if ( typeof propSpec . coerce === 'function' ) value = propSpec . coerce ( value ) ; // If an array of choices was passed in, validate that the input is one of // the valid choices: var choices = propSpec . choices ; if ( choices && choices . constructor && choices . constructor . name === 'Array' ) { if ( choices . indexOf ( value ) === - 1 ) { if ( fallbackValue !== undefined ) value = fallbackValue ; else return undefined ; } } if ( propSpec . trim && ( typeof value . trim === 'function' ) ) value = value . trim ( ) ; if ( propSpec . max && ( value > propSpec . max ) ) value = propSpec . max ; if ( propSpec . min && ( value < propSpec . min ) ) value = propSpec . min ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow use of shorthand properties like myprop : Backprop . Boolean () . This avoids having to pass in an explicit coerce function when you are just casting to a JS type . If you do pass in a coerce function it will still work but the type cast will be applied first . [CODESPLIT] function ( typeCoerce ) { return function ( specObj ) { specObj = specObj || { } ; var innerCoerce = specObj . coerce ; if ( typeof innerCoerce === 'function' ) { specObj . coerce = function ( x ) { return innerCoerce ( typeCoerce ( x ) ) ; } ; } else { specObj . coerce = typeCoerce ; } return new PropPlaceholder ( specObj ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a palette from theme references . Is defined as {{ paletteName }} . {{ palette . property }} | {{ colorManipulation }} Example : # theme . yaml color : !palette primary . color|accent [CODESPLIT] function ( values , yamlLoader ) { var palettes = luiTheme ( 'core.references.palettes' ) , palette = values . split ( '|' ) [ 0 ] , paletteName = palette . split ( '.' ) [ 0 ] , paletteProp = ( palette . split ( '.' ) [ 1 ] ) ? palette . split ( '.' ) [ 1 ] : null , manipulation = ( values . split ( '|' ) [ 1 ] ) ? values . split ( '|' ) [ 1 ] : null , result = palettes . colors [ paletteName ] ; if ( paletteProp && result [ paletteProp ] ) result = result [ paletteProp ] ; if ( manipulation ) { result = palettes . manipulations [ manipulation ] [ 0 ] + '(' + result + ', ' + palettes . manipulations [ manipulation ] [ 1 ] + ')' ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the YAML schema based on default and passed custom types . [CODESPLIT] function createYamlSchema ( customTypes ) { var yamlTypes = [ ] ; _ . each ( customTypes , function ( resolver , tagAndKindString ) { var tagAndKind = tagAndKindString . split ( / \\s+ / ) , yamlType = new yaml . Type ( tagAndKind [ 0 ] , { kind : tagAndKind [ 1 ] , construct : function ( data ) { var result = resolver . call ( this , data , loadYamlFile ) ; if ( _ . isUndefined ( result ) || _ . isFunction ( result ) ) { return null ; } else { return result ; } } } ) ; yamlTypes . push ( yamlType ) ; } ) ; return yaml . Schema . create ( yamlTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads a YAML file and parses it into an Object . [CODESPLIT] function loadYamlFile ( filepath ) { try { return yaml . safeLoad ( fs . readFileSync ( filepath ) , { schema : yamlSchema , filename : filepath } ) ; } catch ( err ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load theme variables from a YAML file . [CODESPLIT] function loadTheme ( props ) { var relPath = '/' + props . join ( '/' ) + '.yml' , defaultsPath = path . resolve ( base + '/scss/themes/default' + relPath ) , customPath = ( custom ) ? custom + relPath : null , defaultVars = { } , customVars = null , result = { } ; // Try loading a custom theme file customVars = loadYamlFile ( customPath ) ; // If merge mode is set to \"replace\", don't even load the defaults if ( customVars && customVars [ 'merge-mode' ] === 'replace' ) { result = _ . omit ( customVars , 'merge-mode' ) ; } else { defaultVars = loadYamlFile ( defaultsPath ) ; result = _ . merge ( defaultVars , customVars ) ; } // Store variables in cached theme var _ . set ( theme , props . join ( '.' ) , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves theme variables from cached theme var or from file if need be [CODESPLIT] function luiTheme ( props ) { var propsS = ( _ . isArray ( props ) ) ? props . join ( '.' ) : props , propsA = ( _ . isString ( props ) ) ? props . split ( '.' ) : props , objectVars , objectPath = [ ] ; objectVars = _ . result ( theme , propsS ) ; // If object is already cached in theme, return it if ( objectVars ) { return objectVars ; // Else load it from file } else { // Find the object fromp build file _ . each ( propsA , function ( prop ) { if ( _ . result ( build , _ . union ( objectPath , [ prop ] ) . join ( '.' ) ) || ( _ . includes ( _ . result ( build , objectPath . join ( '.' ) ) , prop ) ) ) { objectPath . push ( prop ) ; } else { return objectPath ; } } ) ; loadTheme ( objectPath ) ; return _ . result ( theme , propsS ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a string in a file . [CODESPLIT] function write ( destination , data , callback ) { // Create directories if needs be mkdirp ( path . dirname ( destination ) , null , ( err , made ) => { if ( err ) { console . error ( err ) ; } else { fs . writeFile ( destination , data , ( err ) => { if ( err ) { console . error ( err ) ; } if ( typeof ( callback ) == 'function' ) { callback ( destination , data ) ; } } ) ; } } ) ; return destination ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes global variables . In particular merges defaults and custom options . [CODESPLIT] function init ( _options ) { // Build global options var options = _ . merge ( defaults , _options ) ; // Store paths base = options . base ; custom = options . custom ; // Retrieve build definition build = options . build = ( typeof options . build === 'object' ) ? options . build : require ( options . build ) ; // Create YAML schema (create custom types) yamlSchema = createYamlSchema ( options . customTypes ) ; return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles build definitions and theme variables into a ready - to - import scss string . [CODESPLIT] function redact ( _options , callback ) { var imports = [ ] , // List of scss to import output = '' , // The scss output errors = [ ] ; // List of errors encountered // Build core theme [ 'core' ] = { } ; _ . each ( _options . build . core , function ( objects , family ) { theme [ 'core' ] [ family ] = { } ; _ . each ( objects , function ( objectName ) { luiTheme ( 'core.' + family + '.' + objectName ) ; imports . push ( 'core/' + family + '/' + objectName ) ; } ) ; } ) ; // Build plugins if ( _options . build . plugins ) { theme [ 'plugins' ] = { } ; _ . each ( _options . build . plugins , function ( plugin ) { luiTheme ( 'plugins.' + plugin ) ; } ) ; } output = tosass . format ( { theme : theme , imports : imports } ) ; if ( typeof ( callback ) === 'function' ) { callback ( output ) ; } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the scss and writes it into destination file passed in options . [CODESPLIT] function ( _options , callback ) { var options = init ( _options ) ; return write ( options . dest , redact ( options ) , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts objects to a map typed scss variable [CODESPLIT] function ( map ) { return '(' + Object . keys ( map ) . map ( function ( key ) { return key + ': ' + parseValue ( map [ key ] ) ; } ) . join ( ',' ) + ')' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a Javascript Object and returns a sass map string [CODESPLIT] function objectToSass ( object ) { return Object . keys ( object ) . map ( function ( key ) { return '$' + key + ': ' + parseValue ( object [ key ] ) + ';' ; } ) . join ( '\\n' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Distinguishes between strings list and maps and calls the appropriate parser [CODESPLIT] function parseValue ( value ) { if ( _ . isArray ( value ) ) return converters . list ( value ) ; else if ( _ . isPlainObject ( value ) ) return converters . map ( value ) ; else return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats data into a string that can be evaluated as Scss / Sass [CODESPLIT] function formatData ( data ) { var result = '// ===================================\\n' + '// =============== CORE ==============\\n' + '// ===================================\\n' + '@import \"core/core\";\\n\\n' + '// ===================================\\n' + '// ========= THEME VARIABLES =========\\n' + '// ===================================\\n' + objectToSass ( { theme : data . theme } ) + '\\n\\n' + '// ===================================\\n' + '// ============= OBJECTS =============\\n' + '// ===================================\\n' + '@import \"' + data . imports . join ( '\",\\n        \"' ) + '\";' ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NORMAL RANDOM VARIATES // FUNCTION : random ( [ dims ] [ opts ] ) Creates a matrix or array filled with normal random numbers . [CODESPLIT] function random ( dims , options ) { var opts = { } ; var isArray ; var ndims ; var err ; var len ; var mu ; var sigma ; var rand ; var dt ; if ( arguments . length > 0 ) { isArray = isPositiveIntegerArray ( dims ) ; if ( ! isArray && ! isPositiveInteger ( dims ) ) { throw new TypeError ( 'invalid input argument. Dimensions argument must be either a positive integer or a positive integer array. Value: `' + dims + '`.' ) ; } } if ( arguments . length > 1 ) { err = validate ( opts , options ) ; if ( err ) { throw err ; } } if ( opts . seed ) { rand = lcg ( opts . seed ) ; } else { rand = RAND ; } dt = opts . dtype || 'generic' ; mu = typeof opts . mu !== 'undefined' ? opts . mu : 0 ; sigma = typeof opts . sigma !== 'undefined' ? opts . sigma : 1 ; if ( arguments . length === 0 ) { return number ( mu , sigma , rand ) ; } if ( isArray ) { ndims = dims . length ; if ( ndims < 2 ) { len = dims [ 0 ] ; } } else { ndims = 1 ; len = dims ; } // 1-dimensional data structures... if ( ndims === 1 ) { if ( len === 1 ) { return number ( mu , sigma , rand ) ; } if ( dt === 'generic' ) { return array ( len , mu , sigma , rand ) ; } return typedarray ( len , dt , mu , sigma , rand ) ; } // Multidimensional data structures... if ( dt !== 'generic' ) { if ( ndims === 2 ) { return matrix ( dims , dt , mu , sigma , rand ) ; } // TODO: dstructs-ndarray support goes here. Until then, fall through to plain arrays... } return arrayarray ( dims , mu , sigma , rand ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generate a guid that is tested unique against id s on the current doc [CODESPLIT] function domSafeRandomGuid ( ) { var _arguments = arguments ; var _again = true ; _function : while ( _again ) { numberOfBlocks = output = num = undefined ; var s4 = function s4 ( ) { return Math . floor ( ( 1 + Math . random ( ) ) * 65536 ) . toString ( 16 ) . substring ( 1 ) ; } ; _again = false ; var numberOfBlocks = _arguments [ 0 ] === undefined ? 4 : _arguments [ 0 ] ; var output = '' ; var num = numberOfBlocks ; while ( num > 0 ) { output += s4 ( ) ; if ( num > 1 ) output += '-' ; num -- ; } if ( null === document . getElementById ( output ) ) { return output ; } else { _arguments = [ numberOfBlocks ] ; _again = true ; continue _function ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@class The ChainFunction wraps the functionality of a function executed on a chain context . [CODESPLIT] function ( options ) { options = Safe . object ( options ) ; this . name = Safe . string ( options . name , \"?\" ) ; this . fn = Safe . function ( options . fn , function ( ) { } ) ; this . args = Safe . array ( options . args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * eslint - disable no - console [CODESPLIT] function I ( obj ) { function isObject ( v ) { return { } . toString . call ( v ) === '[object Object]' ; } function isArray ( v ) { return { } . toString . call ( v ) === '[object Array]' ; } function isFunc ( v ) { return { } . toString . call ( v ) === '[object Function]' ; } function assertA ( v , msg ) { if ( ! isArray ( v ) ) throw new Error ( msg ) ; } function assertAO ( v , msg ) { if ( ! isArray ( v ) && ! isObject ( v ) ) throw new Error ( msg ) ; } function _get ( o , p ) { var key = isFunc ( p [ 0 ] ) ? o . findIndex ( p [ 0 ] ) : p [ 0 ] ; return p . length ? _get ( o [ key ] , p . slice ( 1 ) ) : o ; } function _set ( o , p , v ) { var key = isFunc ( p [ 0 ] ) ? o . findIndex ( p [ 0 ] ) : p [ 0 ] ; // eslint-disable-next-line no-param-reassign if ( p . length === 1 ) o [ key ] = v ; else _set ( o [ key ] , p . slice ( 1 ) , v ) ; } function _copy ( o , path ) { var p = [ ] . concat ( toConsumableArray ( path ) ) ; var n = p . splice ( 0 , 1 ) [ 0 ] ; if ( isFunc ( n ) ) n = o . findIndex ( n ) ; if ( n !== undefined ) { if ( o [ n ] === undefined ) throw new Error ( 'Path not found' ) ; return isArray ( o ) ? [ ] . concat ( toConsumableArray ( o . slice ( 0 , n ) ) , [ _copy ( o [ n ] , p ) ] , toConsumableArray ( o . slice ( n + 1 ) ) ) : _extends ( { } , o , defineProperty ( { } , n , _copy ( o [ n ] , p ) ) ) ; } return isArray ( o ) ? [ ] . concat ( toConsumableArray ( o ) ) : _extends ( { } , o ) ; } function _diff ( a , b ) { var path = arguments . length > 2 && arguments [ 2 ] !== undefined ? arguments [ 2 ] : [ ] ; var acc = arguments . length > 3 && arguments [ 3 ] !== undefined ? arguments [ 3 ] : 0 ; function log ( p , msg , value ) { acc . push ( value ? { path : p , msg : msg , value : value } : { path : p , msg : msg } ) ; } function strPath ( p , key ) { var p2 = key !== undefined ? [ ] . concat ( toConsumableArray ( p ) , [ key ] ) : p ; return p2 . length ? p2 . join ( '.' ) : '(root)' ; } if ( isArray ( a ) && isArray ( b ) ) { if ( a !== b ) log ( strPath ( path ) , 'different reference' ) ; var deletions = { } ; b . forEach ( function ( v , k ) { if ( a . indexOf ( v ) === - 1 ) deletions [ k ] = v ; } ) ; a . forEach ( function ( v , k ) { var bk = b . indexOf ( v ) ; if ( bk === - 1 ) { if ( deletions [ k ] !== undefined ) { log ( strPath ( path , k ) , 'replace' , v ) ; delete deletions [ k ] ; } else { log ( strPath ( path , k ) , 'add' , v ) ; } } else if ( bk !== k && ! Object . keys ( deletions ) ) log ( strPath ( path , k ) , 'index changed from ' + bk , v ) ; } ) ; Object . keys ( deletions ) . forEach ( function ( k ) { return log ( strPath ( path , k ) , 'delete' ) ; } ) ; } else if ( isObject ( a ) && isObject ( b ) ) { if ( a !== b ) log ( strPath ( path ) , 'different reference' ) ; Object . keys ( b ) . forEach ( function ( k ) { if ( a [ k ] === undefined ) log ( strPath ( path , k ) , 'delete' , b [ k ] ) ; } ) ; Object . keys ( a ) . forEach ( function ( k ) { if ( b [ k ] === undefined ) log ( strPath ( path , k ) , 'add' , a [ k ] ) ; else if ( a [ k ] !== b [ k ] ) _diff ( a [ k ] , b [ k ] , path . concat ( [ k ] ) , acc ) ; } ) ; } else if ( ( typeof a === 'undefined' ? 'undefined' : _typeof ( a ) ) === 'object' || ( typeof b === 'undefined' ? 'undefined' : _typeof ( b ) ) === 'object' ) log ( strPath ( path ) , 'different types!' ) ; else if ( a !== b ) log ( strPath ( path ) , 'change' , a ) ; } assertAO ( obj , 'obj must be an object or array' ) ; return { result : obj , get : function get$$1 ( path ) { assertA ( path , 'path must be an array' ) ; return _get ( this . result , path ) ; } , set : function set$$1 ( value , path ) { assertA ( path , 'path must be an array' ) ; if ( this . copy ( path . slice ( 0 , path . length - 1 ) ) ) { _set ( this . result , path , value ) ; } return this ; } , push : function push ( value ) { var path = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : [ ] ; assertA ( path , 'path must be an array' ) ; if ( this . copy ( path ) ) { if ( path . length ) _set ( this . result , path , [ ] . concat ( toConsumableArray ( _get ( this . result , path ) ) , [ value ] ) ) ; else this . result . push ( value ) ; } return this ; } , delete : function _delete ( path ) { assertA ( path , 'path must be an array' ) ; var parentPath = path . slice ( 0 , path . length - 1 ) ; var last = path . slice ( path . length - 1 , path . length ) [ 0 ] ; if ( this . copy ( parentPath ) ) { var o = parentPath . length ? _get ( this . result , parentPath ) : this . result ; if ( isArray ( o ) ) { if ( isFunc ( last ) ) last = o . findIndex ( last ) ; if ( parentPath . length ) { _set ( this . result , parentPath , [ ] . concat ( toConsumableArray ( o . slice ( 0 , last ) ) , toConsumableArray ( o . slice ( last + 1 ) ) ) ) ; } else this . result = [ ] . concat ( toConsumableArray ( o . slice ( 0 , last ) ) , toConsumableArray ( o . slice ( last + 1 ) ) ) ; } else delete o [ last ] ; } return this ; } , copy : function copy ( path ) { assertA ( path , 'path must be an array' ) ; try { this . result = _copy ( this . result , path ) ; } catch ( e ) { console . warn ( e ) ; return false ; } return this ; } , diff : function diff ( other ) { var acc = [ ] ; _diff ( this . result , other , [ ] , acc ) ; return acc ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "VALIDATE // FUNCTION : validate ( opts options ) Validates function options . [CODESPLIT] function validate ( opts , options ) { if ( ! isObject ( options ) ) { return new TypeError ( 'invalid input argument. Options argument must be an object. Value: `' + options + '`.' ) ; } if ( options . hasOwnProperty ( 'mu' ) ) { opts . mu = options . mu ; if ( ! isNumber ( opts . mu ) ) { return new TypeError ( 'invalid option. `mu` parameter must be a number primitive. Option: `' + opts . mu + '`.' ) ; } } if ( options . hasOwnProperty ( 'sigma' ) ) { opts . sigma = options . sigma ; if ( ! isNonNegative ( opts . sigma ) ) { return new TypeError ( 'invalid option. `sigma` parameter must be a non-negative number. Option: `' + opts . sigma + '`.' ) ; } } if ( options . hasOwnProperty ( 'dtype' ) ) { opts . dtype = options . dtype ; if ( ! isString ( opts . dtype ) ) { return new TypeError ( 'invalid option. Data type option must be a string primitive. Option: `' + opts . dtype + '`.' ) ; } } if ( options . hasOwnProperty ( 'seed' ) ) { opts . seed = options . seed ; if ( ! isPositiveInteger ( opts . seed ) ) { return new TypeError ( 'invalid option. Seed option must be a positive integer. Option: `' + opts . seed + '`.' ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Object to yaml string formatter [CODESPLIT] function objectProperty ( obj , indentLength = 1 , inArray = 0 ) { if ( Object . keys ( obj ) . length === 0 ) { return ' {}' ; } let str = '\\n' ; const objectPrefix = getPrefix ( indentLength , indentChars ) ; Object . keys ( obj ) . forEach ( ( name ) => { const value = obj [ name ] ; const type = typeOf ( value ) ; const inArrayPrefix = getPrefix ( inArray , '  ' ) ; const afterPropsIndent = NO_INDENT_TYPES . includes ( type ) ? '' : ' ' ; const valueString = checkCircular ( value ) ? ' [Circular]' : typifiedString ( type , value , indentLength + 1 , inArray ) ; str += ` ${ inArrayPrefix } ${ objectPrefix } ${ name } ${ afterPropsIndent } ${ valueString } \\n ` ; } ) ; return str . substring ( 0 , str . length - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Array to yaml string formatter [CODESPLIT] function arrayProperty ( values , indentLength = 1 , inArray = 0 ) { if ( values . length === 0 ) { return ' []' ; } let str = '\\n' ; const arrayPrefix = getPrefix ( indentLength , indentChars ) ; values . forEach ( ( value ) => { const type = typeOf ( value ) ; const inArrayPrefix = getPrefix ( inArray , '  ' ) ; const valueString = checkCircular ( value ) ? '[Circular]' : typifiedString ( type , value , indentLength , inArray + 1 ) . toString ( ) . trimLeft ( ) ; str += ` ${ inArrayPrefix } ${ arrayPrefix } ${ valueString } \\n ` ; } ) ; return str . substring ( 0 , str . length - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "temp solution until https : // github . com / iarna / in - publish / issues / 8 gets fixed . [CODESPLIT] function inCommand ( cmd ) { let npm_config_argv , V ; try { npm_config_argv = JSON . parse ( process . env [ 'npm_config_argv' ] ) ; } catch ( e ) { return false ; } if ( typeof npm_config_argv !== 'object' ) { process . exit ( 1 ) ; } if ( ! npm_config_argv . cooked ) { process . exit ( 1 ) ; } if ( ! npm_config_argv . cooked instanceof Array ) { process . exit ( 1 ) ; } while ( ( V = npm_config_argv . cooked . shift ( ) ) !== undefined ) { if ( cmd . test ( V ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests [CODESPLIT] function mochaTask ( reporter ) { return function ( ) { return gulp . src ( paths . test ) . pipe ( $ . mocha ( { reporter : reporter || \"spec\" } ) ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "RANDOM // FUNCTION : random ( dims mu sigma [ rand ] ) Creates a multidimensional array of normally distributed random numbers . [CODESPLIT] function random ( dims , mu , sigma , rand ) { var draw = partial ( mu , sigma , rand ) ; return recurse ( dims , 0 , draw ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "RANDOM // FUNCTION : random ( len dt mu sigma [ rand ] ) Creates a typed array of normally distributed random numbers . [CODESPLIT] function random ( len , dt , mu , sigma , rand ) { /* jshint newcap:false */ var ctor ; var out ; var draw ; var i ; draw = partial ( mu , sigma , rand ) ; ctor = ctors ( dt ) ; if ( ctor === null ) { throw new Error ( 'invalid value. Data type does not have a corresponding array constructor. Value: `' + dt + '`.' ) ; } out = new ctor ( len ) ; for ( i = 0 ; i < len ; i ++ ) { out [ i ] = draw ( ) ; } return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO refactor this terribleness [CODESPLIT] function parseJson ( inputText ) { // sizeOf (/nEvents/n) is 10 var text = inputText . substring ( inputText . indexOf ( \"\\\\nEvents\\\\n\" ) + 10 , inputText . indexOf ( \"\\\\n\\\\n\\\\nBirths\" ) ) , retArr = [ ] , retString = \"\" , endIndex , startIndex = 0 ; if ( text . length == 0 ) { return retArr ; } while ( true ) { endIndex = text . indexOf ( \"\\\\n\" , startIndex + delimiterSize ) ; var eventText = ( endIndex == - 1 ? text . substring ( startIndex ) : text . substring ( startIndex , endIndex ) ) ; // replace dashes returned in text from Wikipedia's API eventText = eventText . replace ( / \\\\u2013\\s* / g , '' ) ; // add comma after year so Alexa pauses before continuing with the sentence eventText = eventText . replace ( / (^\\d+) / , '$1,' ) ; eventText = 'In ' + eventText ; startIndex = endIndex + delimiterSize ; retArr . push ( eventText ) ; if ( endIndex == - 1 ) { break ; } } if ( retString != \"\" ) { retArr . push ( retString ) ; } retArr . reverse ( ) ; return retArr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param { String } quantifier [CODESPLIT] function getRangeData ( quantifier ) { let rangeType = dateRange . DAY ; let startRange = 'day' ; if ( / seconds? / i . test ( quantifier ) ) { rangeType = dateRange . SEC ; startRange = 'second' ; } else if ( / minutes? / i . test ( quantifier ) ) { rangeType = dateRange . MIN ; startRange = 'minute' ; } else if ( / hours? / i . test ( quantifier ) ) { rangeType = dateRange . HOUR ; startRange = 'hour' ; } else if ( new RegExp ( ` ${ days . join ( 's?|' ) } ` , 'i' ) . test ( quantifier ) ) { rangeType = dateRange . DAY * 7 ; startRange = quantifier ; } return { rangeType : rangeType , startRange : startRange } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manages all communication with a Kubernetes resource endpoint ( i . e . pods ) [CODESPLIT] function ResourceClient ( opts ) { opts = opts || { } this . name = opts . name this . token = opts . token this . baseUrl = opts . baseUrl }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Backend response . [CODESPLIT] function RESTResponse ( url , method , body ) { /** The original request. */ this . request = { url : url , method : method } ; /** The body of the response. */ this . body = body || \"\" ; /** Status of the response. */ this . status = \"200\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "polyfilled Maps with es6 - shim might exist without for .. of [CODESPLIT] function ( map , receive ) { var entries = mapEntries . call ( map ) ; var next ; do { next = entries . next ( ) ; } while ( ! next . done && receive ( next . value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NORMAL TAIL // FUNCTION dRanNormalTail ( dMin iNegative rand ) Transform the tail of the normal distribution to the unit interval and then use rejection technique to generate standar normal variable . Reference : Marsaclia G . ( 1964 ) . Generating a Variable from the Tail of the Normal Distribution . Technometrics 6 ( 1 ) 101–102 . doi : 10 . 1080 / 00401706 . 1964 . 10490150 [CODESPLIT] function dRanNormalTail ( dMin , iNegative , rand ) { var x , y ; do { x = ln ( rand ( ) ) / dMin ; y = ln ( rand ( ) ) ; } while ( - 2 * y < x * x ) ; return iNegative ? x - dMin : dMin - x ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decorator which validates an options hash and delegates to func . If the options are not an object a TypeError is thrown . If the options hash is missing any of the required properties a RangeError is thrown . [CODESPLIT] function reqo ( func , requiredKeys , optionsIndex = 0 , context = undefined ) { return function ( ... args ) { const options = args [ optionsIndex ] ; if ( ! isPlainObject ( options ) ) { throw new TypeError ( 'options must be a plain object literal' ) ; } // Check that all of the properties represented in requiredKeys are present // as properties in the options hash. Does so by taking an intersection // of the options keys and the required keys, and then checking the // intersection is equivalent to the requirements. const optionsKeys = keys ( options ) ; const intersectionOfKeys = intersection ( requiredKeys , optionsKeys ) ; const hasAllRequiredKeys = isEqual ( intersectionOfKeys , requiredKeys ) ; // If any required keys are missing in options hash. if ( ! hasAllRequiredKeys ) { const missingOptions = difference ( requiredKeys , intersectionOfKeys ) ; throw new RangeError ( 'Options must contain ' + missingOptions . toString ( ) ) ; } // Call the decorated function in the right context with its' arguments. const boundFunc = func . bind ( context ) ; return boundFunc ( ... args ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers an item to be managed . [CODESPLIT] function ( component ) { var id = component . getId ( ) ; // <debug> if ( this . map [ id ] ) { Ext . Logger . warn ( 'Registering a component with a id (`' + id + '`) which has already been used. Please ensure the existing component has been destroyed (`Ext.Component#destroy()`.' ) ; } // </debug> this . map [ component . getId ( ) ] = component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Component from the specified config object using the config object s xtype to determine the class to instantiate . [CODESPLIT] function ( component , defaultType ) { if ( component . isComponent ) { return component ; } else if ( Ext . isString ( component ) ) { return Ext . createByAlias ( 'widget.' + component ) ; } else { var type = component . xtype || defaultType ; return Ext . createByAlias ( 'widget.' + type , component ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "runs a name . space [CODESPLIT] function rns ( ) { let jargv = _ . $ ( 'env.jargv' ) let key = _ . get ( jargv , '_[0]' ) let prop = key ? _ . get ( snapptop , key ) : null if ( ! _ . isFunction ( prop ) ) return _ . log ( ` \\n ${ key || 'NO KEY' } \\n ` ) _ . log ( ` \\n ${ key } \\n ` ) _ . log ( jargv ) _ . log ( ) jargv = _ . omit ( jargv , [ '_' ] ) var ret = _ . attempt ( prop , jargv , ( err , result ) => { if ( err ) return _ . log ( err ) _ . log ( result ) } ) if ( _ . isError ( ret ) ) _ . log ( ret ) return ret }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves Ext . dom . Element objects . { @link Ext#get } is alias for { @link Ext . dom . Element#get } . [CODESPLIT] function ( element ) { var cache = this . cache , instance , dom , id ; if ( ! element ) { return null ; } // DOM Id if ( typeof element == 'string' ) { dom = document . getElementById ( element ) ; if ( cache . hasOwnProperty ( element ) ) { instance = cache [ element ] ; } // Is this in the DOM proper if ( dom ) { // Update our Ext Element dom reference with the true DOM (it may have changed) if ( instance ) { instance . dom = dom ; } else { // Create a new instance of Ext Element instance = cache [ element ] = new this ( dom ) ; } } // Not in the DOM, but if its in the cache, we can still use that as a DOM fragment reference, otherwise null else if ( ! instance ) { instance = null ; } return instance ; } // DOM element if ( 'tagName' in element ) { id = element . id ; if ( cache . hasOwnProperty ( id ) ) { instance = cache [ id ] ; instance . dom = element ; return instance ; } else { instance = new this ( element ) ; cache [ instance . getId ( ) ] = instance ; } return instance ; } // Ext Element if ( element . isElement ) { return element ; } // Ext Composite Element if ( element . isComposite ) { return element ; } // Array passed if ( Ext . isArray ( element ) ) { return this . select ( element ) ; } // DOM Document if ( element === document ) { // create a bogus element object representing the document object if ( ! this . documentElement ) { this . documentElement = new this ( document . documentElement ) ; this . documentElement . setId ( 'ext-application' ) ; } return this . documentElement ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a DOM element and its children recursively into a string . [CODESPLIT] function ( node ) { var result = '' , i , n , attr , child ; if ( node . nodeType === document . TEXT_NODE ) { return node . nodeValue ; } result += '<' + node . nodeName ; if ( node . attributes . length ) { for ( i = 0 , n = node . attributes . length ; i < n ; i ++ ) { attr = node . attributes [ i ] ; result += ' ' + attr . name + '=\"' + attr . value + '\"' ; } } result += '>' ; if ( node . childNodes && node . childNodes . length ) { for ( i = 0 , n = node . childNodes . length ; i < n ; i ++ ) { child = node . childNodes [ i ] ; result += this . serializeNode ( child ) ; } } result += '</' + node . nodeName + '>' ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@event painted Fires whenever this Element actually becomes visible ( painted ) on the screen . This is useful when you need to perform read operations on the DOM element i . e : calculating natural sizes and positioning . [CODESPLIT] function ( dom ) { if ( typeof dom == 'string' ) { dom = document . getElementById ( dom ) ; } if ( ! dom ) { throw new Error ( \"Invalid domNode reference or an id of an existing domNode: \" + dom ) ; } /**\n         * The DOM element\n         * @property dom\n         * @type HTMLElement\n         */ this . dom = dom ; this . getUniqueId ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the passed attributes as attributes of this element ( a style attribute can be a string object or function ) . [CODESPLIT] function ( attributes , useSet ) { var dom = this . dom , attribute , value ; for ( attribute in attributes ) { if ( attributes . hasOwnProperty ( attribute ) ) { value = attributes [ attribute ] ; if ( attribute == 'style' ) { this . applyStyles ( value ) ; } else if ( attribute == 'cls' ) { dom . className = value ; } else if ( useSet !== false ) { if ( value === undefined ) { dom . removeAttribute ( attribute ) ; } else { dom . setAttribute ( attribute , value ) ; } } else { dom [ attribute ] = value ; } } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value of an attribute from the element s underlying DOM node . [CODESPLIT] function ( name , namespace ) { var dom = this . dom ; return dom . getAttributeNS ( namespace , name ) || dom . getAttribute ( namespace + \":\" + name ) || dom . getAttribute ( name ) || dom [ name ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes this element s DOM reference . Note that event and cache removal is handled at { [CODESPLIT] function ( ) { this . isDestroyed = true ; var cache = Ext . Element . cache , dom = this . dom ; if ( dom && dom . parentNode && dom . tagName != 'BODY' ) { dom . parentNode . removeChild ( dom ) ; } delete cache [ this . id ] ; delete this . dom ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the globally shared flyweight Element with the passed node as the active element . Do not store a reference to this element - the dom node can be overwritten by other code . { @link Ext#fly } is alias for { @link Ext . dom . Element#fly } . [CODESPLIT] function ( element , named ) { var fly = null , flyweights = Element . _flyweights , cachedElement ; named = named || '_global' ; element = Ext . getDom ( element ) ; if ( element ) { fly = flyweights [ named ] || ( flyweights [ named ] = new Element . Fly ( ) ) ; fly . dom = element ; fly . isSynchronized = false ; cachedElement = Ext . cache [ element . id ] ; if ( cachedElement && cachedElement . isElement ) { cachedElement . isSynchronized = false ; } } return fly ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A client - side router for stateful - controller using the history API @module stateful - controller - browser - router @author Joris van der Wel <joris@jorisvanderwel . com > Construct a new router [CODESPLIT] function Router ( window , urlStateMap , frontController ) { EventEmitter . call ( this ) ; this . window = window ; this . urlStateMap = urlStateMap ; this . frontController = frontController ; this . currentStateList = null ; this . _pendingTransitionPromise = null ; this . _pendingReplace = null ; this . _initialHistoryState = null ; this . _queue = { hasEntry : false , stateList : null , fromHistory : false , upgrade : false , push : false , promise : null , resolve : null , reject : null } ; if ( ! window || ! urlStateMap || ! frontController ) { throw Error ( 'Missing argument' ) ; } if ( typeof this . urlStateMap . toURL !== 'function' || typeof this . urlStateMap . fromURL !== 'function' ) { throw Error ( 'Argument `urlStateMap` must implement toURL(states) and fromURL(url)' ) ; } if ( ! Router . isSupported ( this . window ) ) { throw Error ( 'Argument `window` does not support the history API' ) ; } if ( this . frontController . isStatefulController1 !== true ) { throw Error ( 'Argument `frontController` is not a stateful-controller' ) ; } this . _onpopstate = this . _onpopstate . bind ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts the data in the Store by one or more of its properties . Example usage : [CODESPLIT] function ( sorters , direction , where , doSort ) { var me = this , sorter , sorterFn , newSorters ; if ( Ext . isArray ( sorters ) ) { doSort = where ; where = direction ; newSorters = sorters ; } else if ( Ext . isObject ( sorters ) ) { doSort = where ; where = direction ; newSorters = [ sorters ] ; } else if ( Ext . isString ( sorters ) ) { sorter = me . sorters . get ( sorters ) ; if ( ! sorter ) { sorter = { property : sorters , direction : direction } ; newSorters = [ sorter ] ; } else if ( direction === undefined ) { sorter . toggle ( ) ; } else { sorter . setDirection ( direction ) ; } } if ( newSorters && newSorters . length ) { newSorters = me . decodeSorters ( newSorters ) ; if ( Ext . isString ( where ) ) { if ( where === 'prepend' ) { sorters = me . sorters . clone ( ) . items ; me . sorters . clear ( ) ; me . sorters . addAll ( newSorters ) ; me . sorters . addAll ( sorters ) ; } else { me . sorters . addAll ( newSorters ) ; } } else { me . sorters . clear ( ) ; me . sorters . addAll ( newSorters ) ; } if ( doSort !== false ) { me . onBeforeSort ( newSorters ) ; } } if ( doSort !== false ) { sorters = me . sorters . items ; if ( sorters . length ) { //construct an amalgamated sorter function which combines all of the Sorters passed sorterFn = function ( r1 , r2 ) { var result = sorters [ 0 ] . sort ( r1 , r2 ) , length = sorters . length , i ; //if we have more than one sorter, OR any additional sorter functions together for ( i = 1 ; i < length ; i ++ ) { result = result || sorters [ i ] . sort . call ( this , r1 , r2 ) ; } return result ; } ; me . doSort ( sorterFn ) ; } } return sorters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "plugins = { exportHead : func exportEnd : func exportTypedef : func exportEnum : func exportStruct : func exportStatic : func getExportFile : func } callback ( isok errinfo ) [CODESPLIT] function exportCode ( projname , root , plugins , objname , callback , option ) { if ( option == undefined ) { option = { isclient : false , mainobj : objname , projname : projname } ; } else { if ( ! option . hasOwnProperty ( 'isclient' ) ) { option . isclient = false ; } option . mainobj = objname ; option . projname = projname ; } var lstexport = [ ] ; var obj = base . getGlobalObj ( objname , root ) ; if ( obj != undefined ) { lstexport = addExportObj ( obj , root , lstexport , option ) ; } procStaticTable ( objname , root , option ) ; if ( plugins != undefined ) { if ( ! fs . existsSync ( projname ) ) { fs . mkdirSync ( projname ) ; } var curparams = { projname_up : projname . toUpperCase ( ) , projname : projname } ; //------------------------------------------------------------------------------------ // typedef curparams . block_typedef = [ ] ; var typedefarr = undefined ; for ( var i = 0 ; i < lstexport . length ; ++ i ) { var obj = base . getGlobalObj ( lstexport [ i ] , root ) ; if ( obj != undefined ) { if ( obj . type == 'type' ) { var cs = plugins . exportTypedef ( obj , root , callback , option ) ; if ( cs != undefined ) { if ( typedefarr == undefined ) { typedefarr = [ ] ; for ( var ai = 0 ; ai < cs . length ; ++ ai ) { typedefarr . push ( [ ] ) ; } } for ( var ai = 0 ; ai < cs . length ; ++ ai ) { typedefarr [ ai ] . push ( cs [ ai ] ) ; } } } } } if ( typedefarr != undefined ) { curparams . block_typedef = alignCodeEx ( typedefarr , '' ) ; } //------------------------------------------------------------------------------------ // enum curparams . block_enum = [ ] ; for ( var i = 0 ; i < lstexport . length ; ++ i ) { var obj = base . getGlobalObj ( lstexport [ i ] , root ) ; if ( obj != undefined ) { if ( obj . type == 'enum' ) { var enumobj = plugins . exportEnum ( obj , root , callback , option ) ; if ( enumobj != undefined ) { curparams . block_enum . push ( enumobj ) ; } } } } //------------------------------------------------------------------------------------ // struct curparams . block_struct = [ ] ; curparams . csvloader = [ ] ; for ( var i = 0 ; i < lstexport . length ; ++ i ) { var obj = base . getGlobalObj ( lstexport [ i ] , root ) ; if ( obj != undefined ) { if ( obj . name == objname ) { var mainobj = plugins . exportMainObj ( obj , root , callback , option ) ; if ( mainobj != undefined ) { curparams . mainobj = mainobj ; } base . forEachStruct ( obj . name , obj , root , function ( structname , cobj , root ) { if ( option . isclient ) { if ( cobj . name . name . indexOf ( '_' ) == 0 ) { return ; } } if ( base . isStatic ( cobj . type , root ) ) { var csvloader = plugins . exportCSVLoader ( cobj , root , callback , option ) ; if ( csvloader != undefined ) { curparams . csvloader . push ( csvloader ) ; } } } ) ; } else if ( obj . type == 'struct' ) { var structobj = plugins . exportStruct ( obj , root , callback , option ) ; if ( structobj != undefined ) { curparams . block_struct . push ( structobj ) ; } } else if ( obj . type == 'static' ) { var structobj = plugins . exportStatic ( obj , root , callback , option ) ; if ( structobj != undefined ) { curparams . block_struct . push ( structobj ) ; } } } } //------------------------------------------------------------------------------------ // message curparams . block_sendmsg = [ ] ; curparams . block_onmsg = [ ] ; for ( var i = 0 ; i < root . length ; ++ i ) { if ( root [ i ] . type == 'message' ) { if ( base . isReqMsg ( root [ i ] . name ) ) { var co = plugins . exportSendMsg ( root [ i ] , root , callback , option ) ; curparams . block_sendmsg . push ( co ) ; } else if ( base . isResMsg ( root [ i ] . name ) ) { var co = plugins . exportOnMsg ( root [ i ] , root , callback , option ) ; curparams . block_onmsg . push ( co ) ; } } } //------------------------------------------------------------------------------------ // template var tmpfilename = plugins . getTemplate ( projname , option ) ; var tmpbuf = fs . readFileSync ( path . join ( __dirname , 'plugins' , tmpfilename ) , 'utf-8' ) ; var tmphb = handlebars . compile ( tmpbuf ) ; tmpbuf = tmphb ( curparams ) ; tmpbuf = replaceStr ( tmpbuf ) ; var tmparr = JSON . parse ( tmpbuf ) ; if ( tmparr != undefined ) { for ( var ti = 0 ; ti < tmparr . length ; ++ ti ) { var curtmpbuf = fs . readFileSync ( path . join ( __dirname , 'plugins' , tmparr [ ti ] . srcfile ) , 'utf-8' ) ; var curtemplate = handlebars . compile ( curtmpbuf ) ; var strbuf = curtemplate ( curparams ) ; strbuf = replaceStr ( strbuf ) ; fs . writeFileSync ( projname + '/' + tmparr [ ti ] . filename , strbuf , 'utf-8' ) ; } } return tmparr ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An eventual schema exists for a key - value object . [CODESPLIT] function ( rules ) { this . _instantiatedDate = new Date ( ) ; this . _instanceCount = 0 ; this . _propertyCount = 0 ; this . _collatedInstances = null ; this . _rules = ( rules && this . _checkRules ( rules ) ) || [ ] ; this . initEventualSchema ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read associated data [CODESPLIT] function ( record , reader , associationData ) { var inverse = this . getInverseAssociation ( ) , newRecord = reader . read ( [ associationData ] ) . getRecords ( ) [ 0 ] ; record [ this . getSetterName ( ) ] . call ( record , newRecord ) ; //if the inverse association was found, set it now on each record we've just created if ( inverse ) { newRecord [ inverse . getInstanceName ( ) ] = record ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method adds all the sorters in a passed array . [CODESPLIT] function ( sorters , defaultDirection ) { var currentSorters = this . getSorters ( ) ; return this . insertSorters ( currentSorters ? currentSorters . length : 0 , sorters , defaultDirection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method inserts all the sorters in the passed array at the given index . [CODESPLIT] function ( index , sorters , defaultDirection ) { // We begin by making sure we are dealing with an array of sorters if ( ! Ext . isArray ( sorters ) ) { sorters = [ sorters ] ; } var ln = sorters . length , direction = defaultDirection || this . getDefaultSortDirection ( ) , sortRoot = this . getSortRoot ( ) , currentSorters = this . getSorters ( ) , newSorters = [ ] , sorterConfig , i , sorter , currentSorter ; if ( ! currentSorters ) { // This will guarantee that we get the collection currentSorters = this . createSortersCollection ( ) ; } // We first have to convert every sorter into a proper Sorter instance for ( i = 0 ; i < ln ; i ++ ) { sorter = sorters [ i ] ; sorterConfig = { direction : direction , root : sortRoot } ; // If we are dealing with a string we assume it is a property they want to sort on. if ( typeof sorter === 'string' ) { currentSorter = currentSorters . get ( sorter ) ; if ( ! currentSorter ) { sorterConfig . property = sorter ; } else { if ( defaultDirection ) { currentSorter . setDirection ( defaultDirection ) ; } else { // If we already have a sorter for this property we just toggle its direction. currentSorter . toggle ( ) ; } continue ; } } // If it is a function, we assume its a sorting function. else if ( Ext . isFunction ( sorter ) ) { sorterConfig . sorterFn = sorter ; } // 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 ( sorter ) ) { if ( ! sorter . isSorter ) { if ( sorter . fn ) { sorter . sorterFn = sorter . fn ; delete sorter . fn ; } sorterConfig = Ext . apply ( sorterConfig , sorter ) ; } else { newSorters . push ( sorter ) ; if ( ! sorter . getRoot ( ) ) { sorter . setRoot ( sortRoot ) ; } continue ; } } // Finally we get to the point where it has to be invalid // <debug> else { Ext . Logger . warn ( 'Invalid sorter specified:' , sorter ) ; } // </debug> // If a sorter config was created, make it an instance sorter = Ext . create ( 'Ext.util.Sorter' , sorterConfig ) ; newSorters . push ( sorter ) ; } // Now lets add the newly created sorters. for ( i = 0 , ln = newSorters . length ; i < ln ; i ++ ) { currentSorters . insert ( index + i , newSorters [ i ] ) ; } this . dirtySortFn = true ; if ( currentSorters . length ) { this . sorted = true ; } return currentSorters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method removes all the sorters in a passed array . [CODESPLIT] function ( sorters ) { // We begin by making sure we are dealing with an array of sorters if ( ! Ext . isArray ( sorters ) ) { sorters = [ sorters ] ; } var ln = sorters . length , currentSorters = this . getSorters ( ) , i , sorter ; for ( i = 0 ; i < ln ; i ++ ) { sorter = sorters [ i ] ; if ( typeof sorter === 'string' ) { currentSorters . removeAtKey ( sorter ) ; } else if ( typeof sorter === 'function' ) { currentSorters . each ( function ( item ) { if ( item . getSorterFn ( ) === sorter ) { currentSorters . remove ( item ) ; } } ) ; } else if ( sorter . isSorter ) { currentSorters . remove ( sorter ) ; } } if ( ! currentSorters . length ) { this . sorted = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This updates the cached sortFn based on the current sorters . [CODESPLIT] function ( ) { var sorters = this . getSorters ( ) . items ; this . sortFn = function ( r1 , r2 ) { var ln = sorters . length , result , i ; // We loop over each sorter and check if r1 should be before or after r2 for ( i = 0 ; i < ln ; i ++ ) { result = sorters [ i ] . sort . call ( this , r1 , r2 ) ; // If the result is -1 or 1 at this point it means that the sort is done. // Only if they are equal (0) we continue to see if a next sort function // actually might find a winner. if ( result !== 0 ) { break ; } } return result ; } ; this . dirtySortFn = false ; return this . sortFn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns the index that a given item would be inserted into a given array based on the current sorters . [CODESPLIT] function ( items , item , sortFn , containsItem ) { var start = 0 , end = items . length - 1 , sorterFn = sortFn || this . getSortFn ( ) , middle , comparison ; while ( start < end || start === end && ! containsItem ) { middle = ( start + end ) >> 1 ; var middleItem = items [ middle ] ; if ( middleItem === item ) { start = middle ; break ; } comparison = sorterFn ( item , middleItem ) ; if ( comparison > 0 || ( ! containsItem && comparison === 0 ) ) { start = middle + 1 ; } else if ( comparison < 0 ) { end = middle - 1 ; } else if ( containsItem && ( start !== end ) ) { start = middle + 1 ; } } return start ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines a metric that measures reliability by success / error responses [CODESPLIT] function ReliabilityMetric ( ) { if ( ! ( this instanceof ReliabilityMetric ) ) { return new ReliabilityMetric ( ) } Metric . call ( this ) this . key = 'reliability' this . default = [ 0 , 0 ] // [success,error] this . hooks = [ { trigger : 'before' , event : 'receive' , handler : this . _recordResponseType } ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FUNCTION : cmin ( arr ) Computes the cumulative minimum of a numeric array . [CODESPLIT] function cmin ( arr ) { if ( ! Array . isArray ( arr ) ) { throw new TypeError ( 'cmin()::invalid input argument. Must provide an array.' ) ; } var len = arr . length , v = new Array ( len ) , min ; min = arr [ 0 ] ; v [ 0 ] = min ; for ( var i = 1 ; i < len ; i ++ ) { if ( arr [ i ] < min ) { min = arr [ i ] ; } v [ i ] = min ; } return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "callback ( isok err ) [CODESPLIT] function exportTable ( obj , callback , root ) { if ( obj . type == 'struct' ) { var isautoinc = false ; var autoincval = 1 ; var str = \"-- \" + obj . comment + '\\r\\n' ; str += \"CREATE TABLE IF NOT EXISTS `\" + getTableName ( obj . name ) + \"` (\" + '\\r\\n' ; var lastcomment = '' ; var lstmember = [ ] ; base . forEachStruct ( obj . name , obj , root , function ( structname , memberobj , root ) { lstmember . push ( memberobj ) ; } ) ; var validindex = [ ] ; for ( var i = 0 ; i < lstmember . length ; ++ i ) { var membername = lstmember [ i ] . name . name ; // type var t = base . getRealType_Enum ( lstmember [ i ] . type , root ) ; if ( t == '[ERR]' ) { callback ( false , 'struct ' + obj . name + '.' + membername + ': type is Error!' ) ; return ; } else if ( t == 'int' ) { validindex . push ( i ) ; } else if ( t == 'string' ) { validindex . push ( i ) ; } else if ( t == 'time' ) { validindex . push ( i ) ; } else if ( base . isStruct ( t , root ) ) { } else { callback ( false , 'struct ' + obj . name + '.' + membername + ': type not defined!' ) ; return ; } } var keyblocknums = 0 ; // PRIMARY & INDEX for ( var i = 0 ; i < lstmember . length ; ++ i ) { if ( lstmember [ i ] . hasOwnProperty ( 'type2' ) ) { var membername = lstmember [ i ] . name . name ; var fn = base . getMemberName ( membername ) ; if ( lstmember [ i ] . type2 == 'primary' ) { keyblocknums ++ ; } else if ( lstmember [ i ] . type2 == 'primary0' || lstmember [ i ] . type2 == 'primary1' || lstmember [ i ] . type2 == 'index' ) { keyblocknums ++ ; } if ( lstmember [ i ] . type2 == 'unique' ) { keyblocknums ++ ; } } } var tarr = [ [ ] , [ ] ] ; for ( var k = 0 ; k < validindex . length ; ++ k ) { var i = validindex [ k ] ; var membername = lstmember [ i ] . name . name ; var fn = base . getMemberName ( membername ) ; // name var cstr = \"`\" + fn + \"` \" ; // type var t = base . getRealType_Enum ( lstmember [ i ] . type , root ) ; if ( t == '[ERR]' ) { callback ( false , 'struct ' + obj . name + '.' + membername + ': type is Error!' ) ; return ; } else if ( t == 'int' ) { cstr += \"int \" ; } else if ( t == 'string' ) { cstr += \"varchar \" ; } else if ( t == 'time' ) { cstr += \"timestamp \" ; } else { callback ( false , 'struct ' + obj . name + '.' + membername + ': type not defined!' ) ; return ; } // NULL if ( typeof ( lstmember [ i ] . val ) == 'object' && lstmember [ i ] . val . type == 'NULL' ) { cstr += 'NULL' ; } else { cstr += 'NOT NULL' ; } // AUTO_INCREMENT if ( typeof ( lstmember [ i ] . val ) == 'object' && lstmember [ i ] . val . val == 'AUTOINC' ) { cstr += ' AUTO_INCREMENT' ; isautoinc = true ; if ( lstmember [ i ] . val . hasOwnProperty ( 'autoinc' ) ) { autoincval = lstmember [ i ] . val . autoinc ; } } // DEFAULT CURRENT_TIMESTAMP else if ( typeof ( lstmember [ i ] . val ) == 'object' && lstmember [ i ] . val . val == 'NOW' ) { cstr += ' DEFAULT CURRENT_TIMESTAMP' ; } if ( k < validindex . length - 1 || keyblocknums > 0 ) { cstr += ',' ; } tarr [ 0 ] . push ( cstr ) ; tarr [ 1 ] . push ( '-- ' + lstmember [ i ] . comment ) ; } str += code . alignCode ( tarr , '  ' ) ; // PRIMARY & INDEX if ( keyblocknums > 0 ) { for ( var i = 0 ; i < lstmember . length ; ++ i ) { if ( lstmember [ i ] . hasOwnProperty ( 'type2' ) ) { var membername = lstmember [ i ] . name . name ; var fn = base . getMemberName ( membername ) ; var newline = false ; if ( lstmember [ i ] . type2 == 'primary' ) { str += \"  PRIMARY KEY (`\" + fn + \"`)\" ; newline = true ; } else if ( lstmember [ i ] . type2 == 'primary0' || lstmember [ i ] . type2 == 'primary1' || lstmember [ i ] . type2 == 'index' ) { str += \"  KEY (`\" + fn + \"`)\" ; newline = true ; } if ( lstmember [ i ] . type2 == 'unique' ) { str += \"  UNIQUE (`\" + fn + \"`)\" ; newline = true ; } if ( newline ) { keyblocknums -- ; if ( keyblocknums > 0 ) { str += ',\\r\\n' ; } else { str += '\\r\\n' ; } } } } } str += \") ENGINE=InnoDB DEFAULT CHARSET=utf8\" ; if ( isautoinc ) { str += ' AUTO_INCREMENT=' + autoincval ; } str += ';\\r\\n' ; return str ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "callback ( isok err ) [CODESPLIT] function exportSql ( obj , callback ) { var str = '' ; if ( Array . isArray ( obj ) ) { for ( var i = 0 ; i < obj . length ; ++ i ) { if ( obj [ i ] . type == 'struct' && base . isExportTypeString ( obj [ i ] . name ) ) { var cs = exportTable ( obj [ i ] , callback , obj ) ; if ( cs == undefined ) { return ; } str += cs + '\\r\\n' ; } } return str ; } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to update a specified attribute on the fieldEl or remove the attribute all together . [CODESPLIT] function ( attribute , newValue ) { var input = this . input ; if ( ! Ext . isEmpty ( newValue , true ) ) { input . dom . setAttribute ( attribute , newValue ) ; } else { input . dom . removeAttribute ( attribute ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the { [CODESPLIT] function ( newCls , oldCls ) { this . input . addCls ( Ext . baseCSSPrefix + 'input-el' ) ; this . input . replaceCls ( oldCls , newCls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the type attribute with the { [CODESPLIT] function ( newType , oldType ) { var prefix = Ext . baseCSSPrefix + 'input-' ; this . input . replaceCls ( prefix + oldType , prefix + newType ) ; this . updateFieldAttribute ( 'type' , newType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the checked value of this field [CODESPLIT] function ( ) { var el = this . input , checked ; if ( el ) { checked = el . dom . checked ; this . _checked = checked ; } return checked ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to set the field as the active input focus . [CODESPLIT] function ( ) { var me = this , el = me . input ; if ( el && el . dom . focus ) { el . dom . focus ( ) ; } return me ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to forcefully blur input focus for the field . [CODESPLIT] function ( ) { var me = this , el = this . input ; if ( el && el . dom . blur ) { el . dom . blur ( ) ; } return me ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to forcefully select all the contents of the input field . [CODESPLIT] function ( ) { var me = this , el = me . input ; if ( el && el . dom . setSelectionRange ) { el . dom . setSelectionRange ( 0 , 9999 ) ; } return me ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create private copy of Ext s Ext . util . Format . format () method - to remove unnecessary dependency - to resolve namespace conflict with MS - Ajax s implementation [CODESPLIT] function xf ( format ) { var args = Array . prototype . slice . call ( arguments , 1 ) ; return format . replace ( / \\{(\\d+)\\} / g , function ( m , i ) { return args [ i ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats a date given the supplied format string . [CODESPLIT] function ( date , format ) { if ( utilDate . formatFunctions [ format ] == null ) { utilDate . createFormat ( format ) ; } var result = utilDate . formatFunctions [ format ] . call ( date ) ; return result + '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a convenient method for performing basic date arithmetic . This method does not modify the Date instance being called - it creates and returns a new Date instance containing the resulting date value . [CODESPLIT] function ( date , interval , value ) { var d = Ext . Date . clone ( date ) ; if ( ! interval || value === 0 ) return d ; switch ( interval . toLowerCase ( ) ) { case Ext . Date . MILLI : d = new Date ( d . valueOf ( ) + value ) ; break ; case Ext . Date . SECOND : d = new Date ( d . valueOf ( ) + value * 1000 ) ; break ; case Ext . Date . MINUTE : d = new Date ( d . valueOf ( ) + value * 60000 ) ; break ; case Ext . Date . HOUR : d = new Date ( d . valueOf ( ) + value * 3600000 ) ; break ; case Ext . Date . DAY : d = new Date ( d . valueOf ( ) + value * 86400000 ) ; break ; case Ext . Date . MONTH : var day = date . getDate ( ) ; if ( day > 28 ) { day = Math . min ( day , Ext . Date . getLastDateOfMonth ( Ext . Date . add ( Ext . Date . getFirstDateOfMonth ( date ) , 'mo' , value ) ) . getDate ( ) ) ; } d . setDate ( day ) ; d . setMonth ( date . getMonth ( ) + value ) ; break ; case Ext . Date . YEAR : d . setFullYear ( date . getFullYear ( ) + value ) ; break ; } return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate how many units are there between two time . [CODESPLIT] function ( min , max , unit ) { var ExtDate = Ext . Date , est , diff = + max - min ; switch ( unit ) { case ExtDate . MILLI : return diff ; case ExtDate . SECOND : return Math . floor ( diff / 1000 ) ; case ExtDate . MINUTE : return Math . floor ( diff / 60000 ) ; case ExtDate . HOUR : return Math . floor ( diff / 3600000 ) ; case ExtDate . DAY : return Math . floor ( diff / 86400000 ) ; case 'w' : return Math . floor ( diff / 604800000 ) ; case ExtDate . MONTH : est = ( max . getFullYear ( ) * 12 + max . getMonth ( ) ) - ( min . getFullYear ( ) * 12 + min . getMonth ( ) ) ; if ( Ext . Date . add ( min , unit , est ) > max ) { return est - 1 ; } else { return est ; } case ExtDate . YEAR : est = max . getFullYear ( ) - min . getFullYear ( ) ; if ( Ext . Date . add ( min , unit , est ) > max ) { return est - 1 ; } else { return est ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Align the date to unit . [CODESPLIT] function ( date , unit , step ) { var num = new Date ( + date ) ; switch ( unit . toLowerCase ( ) ) { case Ext . Date . MILLI : return num ; break ; case Ext . Date . SECOND : num . setUTCSeconds ( num . getUTCSeconds ( ) - num . getUTCSeconds ( ) % step ) ; num . setUTCMilliseconds ( 0 ) ; return num ; break ; case Ext . Date . MINUTE : num . setUTCMinutes ( num . getUTCMinutes ( ) - num . getUTCMinutes ( ) % step ) ; num . setUTCSeconds ( 0 ) ; num . setUTCMilliseconds ( 0 ) ; return num ; break ; case Ext . Date . HOUR : num . setUTCHours ( num . getUTCHours ( ) - num . getUTCHours ( ) % step ) ; num . setUTCMinutes ( 0 ) ; num . setUTCSeconds ( 0 ) ; num . setUTCMilliseconds ( 0 ) ; return num ; break ; case Ext . Date . DAY : if ( step == 7 || step == 14 ) { num . setUTCDate ( num . getUTCDate ( ) - num . getUTCDay ( ) + 1 ) ; } num . setUTCHours ( 0 ) ; num . setUTCMinutes ( 0 ) ; num . setUTCSeconds ( 0 ) ; num . setUTCMilliseconds ( 0 ) ; return num ; break ; case Ext . Date . MONTH : num . setUTCMonth ( num . getUTCMonth ( ) - ( num . getUTCMonth ( ) - 1 ) % step , 1 ) ; num . setUTCHours ( 0 ) ; num . setUTCMinutes ( 0 ) ; num . setUTCSeconds ( 0 ) ; num . setUTCMilliseconds ( 0 ) ; return num ; break ; case Ext . Date . YEAR : num . setUTCFullYear ( num . getUTCFullYear ( ) - num . getUTCFullYear ( ) % step , 1 , 1 ) ; num . setUTCHours ( 0 ) ; num . setUTCMinutes ( 0 ) ; num . setUTCSeconds ( 0 ) ; num . setUTCMilliseconds ( 0 ) ; return date ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Profile userFilter [CODESPLIT] function ( callback ) { var filterFunction = function ( doc , req ) { if ( doc . userId === req . query . key ) { return true ; } else { return false ; } } ; db . addFilter ( 'profile_by_userId' , filterFunction , function ( err ) { if ( err ) { return callback ( err ) ; } return callback ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The base class from which custom contacts inherit ; used by the included { [CODESPLIT] function Contact ( options ) { if ( ! ( this instanceof Contact ) ) { return new Contact ( options ) } assert ( options instanceof Object , 'Invalid options were supplied' ) Object . defineProperty ( this , 'nodeID' , { value : options . nodeID || this . _createNodeID ( ) , configurable : false , enumerable : true } ) assert ( utils . isValidKey ( this . nodeID ) , 'Invalid nodeID was supplied' ) this . seen ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the sliders thumbs with their new value ( s ) [CODESPLIT] function ( newValue , oldValue ) { var thumbs = this . getThumbs ( ) , ln = newValue . length , minValue = this . getMinValue ( ) , offset = this . offsetValueRatio , i ; this . setThumbsCount ( ln ) ; for ( i = 0 ; i < ln ; i ++ ) { thumbs [ i ] . getDraggable ( ) . setExtraConstraint ( null ) . setOffset ( ( newValue [ i ] - minValue ) * offset ) ; } for ( i = 0 ; i < ln ; i ++ ) { this . refreshThumbConstraints ( thumbs [ i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns options for specified message type [CODESPLIT] function getOptions ( messageType ) { const options = Object . assign ( { } , _defaults ) ; if ( messageType in _options ) { Object . assign ( options , _options [ messageType ] ) ; } return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare message and return as string [CODESPLIT] function parse ( messageType , args ) { const options = getOptions ( messageType ) ; /** Interpreter */ if ( typeof options . interpreter === \"function\" ) { for ( const index in args ) { /** Let string be without additional ' ' */ if ( typeof args [ index ] === \"string\" ) { continue ; } args [ index ] = options . interpreter ( args [ index ] ) ; } } /** Label */ if ( options . labels ) { args . unshift ( ` ${ messageType . toUpperCase ( ) } ` ) ; } /** Timestamp */ if ( options . timestamp ) { switch ( typeof options . timestamp ) { case \"boolean\" : args . unshift ( ` ${ new Date ( ) . toLocaleString ( ) } ` ) ; break ; case \"string\" : args . unshift ( ` ${ moment ( ) . format ( options . timestamp ) } ` ) ; break ; default : throw new Error ( ` ${ typeof options . timestamp } ` ) ; } } return args . join ( \" \" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main stdout function [CODESPLIT] function stdout ( messageType ) { return ( ... args ) => { const options = getOptions ( messageType ) ; let message = parse ( messageType , args ) ; /** Add trace to console.trace */ if ( messageType === \"trace\" ) { message += ` \\n ${ getTrace ( ) } ` ; } /** Stdout to console */ if ( ! options . fileOnly ) { _console . log ( message ) ; } /** Stdout to file */ if ( typeof options . filePath === \"string\" && options . filePath . length > 0 ) { fs . appendFileSync ( options . filePath , ` ${ message } \\n ` ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assign user options to object [CODESPLIT] function assignOptions ( defaults , userDefined ) { for ( const optionKey in userDefined ) { if ( defaults . hasOwnProperty ( optionKey ) ) { defaults [ optionKey ] = userDefined [ optionKey ] ; } else { throw new Error ( ` ${ optionKey } ` ) ; } } return defaults ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : this belongs in its own lib [CODESPLIT] function G ( cmd , coords ) { var parts = [ 'G' + cmd , ] ; for ( var coord in coords ) { if ( coords . hasOwnProperty ( coord ) ) { var lcoord = coord . toLowerCase ( ) ; if ( lcoord === 'x' ) { coords [ coord ] += offsetX ; } else if ( lcoord == 'y' ) { coords [ coord ] += offsetY ; } parts . push ( coord . toUpperCase ( ) + ( ( negate ) ? - coords [ coord ] : coords [ coord ] ) ) ; } } if ( ! coords . f && ! coords . F ) { parts . push ( 'F' + feedRate ) ; } gcode . push ( parts . join ( ' ' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "EXPONENT // FUNCTION : exponent ( x ) Returns an integer corresponding to the unbiased exponent of a double - precision floating - point number . [CODESPLIT] function exponent ( x ) { // Extract from the input value a higher order word (unsigned 32-bit integer) which contains the exponent: var high = getHighWord ( x ) ; // Apply a mask to isolate only the exponent bits and then shift off all bits which are part of the fraction: high = ( high & EXP_MASK ) >>> 20 ; // Remove the bias and return: return high - BIAS ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run tartempion [CODESPLIT] function ( ) { // First check if the tartempion.js file exists var files = fs . readdirSync ( process . cwd ( ) ) ; if ( ! ~ files . indexOf ( 'tartempion.js' ) ) { console . error ( \"\\nThe tartempion.js file doesn't exist.\" ) ; console . error ( \"Are you sure you're at the root of your folder?\\n\" ) ; process . exit ( - 1 ) ; } // Spawn the process var node = spawn ( 'node' , [ 'tartempion.js' ] ) ; // And send each output to stdout node . stdout . on ( 'data' , function ( data ) { process . stdout . write ( data ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show help [CODESPLIT] function ( ) { // Just run tartempion with the --help option cp . exec ( 'tartempion --help' , function ( err , stdout , stderr ) { if ( err ) throw err ; process . stdout . write ( stdout ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "repeatZero ( qty ) returns 0 repeated qty times [CODESPLIT] function repeatZero ( qty ) { var result = \"\" ; // exit early // if qty is 0 or a negative number // or doesn't coerce to an integer qty = parseInt ( qty , 10 ) ; if ( ! qty || qty < 1 ) { return result ; } while ( qty ) { result += \"0\" ; qty -= 1 ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "padZero ( str len [ isRight ] ) pads a string with zeros up to a specified length will not pad a string if its length is aready greater than or equal to the specified length default output pads with zeros on the left set isRight to true to pad with zeros on the right [CODESPLIT] function padZero ( str , len , isRight ) { if ( str == null ) { str = \"\" ; } str = \"\" + str ; return ( isRight ? str : \"\" ) + repeatZero ( len - str . length ) + ( isRight ? \"\" : str ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find [CODESPLIT] function find ( array , callback ) { var index = 0 , max = array . length , match ; if ( typeof callback !== \"function\" ) { match = callback ; callback = function ( item ) { return item === match ; } ; } while ( index < max ) { if ( callback ( array [ index ] ) ) { return array [ index ] ; } index += 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "each [CODESPLIT] function each ( array , callback ) { var index = 0 , max = array . length ; if ( ! array || ! max ) { return ; } while ( index < max ) { if ( callback ( array [ index ] , index ) === false ) { return ; } index += 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "map [CODESPLIT] function map ( array , callback ) { var index = 0 , max = array . length , ret = [ ] ; if ( ! array || ! max ) { return ret ; } while ( index < max ) { ret [ index ] = callback ( array [ index ] , index ) ; index += 1 ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compact [CODESPLIT] function compact ( array ) { var ret = [ ] ; each ( array , function ( item ) { if ( item ) { ret . push ( item ) ; } } ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unique [CODESPLIT] function unique ( array ) { var ret = [ ] ; each ( array , function ( _a ) { if ( ! find ( ret , _a ) ) { ret . push ( _a ) ; } } ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "intersection [CODESPLIT] function intersection ( a , b ) { var ret = [ ] ; each ( a , function ( _a ) { each ( b , function ( _b ) { if ( _a === _b ) { ret . push ( _a ) ; } } ) ; } ) ; return unique ( ret ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rest [CODESPLIT] function rest ( array , callback ) { var ret = [ ] ; each ( array , function ( item , index ) { if ( ! callback ( item ) ) { ret = array . slice ( index ) ; return false ; } } ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initial [CODESPLIT] function initial ( array , callback ) { var reversed = array . slice ( ) . reverse ( ) ; return rest ( reversed , callback ) . reverse ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "template used to format duration may be a function or a string template functions are executed with the this binding of the settings object so that template strings may be dynamically generated based on the duration object ( accessible via this . duration ) or any of the other settings [CODESPLIT] function ( ) { var types = this . types , dur = this . duration , lastType = findLast ( types , function ( type ) { return dur . _data [ type ] ; } ) ; // default template strings for each duration dimension type switch ( lastType ) { case \"seconds\" : return \"h:mm:ss\" ; case \"minutes\" : return \"d[d] h:mm\" ; case \"hours\" : return \"d[d] h[h]\" ; case \"days\" : return \"M[m] d[d]\" ; case \"weeks\" : return \"y[y] w[w]\" ; case \"months\" : return \"y[y] M[m]\" ; case \"years\" : return \"y[y]\" ; default : return \"y[y] M[m] d[d] h:mm:ss\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hogan . compile each partial return object of compiled partials [CODESPLIT] function ( partialPath ) { if ( options . verbose ) { grunt . log . writeln ( '- using partial path: %s' , partialPath ) ; } var allPartials = { } ; // for all files in dir grunt . file . recurse ( partialPath , function ( absPath , rootDir , subDir , fileName ) { // file extension does not match if ( ! fileName . match ( tplMatcher ) ) { if ( options . verbose ) { grunt . log . writeln ( '-- ignoring file: %s' , fileName ) ; } return ; } var partialName = absPath . replace ( rootDir , '' ) . replace ( tplMatcher , '' ) . substring ( 1 ) , partialSrc = grunt . file . read ( absPath ) ; if ( options . verbose ) { grunt . log . writeln ( '-- compiling partial: %s' , partialName ) ; } allPartials [ partialName ] = Hogan . compile ( partialSrc ) ; // , { sectionTags: [{o:'_i', c:'i'}] } } ) ; return allPartials ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hogan render each page return rendered pages [CODESPLIT] function ( pagesPath , allPartials ) { if ( options . verbose ) { grunt . log . writeln ( '- using pages path: %s' , pagesPath ) ; } var allPages = { } ; // load fileGlobals from file in [src]/globals.json if ( grunt . file . exists ( options . src + '/globals.json' ) ) { fileGlobals = grunt . file . readJSON ( options . src + '/globals.json' ) ; gruntGlobals = mergeObj ( gruntGlobals , fileGlobals ) ; } // for all files in dir grunt . file . recurse ( pagesPath , function ( absPath , rootDir , subDir , fileName ) { // file extension does not match - ignore if ( ! fileName . match ( tplMatcher ) ) { if ( options . verbose ) { grunt . log . writeln ( '-- ignoring file: %s' , fileName ) ; } return ; } var pageName = absPath . replace ( rootDir , '' ) . replace ( tplMatcher , '' ) . substring ( 1 ) , pageSrc = grunt . file . read ( absPath ) , pageJson = { } , dataPath = absPath . replace ( tplMatcher , '.json' ) , compiledPage = Hogan . compile ( pageSrc ) ; // , { sectionTags: [{o:'_i', c:'i'}] } if ( options . verbose ) { grunt . log . writeln ( '-- compiled page: %s' , pageName ) ; } // read page data from {pageName}.json if ( grunt . file . exists ( dataPath ) ) { if ( options . verbose ) { grunt . log . writeln ( '--- using page data from: %s' , dataPath ) ; } pageJson = grunt . file . readJSON ( dataPath ) ; pageData [ pageName ] = mergeObj ( gruntGlobals , pageJson ) ; if ( options . verbose ) { grunt . log . writeln ( '--- json for %s' , pageName , pageData [ pageName ] ) ; } } else { pageData [ pageName ] = gruntGlobals ; } allPages [ pageName ] = compiledPage . render ( pageData [ pageName ] , allPartials ) ; } ) ; return allPages ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new ddReporter test reporter . [CODESPLIT] function ddReporter ( runner ) { Base . call ( this , runner ) ; var self = this , stats = this . stats , indents = 0 , n = 0 ; function indent ( ) { return Array ( indents ) . join ( '  ' ) } runner . on ( 'start' , function ( ) { console . log ( ) ; } ) ; runner . on ( 'suite' , function ( suite ) { ++ indents ; console . log ( color ( 'suite' , '%s%s' ) , indent ( ) , suite . title ) ; } ) ; runner . on ( 'suite end' , function ( suite ) { -- indents ; if ( 1 == indents ) console . log ( ) ; } ) ; runner . on ( 'pending' , function ( test ) { var fmt = indent ( ) + color ( 'pending' , '  - %s' ) ; console . log ( fmt , test . title ) ; } ) ; runner . on ( 'pass' , function ( test ) { if ( test . isAction ) { var fmt = indent ( ) + color ( 'pending' , '  ⚙ %s');   cursor . CR ( ) ; self . stats . passes -- ; console . log ( fmt , test . title ) ; } else if ( 'fast' == test . speed ) { var fmt = indent ( ) + color ( 'checkmark' , '  ' + Base . symbols . ok ) + color ( 'pass' , ' %s' ) ; cursor . CR ( ) ; console . log ( fmt , test . title ) ; } else { var fmt = indent ( ) + color ( 'checkmark' , '  ' + Base . symbols . ok ) + color ( 'pass' , ' %s' ) + color ( test . speed , ' (%dms)' ) ; cursor . CR ( ) ; console . log ( fmt , test . title , test . duration ) ; } } ) ; runner . on ( 'fail' , function ( test , err ) { cursor . CR ( ) ; console . log ( indent ( ) + color ( 'fail' , '  %d) %s' ) , ++ n , test . title ) ; } ) ; runner . on ( 'end' , self . epilogue . bind ( self ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This gets executed before the original process . stdout . write [CODESPLIT] function ( result ) { // Write result to file if it was opened if ( fd && result . slice ( 0 , 3 ) !== '[D]' && result . match ( / \\u001b\\[ / g ) === null ) { fs . writeSync ( fd , result ) ; } // Prevent the original process.stdout.write from executing if quiet was specified if ( options . quiet ) { return hooker . preempt ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helper function for asyncjs [CODESPLIT] function ( cb , param ) { return function ( ) { var args = Array . prototype . slice . call ( arguments , 1 ) ; if ( typeof param !== 'undefined' ) { args . unshift ( param ) ; } else if ( arguments . length === 1 ) { args . unshift ( arguments [ 0 ] ) ; } args . unshift ( null ) ; cb . apply ( null , args ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check if selenium server is already running [CODESPLIT] function ( callback ) { if ( tunnel ) { return callback ( null ) ; } grunt . log . debug ( 'checking if selenium is running' ) ; var options = { host : capabilities . host || 'localhost' , port : capabilities . port || 4444 , path : '/wd/hub/status' } ; http . get ( options , function ( ) { grunt . log . debug ( 'selenium is running' ) ; isSeleniumServerRunning = true ; callback ( null ) ; } ) . on ( 'error' , function ( ) { grunt . log . debug ( 'selenium is not running' ) ; callback ( null ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "install drivers if needed [CODESPLIT] function ( callback ) { if ( tunnel || isSeleniumServerRunning ) { return callback ( null ) ; } grunt . log . debug ( 'installing driver if needed' ) ; selenium . install ( options . seleniumInstallOptions , function ( err ) { if ( err ) { return callback ( err ) ; } grunt . log . debug ( 'driver installed' ) ; callback ( null ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start selenium server or sauce tunnel ( if not already started ) [CODESPLIT] function ( callback ) { if ( tunnel ) { if ( isSauceTunnelRunning ) { return callback ( null , true ) ; } grunt . log . debug ( 'start sauce tunnel' ) ; /**\n                     * start sauce tunnel\n                     */ tunnel . start ( function ( hasTunnelStarted ) { // output here means if tunnel was created successfully if ( hasTunnelStarted === false ) { callback ( new Error ( 'Sauce-Tunnel couldn\\'t created successfully' ) ) ; } grunt . log . debug ( 'tunnel created successfully' ) ; isSauceTunnelRunning = true ; callback ( null ) ; } ) ; } else if ( ! server && ! isSeleniumServerRunning && ! options . nospawn ) { grunt . log . debug ( 'start selenium standalone server' ) ; /**\n                     * starts selenium standalone server if its not running\n                     */ server = selenium . start ( options . seleniumOptions , function ( err , child ) { if ( err ) { return callback ( err ) ; } grunt . log . debug ( 'selenium successfully started' ) ; seleniumServer = child ; isSeleniumServerRunning = true ; callback ( null , true ) ; } ) ; } else { grunt . log . debug ( 'standalone server or sauce tunnel is running' ) ; callback ( null , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "init WebdriverIO instance [CODESPLIT] function ( ) { var callback = arguments [ arguments . length - 1 ] ; grunt . log . debug ( 'init WebdriverIO instance' ) ; GLOBAL . browser . init ( function ( err ) { /**\n                     * gracefully kill process if init fails\n                     */ callback ( err ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "run mocha tests [CODESPLIT] function ( callback ) { grunt . log . debug ( 'run mocha tests' ) ; /**\n                 * save session ID\n                 */ sessionID = GLOBAL . browser . requestHandler . sessionID ; mocha . run ( next ( callback ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "end selenium session [CODESPLIT] function ( result , callback ) { grunt . log . debug ( 'end selenium session' ) ; // Restore grunt exception handling unmanageExceptions ( ) ; // Close Remote sessions if needed GLOBAL . browser . end ( next ( callback , result === 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "destroy sauce tunnel if connected ( once all tasks were executed ) or kill selenium server process if created [CODESPLIT] function ( result ) { var callback = arguments [ arguments . length - 1 ] ; if ( isLastTask && isSauceTunnelRunning ) { grunt . log . debug ( 'destroy sauce tunnel if connected (once all tasks were executed)' ) ; return tunnel . stop ( next ( callback , result ) ) ; } else if ( isLastTask && seleniumServer ) { grunt . log . debug ( 'kill selenium server' ) ; seleniumServer . kill ( ) ; } callback ( null , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "update job on Sauce Labs [CODESPLIT] function ( result ) { var callback = arguments [ arguments . length - 1 ] ; if ( ! options . user && ! options . key && ! options . updateSauceJob ) { return callback ( null , result ) ; } grunt . log . debug ( 'update job on Sauce Labs' ) ; var sauceAccount = new SauceLabs ( { username : options . user , password : options . key } ) ; sauceAccount . updateJob ( sessionID , { passed : result , public : true } , next ( callback , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "finish grunt task [CODESPLIT] function ( result ) { var callback = arguments [ arguments . length - 1 ] ; grunt . log . debug ( 'finish grunt task' ) ; if ( isLastTask ) { // close the file if it was opened if ( fd ) { fs . closeSync ( fd ) ; } // Restore process.stdout.write to its original value hooker . unhook ( process . stdout , 'write' ) ; } done ( result ) ; callback ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called from GhostTrain#send makes the request via the routing service . Takes a verb url optional params and a callback that passes in an err object and the data response from the router . [CODESPLIT] function send ( ghosttrain , verb , url , params , callback ) { var req , res ; verb = verb . toLowerCase ( ) ; // Allow `params` to be optional if ( typeof arguments [ 3 ] === 'function' ) { callback = params ; params = { } ; } // Clones if `params` is an object var options = clone ( params ) ; // Set up headers if ( ! options . headers ) options . headers = { } ; if ( options . contentType ) options . headers [ 'Content-Type' ] = options . contentType ; // We take out all the host information from the URL so we can match it var parsedURL = parseURL ( url , true ) ; var route = findRoute ( ghosttrain , verb , parsedURL ) ; reqDebug ( ghosttrain , 'REQ' , verb , url ) ; function execute ( ) { if ( route ) { req = new Request ( ghosttrain , route , parsedURL , options ) ; res = new Response ( ghosttrain , success ) ; route . callback ( req , res ) ; } else { if ( callback ) callback ( '404: No route found.' , null , null ) ; } } // Ensure the processing is asynchronous setTimeout ( execute , options . delay || ghosttrain . get ( 'delay' ) || 0 ) ; function success ( data ) { var response = render ( req , res , data ) ; reqDebug ( ghosttrain , 'RES' , verb , url , response ) ; if ( ! callback ) return ; // TODO error handling from router callback ( null , response , data ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a request response and body object and return a response object for the send callback . [CODESPLIT] function render ( req , res , body ) { var response = { } ; var parsedURL = parseURL ( req . url ) ; // Append URL properties for ( var prop in parsedURL ) response [ prop ] = parsedURL [ prop ] ; // Append select `req` properties [ 'method' , 'url' ] . forEach ( function ( prop ) { response [ prop ] = req [ prop ] ; } ) ; // Append select `res` properties [ 'headers' , 'statusCode' ] . forEach ( function ( prop ) { response [ prop ] = res [ prop ] ; } ) ; response . body = body ; return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FACTORY // FUNCTION : factory ( options clbk ) Returns a function for sending a POST request to a Travis CI API endpoint . [CODESPLIT] function factory ( options , clbk ) { var opts ; var err ; opts = copy ( defaults ) ; err = validate ( opts , options ) ; if ( err ) { throw err ; } if ( opts . port === null ) { if ( opts . protocol === 'https' ) { opts . port = DEFAULT_HTTPS_PORT ; } else { opts . port = DEFAULT_HTTP_PORT ; } } if ( ! isFunction ( clbk ) ) { throw new TypeError ( 'invalid input argument. Callback argument must be a function. Value: `' + clbk + '`.' ) ; } /**\n\t* FUNCTION: post( [data] )\n\t*\tSends a POST request to an endpoint.\n\t*\n\t* @param {String|Object} [data] - request data\n\t* @returns {Void}\n\t*/ return function post ( data ) { var d ; if ( arguments . length && ! isString ( data ) && ! isObject ( data ) ) { throw new TypeError ( 'invalid input argument. Request data must be either a string or an object. Value: `' + data + '`.' ) ; } d = data || '' ; query ( d , opts , done ) ; } ; // end FUNCTION post() /**\n\t* FUNCTION: done( error, results )\n\t*\tCallback invoked after completing query.\n\t*\n\t* @private\n\t* @param {Error|Null} error - error object\n\t* @param {Object[]} results - query results\n\t* @returns {Void}\n\t*/ function done ( error , results ) { if ( error ) { return clbk ( error ) ; } clbk ( null , results ) ; } // end FUNCTION done() }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wrapper for bellow each loop [CODESPLIT] function ( val , key ) { const optVal = _M . _option . getIn ( key ) ; //check for init key match if ( optVal !== null ) { if ( _ . isObject ( optVal ) ) { //merge in option to the defaults _M . _option . mergeIn ( key , _ . defaultsDeep ( val , _M . _option . getIn ( key ) ) ) ; } else { //merge in option to the defaults _M . _option . mergeIn ( key , val ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wrapper for set option [CODESPLIT] function ( optionObj ) { //@hacky fix for #388 if ( _ . hasIn ( optionObj , [ 'transitionDefault' ] ) ) { _M . _option . updateTransDefault ( optionObj . transitionDefault ) ; delete optionObj . transitionDefault ; } //cycle to check if it option object has any global opts _ . each ( optionObj , function ( val , key ) { //if sub-object if ( _ . isObject ( val ) ) { _ . each ( val , function ( _val , _key ) { mergeOption ( _val , [ key , _key ] ) ; } ) ; } else { mergeOption ( val , [ key ] ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The heart of CTR throbbing you . Dispatches composes and manages - > it s our main man ( or woman ) [CODESPLIT] function ( _data , _target , type = 'style' ) { const self = this ; //config data const configData = function ( data , target ) { //Keys which we will exclude from the dataMap const excludeKeys = self . initRun ? [ ] : [ 'option' , 'query' , 'shorthand' , 'mixin' ] ; self . initRun = false ; //data map struc to be popultated const emptyDataMap = Immutable . Map ( { static : Immutable . OrderedMap ( ) , obj : Immutable . OrderedMap ( ) } ) ; //check for use keywork, if false we don't use the data data = self . doNotUse ( data ) ; if ( ! data ) { return { emptyDataMap , target } ; } //we need to map out the raw objects into two maps, obj and staic const dataMap = _ . reduce ( data , function ( map , val , key ) { const addTo = _ . isPlainObject ( val ) ? 'obj' : 'static' ; if ( ! _ . includes ( excludeKeys , key ) ) { return map . update ( addTo , function ( m ) { return m . set ( key , val ) ; } ) ; } return map ; } , emptyDataMap ) ; return { dataMap , target } ; } ; //config target const configTarget = function ( dataMap , target ) { //set defualt is not present if ( ! target ) { //set init selector values. target = Immutable . fromJS ( { selector : self . selector , selectorCar : '' , selectorCdr : '' , selectorMedia : '' } ) ; const indexId = _H . util . _id . gen ( 'index' ) ; self . initIndex = indexId ; const data = dataMap . get ( 'static' ) ; //pick up local option const option = dataMap . getIn ( [ 'obj' , 'option' ] ) || { } ; if ( option ) { dataMap = dataMap . deleteIn ( [ 'obj' , 'option' ] ) ; } target = _T . util . set ( Immutable . fromJS ( { key : '' , data : data , option : option , type : 'index' , id : indexId } ) , target ) ; } return { dataMap , target } ; } ; /**\n     * The plan for this fn is to cycle through the various\n     * components, and then merge and res of said comps\n     */ const composeData = function ( dataMap , target ) { //dataMap let staticArgs = dataMap . get ( 'static' ) ; let objectArgs = dataMap . get ( 'obj' ) ; //transform/matrix helpers are objs so we need to check and processes //them before seting static to keep source order if ( objectArgs . size ) { if ( objectArgs . has ( 'transform' ) ) { ( { staticArgs , objectArgs } = _H . helperKeys . transform ( objectArgs , staticArgs ) ) ; } else if ( objectArgs . has ( 'matrix' ) ) { ( { staticArgs , objectArgs } = _H . helperKeys . matrix ( objectArgs , staticArgs ) ) ; } } //check for filter, can be string/array/obj const filter = staticArgs . has ( 'filter' ) || objectArgs . has ( 'filter' ) ; if ( filter ) { ( { staticArgs , objectArgs } = _H . helperKeys . filter ( staticArgs , objectArgs ) ) ; } //add static, as in non-obj key pairs if ( staticArgs . size ) { //check and process helpers if present staticArgs = _H . helperKeys . processHelperArgs ( staticArgs , target ) ; //hardcoded helper, kinds hacker tied to #396 if ( staticArgs . has ( '__inheritProps__' ) ) { //remove staticArgs = staticArgs . delete ( '__inheritProps__' ) ; } if ( type !== 'style' || self . processStyle ) { //apply static args self . indexMgr . set ( staticArgs , target ) ; } } //deflate check due to helpers like font-size: responsive if ( _M . _queue . deflateQueue . size ) { _M . _queue . deflateNext ( ) ; } /*\n      If gate for the real fun;\n       */ if ( objectArgs . size ) { //infinite loop saftey catch set self . processedHash = objectArgs . hashCode ( ) ; /**\n         * So the gist of this funk is its a wrapper funk for the passed in args.\n         * I would take a look at whats happening below in the loop to get a better\n         * idea of whats going on but we are just passing the keyArgs into this funk\n         * @param  {str}  key     -> Key from the objectArgs\n         * @param  {str}  keyList -> the regex ref in the _H.util\n         * @param  {str}  plural  -> The plural name which will then cycle through\n         *                           the cylceCallFn\n         * @param  {fn}  funk     -> The funk which we will invoke if it passes the\n         *                           if gate\n         * @param  {bln} passKey  -> If we need to pass the key to the funk\n         * @return {---}          -> A whole shit load could happen but nothing\n         *                           is returned directly\n         */ const keyCheck = function ( key , keyType , funk , passKey = true ) { //test from list, check out the util if ( _H . util . regularExp . keyTest ( key , keyType ) ) { //checks for use key const data = self . doNotUse ( objectArgs . get ( key ) , keyType ) ; if ( ! data ) { return true ; } //send off to be processed if ( passKey ) { funk ( key , data , target , keyType ) ; } else { funk ( data , target , keyType , key ) ; } return true ; } } ; // The gist here is to cycle though all the object keys // and then sub cycle the above key funks to see if // we have a regex match. If we have a match processes said match // and return true so we can bust the loop and move on const keyArgs = [ //single, plural, function [ 'grid' , processGrid , false ] , [ 'transition' , processTrans ] , [ 'animation' , processAnim ] , [ 'media' , processMedia , false ] , [ 'state' , processState ] , [ 'non' , processElm ] , [ 'element' , processElm ] , [ 'attribute' , processAttr ] , [ 'component' , processComp ] ] ; const keyList = objectArgs . keys ( ) ; //cycle through keys and inkove fns to match regex for ( let key of keyList ) { for ( let f = 0 ; f < keyArgs . length ; f ++ ) { const keyArg = keyArgs [ f ] ; //add key to the front of the line keyArg . unshift ( key ) ; const fnRes = keyCheck . apply ( null , keyArg ) ; //remove the key from the front of the line keyArg . shift ( ) ; if ( fnRes ) { //remove key objectArgs = objectArgs . delete ( key ) ; //bust loop f += keyArgs . length ; } } } } /**\n       * Deflate and tmpl features before moving onto the next cycle\n       */ if ( _M . _queue . deflateQueue . size ) { _M . _queue . deflateNext ( ) ; } return { objectArgs , target } ; } ; //process data const processData = function ( objectArgs , target ) { //run till nothing left to process if ( objectArgs . size ) { //infinite loop saftey catch if ( objectArgs . hashCode ( ) !== self . processedHash ) { //first check; so we try to extract style one more time //just to make sure before we throw an error self . extractStyle ( objectArgs . toJS ( ) , target ) ; } else { _H . throwErr ( { type : 'Infinite Loop' , code : JSON . stringify ( objectArgs . toJS ( ) ) , msg : [ 'Something does not belong and I can not process' , 'the above object so rather than throwing a nasty' , 'stylus error I will just remove it and tell you' , 'to take care of it. So take care of it and fix it.' ] . join ( ' ' ) } ) ; } } /**\n       * Processes, formats, and renders our CSS styles in the stack\n       */ if ( target . get ( 'stack' ) . size === 1 ) { let queueDone = false ; //while river while ( queueDone !== true ) { queueDone = _M . _queue . next ( ) ; } //formats and renders our styles via stylus if ( self . indexMgr . stack . size ) { renderStyle ( self . indexMgr , false , target ) ; } } //Final return for the whole show return ; } ; /*-----------------------------*/ /// Main Call /*-----------------------------*/ return teFlow . call ( { args : { data : _data , target : _target } } , configData , configTarget , composeData , processData ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "config data [CODESPLIT] function ( data , target ) { //Keys which we will exclude from the dataMap const excludeKeys = self . initRun ? [ ] : [ 'option' , 'query' , 'shorthand' , 'mixin' ] ; self . initRun = false ; //data map struc to be popultated const emptyDataMap = Immutable . Map ( { static : Immutable . OrderedMap ( ) , obj : Immutable . OrderedMap ( ) } ) ; //check for use keywork, if false we don't use the data data = self . doNotUse ( data ) ; if ( ! data ) { return { emptyDataMap , target } ; } //we need to map out the raw objects into two maps, obj and staic const dataMap = _ . reduce ( data , function ( map , val , key ) { const addTo = _ . isPlainObject ( val ) ? 'obj' : 'static' ; if ( ! _ . includes ( excludeKeys , key ) ) { return map . update ( addTo , function ( m ) { return m . set ( key , val ) ; } ) ; } return map ; } , emptyDataMap ) ; return { dataMap , target } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "config target [CODESPLIT] function ( dataMap , target ) { //set defualt is not present if ( ! target ) { //set init selector values. target = Immutable . fromJS ( { selector : self . selector , selectorCar : '' , selectorCdr : '' , selectorMedia : '' } ) ; const indexId = _H . util . _id . gen ( 'index' ) ; self . initIndex = indexId ; const data = dataMap . get ( 'static' ) ; //pick up local option const option = dataMap . getIn ( [ 'obj' , 'option' ] ) || { } ; if ( option ) { dataMap = dataMap . deleteIn ( [ 'obj' , 'option' ] ) ; } target = _T . util . set ( Immutable . fromJS ( { key : '' , data : data , option : option , type : 'index' , id : indexId } ) , target ) ; } return { dataMap , target } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The plan for this fn is to cycle through the various components and then merge and res of said comps [CODESPLIT] function ( dataMap , target ) { //dataMap let staticArgs = dataMap . get ( 'static' ) ; let objectArgs = dataMap . get ( 'obj' ) ; //transform/matrix helpers are objs so we need to check and processes //them before seting static to keep source order if ( objectArgs . size ) { if ( objectArgs . has ( 'transform' ) ) { ( { staticArgs , objectArgs } = _H . helperKeys . transform ( objectArgs , staticArgs ) ) ; } else if ( objectArgs . has ( 'matrix' ) ) { ( { staticArgs , objectArgs } = _H . helperKeys . matrix ( objectArgs , staticArgs ) ) ; } } //check for filter, can be string/array/obj const filter = staticArgs . has ( 'filter' ) || objectArgs . has ( 'filter' ) ; if ( filter ) { ( { staticArgs , objectArgs } = _H . helperKeys . filter ( staticArgs , objectArgs ) ) ; } //add static, as in non-obj key pairs if ( staticArgs . size ) { //check and process helpers if present staticArgs = _H . helperKeys . processHelperArgs ( staticArgs , target ) ; //hardcoded helper, kinds hacker tied to #396 if ( staticArgs . has ( '__inheritProps__' ) ) { //remove staticArgs = staticArgs . delete ( '__inheritProps__' ) ; } if ( type !== 'style' || self . processStyle ) { //apply static args self . indexMgr . set ( staticArgs , target ) ; } } //deflate check due to helpers like font-size: responsive if ( _M . _queue . deflateQueue . size ) { _M . _queue . deflateNext ( ) ; } /*\n      If gate for the real fun;\n       */ if ( objectArgs . size ) { //infinite loop saftey catch set self . processedHash = objectArgs . hashCode ( ) ; /**\n         * So the gist of this funk is its a wrapper funk for the passed in args.\n         * I would take a look at whats happening below in the loop to get a better\n         * idea of whats going on but we are just passing the keyArgs into this funk\n         * @param  {str}  key     -> Key from the objectArgs\n         * @param  {str}  keyList -> the regex ref in the _H.util\n         * @param  {str}  plural  -> The plural name which will then cycle through\n         *                           the cylceCallFn\n         * @param  {fn}  funk     -> The funk which we will invoke if it passes the\n         *                           if gate\n         * @param  {bln} passKey  -> If we need to pass the key to the funk\n         * @return {---}          -> A whole shit load could happen but nothing\n         *                           is returned directly\n         */ const keyCheck = function ( key , keyType , funk , passKey = true ) { //test from list, check out the util if ( _H . util . regularExp . keyTest ( key , keyType ) ) { //checks for use key const data = self . doNotUse ( objectArgs . get ( key ) , keyType ) ; if ( ! data ) { return true ; } //send off to be processed if ( passKey ) { funk ( key , data , target , keyType ) ; } else { funk ( data , target , keyType , key ) ; } return true ; } } ; // The gist here is to cycle though all the object keys // and then sub cycle the above key funks to see if // we have a regex match. If we have a match processes said match // and return true so we can bust the loop and move on const keyArgs = [ //single, plural, function [ 'grid' , processGrid , false ] , [ 'transition' , processTrans ] , [ 'animation' , processAnim ] , [ 'media' , processMedia , false ] , [ 'state' , processState ] , [ 'non' , processElm ] , [ 'element' , processElm ] , [ 'attribute' , processAttr ] , [ 'component' , processComp ] ] ; const keyList = objectArgs . keys ( ) ; //cycle through keys and inkove fns to match regex for ( let key of keyList ) { for ( let f = 0 ; f < keyArgs . length ; f ++ ) { const keyArg = keyArgs [ f ] ; //add key to the front of the line keyArg . unshift ( key ) ; const fnRes = keyCheck . apply ( null , keyArg ) ; //remove the key from the front of the line keyArg . shift ( ) ; if ( fnRes ) { //remove key objectArgs = objectArgs . delete ( key ) ; //bust loop f += keyArgs . length ; } } } } /**\n       * Deflate and tmpl features before moving onto the next cycle\n       */ if ( _M . _queue . deflateQueue . size ) { _M . _queue . deflateNext ( ) ; } return { objectArgs , target } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "So the gist of this funk is its a wrapper funk for the passed in args . I would take a look at whats happening below in the loop to get a better idea of whats going on but we are just passing the keyArgs into this funk [CODESPLIT] function ( key , keyType , funk , passKey = true ) { //test from list, check out the util if ( _H . util . regularExp . keyTest ( key , keyType ) ) { //checks for use key const data = self . doNotUse ( objectArgs . get ( key ) , keyType ) ; if ( ! data ) { return true ; } //send off to be processed if ( passKey ) { funk ( key , data , target , keyType ) ; } else { funk ( data , target , keyType , key ) ; } return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "process data [CODESPLIT] function ( objectArgs , target ) { //run till nothing left to process if ( objectArgs . size ) { //infinite loop saftey catch if ( objectArgs . hashCode ( ) !== self . processedHash ) { //first check; so we try to extract style one more time //just to make sure before we throw an error self . extractStyle ( objectArgs . toJS ( ) , target ) ; } else { _H . throwErr ( { type : 'Infinite Loop' , code : JSON . stringify ( objectArgs . toJS ( ) ) , msg : [ 'Something does not belong and I can not process' , 'the above object so rather than throwing a nasty' , 'stylus error I will just remove it and tell you' , 'to take care of it. So take care of it and fix it.' ] . join ( ' ' ) } ) ; } } /**\n       * Processes, formats, and renders our CSS styles in the stack\n       */ if ( target . get ( 'stack' ) . size === 1 ) { let queueDone = false ; //while river while ( queueDone !== true ) { queueDone = _M . _queue . next ( ) ; } //formats and renders our styles via stylus if ( self . indexMgr . stack . size ) { renderStyle ( self . indexMgr , false , target ) ; } } //Final return for the whole show return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check for use / omit in objs [CODESPLIT] function ( data , key = false ) { const useIsFalse = function ( obj ) { return _ . includes ( [ false , 'false' ] , obj ) ; } ; const useIsTrue = function ( obj ) { return _ . includes ( [ true , 'true' ] , obj ) ; } ; //init data check if ( ! key ) { const use = _ . get ( data , 'use' ) ; if ( useIsFalse ( use ) ) { return false ; } else if ( useIsTrue ( use ) ) { //remove use from data return _ . omit ( data , 'use' ) ; } } //cycle check if ( useIsFalse ( _ . get ( data , 'use' ) ) ) { return false ; } else if ( useIsTrue ( _ . get ( data , 'use' ) ) ) { data = _ . omit ( data , 'use' ) ; } //recurse check these, since there may be deeper options like tl to remove const searchObject = function ( sourceObj ) { //processing object - loop de loop for ( const property in sourceObj ) { if ( sourceObj . hasOwnProperty ( property ) ) { if ( _ . isPlainObject ( sourceObj [ property ] ) ) { const use = _ . get ( sourceObj [ property ] , 'use' ) ; if ( useIsFalse ( use ) ) { sourceObj = _ . omit ( sourceObj , property ) ; } else { if ( useIsTrue ( use ) ) { //removes ture ueses sourceObj [ property ] = _ . omit ( sourceObj [ property ] , 'use' ) ; } sourceObj [ property ] = searchObject ( sourceObj [ property ] ) ; } } } } return sourceObj ; } ; data = searchObject ( data ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recurse check these since there may be deeper options like tl to remove [CODESPLIT] function ( sourceObj ) { //processing object - loop de loop for ( const property in sourceObj ) { if ( sourceObj . hasOwnProperty ( property ) ) { if ( _ . isPlainObject ( sourceObj [ property ] ) ) { const use = _ . get ( sourceObj [ property ] , 'use' ) ; if ( useIsFalse ( use ) ) { sourceObj = _ . omit ( sourceObj , property ) ; } else { if ( useIsTrue ( use ) ) { //removes ture ueses sourceObj [ property ] = _ . omit ( sourceObj [ property ] , 'use' ) ; } sourceObj [ property ] = searchObject ( sourceObj [ property ] ) ; } } } } return sourceObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add - add reducers [CODESPLIT] function add ( reducers , scope , defaultState ) { if ( scope === undefined ) scope = \"general\" ; // Add combine reducer _combines [ scope ] !== undefined || defineReducer ( scope ) ; // Add data var scopeReducers = _reducers [ scope ] || { } ; for ( var type in reducers ) { var reducer = reducers [ type ] ; if ( typeof reducer === 'function' ) { if ( scopeReducers [ type ] === undefined ) { scopeReducers [ type ] = [ reducer ] ; } else { scopeReducers [ type ] . push ( reducer ) ; } } } if ( defaultState !== undefined ) { scopeReducers . _default = defaultState ; } _reducers [ scope ] = scopeReducers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove - remove reducers by scope & type [CODESPLIT] function remove ( scope , type ) { if ( scope === undefined ) scope = \"general\" ; if ( type === undefined ) { delete _combines [ scope ] ; delete _reducers [ scope ] ; } else { delete _reducers [ scope ] [ type ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "replace - replace with new reducers [CODESPLIT] function replace ( reducers , scope , defaultState ) { remove ( scope ) ; add ( reducers , scope , defaultState ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "m . query = _plugins [ loggly ] ? _plugins [ loggly ] . query : function () { throw new Error ( log . query () not available . Load a plugin that supports it . ) } [CODESPLIT] function createGoal ( type , goalName , params , opts ) { opts = opts || { } opts . type = type var newGoalInstance = new Goal ( goalName , params , opts ) m . log ( 'Starting ' + goalName , { params : params } , { custom : { goalId : newGoalInstance . goalId } } ) var newGoal = m . context ( { goalInstance : newGoalInstance , name : goalName } ) return newGoal }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to an integer . [CODESPLIT] function toInteger ( value ) { if ( ! value ) { return value === 0 ? value : 0 ; } value = toNumber ( value ) ; if ( value === INFINITY || value === - INFINITY ) { var sign = ( value < 0 ? - 1 : 1 ) ; return sign * MAX_INTEGER ; } var remainder = value % 1 ; return value === value ? ( remainder ? value - remainder : value ) : 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FUNCTION : onResponse ( error results ) Callback invoked upon receiving a response . [CODESPLIT] function onResponse ( error , results ) { if ( error ) { throw new Error ( error . message ) ; } console . log ( results ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a method decorator taking a callback which will be invoked before the execution of the decorated function * unless * the callback returns false . [CODESPLIT] function before ( fn , callback ) { return function ( ) { for ( var _len = arguments . length , args = Array ( _len ) , _key = 0 ; _key < _len ; _key ++ ) { args [ _key ] = arguments [ _key ] ; } if ( callback . apply ( this , [ fn . bind ( this ) ] . concat ( args ) ) !== false ) { return fn . apply ( this , args ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an error to the errors buffer [CODESPLIT] function writeError ( type , file , line , message ) { if ( ! messages [ type ] ) { messages [ type ] = [ ] ; } messages [ type ] . push ( { type : type , file : file , line : line , message : message } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flush the errors buffer [CODESPLIT] function flushMessages ( ) { Object . keys ( messages ) . forEach ( function ( type ) { messages [ type ] . forEach ( function ( msg ) { writeLine ( msg . type + \" error: [\" + msg . file + \":\" + msg . line + \"] \" + msg . message ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a JSON based config file [CODESPLIT] function getConfig ( file ) { var config = { } , subConfig ; try { config = JSON . parse ( fs . readFileSync ( file , \"utf8\" ) ) ; if ( config . extends ) { subConfig = JSON . parse ( fs . readFileSync ( config . extends , \"utf8\" ) ) ; util . _extend ( subConfig , config ) ; delete subConfig . extends ; config = subConfig ; } } catch ( e ) { // empty } return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a filename matches an ignore pattern [CODESPLIT] function isIgnored ( file ) { return ignorePatterns . some ( function ( pattern ) { return minimatch ( file , pattern , { nocase : true , matchBase : true } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace non css content in a html file with empty lines [CODESPLIT] function extractStyles ( src ) { var isInBlock = false , lines = [ ] ; src . replace ( / \\r / g , \"\" ) . split ( \"\\n\" ) . forEach ( function ( l ) { // we're at the end of the style tag if ( l . indexOf ( \"</style\" ) > - 1 ) { lines [ lines . length ] = \"\" ; isInBlock = false ; return ; } if ( isInBlock ) { lines [ lines . length ] = l ; } else { lines [ lines . length ] = \"\" ; } if ( l . indexOf ( \"<style\" ) > - 1 ) { isInBlock = true ; } } ) ; return lines . join ( \"\\n\" ) . replace ( / \\{\\$(\\w+\\.)*\\w+\\} / g , \"{}\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get file contents and file name from process . argv [CODESPLIT] function read ( ) { var filename = process . argv [ 2 ] , src = fs . readFileSync ( process . argv [ 3 ] , \"utf8\" ) ; // attempt to modify any src passing through the pre-commit hook try { src = require ( path . join ( process . cwd ( ) , \".git-hooks/pre-commit-plugins/pre-commit-modifier\" ) ) ( filename , src ) ; } catch ( e ) { // empty } // filename, src return Bluebird . resolve ( { filename : filename , src : src } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load all file checking plugins [CODESPLIT] function loadFileCheckerPlugins ( ) { var checkers = { } ; try { fs . readdirSync ( path . join ( process . cwd ( ) , \".git-hooks/pre-commit-plugins/plugins\" ) ) . forEach ( function ( file ) { var check = file . replace ( / \\.js$ / , \"\" ) ; if ( ! ( / \\.js$ / ) . test ( file ) ) { return ; } checkers [ check ] = require ( path . join ( process . cwd ( ) , \".git-hooks/pre-commit-plugins/plugins\" , file ) ) ; } ) ; } catch ( e ) { // empty } return checkers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getData : function () { var to = this . getTo () from = this . getFrom () out = this . getOut () direction = this . getDirection () el = this . getElement () elW = el . getWidth () elH = el . getHeight () halfWidth = ( elW / 2 ) halfHeight = ( elH / 2 ) fromTransform = {} toTransform = {} originalFromTransform = { rotateY : 0 translateX : 0 translateZ : 0 } originalToTransform = { rotateY : 90 translateX : halfWidth translateZ : halfWidth } originalVerticalFromTransform = { rotateX : 0 translateY : 0 translateZ : 0 } originalVerticalToTransform = { rotateX : 90 translateY : halfHeight translateZ : halfHeight } tempTransform ; if ( direction == left || direction == right ) { if ( out ) { toTransform = originalToTransform ; fromTransform = originalFromTransform ; } else { toTransform = originalFromTransform ; fromTransform = originalToTransform ; fromTransform . rotateY * = - 1 ; fromTransform . translateX * = - 1 ; } if ( direction === right ) { tempTransform = fromTransform ; fromTransform = toTransform ; toTransform = tempTransform ; } } if ( direction == up || direction == down ) { if ( out ) { toTransform = originalVerticalFromTransform ; fromTransform = { rotateX : - 90 translateY : halfHeight translateZ : halfHeight } ; } else { fromTransform = originalVerticalFromTransform ; toTransform = { rotateX : 90 translateY : - halfHeight translateZ : halfHeight } ; } if ( direction == up ) { tempTransform = fromTransform ; fromTransform = toTransform ; toTransform = tempTransform ; } } from . set ( transform fromTransform ) ; to . set ( transform toTransform ) ; return this . callParent ( arguments ) ; } [CODESPLIT] function ( ) { var to = this . getTo ( ) , from = this . getFrom ( ) , before = this . getBefore ( ) , after = this . getAfter ( ) , out = this . getOut ( ) , direction = this . getDirection ( ) , el = this . getElement ( ) , elW = el . getWidth ( ) , elH = el . getHeight ( ) , origin = out ? '100% 100%' : '0% 0%' , fromOpacity = 1 , toOpacity = 1 , transformFrom = { rotateY : 0 , translateZ : 0 } , transformTo = { rotateY : 0 , translateZ : 0 } ; if ( direction == \"left\" || direction == \"right\" ) { if ( out ) { toOpacity = 0.5 ; transformTo . translateZ = elW ; transformTo . rotateY = - 90 ; } else { fromOpacity = 0.5 ; transformFrom . translateZ = elW ; transformFrom . rotateY = 90 ; } } before [ 'transform-origin' ] = origin ; after [ 'transform-origin' ] = null ; to . set ( 'transform' , transformTo ) ; from . set ( 'transform' , transformFrom ) ; from . set ( 'opacity' , fromOpacity ) ; to . set ( 'opacity' , toOpacity ) ; return this . callParent ( arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@private @deprecated as of v2 . 0 . 0 on an association . Instead use the store configuration . [CODESPLIT] function ( storeConfig ) { var me = this , associatedModel = me . getAssociatedModel ( ) , storeName = me . getStoreName ( ) , foreignKey = me . getForeignKey ( ) , primaryKey = me . getPrimaryKey ( ) , filterProperty = me . getFilterProperty ( ) , autoLoad = me . getAutoLoad ( ) , autoSync = me . getAutoSync ( ) ; return function ( ) { var record = this , config , filter , store , modelDefaults = { } , listeners = { addrecords : me . onAddRecords , removerecords : me . onRemoveRecords , scope : me } ; if ( record [ storeName ] === undefined ) { if ( filterProperty ) { filter = { property : filterProperty , value : record . get ( filterProperty ) , exactMatch : true } ; } else { filter = { property : foreignKey , value : record . get ( primaryKey ) , exactMatch : true } ; } modelDefaults [ foreignKey ] = record . get ( primaryKey ) ; config = Ext . apply ( { } , storeConfig , { model : associatedModel , filters : [ filter ] , remoteFilter : true , autoSync : autoSync , modelDefaults : modelDefaults } ) ; store = record [ storeName ] = Ext . create ( 'Ext.data.Store' , config ) ; store . boundTo = record ; store . onAfter ( listeners ) ; if ( autoLoad ) { record [ storeName ] . load ( ) ; } } return record [ storeName ] ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read associated data [CODESPLIT] function ( record , reader , associationData ) { var store = record [ this . getName ( ) ] ( ) , records = reader . read ( associationData ) . getRecords ( ) ; store . add ( records ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given CSS class ( es ) to this Element . [CODESPLIT] function ( names , prefix , suffix ) { if ( ! names ) { return this ; } if ( ! this . isSynchronized ) { this . synchronize ( ) ; } var dom = this . dom , map = this . hasClassMap , classList = this . classList , SEPARATOR = this . SEPARATOR , i , ln , name ; prefix = prefix ? prefix + SEPARATOR : '' ; suffix = suffix ? SEPARATOR + suffix : '' ; if ( typeof names == 'string' ) { names = names . split ( this . spacesRe ) ; } for ( i = 0 , ln = names . length ; i < ln ; i ++ ) { name = prefix + names [ i ] + suffix ; if ( ! map [ name ] ) { map [ name ] = true ; classList . push ( name ) ; } } dom . className = classList . join ( ' ' ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the given CSS class ( es ) from this Element . [CODESPLIT] function ( names , prefix , suffix ) { if ( ! names ) { return this ; } if ( ! this . isSynchronized ) { this . synchronize ( ) ; } if ( ! suffix ) { suffix = '' ; } var dom = this . dom , map = this . hasClassMap , classList = this . classList , SEPARATOR = this . SEPARATOR , i , ln , name ; prefix = prefix ? prefix + SEPARATOR : '' ; suffix = suffix ? SEPARATOR + suffix : '' ; if ( typeof names == 'string' ) { names = names . split ( this . spacesRe ) ; } for ( i = 0 , ln = names . length ; i < ln ; i ++ ) { name = prefix + names [ i ] + suffix ; if ( map [ name ] ) { delete map [ name ] ; Ext . Array . remove ( classList , name ) ; } } dom . className = classList . join ( ' ' ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces a CSS class on the element with another . If the old name does not exist the new name will simply be added . [CODESPLIT] function ( oldName , newName , prefix , suffix ) { if ( ! oldName && ! newName ) { return this ; } oldName = oldName || [ ] ; newName = newName || [ ] ; if ( ! this . isSynchronized ) { this . synchronize ( ) ; } if ( ! suffix ) { suffix = '' ; } var dom = this . dom , map = this . hasClassMap , classList = this . classList , SEPARATOR = this . SEPARATOR , i , ln , name ; prefix = prefix ? prefix + SEPARATOR : '' ; suffix = suffix ? SEPARATOR + suffix : '' ; if ( typeof oldName == 'string' ) { oldName = oldName . split ( this . spacesRe ) ; } if ( typeof newName == 'string' ) { newName = newName . split ( this . spacesRe ) ; } for ( i = 0 , ln = oldName . length ; i < ln ; i ++ ) { name = prefix + oldName [ i ] + suffix ; if ( map [ name ] ) { delete map [ name ] ; Ext . Array . remove ( classList , name ) ; } } for ( i = 0 , ln = newName . length ; i < ln ; i ++ ) { name = prefix + newName [ i ] + suffix ; if ( ! map [ name ] ) { map [ name ] = true ; classList . push ( name ) ; } } dom . className = classList . join ( ' ' ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified CSS class on this element s DOM node . [CODESPLIT] function ( className ) { var map = this . hasClassMap , i , ln , name ; if ( typeof className == 'string' ) { className = className . split ( this . spacesRe ) ; } for ( i = 0 , ln = className . length ; i < ln ; i ++ ) { name = className [ i ] ; if ( ! map [ name ] ) { map [ name ] = true ; } } this . classList = className . slice ( ) ; this . dom . className = className . join ( ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Toggles the specified CSS class on this element ( removes it if it already exists otherwise adds it ) . [CODESPLIT] function ( className , force ) { if ( typeof force !== 'boolean' ) { force = ! this . hasCls ( className ) ; } return ( force ) ? this . addCls ( className ) : this . removeCls ( className ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the size of this Element . [CODESPLIT] function ( width , height ) { if ( Ext . isObject ( width ) ) { // in case of object from getSize() height = width . height ; width = width . width ; } this . setWidth ( width ) ; this . setHeight ( height ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the visibility of the element ( see details ) . If the visibilityMode is set to Element . DISPLAY it will use the display property to hide the element otherwise it uses visibility . The default is to hide and show using the visibility property . [CODESPLIT] function ( visible ) { var mode = this . getVisibilityMode ( ) , method = visible ? 'removeCls' : 'addCls' ; switch ( mode ) { case this . VISIBILITY : this . removeCls ( [ 'x-hidden-display' , 'x-hidden-offsets' ] ) ; this [ method ] ( 'x-hidden-visibility' ) ; break ; case this . DISPLAY : this . removeCls ( [ 'x-hidden-visibility' , 'x-hidden-offsets' ] ) ; this [ method ] ( 'x-hidden-display' ) ; break ; case this . OFFSETS : this . removeCls ( [ 'x-hidden-visibility' , 'x-hidden-display' ] ) ; this [ method ] ( 'x-hidden-offsets' ) ; break ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalizes currentStyle and computedStyle . [CODESPLIT] function ( prop ) { var me = this , dom = me . dom , hook = me . styleHooks [ prop ] , cs , result ; if ( dom == document ) { return null ; } if ( ! hook ) { me . styleHooks [ prop ] = hook = { name : Ext . dom . Element . normalize ( prop ) } ; } if ( hook . get ) { return hook . get ( dom , me ) ; } cs = window . getComputedStyle ( dom , '' ) ; // why the dom.style lookup? It is not true that \"style == computedStyle\" as // well as the fact that 0/false are valid answers... result = ( cs && cs [ hook . name ] ) ; // || dom.style[hook.name]; // WebKit returns rgb values for transparent, how does this work n IE9+ //        if (!supportsTransparentColor && result == 'rgba(0, 0, 0, 0)') { //            result = 'transparent'; //        } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for setting style properties also takes single object parameter of multiple styles . [CODESPLIT] function ( prop , value ) { var me = this , dom = me . dom , hooks = me . styleHooks , style = dom . style , valueFrom = Ext . valueFrom , name , hook ; // we don't promote the 2-arg form to object-form to avoid the overhead... if ( typeof prop == 'string' ) { hook = hooks [ prop ] ; if ( ! hook ) { hooks [ prop ] = hook = { name : Ext . dom . Element . normalize ( prop ) } ; } value = valueFrom ( value , '' ) ; if ( hook . set ) { hook . set ( dom , value , me ) ; } else { style [ hook . name ] = value ; } } else { for ( name in prop ) { if ( prop . hasOwnProperty ( name ) ) { hook = hooks [ name ] ; if ( ! hook ) { hooks [ name ] = hook = { name : Ext . dom . Element . normalize ( name ) } ; } value = valueFrom ( prop [ name ] , '' ) ; if ( hook . set ) { hook . set ( dom , value , me ) ; } else { style [ hook . name ] = value ; } } } } return me ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an object with properties top left right and bottom representing the margins of this element unless sides is passed then it returns the calculated width of the sides ( see { [CODESPLIT] function ( side ) { var me = this , hash = { t : \"top\" , l : \"left\" , r : \"right\" , b : \"bottom\" } , o = { } , key ; if ( ! side ) { for ( key in me . margins ) { o [ hash [ key ] ] = parseFloat ( me . getStyle ( me . margins [ key ] ) ) || 0 ; } return o ; } else { return me . addStyles . call ( me , side , me . margins ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the dimensions of the element available to lay content out in . [CODESPLIT] function ( ) { //<debug warn> Ext . Logger . deprecate ( \"Ext.dom.Element.getViewSize() is deprecated\" , this ) ; //</debug> var doc = document , dom = this . dom ; if ( dom == doc || dom == doc . body ) { return { width : Element . getViewportWidth ( ) , height : Element . getViewportHeight ( ) } ; } else { return { width : dom . clientWidth , height : dom . clientHeight } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the value of the given property is visually transparent . This may be due to a transparent style value or an rgba value with 0 in the alpha component . [CODESPLIT] function ( prop ) { //<debug warn> Ext . Logger . deprecate ( \"Ext.dom.Element.isTransparent() is deprecated\" , this ) ; //</debug> var value = this . getStyle ( prop ) ; return value ? this . transparentRe . test ( value ) : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds one or more CSS classes to this element and removes the same class ( es ) from all siblings . [CODESPLIT] function ( className ) { //<debug warn> Ext . Logger . deprecate ( \"Ext.dom.Element.radioCls() is deprecated\" , this ) ; //</debug> var cn = this . dom . parentNode . childNodes , v ; className = Ext . isArray ( className ) ? className : [ className ] ; for ( var i = 0 , len = cn . length ; i < len ; i ++ ) { v = cn [ i ] ; if ( v && v . nodeType == 1 ) { Ext . fly ( v , '_internal' ) . removeCls ( className ) ; } } return this . addCls ( className ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "function getAllKeys [CODESPLIT] function getAllKeys ( forValue , inObject ) { var keys = [ ] for ( let key of Object . keys ( inObject ) ) { if ( inObject [ key ] === forValue ) { keys . push ( key ) } } return keys }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a character to the screen indicating lint status [CODESPLIT] function printCounter ( indicator ) { counter ++ ; process . stdout . write ( indicator ) ; if ( counter === filesLength || counter % lineLength === 0 ) { process . stdout . write ( lineSpacing . slice ( - 1 * ( ( lineLength - counter ) % lineLength ) ) + \" \" ) ; process . stdout . write ( String ( \"   \" + counter ) . slice ( - 3 ) + \" / \" + String ( \"   \" + filesLength ) . slice ( - 3 ) ) ; process . stdout . write ( \"\\n\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@cfg { String } type The type of animation to use . The possible values are : [CODESPLIT] function ( config ) { var defaultClass = Ext . fx . animation . Abstract , type ; if ( typeof config == 'string' ) { type = config ; config = { } ; } else if ( config && config . type ) { type = config . type ; } if ( type ) { if ( Ext . browser . is . AndroidStock2 ) { if ( type == 'pop' ) { type = 'fade' ; } if ( type == 'popIn' ) { type = 'fadeIn' ; } if ( type == 'popOut' ) { type = 'fadeOut' ; } } defaultClass = Ext . ClassManager . getByAlias ( 'animation.' + type ) ; //<debug error> if ( ! defaultClass ) { Ext . Logger . error ( \"Invalid animation type of: '\" + type + \"'\" ) ; } //</debug> } return Ext . factory ( config , defaultClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rfc3986 compatable encode of a string [CODESPLIT] function encode ( string ) { function hex ( code ) { var hex_code = code . toString ( 16 ) . toUpperCase ( ) ; if ( hex_code . length < 2 ) { hex_code = 0 + hex_code ; } return '%' + hex_code ; } string = string + '' ; var reserved_chars = / [ :\\/?#\\[\\]@!$&'()*+,;=<>\"{}|\\\\`\\^%\\r\\n\\u0080-\\uffff] / ; var str_len = string . length ; var i ; var string_arr = string . split ( '' ) ; var c ; for ( i = 0 ; i < str_len ; i += 1 ) { if ( c = string_arr [ i ] . match ( reserved_chars ) ) { c = c [ 0 ] . charCodeAt ( 0 ) ; if ( c < 128 ) { string_arr [ i ] = hex ( c ) ; } else if ( c < 2048 ) { string_arr [ i ] = hex ( 192 + ( c >> 6 ) ) + hex ( 128 + ( c & 63 ) ) ; } else if ( c < 65536 ) { string_arr [ i ] = hex ( 224 + ( c >> 12 ) ) + hex ( 128 + ( ( c >> 6 ) & 63 ) ) + hex ( 128 + ( c & 63 ) ) ; } else if ( c < 2097152 ) { string_arr [ i ] = hex ( 240 + ( c >> 18 ) ) + hex ( 128 + ( ( c >> 12 ) & 63 ) ) + hex ( 128 + ( ( c >> 6 ) & 63 ) ) + hex ( 128 + ( c & 63 ) ) ; } } } return string_arr . join ( '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rfc3986 compatable decode of a string [CODESPLIT] function decode ( string ) { return string . replace ( / %[a-fA-F0-9]{2} / ig , function ( match ) { return String . fromCharCode ( parseInt ( match . replace ( '%' , '' ) , 16 ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a nonce for the request [CODESPLIT] function getNonce ( key_length ) { function rand ( ) { return Math . floor ( Math . random ( ) * chars . length ) ; } key_length = key_length || 64 ; var key_bytes = key_length / 8 ; var value = '' ; var key_iter = key_bytes / 4 ; var key_remainder = key_bytes % 4 ; var i ; var chars = [ '20' , '21' , '22' , '23' , '24' , '25' , '26' , '27' , '28' , '29' , '2A' , '2B' , '2C' , '2D' , '2E' , '2F' , '30' , '31' , '32' , '33' , '34' , '35' , '36' , '37' , '38' , '39' , '3A' , '3B' , '3C' , '3D' , '3E' , '3F' , '40' , '41' , '42' , '43' , '44' , '45' , '46' , '47' , '48' , '49' , '4A' , '4B' , '4C' , '4D' , '4E' , '4F' , '50' , '51' , '52' , '53' , '54' , '55' , '56' , '57' , '58' , '59' , '5A' , '5B' , '5C' , '5D' , '5E' , '5F' , '60' , '61' , '62' , '63' , '64' , '65' , '66' , '67' , '68' , '69' , '6A' , '6B' , '6C' , '6D' , '6E' , '6F' , '70' , '71' , '72' , '73' , '74' , '75' , '76' , '77' , '78' , '79' , '7A' , '7B' , '7C' , '7D' , '7E' ] ; for ( i = 0 ; i < key_iter ; i += 1 ) { value += chars [ rand ( ) ] + chars [ rand ( ) ] + chars [ rand ( ) ] + chars [ rand ( ) ] ; } // handle remaing bytes for ( i = 0 ; i < key_remainder ; i += 1 ) { value += chars [ rand ( ) ] ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a string of the parameters for the OAuth Authorization header [CODESPLIT] function toHeaderString ( params , realm ) { var arr = [ ] ; var i ; for ( i in params ) { if ( typeof params [ i ] !== 'object' && params [ i ] !== '' && params [ i ] !== undefined ) { arr . push ( encode ( i ) + '=\"' + encode ( params [ i ] ) + '\"' ) ; } } arr . sort ( ) ; if ( realm ) { arr . unshift ( 'realm=\"' + encode ( realm ) + '\"' ) ; } return arr . join ( ', ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a signature base string for the request [CODESPLIT] function toSignatureBaseString ( method , url , header_params , query_params ) { var arr = [ ] ; var i ; for ( i in header_params ) { if ( header_params [ i ] !== undefined && header_params [ i ] !== '' ) { arr . push ( [ encode ( i ) , encode ( header_params [ i ] + '' ) ] ) ; } } for ( i in query_params ) { if ( query_params [ i ] !== undefined && query_params [ i ] !== '' ) { arr . push ( [ encode ( i ) , encode ( query_params [ i ] + '' ) ] ) ; } } arr = arr . sort ( function lexicalSort ( a , b ) { if ( a [ 0 ] < b [ 0 ] ) { return - 1 ; } else if ( a [ 0 ] > b [ 0 ] ) { return 1 ; } else { if ( a [ 1 ] < b [ 1 ] ) { return - 1 ; } else if ( a [ 1 ] > b [ 1 ] ) { return 1 ; } else { return 0 ; } } } ) . map ( function ( el ) { return el . join ( \"=\" ) ; } ) ; return [ method , encode ( url ) , encode ( arr . join ( '&' ) ) ] . join ( '&' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "request [CODESPLIT] function ( method , url , async , user , password ) { var xhr = this . request ; xhr . method = method . toUpperCase ( ) ; xhr . url = Url . parse ( url , true ) ; xhr . async = async ; xhr . user = password ; xhr . open ( xhr . method , xhr . url , xhr . async , xhr . user , xhr . password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sign the request [CODESPLIT] function ( application_secret , token_secret , signature_base ) { var passphrase ; var signature ; application_secret = encode ( application_secret ) ; token_secret = encode ( token_secret || '' ) ; passphrase = application_secret + '&' + token_secret ; signature = Cryptography . hmac ( Cryptography . SHA1 , passphrase , signature_base ) ; return btoa ( signature ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tbl model new Tbl () [CODESPLIT] function ( fileName , tmpL , idx , indexColumn ) { var self = this ; var fNameList = tmpL . splice ( 0 , 1 ) [ 0 ] ; var fTypeList = tmpL . splice ( 0 , 1 ) [ 0 ] ; if ( indexColumn != undefined ) { idx = fNameList [ indexColumn ] ; } var fieldsName = { } ; fNameList . forEach ( function ( value , index ) { fieldsName [ value ] = index ; } ) ; self . data = { } ; tmpL . forEach ( function ( item ) { var obj = { } ; for ( var k in fieldsName ) { //obj[k] = item[fieldsName[k]]; var retVal = parseValue ( item [ fieldsName [ k ] ] , fTypeList [ fieldsName [ k ] ] ) ; if ( retVal == undefined ) { logger . error ( 'Parse config file \"{}\" \\'s filed \"{}\" error,the value is:\"{}\",the type is:\"{}\"' . format ( fileName , k , item [ fieldsName [ k ] ] , fTypeList [ fieldsName [ k ] ] ) ) } obj [ k ] = retVal } if ( self . data . hasOwnProperty ( obj [ idx ] ) ) { logger . error ( 'Index column can not have duplicate value,please check the config file :%s' , fileName + '.csv' ) ; } else { if ( obj [ idx ] ) { self . data [ obj [ idx ] ] = obj ; } else { logger . error ( 'No `%s` exists in tbl=%s' , idx , util . inspect ( fNameList , { showHidden : false , depth : 1 } ) ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { [CODESPLIT] function ( config ) { if ( typeof config == \"string\" ) { config = { title : config } ; } var minHeight = '1.3em' ; if ( Ext . theme . is . Cupertino ) { minHeight = '1.5em' } else if ( Ext . filterPlatform ( 'blackberry' ) || Ext . filterPlatform ( 'ie10' ) ) { minHeight = '2.6em' ; } Ext . applyIf ( config , { docked : 'top' , minHeight : minHeight , ui : Ext . filterPlatform ( 'blackberry' ) ? 'light' : 'dark' , cls : this . getBaseCls ( ) + '-title' } ) ; if ( Ext . theme . is . Tizen ) { Ext . applyIf ( config , { centered : false } ) ; } return Ext . factory ( config , Ext . Toolbar , this . getTitle ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the new { [CODESPLIT] function ( newButtons ) { var me = this ; // If there are no new buttons or it is an empty array, set newButtons // to false newButtons = ( ! newButtons || newButtons . length === 0 ) ? false : newButtons ; if ( newButtons ) { if ( me . buttonsToolbar ) { me . buttonsToolbar . show ( ) ; me . buttonsToolbar . removeAll ( ) ; me . buttonsToolbar . setItems ( newButtons ) ; } else { var layout = { type : 'hbox' , pack : 'center' } ; var isFlexed = Ext . theme . is . CupertinoClassic || Ext . theme . is . MountainView || Ext . theme . is . Blackberry || Ext . theme . is . Blackberry103 ; me . buttonsToolbar = Ext . create ( 'Ext.Toolbar' , { docked : 'bottom' , defaultType : 'button' , defaults : { flex : ( isFlexed ) ? 1 : undefined , ui : ( Ext . theme . is . Blackberry || Ext . theme . is . Blackberry103 ) ? 'action' : undefined } , layout : layout , ui : me . getUi ( ) , cls : me . getBaseCls ( ) + '-buttons' , items : newButtons } ) ; me . add ( me . buttonsToolbar ) ; } } else if ( me . buttonsToolbar ) { me . buttonsToolbar . hide ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Displays the { @link Ext . MessageBox } with a specified configuration . All display functions ( e . g . { @link #method - prompt } { @link #alert } { @link #confirm } ) on MessageBox call this function internally although those calls are basic shortcuts and do not support all of the config options allowed here . [CODESPLIT] function ( initialConfig ) { Ext . util . InputBlocker . blockInputs ( ) ; //if it has not been added to a container, add it to the Viewport. if ( ! this . getParent ( ) && Ext . Viewport ) { Ext . Viewport . add ( this ) ; } if ( ! initialConfig ) { return this . callParent ( ) ; } var config = Ext . Object . merge ( { } , { value : '' } , initialConfig ) ; var buttons = initialConfig . buttons || Ext . MessageBox . OK || [ ] , buttonBarItems = [ ] , userConfig = initialConfig ; Ext . each ( buttons , function ( buttonConfig ) { if ( ! buttonConfig ) { return ; } buttonBarItems . push ( Ext . apply ( { userConfig : userConfig , scope : this , handler : 'onClick' } , buttonConfig ) ) ; } , this ) ; config . buttons = buttonBarItems ; if ( config . promptConfig ) { //<debug warn> Ext . Logger . deprecate ( \"'promptConfig' config is deprecated, please use 'prompt' config instead\" , this ) ; //</debug> } config . prompt = ( config . promptConfig || config . prompt ) || null ; if ( config . multiLine ) { config . prompt = config . prompt || { } ; config . prompt . multiLine = config . multiLine ; delete config . multiLine ; } config = Ext . merge ( { } , this . defaultAllowedConfig , config ) ; this . setConfig ( config ) ; var prompt = this . getPrompt ( ) ; if ( prompt ) { prompt . setValue ( initialConfig . value || '' ) ; } this . callParent ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Displays a confirmation message box with Yes and No buttons ( comparable to JavaScript s confirm ) . If a callback function is passed it will be called after the user clicks either button and the id of the button that was clicked will be passed as the only parameter to the callback ( could also be the top - right close button ) . [CODESPLIT] function ( title , message , fn , scope ) { return this . show ( { title : title || null , message : message || null , buttons : Ext . MessageBox . YESNO , promptConfig : false , scope : scope , fn : function ( ) { if ( fn ) { fn . apply ( scope , arguments ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Displays a message box with OK and Cancel buttons prompting the user to enter some text ( comparable to JavaScript s prompt ) . The prompt can be a single - line or multi - line textbox . If a callback function is passed it will be called after the user clicks either button and the id of the button that was clicked ( could also be the top - right close button ) and the text that was entered will be passed as the two parameters to the callback . [CODESPLIT] function ( title , message , fn , scope , multiLine , value , prompt ) { return this . show ( { title : title || null , message : message || null , buttons : Ext . MessageBox . OKCANCEL , scope : scope , prompt : prompt || true , multiLine : multiLine , value : value , fn : function ( ) { if ( fn ) { fn . apply ( scope , arguments ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the { [CODESPLIT] function ( newComponent ) { this . callParent ( arguments ) ; var cls = this . getCls ( ) ; if ( newComponent ) { this . spinDownButton = Ext . Element . create ( { cls : cls + '-button ' + cls + '-button-down' , html : '-' } ) ; this . spinUpButton = Ext . Element . create ( { cls : cls + '-button ' + cls + '-button-up' , html : '+' } ) ; this . downRepeater = this . createRepeater ( this . spinDownButton , this . onSpinDown ) ; this . upRepeater = this . createRepeater ( this . spinUpButton , this . onSpinUp ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * global module [CODESPLIT] function ( val , type ) { var ret ; // allows Num(...) to be used directly without new. For shame! if ( ! ( this instanceof Num ) ) { return new Num ( val , type ) ; } this . original = val ; if ( ( val instanceof Num ) && ( val . type === \"NaN\" ) ) { return val ; } if ( type ) { this . type = type ; ret = this . parse ( ) ; // will convert original into appropriate val } else if ( typeof val === \"string\" ) { ret = Num . tryParse ( this ) ; } else if ( val . type ) { this . type = val . type ; ret = this . parse ( ) ; } else if ( typeof val === \"number\" ) { if ( Math . floor ( val ) === val ) { ret = Num . int ( val ) ; } else { ret = Num . float ( val ) ; } } else { ret = false ; } //this.original = val; if ( ret === false ) { ret = this ; this . type = \"NaN\" ; this . val = NaN ; } if ( val instanceof Num ) { // to make original more viewable for debugging if ( val . type === \"NaN\" ) { return val ; } ret . original = val . str ( ) ; } if ( ! ret ) { ret = this ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the { [CODESPLIT] function ( config ) { if ( config ) { if ( Ext . isBoolean ( config ) ) { config = { } ; } if ( typeof config == \"string\" ) { config = { text : config } ; } Ext . applyIf ( config , { ui : 'action' , align : 'right' , text : 'Done' } ) ; } return Ext . factory ( config , 'Ext.Button' , this . getDoneButton ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the { [CODESPLIT] function ( config ) { if ( config ) { if ( Ext . isBoolean ( config ) ) { config = { } ; } if ( typeof config == \"string\" ) { config = { text : config } ; } Ext . applyIf ( config , { align : 'left' , text : 'Cancel' } ) ; } return Ext . factory ( config , 'Ext.Button' , this . getCancelButton ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds any new { [CODESPLIT] function ( newSlots ) { var bcss = Ext . baseCSSPrefix , innerItems ; this . removeAll ( ) ; if ( newSlots ) { this . add ( newSlots ) ; } innerItems = this . getInnerItems ( ) ; if ( innerItems . length > 0 ) { innerItems [ 0 ] . addCls ( bcss + 'first' ) ; innerItems [ innerItems . length - 1 ] . addCls ( bcss + 'last' ) ; } this . updateUseTitles ( this . getUseTitles ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the values of the pickers slots . [CODESPLIT] function ( values , animated ) { var me = this , slots = me . getInnerItems ( ) , ln = slots . length , key , slot , loopSlot , i , value ; if ( ! values ) { values = { } ; for ( i = 0 ; i < ln ; i ++ ) { //set the value to false so the slot will return null when getValue is called values [ slots [ i ] . config . name ] = null ; } } for ( key in values ) { slot = null ; value = values [ key ] ; for ( i = 0 ; i < slots . length ; i ++ ) { loopSlot = slots [ i ] ; if ( loopSlot . config . name == key ) { slot = loopSlot ; break ; } } if ( slot ) { if ( animated ) { slot . setValueAnimated ( value ) ; } else { slot . setValue ( value ) ; } } } me . _values = me . _value = values ; return me ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the values of each of the pickers slots [CODESPLIT] function ( useDom ) { var values = { } , items = this . getItems ( ) . items , ln = items . length , item , i ; if ( useDom ) { for ( i = 0 ; i < ln ; i ++ ) { item = items [ i ] ; if ( item && item . isSlot ) { values [ item . getName ( ) ] = item . getValue ( useDom ) ; } } this . _values = values ; } return this . _values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "========================================================================== HELPERS ========================================================================== [CODESPLIT] function behatRunner ( data , callback ) { var spawn = require ( 'child_process' ) . spawn , behat = spawn ( data . cmd , data . args ) , stderr = '' , stdout = '' , options = data . options || { } ; if ( typeof options . failOnUndefined === 'undefined' ) { options . failOnUndefined = false ; } if ( typeof options . failOnFailed === 'undefined' ) { options . failOnFailed = true ; } behat . stdout . on ( 'data' , function ( data ) { stdout += data ; } ) ; behat . stderr . on ( 'data' , function ( data ) { stderr += data ; } ) ; behat . on ( 'exit' , function ( code ) { if ( code === 127 ) { grunt . log . errorlns ( 'In order for this task to work properly, Behat must be ' + 'installed and in the system PATH (if you can run \"behat\" at' + ' the command line, this task should work). Unfortunately, ' + 'Behat cannot be installed automatically via npm or grunt. ' + 'See the Behat installation instructions: ' + 'http://docs.behat.org/quick_intro.html#installation' ) ; grunt . warn ( 'Behat not found.' , code ) ; } else { if ( options . failOnUndefined && hasUndefinedSteps ( stdout ) ) { grunt . verbose . writeln ( stdout ) ; stderr = 'Undefined Steps' ; if ( options . output ) { stderr = stdout ; } } if ( options . failOnFailed && hasFailedSteps ( stdout ) ) { grunt . verbose . writeln ( stdout ) ; stderr = 'Failed Steps' ; if ( options . output ) { stderr = stdout ; } } if ( stderr === '' && options . output ) { grunt . log . write ( stdout ) ; } } callback ( stderr , stdout ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "addTranslation - add translations [CODESPLIT] function addTranslation ( translations , locale ) { if ( typeof translations !== 'object' ) { return ; } // add translations with format like // { //  en: {}, //  fr: {}, // } if ( locale === undefined ) { for ( var key in translations ) { addTranslation ( translations [ key ] , key ) ; } return ; } if ( I18n . translations [ locale ] === undefined ) { I18n . translations [ locale ] = translations ; } else { Object . assign ( I18n . translations [ locale ] , translations ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We override initItems so we can check for the pressed config . [CODESPLIT] function ( ) { var me = this , pressedButtons = [ ] , ln , i , item , items ; //call the parent first so the items get converted into a MixedCollection me . callParent ( arguments ) ; items = this . getItems ( ) ; ln = items . length ; for ( i = 0 ; i < ln ; i ++ ) { item = items . items [ i ] ; if ( item . getInitialConfig ( 'pressed' ) ) { pressedButtons . push ( items . items [ i ] ) ; } } me . updateFirstAndLastCls ( items ) ; me . setPressedButtons ( pressedButtons ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Button sets a timeout of 10ms to remove the { [CODESPLIT] function ( button ) { if ( ! this . getAllowToggle ( ) ) { return ; } var me = this , pressedButtons = me . getPressedButtons ( ) || [ ] , buttons = [ ] , alreadyPressed ; if ( ! me . getDisabled ( ) && ! button . getDisabled ( ) ) { //if we allow for multiple pressed buttons, use the existing pressed buttons if ( me . getAllowMultiple ( ) ) { buttons = pressedButtons . concat ( buttons ) ; } alreadyPressed = ( buttons . indexOf ( button ) !== - 1 ) || ( pressedButtons . indexOf ( button ) !== - 1 ) ; //if we allow for depressing buttons, and the new pressed button is currently pressed, remove it if ( alreadyPressed && me . getAllowDepress ( ) ) { Ext . Array . remove ( buttons , button ) ; } else if ( ! alreadyPressed || ! me . getAllowDepress ( ) ) { buttons . push ( button ) ; } me . setPressedButtons ( buttons ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the pressed buttons . [CODESPLIT] function ( newButtons , oldButtons ) { var me = this , items = me . getItems ( ) , pressedCls = me . getPressedCls ( ) , events = [ ] , item , button , ln , i , e ; //loop through existing items and remove the pressed cls from them ln = items . length ; if ( oldButtons && oldButtons . length ) { for ( i = 0 ; i < ln ; i ++ ) { item = items . items [ i ] ; if ( oldButtons . indexOf ( item ) != - 1 && newButtons . indexOf ( item ) == - 1 ) { item . removeCls ( [ pressedCls , item . getPressedCls ( ) ] ) ; events . push ( { item : item , toggle : false } ) ; } } } //loop through the new pressed buttons and add the pressed cls to them ln = newButtons . length ; for ( i = 0 ; i < ln ; i ++ ) { button = newButtons [ i ] ; if ( ! oldButtons || oldButtons . indexOf ( button ) == - 1 ) { button . addCls ( pressedCls ) ; events . push ( { item : button , toggle : true } ) ; } } //loop through each of the events and fire them after a delay ln = events . length ; if ( ln && oldButtons !== undefined ) { Ext . defer ( function ( ) { for ( i = 0 ; i < ln ; i ++ ) { e = events [ i ] ; me . fireEvent ( 'toggle' , me , e . item , e . toggle ) ; } } , 50 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shows the picker for the select field whether that is a { [CODESPLIT] function ( ) { var me = this , store = me . getStore ( ) , value = me . getValue ( ) ; //check if the store is empty, if it is, return if ( ! store || store . getCount ( ) === 0 ) { return ; } if ( me . getReadOnly ( ) ) { return ; } me . isFocused = true ; if ( me . getUsePicker ( ) ) { var picker = me . getPhonePicker ( ) , name = me . getName ( ) , pickerValue = { } ; pickerValue [ name ] = value ; picker . setValue ( pickerValue ) ; if ( ! picker . getParent ( ) ) { Ext . Viewport . add ( picker ) ; } picker . show ( ) ; } else { var listPanel = me . getTabletPicker ( ) , list = listPanel . down ( 'list' ) , index , record ; if ( ! listPanel . getParent ( ) ) { Ext . Viewport . add ( listPanel ) ; } listPanel . showBy ( me . getComponent ( ) , null ) ; if ( value || me . getAutoSelect ( ) ) { store = list . getStore ( ) ; index = store . find ( me . getValueField ( ) , value , null , null , null , true ) ; record = store . getAt ( index ) ; if ( record ) { list . select ( record , null , true ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the underlying <options > list with new values . [CODESPLIT] function ( newOptions ) { var store = this . getStore ( ) ; if ( ! store ) { this . setStore ( true ) ; store = this . _store ; } if ( ! newOptions ) { store . clearData ( ) ; } else { store . setData ( newOptions ) ; this . onStoreDataChanged ( store ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the internal { [CODESPLIT] function ( store ) { var initialConfig = this . getInitialConfig ( ) , value = this . getValue ( ) ; if ( value || value == 0 ) { this . updateValue ( this . applyValue ( value ) ) ; } if ( this . getValue ( ) === null ) { if ( initialConfig . hasOwnProperty ( 'value' ) ) { this . setValue ( initialConfig . value ) ; } if ( this . getValue ( ) === null && this . getAutoSelect ( ) ) { if ( store . getCount ( ) > 0 ) { this . setValue ( store . getAt ( 0 ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the Select field to the value of the first record in the store . [CODESPLIT] function ( ) { var me = this , record ; if ( me . getAutoSelect ( ) ) { var store = me . getStore ( ) ; record = ( me . originalValue ) ? me . originalValue : store . getAt ( 0 ) ; } else { var usePicker = me . getUsePicker ( ) , picker = usePicker ? me . picker : me . listPanel ; if ( picker ) { picker = picker . child ( usePicker ? 'pickerslot' : 'dataview' ) ; picker . deselectAll ( ) ; } record = null ; } me . setValue ( record ) ; return me ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts JSON schema to SQL schema [CODESPLIT] function generateSqlSchema ( dbDialect , metadata , prefix = undefined ) { check . assert . nonEmptyString ( dbDialect ) check . assert . object ( metadata ) check . assert . maybe . string ( prefix ) if ( ! Dialects . isSupported ( dbDialect ) ) { throw new Error ( ` ${ dbDialect } ` ) } prefix = prefix || '' const sqlSerializer = new SqlSerializer ( dbDialect ) const orderedEntities = getEntitiesOrderedByRelations ( metadata ) let queries = [ ] _ . forEach ( orderedEntities , ( entityName ) => { const entity = metadata [ entityName ] const tableName = pgEscape . ident ( ` ${ prefix } ${ entityName } ` ) let createQueries = [ ] _ . forOwn ( entity . fields , ( field , fieldName ) => { const columnName = pgEscape . ident ( fieldName ) let columnQuery = '' columnQuery += columnName let columnConstraints = [ ] const columnType = SqlSerializer . resolveType ( field . type ) columnQuery += ` ${ columnType } ` if ( field . enum ) { const enumValues = field . enum . map ( ( value ) => sqlSerializer . serializeValue ( field . type , value ) ) . join ( ', ' ) const expression = columnType . match ( / (\\[\\d*\\])+ / g ) ? ` ${ enumValues } ` : ` ${ enumValues } ` columnConstraints . push ( ` ${ columnName } ${ expression } ` ) } // SQL doesn't have an \"undefined\" value, thus no-default would result a nullable column columnConstraints . push ( ( field . nullable || ( field . default === undefined && ! field . identity ) ) ? 'NULL' : 'NOT NULL' ) if ( field . default !== undefined ) { const value = sqlSerializer . serializeValue ( field . type , field . default ) columnConstraints . push ( ` ${ value } ` ) } if ( columnConstraints . length > 0 ) { columnQuery += ` ${ columnConstraints . join ( ' ' ) } ` } createQueries . push ( ` \\n \\t ${ columnQuery } ` ) } ) const identity = _ . chain ( entity . fields ) . pickBy ( ( field ) => field . identity ) . map ( ( field , fieldName ) => pgEscape . ident ( fieldName ) ) . value ( ) if ( identity . length > 0 ) { const primaryKeyName = pgEscape . ident ( ` ${ prefix } ${ entityName } ` ) const uniqueName = pgEscape . ident ( ` ${ prefix } ${ entityName } ` ) const columns = identity . join ( ', ' ) createQueries . push ( ` \\n \\t ${ primaryKeyName } ${ columns } ` ) createQueries . push ( ` \\n \\t ${ uniqueName } ${ columns } ` ) } let referencesCount = 0 const references = _ . chain ( entity . fields ) . pickBy ( ( field ) => field . relation ) . toPairs ( ) . groupBy ( ( pair ) => pair [ 1 ] . relation . entity ) . value ( ) _ . forOwn ( references , ( pairs , otherEntityName ) => { const otherTableName = pgEscape . ident ( ` ${ prefix } ${ otherEntityName } ` ) const constraintName = pgEscape . ident ( ` ${ prefix } ${ entityName } ${ referencesCount ++ } ` ) pairs = _ . zip ( ... pairs ) const fieldsList = pairs [ 0 ] . map ( ( fieldName ) => pgEscape . ident ( fieldName ) ) . join ( ', ' ) const otherEntityFieldsList = pairs [ 1 ] . map ( ( field ) => pgEscape . ident ( field . relation . field ) ) . join ( ', ' ) let foreignConstraint = '' foreignConstraint += ` \\n \\t ${ constraintName } ${ fieldsList } ` foreignConstraint += ` \\n \\t \\t ${ otherTableName } ${ otherEntityFieldsList } ` foreignConstraint += '\\n\\t\\tON DELETE CASCADE' foreignConstraint += '\\n\\t\\tON UPDATE CASCADE' createQueries . push ( foreignConstraint ) } ) let createQuery = '' createQuery += ` ${ tableName } ` createQuery += createQueries . join ( ',' ) createQuery += createQueries . length > 0 ? '\\n)' : ')' queries . push ( createQuery ) } ) return queries }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据名字获取全局对象 [CODESPLIT] function getGlobalObj ( str , root ) { for ( var i = 0 ; i < root . length ; ++ i ) { if ( root [ i ] . name == str ) { return root [ i ] ; } } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "callback ( structname obj root ) [CODESPLIT] function forEachStruct ( structname , obj , root , callback , noexline ) { if ( noexline == undefined ) { noexline = false ; } for ( var i = 0 ; i < obj . val . length ; ++ i ) { if ( noexline && obj . val [ i ] . name . name . indexOf ( '_' ) == 0 ) { continue ; } if ( obj . val [ i ] . hasOwnProperty ( 'type2' ) && obj . val [ i ] . type2 == 'expand' ) { if ( ! obj . val [ i ] . hasOwnProperty ( 'expand' ) ) { forEachStruct ( structname , getGlobalObj ( obj . val [ i ] . type , root ) , root , callback ) ; } else { var expandobj = getGlobalObj ( obj . val [ i ] . expand , root ) ; for ( var eoi = 0 ; eoi < expandobj . val . length ; ++ eoi ) { callback ( structname , { name : { name : getEnumMemberRealName ( expandobj . val [ eoi ] . name , expandobj . name ) } , type : obj . val [ i ] . type , comment : expandobj . val [ eoi ] . comment } , root ) ; } } } else { if ( obj . name != structname && obj . val [ i ] . hasOwnProperty ( 'type2' ) && obj . val [ i ] . type2 == 'primary' ) { callback ( structname , { name : obj . val [ i ] . name , val : obj . val [ i ] . val , type : obj . val [ i ] . type , type2 : 'unique' } , root ) ; } else { callback ( structname , obj . val [ i ] , root ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "function isStaticStruct ( name root ) { var obj = getGlobalObj ( name root ) ; if ( obj ! = undefined ) { if ( obj . type == static ) { return true ; } if ( obj . type == struct ) { for ( var i = 0 ; i < obj . val . length ; ++ i ) { if ( isBaseType ( obj . val [ i ] . type )) { if ( ! ( obj . val [ i ] . hasOwnProperty ( type2 ) && obj . val [ i ] . type2 == primary )) { return false ; } } else { if ( !isStaticStruct ( obj . val [ i ] . type root )) { return false ; } } } return true ; } } return false ; } [CODESPLIT] function getStructMemberType ( membername , structname , root ) { var obj = getGlobalObj ( structname , root ) ; if ( obj != undefined ) { if ( obj . type == 'message' || obj . type == 'struct' || obj . type == 'static' ) { for ( var i = 0 ; i < obj . val . length ; ++ i ) { if ( obj . val [ i ] . name . name == membername ) { return obj . val [ i ] . type ; } } } } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据名字取到成员 [CODESPLIT] function getMember ( obj , name , root ) { var ii = str . indexOf ( '.' ) ; if ( ii < 0 ) { var curobj = undefined ; forEachStruct ( obj . name , obj , root , function ( structname , cobj , root ) { if ( name == cobj . name . name ) { curobj = cobj ; } } ) ; return curobj ; } if ( ii == 0 ) { return ; } var curtype = undefined ; var cur = str . slice ( 0 , ii ) ; forEachStruct ( obj . name , obj , root , function ( structname , cobj , root ) { if ( cur == cobj . name . name ) { curtype = cobj . type ; } } ) ; if ( curtype != undefined ) { return getMember ( getGlobalObj ( curtype , root ) , str . slice ( ii + 1 ) , root ) ; } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "为结构增加标识 [CODESPLIT] function setInMessage ( obj , root ) { obj . inmessage = true ; if ( obj . type == 'static' || obj . type == 'struct' || obj . type == 'message' ) { for ( var i = 0 ; i < obj . val . length ; ++ i ) { var cval = obj . val [ i ] ; if ( cval . hasOwnProperty ( 'type2' ) && 'expand' == cval . type2 ) { continue ; } var mytype = getRealType ( cval . type , root ) ; if ( isBaseType ( mytype ) ) { continue ; } setInMessage ( getGlobalObj ( mytype , root ) , root ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "为所有消息内结构增加标识 [CODESPLIT] function procInMessage ( root ) { for ( var i = 0 ; i < root . length ; ++ i ) { if ( 'message' == root [ i ] . type ) { setInMessage ( root [ i ] , root ) ; } } return root ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取版本号 [CODESPLIT] function getVer ( root ) { let cur = getGlobalObj ( 'VER' , root ) ; if ( cur == undefined ) { return '' ; } return cur . val . val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents an RPC interface [CODESPLIT] function RPC ( contact , options ) { assert ( this instanceof RPC , 'Invalid instance supplied' ) assert ( contact instanceof Contact , 'Invalid contact was supplied' ) events . EventEmitter . call ( this ) options = options || { } if ( options . replyto ) { assert ( options . replyto instanceof Contact , 'Invalid contact was supplied' ) } this . _hooks = { before : { } , after : { } } this . _pendingCalls = { } this . _contact = options . replyto || contact this . _log = options && options . logger this . readyState = 0 this . open ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the passed element ( s ) match the passed simple selector ( e . g . div . some - class or span : first - child ) [CODESPLIT] function ( el , q ) { var root , is , i , ln ; if ( typeof el == \"string\" ) { el = document . getElementById ( el ) ; } if ( Ext . isArray ( el ) ) { is = true ; ln = el . length ; for ( i = 0 ; i < ln ; i ++ ) { if ( ! this . is ( el [ i ] , q ) ) { is = false ; break ; } } } else { root = el . parentNode ; if ( ! root ) { root = document . createDocumentFragment ( ) ; root . appendChild ( el ) ; is = this . select ( q , root ) . indexOf ( el ) !== - 1 ; root . removeChild ( el ) ; root = null ; } else { is = this . select ( q , root ) . indexOf ( el ) !== - 1 ; } } return is ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An Channel is where messages are sent to and receive [CODESPLIT] function Channel ( id , exchange ) { var self = this ; events . EventEmitter . call ( this ) ; this . id = id ; this . exchange = exchange ; this . exchange . on ( this . id , function ( message ) { self . emit ( 'message' , message ) ; } ) ; this . setMaxListeners ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines a metric that measures availability by number of requests / responses [CODESPLIT] function AvailabilityMetric ( ) { if ( ! ( this instanceof AvailabilityMetric ) ) { return new AvailabilityMetric ( ) } Metric . call ( this ) this . key = 'availability' this . default = [ 0 , 0 ] // [requests,responses] this . hooks = [ { trigger : 'before' , event : 'send' , handler : this . _start } , { trigger : 'before' , event : 'receive' , handler : this . _stop } ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "# HELPERS Additional functions that adds to the original jam function . [CODESPLIT] function includeHelpers ( func ) { // ## jam.identity() // Simple function that passes the values it receives to the next function. // Useful if you need a `process.nextTick` inserted in-between your call chain. func . identity = function ( next ) { function _identity ( next ) { var args = arguments ; tick ( function ( ) { next . apply ( this , replaceHead ( args , null ) ) ; } ) ; } // This function can also be passed to jam verbatim. return ( typeof next === 'function' ) ? _identity . apply ( this , arguments ) : _identity ; } ; // ## jam.nextTick() // Alias for `.identity`. Use when you need a `process.nextTick` inserted in-between // your call chain. func . nextTick = func . identity // ## jam.return( [args...] ) // Returns a set of values to the next function in the chain. Useful when you want to // pass in the next function verbatim without wrapping it in a `function() { }` just // to pass values into it. func . return = function ( ) { var args = toArgs ( arguments ) ; return function ( next ) { args . unshift ( null ) ; next . apply ( this , args ) ; } ; } ; // ## jam.null() // Similar to `.identity` but absorbs all arguments that has been passed to it and // forward nothing to the next function. Effectively nullifying any arguments passed // from previous jam call. //  // Like `jam.identity`, this function can be passed to the jam chain verbatim. func . null = function ( next ) { function _null ( next ) { next ( ) ; } return ( typeof next === 'function' ) ? _null . call ( this , next ) : _null ; } ; // ## jam.call( function, [args...] ) // Convenience for calling functions that accepts arguments in standard node.js // convention. Since jam insert `next` as first argument, most functions cannot be // passed directly into the jam chain, thus this helper function. //  // If no `args` is given, this function passes arguments given to `next()` call from // previous function directly to the function (with proper callback) placement). //  // Use this in combination with `jam.return` or `jam.null` if you want to control the // arguments that are passed to the function. func . call = function ( func ) { ensureFunc ( func , 'function' ) ; var args = toArgs ( arguments ) ; args . shift ( ) ; // func if ( args . length ) { // use provided arguments return function ( next ) { args . push ( next ) ; func . apply ( this , args ) ; } ; } else { // use passed-in arguments during chain resolution return function ( next ) { args = toArgs ( arguments ) ; args . shift ( ) ; // move next to last position args . push ( next ) ; func . apply ( this , args ) ; } ; } } ; // ## jam.each( array, iterator( next, element, index ) ) // Execute the given `iterator` function for each element given in the `array`. The // iterator is given a `next` function and the element to act on. The next step in the // chain will receive the original array passed verbatim so you can chain multiple // `.each` calls to act on the same array. //  // You can also pass `arguments` and `\"strings\"` as an array or you can omit the array // entirely, in which case this method will assume that the previous chain step // returns something that looks like an array as its first result. //  // Under the hood, a JAM step is added for each element. So the iterator will be // called serially, one after another finish. A parallel version maybe added in the // future. func . each = function ( array , iterator ) { if ( typeof array === 'function' ) { iterator = array ; array = null } else { ensureArray ( array , 'array' ) ; } ensureFunc ( iterator , 'iterator' ) ; return function ( next , array_ ) { var arr = array || array_ ; // Builds another JAM chain internally var chain = jam ( jam . identity ) , count = arr . length ; for ( var i = 0 ; i < count ; i ++ ) ( function ( element , i ) { chain = chain ( function ( next ) { iterator ( next , element , i ) ; } ) ; } ) ( arr [ i ] , i ) ; chain = chain ( function ( next ) { next ( null , arr ) ; } ) ; return chain ( next ) ; } ; } ; // ## jam.map( array, iterator( next, element, index ) ) // Works exactly like the `each` helper but if a value is passed to the iterator's // `next` function, it is collected into a new array which will be passed to the next // function in the JAM chain after `map`. //  // Like with `each`, you can omit the `array` input, in which case this method will // assume that the previous chain step returns something that looks like an array as // its first result. func . map = function ( array , iterator ) { if ( typeof array === 'function' ) { iterator = array ; array = null ; } else { ensureArray ( array , 'array' ) ; } ensureFunc ( iterator , 'iterator' ) ; return function ( next , array_ ) { var arr = array || array_ ; // Builds another JAM chain internally and collect results. // TODO: Dry with .each? var chain = jam ( jam . identity ) , count = arr . length , result = [ ] ; for ( var i = 0 ; i < count ; i ++ ) ( function ( element , i ) { chain = chain ( function ( next , previous ) { result . push ( previous ) ; iterator ( next , element , i ) ; } ) ; } ) ( arr [ i ] , i ) ; chain = chain ( function ( next , last ) { result . push ( last ) ; result . shift ( ) ; // discard first undefined element next ( null , result ) ; } ) ; return chain ( next ) ; } ; } ; // ## jam.timeout( timeout ) // Pauses the chain for the specified `timeout` using `setTimeout`. Useful for // inserting a delay in-between a long jam chain. func . timeout = function ( timeout ) { ensureNum ( timeout , 'timeout' ) ; return function ( next ) { var args = replaceHead ( arguments , null ) ; setTimeout ( function ( ) { next . apply ( this , args ) ; } , timeout ) ; } ; } ; // ## jam.promise( [chain] ) // Returns a JAM promise, useful when you are starting an asynchronous call outside of // the JAM chain itself but wants the callback to call into the chain. In other words, // this allow you to put a 'waiting point' (aka promise?) into existing JAM chain that // waits for the initial call to finish and also pass any arguments passed to the // callback to the next step in the JAM chain as well. // // This function will returns a callback that automatically bridges into the JAM // chain. You can pass the returned callback to any asynchronous function and the JAM // chain (at the point of calling .promise()) will wait for that asynchronous function // to finish effectively creating a 'waiting point'. // // Additionally, any arguments passed to the callback are forwarded to the next call // in the JAM chain as well. If errors are passed, then it is fast-forwarded to the // last handler normally like normal JAM steps. func . promise = function ( chain ) { chain = typeof chain === 'function' ? chain : // chain is supplied typeof this === 'function' ? this : // called from the chain variable ensureFunc ( chain , 'chain' ) ; // fails if ( typeof chain === 'undefined' && typeof this === 'function' ) { chain = this ; } var args = null , next = null ; chain ( function ( next_ ) { if ( args ) return next_ . apply ( this , args ) ; // callback already called next = next_ ; // wait for callback } ) ; return function ( ) { if ( next ) return next . apply ( this , arguments ) ; // chain promise already called args = arguments ; // wait for chain to call the promise } ; } ; // TODO: noError() ? or absorbError() return func ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "# JAM function Exported function starts the asynchronous call chain . [CODESPLIT] function jam ( func , context ) { ensureFunc ( func , 'function' ) ; var steps = [ ] ; // ##### Chain resolver. // The resolver will execute all functions passed to the chain as soon as `nextTick`. // Thus jam will not works across async context where the chain is not built all at // once in a single event loop, which is not really a problem from my personal // experience. tick ( function resolve ( e ) { var args = Array . prototype . slice . call ( arguments ) ; // Any errors passed to next() are (fast-)forwarded to the last function in the // chain skipping any functions that's left to be executed. if ( e ) return steps [ steps . length - 1 ] . apply ( this , args ) ; // Any parameters given to next() are passed as arguments to the next function in // the chain (except for errors, of course.) var next = steps . shift ( ) , args = Array . prototype . slice . call ( arguments ) if ( steps . length ) { args . shift ( ) ; // error arg args . unshift ( resolve ) ; // next() function } return next . apply ( this , args ) ; } ) ; // ##### Chain context continuation. // Subsequent invocation of the function returned from the `jam` function simply adds // the given function to the chain. function continuable ( func , context ) { ensureFunc ( func , 'function' ) ; if ( context ) { // TODO: Handle falsy things? func = bind ( func , context ) ; } steps . push ( func ) ; return continuable ; } ; return includeHelpers ( continuable ( func , context ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subsequent invocation of the function returned from the jam function simply adds the given function to the chain . [CODESPLIT] function continuable ( func , context ) { ensureFunc ( func , 'function' ) ; if ( context ) { // TODO: Handle falsy things? func = bind ( func , context ) ; } steps . push ( func ) ; return continuable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts description from contents of a readme file in markdown format [CODESPLIT] function extractDescription ( d ) { if ( ! d ) return ; if ( d === \"ERROR: No README data found!\" ) return ; // the first block of text before the first heading // that isn't the first line heading d = d . trim ( ) . split ( '\\n' ) for ( var s = 0 ; d [ s ] && d [ s ] . trim ( ) . match ( / ^(#|$) / ) ; s ++ ) ; var l = d . length for ( var e = s + 1 ; e < l && d [ e ] . trim ( ) ; e ++ ) ; return d . slice ( s , e ) . join ( ' ' ) . trim ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "7 . 4 Comments [CODESPLIT] function addComment ( type , value , start , end , loc ) { var comment ; assert ( typeof start === 'number' , 'Comment must have valid position' ) ; // Because the way the actual token is scanned, often the comments // (if any) are skipped twice during the lexical analysis. // Thus, we need to skip adding a comment if the comment array already // handled it. if ( state . lastCommentStart >= start ) { return ; } state . lastCommentStart = start ; comment = { type : type , value : value } ; if ( extra . range ) { comment . range = [ start , end ] ; } if ( extra . loc ) { comment . loc = loc ; } extra . comments . push ( comment ) ; if ( extra . attachComment ) { extra . leadingComments . push ( comment ) ; extra . trailingComments . push ( comment ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "7 . 7 Punctuators [CODESPLIT] function scanPunctuator ( ) { var start = index , code = source . charCodeAt ( index ) , code2 , ch1 = source [ index ] , ch2 , ch3 , ch4 ; if ( state . inJSXTag || state . inJSXChild ) { // Don't need to check for '{' and '}' as it's already handled // correctly by default. switch ( code ) { case 60 : // < case 62 : // > ++ index ; return { type : Token . Punctuator , value : String . fromCharCode ( code ) , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } } switch ( code ) { // Check for most common single-character punctuators. case 40 : // ( open bracket case 41 : // ) close bracket case 59 : // ; semicolon case 44 : // , comma case 91 : // [ case 93 : // ] case 58 : // : case 63 : // ? case 126 : // ~ ++ index ; if ( extra . tokenize && code === 40 ) { extra . openParenToken = extra . tokens . length ; } return { type : Token . Punctuator , value : String . fromCharCode ( code ) , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; case 123 : // { open curly brace case 125 : // } close curly brace ++ index ; if ( extra . tokenize && code === 123 ) { extra . openCurlyToken = extra . tokens . length ; } // lookahead2 function can cause tokens to be scanned twice and in doing so // would wreck the curly stack by pushing the same token onto the stack twice. // curlyLastIndex ensures each token is pushed or popped exactly once if ( index > state . curlyLastIndex ) { state . curlyLastIndex = index ; if ( code === 123 ) { state . curlyStack . push ( '{' ) ; } else { state . curlyStack . pop ( ) ; } } return { type : Token . Punctuator , value : String . fromCharCode ( code ) , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; default : code2 = source . charCodeAt ( index + 1 ) ; // '=' (char #61) marks an assignment or comparison operator. if ( code2 === 61 ) { switch ( code ) { case 37 : // % case 38 : // & case 42 : // *: case 43 : // + case 45 : // - case 47 : // / case 60 : // < case 62 : // > case 94 : // ^ case 124 : // | index += 2 ; return { type : Token . Punctuator , value : String . fromCharCode ( code ) + String . fromCharCode ( code2 ) , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; case 33 : // ! case 61 : // = index += 2 ; // !== and === if ( source . charCodeAt ( index ) === 61 ) { ++ index ; } return { type : Token . Punctuator , value : source . slice ( start , index ) , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; default : break ; } } break ; } // Peek more characters. ch2 = source [ index + 1 ] ; ch3 = source [ index + 2 ] ; ch4 = source [ index + 3 ] ; // 4-character punctuator: >>>= if ( ch1 === '>' && ch2 === '>' && ch3 === '>' ) { if ( ch4 === '=' ) { index += 4 ; return { type : Token . Punctuator , value : '>>>=' , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } } // 3-character punctuators: === !== >>> <<= >>= if ( ch1 === '>' && ch2 === '>' && ch3 === '>' && ! state . inType ) { index += 3 ; return { type : Token . Punctuator , value : '>>>' , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } if ( ch1 === '<' && ch2 === '<' && ch3 === '=' ) { index += 3 ; return { type : Token . Punctuator , value : '<<=' , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } if ( ch1 === '>' && ch2 === '>' && ch3 === '=' ) { index += 3 ; return { type : Token . Punctuator , value : '>>=' , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } if ( ch1 === '.' && ch2 === '.' && ch3 === '.' ) { index += 3 ; return { type : Token . Punctuator , value : '...' , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } // Other 2-character punctuators: ++ -- << >> && || // Don't match these tokens if we're in a type, since they never can // occur and can mess up types like Map<string, Array<string>> if ( ch1 === ch2 && ( '+-<>&|' . indexOf ( ch1 ) >= 0 ) && ! state . inType ) { index += 2 ; return { type : Token . Punctuator , value : ch1 + ch2 , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } if ( ch1 === '=' && ch2 === '>' ) { index += 2 ; return { type : Token . Punctuator , value : '=>' , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } if ( '<>=!+-*%&|^/' . indexOf ( ch1 ) >= 0 ) { ++ index ; return { type : Token . Punctuator , value : ch1 , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } if ( ch1 === '.' ) { ++ index ; return { type : Token . Punctuator , value : ch1 , lineNumber : lineNumber , lineStart : lineStart , range : [ start , index ] } ; } throwError ( { } , Messages . UnexpectedToken , 'ILLEGAL' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expect the next token to match the specified keyword . If not an exception will be thrown . [CODESPLIT] function expectKeyword ( keyword , contextual ) { var token = lex ( ) ; if ( token . type !== ( contextual ? Token . Identifier : Token . Keyword ) || token . value !== keyword ) { throwUnexpected ( token ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "11 . 1 . 4 Array Initialiser [CODESPLIT] function parseArrayInitialiser ( ) { var elements = [ ] , blocks = [ ] , filter = null , tmp , possiblecomprehension = true , marker = markerCreate ( ) ; expect ( '[' ) ; while ( ! match ( ']' ) ) { if ( lookahead . value === 'for' && lookahead . type === Token . Keyword ) { if ( ! possiblecomprehension ) { throwError ( { } , Messages . ComprehensionError ) ; } matchKeyword ( 'for' ) ; tmp = parseForStatement ( { ignoreBody : true } ) ; tmp . of = tmp . type === Syntax . ForOfStatement ; tmp . type = Syntax . ComprehensionBlock ; if ( tmp . left . kind ) { // can't be let or const throwError ( { } , Messages . ComprehensionError ) ; } blocks . push ( tmp ) ; } else if ( lookahead . value === 'if' && lookahead . type === Token . Keyword ) { if ( ! possiblecomprehension ) { throwError ( { } , Messages . ComprehensionError ) ; } expectKeyword ( 'if' ) ; expect ( '(' ) ; filter = parseExpression ( ) ; expect ( ')' ) ; } else if ( lookahead . value === ',' && lookahead . type === Token . Punctuator ) { possiblecomprehension = false ; // no longer allowed. lex ( ) ; elements . push ( null ) ; } else { tmp = parseSpreadOrAssignmentExpression ( ) ; elements . push ( tmp ) ; if ( tmp && tmp . type === Syntax . SpreadElement ) { if ( ! match ( ']' ) ) { throwError ( { } , Messages . ElementAfterSpreadElement ) ; } } else if ( ! ( match ( ']' ) || matchKeyword ( 'for' ) || matchKeyword ( 'if' ) ) ) { expect ( ',' ) ; // this lexes. possiblecomprehension = false ; } } } expect ( ']' ) ; if ( filter && ! blocks . length ) { throwError ( { } , Messages . ComprehensionRequiresBlock ) ; } if ( blocks . length ) { if ( elements . length !== 1 ) { throwError ( { } , Messages . ComprehensionError ) ; } return markerApply ( marker , delegate . createComprehensionExpression ( filter , blocks , elements [ 0 ] ) ) ; } return markerApply ( marker , delegate . createArrayExpression ( elements ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "11 . 1 . 5 Object Initialiser [CODESPLIT] function parsePropertyFunction ( options ) { var previousStrict , previousYieldAllowed , previousAwaitAllowed , params , defaults , body , marker = markerCreate ( ) ; previousStrict = strict ; previousYieldAllowed = state . yieldAllowed ; state . yieldAllowed = options . generator ; previousAwaitAllowed = state . awaitAllowed ; state . awaitAllowed = options . async ; params = options . params || [ ] ; defaults = options . defaults || [ ] ; body = parseConciseBody ( ) ; if ( options . name && strict && isRestrictedWord ( params [ 0 ] . name ) ) { throwErrorTolerant ( options . name , Messages . StrictParamName ) ; } strict = previousStrict ; state . yieldAllowed = previousYieldAllowed ; state . awaitAllowed = previousAwaitAllowed ; return markerApply ( marker , delegate . createFunctionExpression ( null , params , defaults , body , options . rest || null , options . generator , body . type !== Syntax . BlockStatement , options . async , options . returnType , options . typeParameters ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "11 . 3 Postfix Expressions [CODESPLIT] function parsePostfixExpression ( ) { var marker = markerCreate ( ) , expr = parseLeftHandSideExpressionAllowCall ( ) , token ; if ( lookahead . type !== Token . Punctuator ) { return expr ; } if ( ( match ( '++' ) || match ( '--' ) ) && ! peekLineTerminator ( ) ) { // 11.3.1, 11.3.2 if ( strict && expr . type === Syntax . Identifier && isRestrictedWord ( expr . name ) ) { throwErrorTolerant ( { } , Messages . StrictLHSPostfix ) ; } if ( ! isLeftHandSide ( expr ) ) { throwError ( { } , Messages . InvalidLHSInAssignment ) ; } token = lex ( ) ; expr = markerApply ( marker , delegate . createPostfixExpression ( token . value , expr ) ) ; } return expr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "11 . 4 Unary Operators [CODESPLIT] function parseUnaryExpression ( ) { var marker , token , expr ; if ( lookahead . type !== Token . Punctuator && lookahead . type !== Token . Keyword ) { return parsePostfixExpression ( ) ; } if ( match ( '++' ) || match ( '--' ) ) { marker = markerCreate ( ) ; token = lex ( ) ; expr = parseUnaryExpression ( ) ; // 11.4.4, 11.4.5 if ( strict && expr . type === Syntax . Identifier && isRestrictedWord ( expr . name ) ) { throwErrorTolerant ( { } , Messages . StrictLHSPrefix ) ; } if ( ! isLeftHandSide ( expr ) ) { throwError ( { } , Messages . InvalidLHSInAssignment ) ; } return markerApply ( marker , delegate . createUnaryExpression ( token . value , expr ) ) ; } if ( match ( '+' ) || match ( '-' ) || match ( '~' ) || match ( '!' ) ) { marker = markerCreate ( ) ; token = lex ( ) ; expr = parseUnaryExpression ( ) ; return markerApply ( marker , delegate . createUnaryExpression ( token . value , expr ) ) ; } if ( matchKeyword ( 'delete' ) || matchKeyword ( 'void' ) || matchKeyword ( 'typeof' ) ) { marker = markerCreate ( ) ; token = lex ( ) ; expr = parseUnaryExpression ( ) ; expr = markerApply ( marker , delegate . createUnaryExpression ( token . value , expr ) ) ; if ( strict && expr . operator === 'delete' && expr . argument . type === Syntax . Identifier ) { throwErrorTolerant ( { } , Messages . StrictDelete ) ; } return expr ; } return parsePostfixExpression ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "11 . 13 Assignment Operators 12 . 14 . 5 AssignmentPattern [CODESPLIT] function reinterpretAsAssignmentBindingPattern ( expr ) { var i , len , property , element ; if ( expr . type === Syntax . ObjectExpression ) { expr . type = Syntax . ObjectPattern ; for ( i = 0 , len = expr . properties . length ; i < len ; i += 1 ) { property = expr . properties [ i ] ; if ( property . type === Syntax . SpreadProperty ) { if ( i < len - 1 ) { throwError ( { } , Messages . PropertyAfterSpreadProperty ) ; } reinterpretAsAssignmentBindingPattern ( property . argument ) ; } else { if ( property . kind !== 'init' ) { throwError ( { } , Messages . InvalidLHSInAssignment ) ; } reinterpretAsAssignmentBindingPattern ( property . value ) ; } } } else if ( expr . type === Syntax . ArrayExpression ) { expr . type = Syntax . ArrayPattern ; for ( i = 0 , len = expr . elements . length ; i < len ; i += 1 ) { element = expr . elements [ i ] ; /* istanbul ignore else */ if ( element ) { reinterpretAsAssignmentBindingPattern ( element ) ; } } } else if ( expr . type === Syntax . Identifier ) { if ( isRestrictedWord ( expr . name ) ) { throwError ( { } , Messages . InvalidLHSInAssignment ) ; } } else if ( expr . type === Syntax . SpreadElement ) { reinterpretAsAssignmentBindingPattern ( expr . argument ) ; if ( expr . argument . type === Syntax . ObjectPattern ) { throwError ( { } , Messages . ObjectPatternAsSpread ) ; } } else { /* istanbul ignore else */ if ( expr . type !== Syntax . MemberExpression && expr . type !== Syntax . CallExpression && expr . type !== Syntax . NewExpression ) { throwError ( { } , Messages . InvalidLHSInAssignment ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "12 . 4 Expression Statement [CODESPLIT] function parseExpressionStatement ( ) { var marker = markerCreate ( ) , expr = parseExpression ( ) ; consumeSemicolon ( ) ; return markerApply ( marker , delegate . createExpressionStatement ( expr ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "12 . 9 The return statement [CODESPLIT] function parseReturnStatement ( ) { var argument = null , marker = markerCreate ( ) ; expectKeyword ( 'return' ) ; if ( ! state . inFunctionBody ) { throwErrorTolerant ( { } , Messages . IllegalReturn ) ; } // 'return' followed by a space and an identifier is very common. if ( source . charCodeAt ( index ) === 32 ) { if ( isIdentifierStart ( source . charCodeAt ( index + 1 ) ) ) { argument = parseExpression ( ) ; consumeSemicolon ( ) ; return markerApply ( marker , delegate . createReturnStatement ( argument ) ) ; } } if ( peekLineTerminator ( ) ) { return markerApply ( marker , delegate . createReturnStatement ( null ) ) ; } if ( ! match ( ';' ) ) { if ( ! match ( '}' ) && lookahead . type !== Token . EOF ) { argument = parseExpression ( ) ; } } consumeSemicolon ( ) ; return markerApply ( marker , delegate . createReturnStatement ( argument ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "12 Statements [CODESPLIT] function parseStatement ( ) { var type = lookahead . type , marker , expr , labeledBody ; if ( type === Token . EOF ) { throwUnexpected ( lookahead ) ; } if ( type === Token . Punctuator ) { switch ( lookahead . value ) { case ';' : return parseEmptyStatement ( ) ; case '{' : return parseBlock ( ) ; case '(' : return parseExpressionStatement ( ) ; default : break ; } } if ( type === Token . Keyword ) { switch ( lookahead . value ) { case 'break' : return parseBreakStatement ( ) ; case 'continue' : return parseContinueStatement ( ) ; case 'debugger' : return parseDebuggerStatement ( ) ; case 'do' : return parseDoWhileStatement ( ) ; case 'for' : return parseForStatement ( ) ; case 'function' : return parseFunctionDeclaration ( ) ; case 'class' : return parseClassDeclaration ( ) ; case 'if' : return parseIfStatement ( ) ; case 'return' : return parseReturnStatement ( ) ; case 'switch' : return parseSwitchStatement ( ) ; case 'throw' : return parseThrowStatement ( ) ; case 'try' : return parseTryStatement ( ) ; case 'var' : return parseVariableStatement ( ) ; case 'while' : return parseWhileStatement ( ) ; case 'with' : return parseWithStatement ( ) ; default : break ; } } if ( matchAsyncFuncExprOrDecl ( ) ) { return parseFunctionDeclaration ( ) ; } marker = markerCreate ( ) ; expr = parseExpression ( ) ; // 12.12 Labelled Statements if ( ( expr . type === Syntax . Identifier ) && match ( ':' ) ) { lex ( ) ; if ( state . labelSet . has ( expr . name ) ) { throwError ( { } , Messages . Redeclaration , 'Label' , expr . name ) ; } state . labelSet . set ( expr . name , true ) ; labeledBody = parseStatement ( ) ; state . labelSet . delete ( expr . name ) ; return markerApply ( marker , delegate . createLabeledStatement ( expr , labeledBody ) ) ; } consumeSemicolon ( ) ; return markerApply ( marker , delegate . createExpressionStatement ( expr ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "15 Program [CODESPLIT] function parseSourceElement ( ) { var token ; if ( lookahead . type === Token . Keyword ) { switch ( lookahead . value ) { case 'const' : case 'let' : return parseConstLetDeclaration ( lookahead . value ) ; case 'function' : return parseFunctionDeclaration ( ) ; case 'export' : throwErrorTolerant ( { } , Messages . IllegalExportDeclaration ) ; return parseExportDeclaration ( ) ; case 'import' : throwErrorTolerant ( { } , Messages . IllegalImportDeclaration ) ; return parseImportDeclaration ( ) ; case 'interface' : if ( lookahead2 ( ) . type === Token . Identifier ) { return parseInterface ( ) ; } return parseStatement ( ) ; default : return parseStatement ( ) ; } } if ( matchContextualKeyword ( 'type' ) && lookahead2 ( ) . type === Token . Identifier ) { return parseTypeAlias ( ) ; } if ( matchContextualKeyword ( 'interface' ) && lookahead2 ( ) . type === Token . Identifier ) { return parseInterface ( ) ; } if ( matchContextualKeyword ( 'declare' ) ) { token = lookahead2 ( ) ; if ( token . type === Token . Keyword ) { switch ( token . value ) { case 'class' : return parseDeclareClass ( ) ; case 'function' : return parseDeclareFunction ( ) ; case 'var' : return parseDeclareVariable ( ) ; } } else if ( token . type === Token . Identifier && token . value === 'module' ) { return parseDeclareModule ( ) ; } } if ( lookahead . type !== Token . EOF ) { return parseStatement ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Between JSX opening and closing tags ( e . g . <foo > HERE< / foo > ) anything that is not another JSX tag and is not an expression wrapped by {} is text . [CODESPLIT] function advanceJSXChild ( ) { var ch = source . charCodeAt ( index ) ; // '<' 60, '>' 62, '{' 123, '}' 125 if ( ch !== 60 && ch !== 62 && ch !== 123 && ch !== 125 ) { return scanJSXText ( [ '<' , '>' , '{' , '}' ] ) ; } return scanPunctuator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is used to modify the delegate . [CODESPLIT] function extend ( object , properties ) { var entry , result = { } ; for ( entry in object ) { /* istanbul ignore else */ if ( object . hasOwnProperty ( entry ) ) { result [ entry ] = object [ entry ] ; } } for ( entry in properties ) { /* istanbul ignore else */ if ( properties . hasOwnProperty ( entry ) ) { result [ entry ] = properties [ entry ] ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts bef : aft to { _before : bef _after : aft } and resolves undefined before / after from parent or root [CODESPLIT] function resolve ( value , key ) { // resolve before/after from root or parent if it isn't present on the current node if ( ! value . _parent ) return undefined ; // Immediate parent if ( value . _parent . _default && value . _parent . _default [ key ] ) return value . _parent . _default [ key ] ; // Root var root = value . _parent . _parent ; if ( ! root ) return undefined ; return root . _default ? root . _default [ key ] : undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clones ( copies ) an Object using deep copying . [CODESPLIT] function clone ( parent , circular , depth , prototype ) { var filter ; if ( typeof circular === 'object' ) { depth = circular . depth ; prototype = circular . prototype ; filter = circular . filter ; circular = circular . circular } // maintain two arrays for circular references, where corresponding parents // and children have the same index var allParents = [ ] ; var allChildren = [ ] ; var useBuffer = typeof Buffer != 'undefined' ; if ( typeof circular == 'undefined' ) circular = true ; if ( typeof depth == 'undefined' ) depth = Infinity ; // recurse this function so we don't reset allParents and allChildren function _clone ( parent , depth ) { // cloning null always returns null if ( parent === null ) return null ; if ( depth == 0 ) return parent ; var child ; var proto ; if ( typeof parent != 'object' ) { return parent ; } if ( clone . __isArray ( parent ) ) { child = [ ] ; } else if ( clone . __isRegExp ( parent ) ) { child = new RegExp ( parent . source , __getRegExpFlags ( parent ) ) ; if ( parent . lastIndex ) child . lastIndex = parent . lastIndex ; } else if ( clone . __isDate ( parent ) ) { child = new Date ( parent . getTime ( ) ) ; } else if ( useBuffer && Buffer . isBuffer ( parent ) ) { child = new Buffer ( parent . length ) ; parent . copy ( child ) ; return child ; } else { if ( typeof prototype == 'undefined' ) { proto = Object . getPrototypeOf ( parent ) ; child = Object . create ( proto ) ; } else { child = Object . create ( prototype ) ; proto = prototype ; } } if ( circular ) { var index = allParents . indexOf ( parent ) ; if ( index != - 1 ) { return allChildren [ index ] ; } allParents . push ( parent ) ; allChildren . push ( child ) ; } for ( var i in parent ) { var attrs ; if ( proto ) { attrs = Object . getOwnPropertyDescriptor ( proto , i ) ; } if ( attrs && attrs . set == null ) { continue ; } child [ i ] = _clone ( parent [ i ] , depth - 1 ) ; } return child ; } return _clone ( parent , depth ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "lotta situps ... [CODESPLIT] function makeAbs ( self , f ) { var abs = f if ( f . charAt ( 0 ) === '/' ) { abs = path . join ( self . root , f ) } else if ( isAbsolute ( f ) || f === '' ) { abs = f } else if ( self . changedCwd ) { abs = path . resolve ( self . cwd , f ) } else { abs = path . resolve ( f ) } return abs }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if value is a plain object that is an object created by the Object constructor or one with a [[ Prototype ]] of null . [CODESPLIT] function isPlainObject ( value ) { var Ctor ; // Exit early for non `Object` objects. if ( ! ( isObjectLike ( value ) && objToString . call ( value ) == objectTag && ! isArguments ( value ) ) || ( ! hasOwnProperty . call ( value , 'constructor' ) && ( Ctor = value . constructor , typeof Ctor == 'function' && ! ( Ctor instanceof Ctor ) ) ) ) { return false ; } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. var result ; // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. baseForIn ( value , function ( subValue , key ) { result = key ; } ) ; return result === undefined || hasOwnProperty . call ( value , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Munge \\ n s and spaces in text so that the number of characters between \\ n s is less than or equal to width . [CODESPLIT] function reflowText ( text , width , gfm ) { // Hard break was inserted by Renderer.prototype.br or is // <br /> when gfm is true var splitRe = gfm ? HARD_RETURN_GFM_RE : HARD_RETURN_RE , sections = text . split ( splitRe ) , reflowed = [ ] ; sections . forEach ( function ( section ) { var words = section . split ( / [ \\t\\n]+ / ) , column = 0 , nextText = '' ; words . forEach ( function ( word ) { var addOne = column != 0 ; if ( ( column + textLength ( word ) + addOne ) > width ) { nextText += '\\n' ; column = 0 ; } else if ( addOne ) { nextText += \" \" ; column += 1 ; } nextText += word ; column += textLength ( word ) ; } ) ; reflowed . push ( nextText ) ; } ) ; return reflowed . join ( '\\n' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if a file path is absolute . [CODESPLIT] function isAbsolute ( fp ) { if ( typeof fp !== 'string' ) { throw new TypeError ( 'isAbsolute expects a string.' ) ; } if ( ! isWindows ( ) && isAbsolute . posix ( fp ) ) { return true ; } return isAbsolute . win32 ( fp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Repeat the given string the specified number of times . [CODESPLIT] function repeat ( str , num ) { if ( typeof str !== 'string' ) { throw new TypeError ( 'repeat-string expects a string.' ) ; } if ( num === 1 ) return str ; if ( num === 2 ) return str + str ; var max = str . length * num ; if ( cache !== str || typeof cache === 'undefined' ) { cache = str ; res = '' ; } while ( max > res . length && num > 0 ) { if ( num & 1 ) { res += str ; } num >>= 1 ; if ( ! num ) break ; str += str ; } return res . substr ( 0 , max ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "2 - a simple Set type is defined [CODESPLIT] function uniqSet ( arr ) { var seen = new Set ( ) ; return arr . filter ( function ( el ) { if ( ! seen . has ( el ) ) { seen . add ( el ) ; return true ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helper methods [CODESPLIT] function ( data , options ) { var handler = new DomHandler ( options ) ; new Parser ( handler , options ) . end ( data ) ; return handler . dom ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shows error message . Throws unless _continue or config . fatal are true [CODESPLIT] function error ( msg , _continue ) { if ( state . error === null ) state . error = '' ; state . error += state . currentCmd + ': ' + msg + '\\n' ; if ( msg . length > 0 ) log ( state . error ) ; if ( config . fatal ) process . exit ( 1 ) ; if ( ! _continue ) throw '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { alice : true bob : false } when passed a dictionary e . g . : parseOptions ( - a { a : alice b : bob } ) ; [CODESPLIT] function parseOptions ( str , map ) { if ( ! map ) error ( 'parseOptions() internal error: no map given' ) ; // All options are false by default var options = { } ; for ( var letter in map ) options [ map [ letter ] ] = false ; if ( ! str ) return options ; // defaults if ( typeof str !== 'string' ) error ( 'parseOptions() internal error: wrong str' ) ; // e.g. match[1] = 'Rf' for str = '-Rf' var match = str . match ( / ^\\-(.+) / ) ; if ( ! match ) return options ; // e.g. chars = ['R', 'f'] var chars = match [ 1 ] . split ( '' ) ; chars . forEach ( function ( c ) { if ( c in map ) options [ map [ c ] ] = true ; else error ( 'option not recognized: ' + c ) ; } ) ; return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expands wildcards with matching ( ie . existing ) file names . For example : expand ( [ file * . js ] ) = [ file1 . js file2 . js ... ] ( if the files file1 . js file2 . js etc exist in the current dir ) [CODESPLIT] function expand ( list ) { var expanded = [ ] ; list . forEach ( function ( listEl ) { // Wildcard present on directory names ? if ( listEl . search ( / \\*[^\\/]*\\/ / ) > - 1 || listEl . search ( / \\*\\*[^\\/]*\\/ / ) > - 1 ) { var match = listEl . match ( / ^([^*]+\\/|)(.*) / ) ; var root = match [ 1 ] ; var rest = match [ 2 ] ; var restRegex = rest . replace ( / \\*\\* / g , \".*\" ) . replace ( / \\* / g , \"[^\\\\/]*\" ) ; restRegex = new RegExp ( restRegex ) ; _ls ( '-R' , root ) . filter ( function ( e ) { return restRegex . test ( e ) ; } ) . forEach ( function ( file ) { expanded . push ( file ) ; } ) ; } // Wildcard present on file names ? else if ( listEl . search ( / \\* / ) > - 1 ) { _ls ( '' , listEl ) . forEach ( function ( file ) { expanded . push ( file ) ; } ) ; } else { expanded . push ( listEl ) ; } } ) ; return expanded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalizes _unlinkSync () across platforms to match Unix behavior i . e . file can be unlinked even if it s read - only see https : // github . com / joyent / node / issues / 3006 [CODESPLIT] function unlinkSync ( file ) { try { fs . unlinkSync ( file ) ; } catch ( e ) { // Try to override file permission if ( e . code === 'EPERM' ) { fs . chmodSync ( file , '0666' ) ; fs . unlinkSync ( file ) ; } else { throw e ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "e . g . shelljs_a5f185d0443ca ... [CODESPLIT] function randomFileName ( ) { function randomHash ( count ) { if ( count === 1 ) return parseInt ( 16 * Math . random ( ) , 10 ) . toString ( 16 ) ; else { var hash = '' ; for ( var i = 0 ; i < count ; i ++ ) hash += randomHash ( 1 ) ; return hash ; } } return 'shelljs_' + randomHash ( 20 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "extend ( target_obj source_obj1 [ source_obj2 ... ] ) Shallow extend e . g . : extend ( { A : 1 } { b : 2 } { c : 3 } ) returns { A : 1 b : 2 c : 3 } [CODESPLIT] function extend ( target ) { var sources = [ ] . slice . call ( arguments , 1 ) ; sources . forEach ( function ( source ) { for ( var key in source ) target [ key ] = source [ key ] ; } ) ; return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Common wrapper for all Unix - like commands [CODESPLIT] function wrap ( cmd , fn , options ) { return function ( ) { var retValue = null ; state . currentCmd = cmd ; state . error = null ; try { var args = [ ] . slice . call ( arguments , 0 ) ; if ( options && options . notUnix ) { retValue = fn . apply ( this , args ) ; } else { if ( args . length === 0 || typeof args [ 0 ] !== 'string' || args [ 0 ] [ 0 ] !== '-' ) args . unshift ( '' ) ; // only add dummy option if '-option' not already present retValue = fn . apply ( this , args ) ; } } catch ( e ) { if ( ! state . error ) { // If state.error hasn't been set it's an error thrown by Node, not us - probably a bug... console . log ( 'shell.js: internal error' ) ; console . log ( e . stack || e ) ; process . exit ( 1 ) ; } if ( config . fatal ) throw e ; } state . currentCmd = 'shell.js' ; return retValue ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conditionally pushes file to list - returns true if pushed false otherwise ( e . g . prevents hidden files to be included unless explicitly told so ) [CODESPLIT] function pushFile ( file , query ) { // hidden file? if ( path . basename ( file ) [ 0 ] === '.' ) { // not explicitly asking for hidden files? if ( ! options . all && ! ( path . basename ( query ) [ 0 ] === '.' && path . basename ( query ) . length > 1 ) ) return false ; } if ( common . platform === 'win' ) file = file . replace ( / \\\\ / g , '/' ) ; list . push ( file ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns false if dir is not a writeable directory dir otherwise [CODESPLIT] function writeableDir ( dir ) { if ( ! dir || ! fs . existsSync ( dir ) ) return false ; if ( ! fs . statSync ( dir ) . isDirectory ( ) ) return false ; var testFile = dir + '/' + common . randomFileName ( ) ; try { fs . writeFileSync ( testFile , ' ' ) ; common . unlinkSync ( testFile ) ; return dir ; } catch ( e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Buffered file copy synchronous ( Using readFileSync () + writeFileSync () could easily cause a memory overflow with large files ) [CODESPLIT] function copyFileSync ( srcFile , destFile ) { if ( ! fs . existsSync ( srcFile ) ) common . error ( 'copyFileSync: no such file or directory: ' + srcFile ) ; var BUF_LENGTH = 64 * 1024 , buf = new Buffer ( BUF_LENGTH ) , bytesRead = BUF_LENGTH , pos = 0 , fdr = null , fdw = null ; try { fdr = fs . openSync ( srcFile , 'r' ) ; } catch ( e ) { common . error ( 'copyFileSync: could not read src file (' + srcFile + ')' ) ; } try { fdw = fs . openSync ( destFile , 'w' ) ; } catch ( e ) { common . error ( 'copyFileSync: could not write to dest file (code=' + e . code + '):' + destFile ) ; } while ( bytesRead === BUF_LENGTH ) { bytesRead = fs . readSync ( fdr , buf , 0 , BUF_LENGTH , pos ) ; fs . writeSync ( fdw , buf , 0 , bytesRead ) ; pos += bytesRead ; } fs . closeSync ( fdr ) ; fs . closeSync ( fdw ) ; fs . chmodSync ( destFile , fs . statSync ( srcFile ) . mode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively copies sourceDir into destDir Adapted from https : // github . com / ryanmcgrath / wrench - js Copyright ( c ) 2010 Ryan McGrath Copyright ( c ) 2012 Artur Adib Licensed under the MIT License http : // www . opensource . org / licenses / mit - license . php [CODESPLIT] function cpdirSyncRecursive ( sourceDir , destDir , opts ) { if ( ! opts ) opts = { } ; /* Create the directory where all our junk is moving to; read the mode of the source directory and mirror it */ var checkDir = fs . statSync ( sourceDir ) ; try { fs . mkdirSync ( destDir , checkDir . mode ) ; } catch ( e ) { //if the directory already exists, that's okay if ( e . code !== 'EEXIST' ) throw e ; } var files = fs . readdirSync ( sourceDir ) ; for ( var i = 0 ; i < files . length ; i ++ ) { var srcFile = sourceDir + \"/\" + files [ i ] ; var destFile = destDir + \"/\" + files [ i ] ; var srcFileStat = fs . lstatSync ( srcFile ) ; if ( srcFileStat . isDirectory ( ) ) { /* recursion this thing right on back. */ cpdirSyncRecursive ( srcFile , destFile , opts ) ; } else if ( srcFileStat . isSymbolicLink ( ) ) { var symlinkFull = fs . readlinkSync ( srcFile ) ; fs . symlinkSync ( symlinkFull , destFile , os . platform ( ) === \"win32\" ? \"junction\" : null ) ; } else { /* At this point, we've hit a file actually worth copying... so copy it on over. */ if ( fs . existsSync ( destFile ) && ! opts . force ) { common . log ( 'skipping existing file: ' + files [ i ] ) ; } else { copyFileSync ( srcFile , destFile ) ; } } } // for files }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively creates dir [CODESPLIT] function mkdirSyncRecursive ( dir ) { var baseDir = path . dirname ( dir ) ; // Base dir exists, no recursion necessary if ( fs . existsSync ( baseDir ) ) { fs . mkdirSync ( dir , parseInt ( '0777' , 8 ) ) ; return ; } // Base dir does not exist, go recursive mkdirSyncRecursive ( baseDir ) ; // Base dir created, can create dir fs . mkdirSync ( dir , parseInt ( '0777' , 8 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cross - platform method for splitting environment PATH variables [CODESPLIT] function splitPath ( p ) { for ( i = 1 ; i < 2 ; i ++ ) { } if ( ! p ) return [ ] ; if ( common . platform === 'win' ) return p . split ( ';' ) ; else return p . split ( ':' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hack to run child_process . exec () synchronously ( sync avoids callback hell ) Uses a custom wait loop that checks for a flag file created when the child process is done . ( Can t do a wait loop that checks for internal Node variables / messages as Node is single - threaded ; callbacks and other internal state changes are done in the event loop ) . [CODESPLIT] function execSync ( cmd , opts ) { var tempDir = _tempDir ( ) ; var stdoutFile = path . resolve ( tempDir + '/' + common . randomFileName ( ) ) , codeFile = path . resolve ( tempDir + '/' + common . randomFileName ( ) ) , scriptFile = path . resolve ( tempDir + '/' + common . randomFileName ( ) ) , sleepFile = path . resolve ( tempDir + '/' + common . randomFileName ( ) ) ; var options = common . extend ( { silent : common . config . silent } , opts ) ; var previousStdoutContent = '' ; // Echoes stdout changes from running process, if not silent function updateStdout ( ) { if ( options . silent || ! fs . existsSync ( stdoutFile ) ) return ; var stdoutContent = fs . readFileSync ( stdoutFile , 'utf8' ) ; // No changes since last time? if ( stdoutContent . length <= previousStdoutContent . length ) return ; process . stdout . write ( stdoutContent . substr ( previousStdoutContent . length ) ) ; previousStdoutContent = stdoutContent ; } function escape ( str ) { return ( str + '' ) . replace ( / ([\\\\\"']) / g , \"\\\\$1\" ) . replace ( / \\0 / g , \"\\\\0\" ) ; } if ( fs . existsSync ( scriptFile ) ) common . unlinkSync ( scriptFile ) ; if ( fs . existsSync ( stdoutFile ) ) common . unlinkSync ( stdoutFile ) ; if ( fs . existsSync ( codeFile ) ) common . unlinkSync ( codeFile ) ; var execCommand = '\"' + process . execPath + '\" ' + scriptFile ; var execOptions = { env : process . env , cwd : _pwd ( ) , maxBuffer : 20 * 1024 * 1024 } ; if ( typeof child . execSync === 'function' ) { var script = [ \"var child = require('child_process')\" , \"  , fs = require('fs');\" , \"var childProcess = child.exec('\" + escape ( cmd ) + \"', {env: process.env, maxBuffer: 20*1024*1024}, function(err) {\" , \"  fs.writeFileSync('\" + escape ( codeFile ) + \"', err ? err.code.toString() : '0');\" , \"});\" , \"var stdoutStream = fs.createWriteStream('\" + escape ( stdoutFile ) + \"');\" , \"childProcess.stdout.pipe(stdoutStream, {end: false});\" , \"childProcess.stderr.pipe(stdoutStream, {end: false});\" , \"childProcess.stdout.pipe(process.stdout);\" , \"childProcess.stderr.pipe(process.stderr);\" , \"var stdoutEnded = false, stderrEnded = false;\" , \"function tryClosing(){ if(stdoutEnded && stderrEnded){ stdoutStream.end(); } }\" , \"childProcess.stdout.on('end', function(){ stdoutEnded = true; tryClosing(); });\" , \"childProcess.stderr.on('end', function(){ stderrEnded = true; tryClosing(); });\" ] . join ( '\\n' ) ; fs . writeFileSync ( scriptFile , script ) ; if ( options . silent ) { execOptions . stdio = 'ignore' ; } else { execOptions . stdio = [ 0 , 1 , 2 ] ; } // Welcome to the future child . execSync ( execCommand , execOptions ) ; } else { cmd += ' > ' + stdoutFile + ' 2>&1' ; // works on both win/unix var script = [ \"var child = require('child_process')\" , \"  , fs = require('fs');\" , \"var childProcess = child.exec('\" + escape ( cmd ) + \"', {env: process.env, maxBuffer: 20*1024*1024}, function(err) {\" , \"  fs.writeFileSync('\" + escape ( codeFile ) + \"', err ? err.code.toString() : '0');\" , \"});\" ] . join ( '\\n' ) ; fs . writeFileSync ( scriptFile , script ) ; child . exec ( execCommand , execOptions ) ; // The wait loop // sleepFile is used as a dummy I/O op to mitigate unnecessary CPU usage // (tried many I/O sync ops, writeFileSync() seems to be only one that is effective in reducing // CPU usage, though apparently not so much on Windows) while ( ! fs . existsSync ( codeFile ) ) { updateStdout ( ) ; fs . writeFileSync ( sleepFile , 'a' ) ; } while ( ! fs . existsSync ( stdoutFile ) ) { updateStdout ( ) ; fs . writeFileSync ( sleepFile , 'a' ) ; } } // At this point codeFile exists, but it's not necessarily flushed yet. // Keep reading it until it is. var code = parseInt ( '' , 10 ) ; while ( isNaN ( code ) ) { code = parseInt ( fs . readFileSync ( codeFile , 'utf8' ) , 10 ) ; } var stdout = fs . readFileSync ( stdoutFile , 'utf8' ) ; // No biggie if we can't erase the files now -- they're in a temp dir anyway try { common . unlinkSync ( scriptFile ) ; } catch ( e ) { } try { common . unlinkSync ( stdoutFile ) ; } catch ( e ) { } try { common . unlinkSync ( codeFile ) ; } catch ( e ) { } try { common . unlinkSync ( sleepFile ) ; } catch ( e ) { } // some shell return codes are defined as errors, per http://tldp.org/LDP/abs/html/exitcodes.html if ( code === 1 || code === 2 || code >= 126 ) { common . error ( '' , true ) ; // unix/shell doesn't really give an error message after non-zero exit codes } // True if successful, false if not var obj = { code : code , output : stdout } ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Echoes stdout changes from running process if not silent [CODESPLIT] function updateStdout ( ) { if ( options . silent || ! fs . existsSync ( stdoutFile ) ) return ; var stdoutContent = fs . readFileSync ( stdoutFile , 'utf8' ) ; // No changes since last time? if ( stdoutContent . length <= previousStdoutContent . length ) return ; process . stdout . write ( stdoutContent . substr ( previousStdoutContent . length ) ) ; previousStdoutContent = stdoutContent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "execSync () Wrapper around exec () to enable echoing output to console in real time [CODESPLIT] function execAsync ( cmd , opts , callback ) { var output = '' ; var options = common . extend ( { silent : common . config . silent } , opts ) ; var c = child . exec ( cmd , { env : process . env , maxBuffer : 20 * 1024 * 1024 } , function ( err ) { if ( callback ) callback ( err ? err . code : 0 , output ) ; } ) ; c . stdout . on ( 'data' , function ( data ) { output += data ; if ( ! options . silent ) process . stdout . write ( data ) ; } ) ; c . stderr . on ( 'data' , function ( data ) { output += data ; if ( ! options . silent ) process . stdout . write ( data ) ; } ) ; return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds ANSI color escape codes if enabled . [CODESPLIT] function formatArgs ( ) { var args = arguments ; var useColors = this . useColors ; var name = this . namespace ; if ( useColors ) { var c = this . color ; args [ 0 ] = '  \\u001b[3' + c + ';1m' + name + ' ' + '\\u001b[0m' + args [ 0 ] + '\\u001b[3' + c + 'm' + ' +' + exports . humanize ( this . diff ) + '\\u001b[0m' ; } else { args [ 0 ] = new Date ( ) . toUTCString ( ) + ' ' + name + ' ' + args [ 0 ] ; } return args ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new GNTP request of the given type . [CODESPLIT] function GNTP ( type , opts ) { opts = opts || { } ; this . type = type ; this . host = opts . host || 'localhost' ; this . port = opts . port || 23053 ; this . request = 'GNTP/1.0 ' + type + ' NONE' + nl ; this . resources = [ ] ; this . attempts = 0 ; this . maxAttempts = 5 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interface for registering Growl applications and sending Growl notifications . [CODESPLIT] function Growly ( ) { this . appname = 'Growly' ; this . notifications = undefined ; this . labels = undefined ; this . count = 0 ; this . registered = false ; this . host = undefined ; this . port = undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a new Command . [CODESPLIT] function Command ( name ) { this . commands = [ ] ; this . options = [ ] ; this . _execs = [ ] ; this . _allowUnknownOption = false ; this . _args = [ ] ; this . _name = name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a duplicate - free version of an array using [ SameValueZero ] ( http : // ecma - international . org / ecma - 262 / 6 . 0 / #sec - samevaluezero ) for equality comparisons in which only the first occurence of each element is kept . Providing true for isSorted performs a faster search algorithm for sorted arrays . If an iteratee function is provided it is invoked for each element in the array to generate the criterion by which uniqueness is computed . The iteratee is bound to thisArg and invoked with three arguments : ( value index array ) . [CODESPLIT] function uniq ( array , isSorted , iteratee , thisArg ) { var length = array ? array . length : 0 ; if ( ! length ) { return [ ] ; } if ( isSorted != null && typeof isSorted != 'boolean' ) { thisArg = iteratee ; iteratee = isIterateeCall ( array , isSorted , thisArg ) ? undefined : isSorted ; isSorted = false ; } iteratee = iteratee == null ? iteratee : baseCallback ( iteratee , thisArg , 3 ) ; return ( isSorted ) ? sortedUniq ( array , iteratee ) : baseUniq ( array , iteratee ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The base implementation of _ . difference which accepts a single array of values to exclude . [CODESPLIT] function baseDifference ( array , values ) { var length = array ? array . length : 0 , result = [ ] ; if ( ! length ) { return result ; } var index = - 1 , indexOf = baseIndexOf , isCommon = true , cache = ( isCommon && values . length >= LARGE_ARRAY_SIZE ) ? createCache ( values ) : null , valuesLength = values . length ; if ( cache ) { indexOf = cacheIndexOf ; isCommon = false ; values = cache ; } outer : while ( ++ index < length ) { var value = array [ index ] ; if ( isCommon && value === value ) { var valuesIndex = valuesLength ; while ( valuesIndex -- ) { if ( values [ valuesIndex ] === value ) { continue outer ; } } result . push ( value ) ; } else if ( indexOf ( values , value , 0 ) < 0 ) { result . push ( value ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### AssertionError [CODESPLIT] function AssertionError ( message , _props , ssf ) { var extend = exclude ( 'name' , 'message' , 'stack' , 'constructor' , 'toJSON' ) , props = extend ( _props || { } ) ; // default values this . message = message || 'Unspecified AssertionError' ; this . showDiff = false ; // copy from properties for ( var key in props ) { this [ key ] = props [ key ] ; } // capture stack trace ssf = ssf || arguments . callee ; if ( ssf && Error . captureStackTrace ) { Error . captureStackTrace ( this , ssf ) ; } else { this . stack = new Error ( ) . stack ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Extract a punctuator out of the next sequence of characters or return null if its not possible . [CODESPLIT] function ( ) { var ch1 = this . peek ( ) ; var ch2 , ch3 , ch4 ; switch ( ch1 ) { // Most common single-character punctuators case \".\" : if ( ( / ^[0-9]$ / ) . test ( this . peek ( 1 ) ) ) { return null ; } if ( this . peek ( 1 ) === \".\" && this . peek ( 2 ) === \".\" ) { return { type : Token . Punctuator , value : \"...\" } ; } /* falls through */ case \"(\" : case \")\" : case \";\" : case \",\" : case \"[\" : case \"]\" : case \":\" : case \"~\" : case \"?\" : return { type : Token . Punctuator , value : ch1 } ; // A block/object opener case \"{\" : this . pushContext ( Context . Block ) ; return { type : Token . Punctuator , value : ch1 } ; // A block/object closer case \"}\" : if ( this . inContext ( Context . Block ) ) { this . popContext ( ) ; } return { type : Token . Punctuator , value : ch1 } ; // A pound sign (for Node shebangs) case \"#\" : return { type : Token . Punctuator , value : ch1 } ; // We're at the end of input case \"\" : return null ; } // Peek more characters ch2 = this . peek ( 1 ) ; ch3 = this . peek ( 2 ) ; ch4 = this . peek ( 3 ) ; // 4-character punctuator: >>>= if ( ch1 === \">\" && ch2 === \">\" && ch3 === \">\" && ch4 === \"=\" ) { return { type : Token . Punctuator , value : \">>>=\" } ; } // 3-character punctuators: === !== >>> <<= >>= if ( ch1 === \"=\" && ch2 === \"=\" && ch3 === \"=\" ) { return { type : Token . Punctuator , value : \"===\" } ; } if ( ch1 === \"!\" && ch2 === \"=\" && ch3 === \"=\" ) { return { type : Token . Punctuator , value : \"!==\" } ; } if ( ch1 === \">\" && ch2 === \">\" && ch3 === \">\" ) { return { type : Token . Punctuator , value : \">>>\" } ; } if ( ch1 === \"<\" && ch2 === \"<\" && ch3 === \"=\" ) { return { type : Token . Punctuator , value : \"<<=\" } ; } if ( ch1 === \">\" && ch2 === \">\" && ch3 === \"=\" ) { return { type : Token . Punctuator , value : \">>=\" } ; } // Fat arrow punctuator if ( ch1 === \"=\" && ch2 === \">\" ) { return { type : Token . Punctuator , value : ch1 + ch2 } ; } // 2-character punctuators: <= >= == != ++ -- << >> && || // += -= *= %= &= |= ^= (but not /=, see below) if ( ch1 === ch2 && ( \"+-<>&|\" . indexOf ( ch1 ) >= 0 ) ) { return { type : Token . Punctuator , value : ch1 + ch2 } ; } if ( \"<>=!+-*%&|^\" . indexOf ( ch1 ) >= 0 ) { if ( ch2 === \"=\" ) { return { type : Token . Punctuator , value : ch1 + ch2 } ; } return { type : Token . Punctuator , value : ch1 } ; } // Special case: /=. if ( ch1 === \"/\" ) { if ( ch2 === \"=\" ) { return { type : Token . Punctuator , value : \"/=\" } ; } return { type : Token . Punctuator , value : \"/\" } ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Extract a numeric literal out of the next sequence of characters or return null if its not possible . This method supports all numeric literals described in section 7 . 8 . 3 of the EcmaScript 5 specification . [CODESPLIT] function ( ) { var index = 0 ; var value = \"\" ; var length = this . input . length ; var char = this . peek ( index ) ; var bad ; var isAllowedDigit = isDecimalDigit ; var base = 10 ; var isLegacy = false ; function isDecimalDigit ( str ) { return ( / ^[0-9]$ / ) . test ( str ) ; } function isOctalDigit ( str ) { return ( / ^[0-7]$ / ) . test ( str ) ; } function isBinaryDigit ( str ) { return ( / ^[01]$ / ) . test ( str ) ; } function isHexDigit ( str ) { return ( / ^[0-9a-fA-F]$ / ) . test ( str ) ; } function isIdentifierStart ( ch ) { return ( ch === \"$\" ) || ( ch === \"_\" ) || ( ch === \"\\\\\" ) || ( ch >= \"a\" && ch <= \"z\" ) || ( ch >= \"A\" && ch <= \"Z\" ) ; } // Numbers must start either with a decimal digit or a point. if ( char !== \".\" && ! isDecimalDigit ( char ) ) { return null ; } if ( char !== \".\" ) { value = this . peek ( index ) ; index += 1 ; char = this . peek ( index ) ; if ( value === \"0\" ) { // Base-16 numbers. if ( char === \"x\" || char === \"X\" ) { isAllowedDigit = isHexDigit ; base = 16 ; index += 1 ; value += char ; } // Base-8 numbers. if ( char === \"o\" || char === \"O\" ) { isAllowedDigit = isOctalDigit ; base = 8 ; if ( ! state . option . esnext ) { this . trigger ( \"warning\" , { code : \"W119\" , line : this . line , character : this . char , data : [ \"Octal integer literal\" ] } ) ; } index += 1 ; value += char ; } // Base-2 numbers. if ( char === \"b\" || char === \"B\" ) { isAllowedDigit = isBinaryDigit ; base = 2 ; if ( ! state . option . esnext ) { this . trigger ( \"warning\" , { code : \"W119\" , line : this . line , character : this . char , data : [ \"Binary integer literal\" ] } ) ; } index += 1 ; value += char ; } // Legacy base-8 numbers. if ( isOctalDigit ( char ) ) { isAllowedDigit = isOctalDigit ; base = 8 ; isLegacy = true ; bad = false ; index += 1 ; value += char ; } // Decimal numbers that start with '0' such as '09' are illegal // but we still parse them and return as malformed. if ( ! isOctalDigit ( char ) && isDecimalDigit ( char ) ) { index += 1 ; value += char ; } } while ( index < length ) { char = this . peek ( index ) ; if ( isLegacy && isDecimalDigit ( char ) ) { // Numbers like '019' (note the 9) are not valid octals // but we still parse them and mark as malformed. bad = true ; } else if ( ! isAllowedDigit ( char ) ) { break ; } value += char ; index += 1 ; } if ( isAllowedDigit !== isDecimalDigit ) { if ( ! isLegacy && value . length <= 2 ) { // 0x return { type : Token . NumericLiteral , value : value , isMalformed : true } ; } if ( index < length ) { char = this . peek ( index ) ; if ( isIdentifierStart ( char ) ) { return null ; } } return { type : Token . NumericLiteral , value : value , base : base , isLegacy : isLegacy , isMalformed : false } ; } } // Decimal digits. if ( char === \".\" ) { value += char ; index += 1 ; while ( index < length ) { char = this . peek ( index ) ; if ( ! isDecimalDigit ( char ) ) { break ; } value += char ; index += 1 ; } } // Exponent part. if ( char === \"e\" || char === \"E\" ) { value += char ; index += 1 ; char = this . peek ( index ) ; if ( char === \"+\" || char === \"-\" ) { value += this . peek ( index ) ; index += 1 ; } char = this . peek ( index ) ; if ( isDecimalDigit ( char ) ) { value += char ; index += 1 ; while ( index < length ) { char = this . peek ( index ) ; if ( ! isDecimalDigit ( char ) ) { break ; } value += char ; index += 1 ; } } else { return null ; } } if ( index < length ) { char = this . peek ( index ) ; if ( isIdentifierStart ( char ) ) { return null ; } } return { type : Token . NumericLiteral , value : value , base : base , isMalformed : ! isFinite ( value ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assumes previously parsed character was \\ ( === \\\\ ) and was not skipped . [CODESPLIT] function ( checks ) { var allowNewLine = false ; var jump = 1 ; this . skip ( ) ; var char = this . peek ( ) ; switch ( char ) { case \"'\" : this . triggerAsync ( \"warning\" , { code : \"W114\" , line : this . line , character : this . char , data : [ \"\\\\'\" ] } , checks , function ( ) { return state . jsonMode ; } ) ; break ; case \"b\" : char = \"\\\\b\" ; break ; case \"f\" : char = \"\\\\f\" ; break ; case \"n\" : char = \"\\\\n\" ; break ; case \"r\" : char = \"\\\\r\" ; break ; case \"t\" : char = \"\\\\t\" ; break ; case \"0\" : char = \"\\\\0\" ; // Octal literals fail in strict mode. // Check if the number is between 00 and 07. var n = parseInt ( this . peek ( 1 ) , 10 ) ; this . triggerAsync ( \"warning\" , { code : \"W115\" , line : this . line , character : this . char } , checks , function ( ) { return n >= 0 && n <= 7 && state . isStrict ( ) ; } ) ; break ; case \"u\" : var hexCode = this . input . substr ( 1 , 4 ) ; var code = parseInt ( hexCode , 16 ) ; if ( isNaN ( code ) ) { this . trigger ( \"warning\" , { code : \"W052\" , line : this . line , character : this . char , data : [ \"u\" + hexCode ] } ) ; } char = String . fromCharCode ( code ) ; jump = 5 ; break ; case \"v\" : this . triggerAsync ( \"warning\" , { code : \"W114\" , line : this . line , character : this . char , data : [ \"\\\\v\" ] } , checks , function ( ) { return state . jsonMode ; } ) ; char = \"\\v\" ; break ; case \"x\" : var x = parseInt ( this . input . substr ( 1 , 2 ) , 16 ) ; this . triggerAsync ( \"warning\" , { code : \"W114\" , line : this . line , character : this . char , data : [ \"\\\\x-\" ] } , checks , function ( ) { return state . jsonMode ; } ) ; char = String . fromCharCode ( x ) ; jump = 3 ; break ; case \"\\\\\" : char = \"\\\\\\\\\" ; break ; case \"\\\"\" : char = \"\\\\\\\"\" ; break ; case \"/\" : break ; case \"\" : allowNewLine = true ; char = \"\" ; break ; } return { char : char , jump : jump , allowNewLine : allowNewLine } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Extract a template literal out of the next sequence of characters and / or lines or return null if its not possible . Since template literals can span across multiple lines this method has to move the char pointer . [CODESPLIT] function ( checks ) { var tokenType ; var value = \"\" ; var ch ; var startLine = this . line ; var startChar = this . char ; var depth = this . templateStarts . length ; if ( ! state . option . esnext ) { // Only lex template strings in ESNext mode. return null ; } else if ( this . peek ( ) === \"`\" ) { // Template must start with a backtick. tokenType = Token . TemplateHead ; this . templateStarts . push ( { line : this . line , char : this . char } ) ; depth = this . templateStarts . length ; this . skip ( 1 ) ; this . pushContext ( Context . Template ) ; } else if ( this . inContext ( Context . Template ) && this . peek ( ) === \"}\" ) { // If we're in a template context, and we have a '}', lex a TemplateMiddle. tokenType = Token . TemplateMiddle ; } else { // Go lex something else. return null ; } while ( this . peek ( ) !== \"`\" ) { while ( ( ch = this . peek ( ) ) === \"\" ) { value += \"\\n\" ; if ( ! this . nextLine ( ) ) { // Unclosed template literal --- point to the starting \"`\" var startPos = this . templateStarts . pop ( ) ; this . trigger ( \"error\" , { code : \"E052\" , line : startPos . line , character : startPos . char } ) ; return { type : tokenType , value : value , startLine : startLine , startChar : startChar , isUnclosed : true , depth : depth , context : this . popContext ( ) } ; } } if ( ch === '$' && this . peek ( 1 ) === '{' ) { value += '${' ; this . skip ( 2 ) ; return { type : tokenType , value : value , startLine : startLine , startChar : startChar , isUnclosed : false , depth : depth , context : this . currentContext ( ) } ; } else if ( ch === '\\\\' ) { var escape = this . scanEscapeSequence ( checks ) ; value += escape . char ; this . skip ( escape . jump ) ; } else if ( ch !== '`' ) { // Otherwise, append the value and continue. value += ch ; this . skip ( 1 ) ; } } // Final value is either NoSubstTemplate or TemplateTail tokenType = tokenType === Token . TemplateHead ? Token . NoSubstTemplate : Token . TemplateTail ; this . skip ( 1 ) ; this . templateStarts . pop ( ) ; return { type : tokenType , value : value , startLine : startLine , startChar : startChar , isUnclosed : false , depth : depth , context : this . popContext ( ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Extract a string out of the next sequence of characters and / or lines or return null if its not possible . Since strings can span across multiple lines this method has to move the char pointer . [CODESPLIT] function ( checks ) { /*jshint loopfunc:true */ var quote = this . peek ( ) ; // String must start with a quote. if ( quote !== \"\\\"\" && quote !== \"'\" ) { return null ; } // In JSON strings must always use double quotes. this . triggerAsync ( \"warning\" , { code : \"W108\" , line : this . line , character : this . char // +1? } , checks , function ( ) { return state . jsonMode && quote !== \"\\\"\" ; } ) ; var value = \"\" ; var startLine = this . line ; var startChar = this . char ; var allowNewLine = false ; this . skip ( ) ; while ( this . peek ( ) !== quote ) { if ( this . peek ( ) === \"\" ) { // End Of Line // If an EOL is not preceded by a backslash, show a warning // and proceed like it was a legit multi-line string where // author simply forgot to escape the newline symbol. // // Another approach is to implicitly close a string on EOL // but it generates too many false positives. if ( ! allowNewLine ) { this . trigger ( \"warning\" , { code : \"W112\" , line : this . line , character : this . char } ) ; } else { allowNewLine = false ; // Otherwise show a warning if multistr option was not set. // For JSON, show warning no matter what. this . triggerAsync ( \"warning\" , { code : \"W043\" , line : this . line , character : this . char } , checks , function ( ) { return ! state . option . multistr ; } ) ; this . triggerAsync ( \"warning\" , { code : \"W042\" , line : this . line , character : this . char } , checks , function ( ) { return state . jsonMode && state . option . multistr ; } ) ; } // If we get an EOF inside of an unclosed string, show an // error and implicitly close it at the EOF point. if ( ! this . nextLine ( ) ) { this . trigger ( \"error\" , { code : \"E029\" , line : startLine , character : startChar } ) ; return { type : Token . StringLiteral , value : value , startLine : startLine , startChar : startChar , isUnclosed : true , quote : quote } ; } } else { // Any character other than End Of Line allowNewLine = false ; var char = this . peek ( ) ; var jump = 1 ; // A length of a jump, after we're done // parsing this character. if ( char < \" \" ) { // Warn about a control character in a string. this . trigger ( \"warning\" , { code : \"W113\" , line : this . line , character : this . char , data : [ \"<non-printable>\" ] } ) ; } // Special treatment for some escaped characters. if ( char === \"\\\\\" ) { var parsed = this . scanEscapeSequence ( checks ) ; char = parsed . char ; jump = parsed . jump ; allowNewLine = parsed . allowNewLine ; } value += char ; this . skip ( jump ) ; } } this . skip ( ) ; return { type : Token . StringLiteral , value : value , startLine : startLine , startChar : startChar , isUnclosed : false , quote : quote } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds an indentifier to the relevant current scope and creates warnings / errors as necessary name : string opts : { type : string token : token isblockscoped : bool } [CODESPLIT] function addlabel ( name , opts ) { var type = opts . type ; var token = opts . token ; var isblockscoped = opts . isblockscoped ; // Define label in the current function in the current scope. if ( type === \"exception\" ) { if ( _ . has ( funct [ \"(context)\" ] , name ) ) { if ( funct [ name ] !== true && ! state . option . node ) { warning ( \"W002\" , state . tokens . next , name ) ; } } } if ( _ . has ( funct , name ) && ! funct [ \"(global)\" ] ) { if ( funct [ name ] === true ) { if ( state . option . latedef ) { if ( ( state . option . latedef === true && _ . contains ( [ funct [ name ] , type ] , \"unction\" ) ) || ! _ . contains ( [ funct [ name ] , type ] , \"unction\" ) ) { warning ( \"W003\" , state . tokens . next , name ) ; } } } else { if ( ( ! state . option . shadow || _ . contains ( [ \"inner\" , \"outer\" ] , state . option . shadow ) ) && type !== \"exception\" || funct [ \"(blockscope)\" ] . getlabel ( name ) ) { warning ( \"W004\" , state . tokens . next , name ) ; } } } if ( funct [ \"(context)\" ] && _ . has ( funct [ \"(context)\" ] , name ) && type !== \"function\" ) { if ( state . option . shadow === \"outer\" ) { warning ( \"W123\" , state . tokens . next , name ) ; } } // if the identifier is blockscoped (a let or a const), add it only to the current blockscope if ( isblockscoped ) { funct [ \"(blockscope)\" ] . current . add ( name , type , state . tokens . curr ) ; if ( funct [ \"(blockscope)\" ] . atTop ( ) && exported [ name ] ) { state . tokens . curr . exported = true ; } } else { funct [ \"(blockscope)\" ] . shadow ( name ) ; funct [ name ] = type ; if ( token ) { funct [ \"(tokens)\" ] [ name ] = token ; } if ( funct [ \"(global)\" ] ) { global [ name ] = funct ; if ( _ . has ( implied , name ) ) { if ( state . option . latedef ) { if ( ( state . option . latedef === true && _ . contains ( [ funct [ name ] , type ] , \"unction\" ) ) || ! _ . contains ( [ funct [ name ] , type ] , \"unction\" ) ) { warning ( \"W003\" , state . tokens . next , name ) ; } } delete implied [ name ] ; } } else { scope [ name ] = funct ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We need a peek function . If it has an argument it peeks that much farther ahead . It is used to distinguish for ( var i in ... from for ( var i = ... [CODESPLIT] function peek ( p ) { var i = p || 0 , j = 0 , t ; while ( j <= i ) { t = lookahead [ j ] ; if ( ! t ) { t = lookahead [ j ] = lex . token ( ) ; } j += 1 ; } // Peeking past the end of the program should produce the \"(end)\" token. if ( ! t && state . tokens . next . id === \"(end)\" ) { return state . tokens . next ; } return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the typeof operator is used with the correct value . For docs on typeof see : https : // developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Operators / typeof [CODESPLIT] function isTypoTypeof ( left , right , state ) { var values ; if ( state . option . notypeof ) return false ; if ( ! left || ! right ) return false ; values = state . inESNext ( ) ? typeofValues . es6 : typeofValues . es3 ; if ( right . type === \"(identifier)\" && right . value === \"typeof\" && left . type === \"(string)\" ) return ! _ . contains ( values , left . value ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "fnparam means that this identifier is being defined as a function argument prop means that this identifier is that of an object property [CODESPLIT] function identifier ( fnparam , prop ) { var i = optionalidentifier ( fnparam , prop , false ) ; if ( i ) { return i ; } // parameter destructuring with rest operator if ( state . tokens . next . value === \"...\" ) { if ( ! state . option . esnext ) { warning ( \"W119\" , state . tokens . next , \"spread/rest operator\" ) ; } advance ( ) ; if ( checkPunctuators ( state . tokens . next , [ \"...\" ] ) ) { warning ( \"E024\" , state . tokens . next , \"...\" ) ; while ( checkPunctuators ( state . tokens . next , [ \"...\" ] ) ) { advance ( ) ; } } if ( ! state . tokens . next . identifier ) { warning ( \"E024\" , state . tokens . curr , \"...\" ) ; return ; } return identifier ( fnparam , prop ) ; } else { error ( \"E030\" , state . tokens . next , state . tokens . next . value ) ; // The token should be consumed after a warning is issued so the parser // can continue as though an identifier were found. The semicolon token // should not be consumed in this way so that the parser interprets it as // a statement delimeter; if ( state . tokens . next . id !== \";\" ) { advance ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether this function has been reached for a destructuring assign with undeclared values [CODESPLIT] function destructuringAssignOrJsonValue ( ) { // lookup for the assignment (esnext only) // if it has semicolons, it is a block, so go parse it as a block // or it's not a block, but there are assignments, check for undeclared variables var block = lookupBlockType ( ) ; if ( block . notJson ) { if ( ! state . inESNext ( ) && block . isDestAssign ) { warning ( \"W104\" , state . tokens . curr , \"destructuring assignment\" ) ; } statements ( ) ; // otherwise parse json value } else { state . option . laxbreak = true ; state . jsonMode = true ; jsonValue ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "array comprehension parsing function parses and defines the three states of the list comprehension in order to avoid defining global variables but keeping them to the list comprehension scope only . The order of the states are as follows : * use which will be the returned iterative part of the list comprehension * define which will define the variables local to the list comprehension * filter which will help filter out values [CODESPLIT] function ( ) { var CompArray = function ( ) { this . mode = \"use\" ; this . variables = [ ] ; } ; var _carrays = [ ] ; var _current ; function declare ( v ) { var l = _current . variables . filter ( function ( elt ) { // if it has, change its undef state if ( elt . value === v ) { elt . undef = false ; return v ; } } ) . length ; return l !== 0 ; } function use ( v ) { var l = _current . variables . filter ( function ( elt ) { // and if it has been defined if ( elt . value === v && ! elt . undef ) { if ( elt . unused === true ) { elt . unused = false ; } return v ; } } ) . length ; // otherwise we warn about it return ( l === 0 ) ; } return { stack : function ( ) { _current = new CompArray ( ) ; _carrays . push ( _current ) ; } , unstack : function ( ) { _current . variables . filter ( function ( v ) { if ( v . unused ) warning ( \"W098\" , v . token , v . raw_text || v . value ) ; if ( v . undef ) isundef ( v . funct , \"W117\" , v . token , v . value ) ; } ) ; _carrays . splice ( - 1 , 1 ) ; _current = _carrays [ _carrays . length - 1 ] ; } , setState : function ( s ) { if ( _ . contains ( [ \"use\" , \"define\" , \"generate\" , \"filter\" ] , s ) ) _current . mode = s ; } , check : function ( v ) { if ( ! _current ) { return ; } // When we are in \"use\" state of the list comp, we enqueue that var if ( _current && _current . mode === \"use\" ) { if ( use ( v ) ) { _current . variables . push ( { funct : funct , token : state . tokens . curr , value : v , undef : true , unused : false } ) ; } return true ; // When we are in \"define\" state of the list comp, } else if ( _current && _current . mode === \"define\" ) { // check if the variable has been used previously if ( ! declare ( v ) ) { _current . variables . push ( { funct : funct , token : state . tokens . curr , value : v , undef : false , unused : true } ) ; } return true ; // When we are in the \"generate\" state of the list comp, } else if ( _current && _current . mode === \"generate\" ) { isundef ( funct , \"W117\" , state . tokens . curr , v ) ; return true ; // When we are in \"filter\" state, } else if ( _current && _current . mode === \"filter\" ) { // we check whether current variable has been declared if ( use ( v ) ) { // if not we warn about it isundef ( funct , \"W117\" , state . tokens . curr , v ) ; } return true ; } return false ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The actual JSHINT function itself . [CODESPLIT] function ( s , o , g ) { var i , k , x , reIgnoreStr , reIgnore ; var optionKeys ; var newOptionObj = { } ; var newIgnoredObj = { } ; o = _ . clone ( o ) ; state . reset ( ) ; if ( o && o . scope ) { JSHINT . scope = o . scope ; } else { JSHINT . errors = [ ] ; JSHINT . undefs = [ ] ; JSHINT . internals = [ ] ; JSHINT . blacklist = { } ; JSHINT . scope = \"(main)\" ; } predefined = Object . create ( null ) ; combine ( predefined , vars . ecmaIdentifiers [ 3 ] ) ; combine ( predefined , vars . reservedVars ) ; combine ( predefined , g || { } ) ; declared = Object . create ( null ) ; exported = Object . create ( null ) ; function each ( obj , cb ) { if ( ! obj ) return ; if ( ! Array . isArray ( obj ) && typeof obj === \"object\" ) obj = Object . keys ( obj ) ; obj . forEach ( cb ) ; } if ( o ) { each ( o . predef || null , function ( item ) { var slice , prop ; if ( item [ 0 ] === \"-\" ) { slice = item . slice ( 1 ) ; JSHINT . blacklist [ slice ] = slice ; // remove from predefined if there delete predefined [ slice ] ; } else { prop = Object . getOwnPropertyDescriptor ( o . predef , item ) ; predefined [ item ] = prop ? prop . value : false ; } } ) ; each ( o . exported || null , function ( item ) { exported [ item ] = true ; } ) ; delete o . predef ; delete o . exported ; optionKeys = Object . keys ( o ) ; for ( x = 0 ; x < optionKeys . length ; x ++ ) { if ( / ^-W\\d{3}$ / g . test ( optionKeys [ x ] ) ) { newIgnoredObj [ optionKeys [ x ] . slice ( 1 ) ] = true ; } else { var optionKey = optionKeys [ x ] ; newOptionObj [ optionKey ] = o [ optionKey ] ; if ( optionKey === \"es5\" ) { if ( o [ optionKey ] ) { warning ( \"I003\" ) ; } } if ( optionKeys [ x ] === \"newcap\" && o [ optionKey ] === false ) newOptionObj [ \"(explicitNewcap)\" ] = true ; } } } state . option = newOptionObj ; state . ignored = newIgnoredObj ; state . option . indent = state . option . indent || 4 ; state . option . maxerr = state . option . maxerr || 50 ; indent = 1 ; global = Object . create ( predefined ) ; scope = global ; funct = functor ( \"(global)\" , null , scope , { \"(global)\" : true , \"(blockscope)\" : blockScope ( ) , \"(comparray)\" : arrayComprehension ( ) , \"(metrics)\" : createMetrics ( state . tokens . next ) } ) ; functions = [ funct ] ; urls = [ ] ; stack = null ; member = { } ; membersOnly = null ; implied = { } ; inblock = false ; lookahead = [ ] ; unuseds = [ ] ; if ( ! isString ( s ) && ! Array . isArray ( s ) ) { errorAt ( \"E004\" , 0 ) ; return false ; } api = { get isJSON ( ) { return state . jsonMode ; } , getOption : function ( name ) { return state . option [ name ] || null ; } , getCache : function ( name ) { return state . cache [ name ] ; } , setCache : function ( name , value ) { state . cache [ name ] = value ; } , warn : function ( code , data ) { warningAt . apply ( null , [ code , data . line , data . char ] . concat ( data . data ) ) ; } , on : function ( names , listener ) { names . split ( \" \" ) . forEach ( function ( name ) { emitter . on ( name , listener ) ; } . bind ( this ) ) ; } } ; emitter . removeAllListeners ( ) ; ( extraModules || [ ] ) . forEach ( function ( func ) { func ( api ) ; } ) ; state . tokens . prev = state . tokens . curr = state . tokens . next = state . syntax [ \"(begin)\" ] ; if ( o && o . ignoreDelimiters ) { if ( ! Array . isArray ( o . ignoreDelimiters ) ) { o . ignoreDelimiters = [ o . ignoreDelimiters ] ; } o . ignoreDelimiters . forEach ( function ( delimiterPair ) { if ( ! delimiterPair . start || ! delimiterPair . end ) return ; reIgnoreStr = escapeRegex ( delimiterPair . start ) + \"[\\\\s\\\\S]*?\" + escapeRegex ( delimiterPair . end ) ; reIgnore = new RegExp ( reIgnoreStr , \"ig\" ) ; s = s . replace ( reIgnore , function ( match ) { return match . replace ( / . / g , \" \" ) ; } ) ; } ) ; } lex = new Lexer ( s ) ; lex . on ( \"warning\" , function ( ev ) { warningAt . apply ( null , [ ev . code , ev . line , ev . character ] . concat ( ev . data ) ) ; } ) ; lex . on ( \"error\" , function ( ev ) { errorAt . apply ( null , [ ev . code , ev . line , ev . character ] . concat ( ev . data ) ) ; } ) ; lex . on ( \"fatal\" , function ( ev ) { quit ( \"E041\" , ev . line , ev . from ) ; } ) ; lex . on ( \"Identifier\" , function ( ev ) { emitter . emit ( \"Identifier\" , ev ) ; } ) ; lex . on ( \"String\" , function ( ev ) { emitter . emit ( \"String\" , ev ) ; } ) ; lex . on ( \"Number\" , function ( ev ) { emitter . emit ( \"Number\" , ev ) ; } ) ; lex . start ( ) ; // Check options for ( var name in o ) { if ( _ . has ( o , name ) ) { checkOption ( name , state . tokens . curr ) ; } } assume ( ) ; // combine the passed globals after we've assumed all our options combine ( predefined , g || { } ) ; //reset values comma . first = true ; try { advance ( ) ; switch ( state . tokens . next . id ) { case \"{\" : case \"[\" : destructuringAssignOrJsonValue ( ) ; break ; default : directives ( ) ; if ( state . isStrict ( ) ) { if ( ! state . option . globalstrict ) { if ( ! ( state . option . module || state . option . node || state . option . phantom || state . option . browserify ) ) { warning ( \"W097\" , state . tokens . prev ) ; } } } statements ( ) ; } if ( state . tokens . next . id !== \"(end)\" ) { quit ( \"E041\" , state . tokens . curr . line ) ; } funct [ \"(blockscope)\" ] . unstack ( ) ; var markDefined = function ( name , context ) { do { if ( typeof context [ name ] === \"string\" ) { // JSHINT marks unused variables as 'unused' and // unused function declaration as 'unction'. This // code changes such instances back 'var' and // 'closure' so that the code in JSHINT.data() // doesn't think they're unused. if ( context [ name ] === \"unused\" ) context [ name ] = \"var\" ; else if ( context [ name ] === \"unction\" ) context [ name ] = \"closure\" ; return true ; } context = context [ \"(context)\" ] ; } while ( context ) ; return false ; } ; var clearImplied = function ( name , line ) { if ( ! implied [ name ] ) return ; var newImplied = [ ] ; for ( var i = 0 ; i < implied [ name ] . length ; i += 1 ) { if ( implied [ name ] [ i ] !== line ) newImplied . push ( implied [ name ] [ i ] ) ; } if ( newImplied . length === 0 ) delete implied [ name ] ; else implied [ name ] = newImplied ; } ; var checkUnused = function ( func , key ) { var type = func [ key ] ; var tkn = func [ \"(tokens)\" ] [ key ] ; if ( key . charAt ( 0 ) === \"(\" ) return ; if ( type !== \"unused\" && type !== \"unction\" ) return ; // Params are checked separately from other variables. if ( func [ \"(params)\" ] && func [ \"(params)\" ] . indexOf ( key ) !== - 1 ) return ; // Variable is in global scope and defined as exported. if ( func [ \"(global)\" ] && _ . has ( exported , key ) ) return ; warnUnused ( key , tkn , \"var\" ) ; } ; // Check queued 'x is not defined' instances to see if they're still undefined. for ( i = 0 ; i < JSHINT . undefs . length ; i += 1 ) { k = JSHINT . undefs [ i ] . slice ( 0 ) ; if ( markDefined ( k [ 2 ] . value , k [ 0 ] ) || k [ 2 ] . forgiveUndef ) { clearImplied ( k [ 2 ] . value , k [ 2 ] . line ) ; } else if ( state . option . undef ) { warning . apply ( warning , k . slice ( 1 ) ) ; } } functions . forEach ( function ( func ) { if ( func [ \"(unusedOption)\" ] === false ) { return ; } for ( var key in func ) { if ( _ . has ( func , key ) ) { checkUnused ( func , key ) ; } } if ( ! func [ \"(params)\" ] ) return ; var params = func [ \"(params)\" ] . slice ( ) ; var param = params . pop ( ) ; var type , unused_opt ; while ( param ) { type = func [ param ] ; unused_opt = func [ \"(unusedOption)\" ] || state . option . unused ; unused_opt = unused_opt === true ? \"last-param\" : unused_opt ; // 'undefined' is a special case for (function(window, undefined) { ... })(); // patterns. if ( param === \"undefined\" ) return ; if ( type === \"unused\" || type === \"unction\" ) { warnUnused ( param , func [ \"(tokens)\" ] [ param ] , \"param\" , func [ \"(unusedOption)\" ] ) ; } else if ( unused_opt === \"last-param\" ) { return ; } param = params . pop ( ) ; } } ) ; for ( var key in declared ) { if ( _ . has ( declared , key ) && ! _ . has ( global , key ) && ! _ . has ( exported , key ) ) { warnUnused ( key , declared [ key ] , \"var\" ) ; } } } catch ( err ) { if ( err && err . name === \"JSHintError\" ) { var nt = state . tokens . next || { } ; JSHINT . errors . push ( { scope : \"(main)\" , raw : err . raw , code : err . code , reason : err . message , line : err . line || nt . line , character : err . character || nt . from } , null ) ; } else { throw err ; } } // Loop over the listed \"internals\", and check them as well. if ( JSHINT . scope === \"(main)\" ) { o = o || { } ; for ( i = 0 ; i < JSHINT . internals . length ; i += 1 ) { k = JSHINT . internals [ i ] ; o . scope = k . elem ; itself ( k . value , o , g ) ; } } return JSHINT . errors . length === 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Rename filepath using transformer [CODESPLIT] function rename ( filepath , transformer ) { var result ; /*\n        Return a file object\n    \n        {\n          dirname\n          basename\n          extname\n          origin\n        }\n      */ var fileObj = parse ( filepath ) ; if ( ! transformer ) { result = stringify ( fileObj ) ; debug ( 'transform to %s with no transformer' , result ) ; return result ; } /*\n        transformed object\n    \n        {\n          dirname\n          prefix\n          basename\n          suffix\n          extname\n        }\n      */ var transformed = util . isFunction ( transformer ) ? transformer ( fileObj ) : transformer ; // rename it when transformer is string as a filepath if ( util . isString ( transformed ) ) { result = transformed || stringify ( fileObj ) ; debug ( 'transform from %j to `%s` with %j' , fileObj , result , transformed ) ; return result ; } if ( ! util . isObject ( transformed ) ) { throw new Error ( 'transformer should be string, function or object.' ) ; } result = transform ( fileObj , transformed ) ; debug ( 'transform from %j to `%s` with %j' , fileObj , result , transformed ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * legacy parse method kept for backwards compatibility [CODESPLIT] function parseLegacy ( ext , content , fileName , customTags , withInlineFiles ) { return parse ( { ext : ext , content : content , fileName : fileName , customTags : customTags , withInlineFiles : withInlineFiles } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! ## parsePath ( path ) [CODESPLIT] function parsePath ( path ) { var str = path . replace ( / ([^\\\\])\\[ / g , '$1.[' ) , parts = str . match ( / (\\\\\\.|[^.]+?)+ / g ) ; return parts . map ( function ( value ) { var re = / ^\\[(\\d+)\\]$ / , mArr = re . exec ( value ) ; if ( mArr ) return { i : parseFloat ( mArr [ 1 ] ) } ; else return { p : value . replace ( / \\\\([.\\[\\]]) / g , '$1' ) } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### . keys ( key1 [ key2 ] [ ... ] ) [CODESPLIT] function assertKeys ( keys ) { var obj = flag ( this , 'object' ) , str , ok = true , mixedArgsMsg = 'keys must be given single argument of Array|Object|String, or multiple String arguments' ; switch ( _ . type ( keys ) ) { case \"array\" : if ( arguments . length > 1 ) throw ( new Error ( mixedArgsMsg ) ) ; break ; case \"object\" : if ( arguments . length > 1 ) throw ( new Error ( mixedArgsMsg ) ) ; keys = Object . keys ( keys ) ; break ; default : keys = Array . prototype . slice . call ( arguments ) ; } if ( ! keys . length ) throw new Error ( 'keys required' ) ; var actual = Object . keys ( obj ) , expected = keys , len = keys . length , any = flag ( this , 'any' ) , all = flag ( this , 'all' ) ; if ( ! any && ! all ) { all = true ; } // Has any if ( any ) { var intersection = expected . filter ( function ( key ) { return ~ actual . indexOf ( key ) ; } ) ; ok = intersection . length > 0 ; } // Has all if ( all ) { ok = keys . every ( function ( key ) { return ~ actual . indexOf ( key ) ; } ) ; if ( ! flag ( this , 'negate' ) && ! flag ( this , 'contains' ) ) { ok = ok && keys . length == actual . length ; } } // Key string if ( len > 1 ) { keys = keys . map ( function ( key ) { return _ . inspect ( key ) ; } ) ; var last = keys . pop ( ) ; if ( all ) { str = keys . join ( ', ' ) + ', and ' + last ; } if ( any ) { str = keys . join ( ', ' ) + ', or ' + last ; } } else { str = _ . inspect ( keys [ 0 ] ) ; } // Form str = ( len > 1 ? 'keys ' : 'key ' ) + str ; // Have / include str = ( flag ( this , 'contains' ) ? 'contain ' : 'have ' ) + str ; // Assertion this . assert ( ok , 'expected #{this} to ' + str , 'expected #{this} to not ' + str , expected . slice ( 0 ) . sort ( ) , actual . sort ( ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### . throw ( constructor ) [CODESPLIT] function assertThrows ( constructor , errMsg , msg ) { if ( msg ) flag ( this , 'message' , msg ) ; var obj = flag ( this , 'object' ) ; new Assertion ( obj , msg ) . is . a ( 'function' ) ; var thrown = false , desiredError = null , name = null , thrownError = null ; if ( arguments . length === 0 ) { errMsg = null ; constructor = null ; } else if ( constructor && ( constructor instanceof RegExp || 'string' === typeof constructor ) ) { errMsg = constructor ; constructor = null ; } else if ( constructor && constructor instanceof Error ) { desiredError = constructor ; constructor = null ; errMsg = null ; } else if ( typeof constructor === 'function' ) { name = constructor . prototype . name || constructor . name ; if ( name === 'Error' && constructor !== Error ) { name = ( new constructor ( ) ) . name ; } } else { constructor = null ; } try { obj ( ) ; } catch ( err ) { // first, check desired error if ( desiredError ) { this . assert ( err === desiredError , 'expected #{this} to throw #{exp} but #{act} was thrown' , 'expected #{this} to not throw #{exp}' , ( desiredError instanceof Error ? desiredError . toString ( ) : desiredError ) , ( err instanceof Error ? err . toString ( ) : err ) ) ; flag ( this , 'object' , err ) ; return this ; } // next, check constructor if ( constructor ) { this . assert ( err instanceof constructor , 'expected #{this} to throw #{exp} but #{act} was thrown' , 'expected #{this} to not throw #{exp} but #{act} was thrown' , name , ( err instanceof Error ? err . toString ( ) : err ) ) ; if ( ! errMsg ) { flag ( this , 'object' , err ) ; return this ; } } // next, check message var message = 'error' === _ . type ( err ) && \"message\" in err ? err . message : '' + err ; if ( ( message != null ) && errMsg && errMsg instanceof RegExp ) { this . assert ( errMsg . exec ( message ) , 'expected #{this} to throw error matching #{exp} but got #{act}' , 'expected #{this} to throw error not matching #{exp}' , errMsg , message ) ; flag ( this , 'object' , err ) ; return this ; } else if ( ( message != null ) && errMsg && 'string' === typeof errMsg ) { this . assert ( ~ message . indexOf ( errMsg ) , 'expected #{this} to throw error including #{exp} but got #{act}' , 'expected #{this} to throw error not including #{act}' , errMsg , message ) ; flag ( this , 'object' , err ) ; return this ; } else { thrown = true ; thrownError = err ; } } var actuallyGot = '' , expectedThrown = name !== null ? name : desiredError ? '#{exp}' //_.inspect(desiredError) : 'an error' ; if ( thrown ) { actuallyGot = ' but #{act} was thrown' } this . assert ( thrown === true , 'expected #{this} to throw ' + expectedThrown + actuallyGot , 'expected #{this} to not throw ' + expectedThrown + actuallyGot , ( desiredError instanceof Error ? desiredError . toString ( ) : desiredError ) , ( thrownError instanceof Error ? thrownError . toString ( ) : thrownError ) ) ; flag ( this , 'object' , thrownError ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### . respondTo ( method ) [CODESPLIT] function respondTo ( method , msg ) { if ( msg ) flag ( this , 'message' , msg ) ; var obj = flag ( this , 'object' ) , itself = flag ( this , 'itself' ) , context = ( 'function' === _ . type ( obj ) && ! itself ) ? obj . prototype [ method ] : obj [ method ] ; this . assert ( 'function' === typeof context , 'expected #{this} to respond to ' + _ . inspect ( method ) , 'expected #{this} to not respond to ' + _ . inspect ( method ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "### . change ( function ) [CODESPLIT] function assertChanges ( object , prop , msg ) { if ( msg ) flag ( this , 'message' , msg ) ; var fn = flag ( this , 'object' ) ; new Assertion ( object , msg ) . to . have . property ( prop ) ; new Assertion ( fn ) . is . a ( 'function' ) ; var initial = object [ prop ] ; fn ( ) ; this . assert ( initial !== object [ prop ] , 'expected .' + prop + ' to change' , 'expected .' + prop + ' to not change' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "explicitly define this method as function as to have it s name to include as ssfi [CODESPLIT] function shouldGetter ( ) { if ( this instanceof String || this instanceof Number || this instanceof Boolean ) { return new Assertion ( this . valueOf ( ) , null , shouldGetter ) ; } return new Assertion ( this , null , shouldGetter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the given function throws the given value when invoked . The value may be : [CODESPLIT] function functionThrows ( fn , context , args , value ) { try { fn . apply ( context , args ) ; } catch ( error ) { if ( value == null ) return true ; if ( _isFunction2 [ 'default' ] ( value ) && error instanceof value ) return true ; var message = error . message || error ; if ( typeof message === 'string' ) { if ( _isRegexp2 [ 'default' ] ( value ) && value . test ( error . message ) ) return true ; if ( typeof value === 'string' && message . indexOf ( value ) !== - 1 ) return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the given object is an instanceof value or its typeof is the given value . [CODESPLIT] function isA ( object , value ) { if ( _isFunction2 [ 'default' ] ( value ) ) return object instanceof value ; if ( value === 'array' ) return Array . isArray ( object ) ; return typeof object === value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add all options to the default command [CODESPLIT] function ( bin , opt ) { cmd = bin ; if ( opt . testing !== 'undefined' ) { opt . dryRun = opt . testing ; } if ( typeof opt . testSuite === 'undefined' ) { opt . testSuite = '' ; } if ( typeof opt . verbose === 'undefined' ) { opt . verbose = '' ; } if ( typeof opt . dryRun === 'undefined' ) { opt . dryRun = false ; } if ( typeof opt . silent === 'undefined' ) { opt . silent = false ; } if ( typeof opt . testing === 'undefined' ) { opt . testing = false ; } if ( typeof opt . debug === 'undefined' ) { opt . debug = false ; } if ( typeof opt . testClass === 'undefined' ) { opt . testClass = '' ; } if ( typeof opt . clear === 'undefined' ) { opt . clear = false ; } if ( typeof opt . flags === 'undefined' ) { opt . flags = '' ; } if ( typeof opt . notify === 'undefined' ) { opt . notify = false ; } if ( typeof opt . noInteraction === 'undefined' ) { opt . noInteraction = true ; } if ( typeof opt . noAnsi === 'undefined' ) { opt . noAnsi = false ; } if ( typeof opt . quiet === 'undefined' ) { opt . quiet = false ; } if ( typeof opt . formatter === 'undefined' ) { opt . formatter = '' ; } cmd = opt . clear ? 'clear && ' + cmd : cmd ; // assign default class and/or test suite if ( opt . testSuite ) { cmd += ' ' + opt . testSuite ; } if ( opt . testClass ) { cmd += ' ' + opt . testClass ; } if ( opt . verbose ) { cmd += ' -' + opt . verbose ; } if ( opt . formatter ) { cmd += ' -f' + opt . formatter ; } if ( opt . quiet ) { cmd += ' --quiet' ; } if ( opt . noInteraction ) { cmd += ' --no-interaction' ; } cmd += opt . noAnsi ? ' --no-ansi' : ' --ansi' ; cmd += ' ' + opt . flags ; cmd . trim ( ) ; // clean up any lingering space remnants return cmd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "how many arguments should we consume based on the nargs option? [CODESPLIT] function eatNargs ( i , key , args ) { var toEat = checkAllAliases ( key , opts . narg ) if ( args . length - ( i + 1 ) < toEat ) error = Error ( __ ( 'Not enough arguments following: %s' , key ) ) for ( var ii = i + 1 ; ii < ( toEat + i + 1 ) ; ii ++ ) { setArg ( key , args [ ii ] ) } return ( i + toEat ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if an option is an array eat all non - hyphenated arguments following it ... YUM! e . g . -- foo apple banana cat becomes [ apple banana cat ] [CODESPLIT] function eatArray ( i , key , args ) { for ( var ii = i + 1 ; ii < args . length ; ii ++ ) { if ( / ^- / . test ( args [ ii ] ) ) break i = ii setArg ( key , args [ ii ] ) } return i }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set args from config . json file this should be applied last so that defaults can be applied . [CODESPLIT] function setConfig ( argv ) { var configLookup = { } // expand defaults/aliases, in-case any happen to reference // the config.json file. applyDefaultsAndAliases ( configLookup , aliases , defaults ) Object . keys ( flags . configs ) . forEach ( function ( configKey ) { var configPath = argv [ configKey ] || configLookup [ configKey ] if ( configPath ) { try { var config = require ( path . resolve ( process . cwd ( ) , configPath ) ) Object . keys ( config ) . forEach ( function ( key ) { // setting arguments via CLI takes precedence over // values within the config file. if ( argv [ key ] === undefined || ( flags . defaulted [ key ] ) ) { delete argv [ key ] setArg ( key , config [ key ] ) } } ) } catch ( ex ) { if ( argv [ configKey ] ) error = Error ( __ ( 'Invalid JSON config file: %s' , configPath ) ) } } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "extend the aliases list with inferred aliases . [CODESPLIT] function extendAliases ( obj ) { Object . keys ( obj || { } ) . forEach ( function ( key ) { aliases [ key ] = [ ] . concat ( opts . alias [ key ] || [ ] ) // For \"--option-name\", also set argv.optionName aliases [ key ] . concat ( key ) . forEach ( function ( x ) { if ( / - / . test ( x ) ) { var c = camelCase ( x ) aliases [ key ] . push ( c ) newAliases [ c ] = true } } ) aliases [ key ] . forEach ( function ( x ) { aliases [ x ] = [ key ] . concat ( aliases [ key ] . filter ( function ( y ) { return x !== y } ) ) } ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check if a flag is set for any of a key s aliases . [CODESPLIT] function checkAllAliases ( key , flag ) { var isSet = false var toCheck = [ ] . concat ( aliases [ key ] || [ ] , key ) toCheck . forEach ( function ( key ) { if ( flag [ key ] ) isSet = flag [ key ] } ) return isSet }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "given a flag enforce a default type . [CODESPLIT] function guessType ( key , flags ) { var type = 'boolean' if ( flags . strings && flags . strings [ key ] ) type = 'string' else if ( flags . arrays && flags . arrays [ key ] ) type = 'array' return type }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return the maximum width of a string in the left - hand column of a table . [CODESPLIT] function maxWidth ( table ) { var width = 0 // table might be of the form [leftColumn], // or {key: leftColumn}} if ( ! Array . isArray ( table ) ) { table = Object . keys ( table ) . map ( function ( key ) { return [ table [ key ] ] } ) } table . forEach ( function ( v ) { width = Math . max ( v [ 0 ] . length , width ) } ) // if we've enabled 'wrap' we should limit // the max-width of the left-column. if ( wrap ) width = Math . min ( width , parseInt ( wrap * 0.5 , 10 ) ) return width }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "make sure any options set for aliases are copied to the keys being aliased . [CODESPLIT] function normalizeAliases ( ) { var demanded = yargs . getDemanded ( ) var options = yargs . getOptions ( ) ; ( Object . keys ( options . alias ) || [ ] ) . forEach ( function ( key ) { options . alias [ key ] . forEach ( function ( alias ) { // copy descriptions. if ( descriptions [ alias ] ) self . describe ( key , descriptions [ alias ] ) // copy demanded. if ( demanded [ alias ] ) yargs . demand ( key , demanded [ alias ] . msg ) // type messages. if ( ~ options . boolean . indexOf ( alias ) ) yargs . boolean ( key ) if ( ~ options . count . indexOf ( alias ) ) yargs . count ( key ) if ( ~ options . string . indexOf ( alias ) ) yargs . string ( key ) if ( ~ options . normalize . indexOf ( alias ) ) yargs . normalize ( key ) if ( ~ options . array . indexOf ( alias ) ) yargs . array ( key ) } ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "format the default - value - string displayed in the right - hand column . [CODESPLIT] function defaultString ( value , defaultDescription ) { var string = '[' + __ ( 'default:' ) + ' ' if ( value === undefined && ! defaultDescription ) return null if ( defaultDescription ) { string += defaultDescription } else { switch ( typeof value ) { case 'string' : string += JSON . stringify ( value ) break case 'object' : string += JSON . stringify ( value ) break default : string += value } } return string + ']' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Hack an instance of Argv with process . argv into Argv so people can do require ( yargs ) ( [ -- beeble = 1 - z zizzle ] ) . argv to parse a list of args and require ( yargs ) . argv to get a parsed version of process . argv . [CODESPLIT] function sigletonify ( inst ) { Object . keys ( inst ) . forEach ( function ( key ) { if ( key === 'argv' ) { Argv . __defineGetter__ ( key , inst . __lookupGetter__ ( key ) ) } else { Argv [ key ] = typeof inst [ key ] === 'function' ? inst [ key ] . bind ( inst ) : inst [ key ] } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find the value form with the given name in the attribute forms otherwise undefined [CODESPLIT] function find_attr_value ( attrForms , attrName ) { var attrVal ; var attrPos = - 1 ; if ( attrForms && Array . isArray ( attrForms ) ) { attrKey = attrForms . find ( function ( form , i ) { attrPos = i ; return ( i % 2 === 1 ) && form . value === attrName ; } ) if ( attrKey && attrPos + 1 < attrForms . length ) { attrVal = attrForms [ attrPos + 1 ] ; } } return attrVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get s user s passports if not on DAO [CODESPLIT] function ( options ) { options = options || { } if ( this . passports && this . passports . every ( t => t instanceof app . orm [ 'Passport' ] ) && options . reload !== true ) { return Promise . resolve ( this ) } else { return this . getPassports ( { transaction : options . transaction || null } ) . then ( passports => { passports = passports || [ ] this . passports = passports this . setDataValue ( 'passports' , passports ) this . set ( 'passports' , passports ) return this } ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Proxy to { @link Ext . Base#override } . Please refer { @link Ext . Base#override } for further details . [CODESPLIT] function ( cls , overrides ) { if ( cls . $isClass ) { return cls . override ( overrides ) ; } else { Ext . apply ( cls . prototype , overrides ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the type of the given variable in string format . List of possible values are : [CODESPLIT] function ( value ) { if ( value === null ) { return 'null' ; } var type = typeof value ; if ( type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean' ) { return type ; } var typeToString = toString . call ( value ) ; switch ( typeToString ) { case '[object Array]' : return 'array' ; case '[object Date]' : return 'date' ; case '[object Boolean]' : return 'boolean' ; case '[object Number]' : return 'number' ; case '[object RegExp]' : return 'regexp' ; } if ( type === 'function' ) { return 'function' ; } if ( type === 'object' ) { if ( value . nodeType !== undefined ) { if ( value . nodeType === 3 ) { return ( / \\S / ) . test ( value . nodeValue ) ? 'textnode' : 'whitespace' ; } else { return 'element' ; } } return 'object' ; } //<debug error> Ext . Error . raise ( { sourceClass : 'Ext' , sourceMethod : 'typeOf' , msg : 'Failed to determine the type of the specified value \"' + value + '\". This is most likely a bug.' } ) ; //</debug> }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "echo str > path . [CODESPLIT] function write ( path , str ) { fs . writeFileSync ( path , str ) ; console . log ( terminal . cyan ( pad ( 'create : ' ) ) + path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "mkdir - p [CODESPLIT] function mkdir ( path , silent ) { if ( ! exists ( path ) ) { fs . mkdirSync ( path , 0755 ) ; if ( ! silent ) console . log ( terminal . cyan ( pad ( 'create : ' ) ) + path ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests if path is empty . [CODESPLIT] function isEmptyDirectory ( path ) { var files ; try { files = fs . readdirSync ( path ) ; if ( files . length > 0 ) { return false ; } } catch ( err ) { if ( err . code ) { terminal . abort ( 'Error: ' , err ) ; } else { throw e ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "of the storage scheme JCM include the epoch of the clock here? [CODESPLIT] function ( config , callback , scope ) { // Ext . data . utilities . check ( 'DatabaseDefinition' , 'constructor' , 'config' , config , [ 'key' , 'database_name' , 'generation' , 'system_name' , 'replica_number' ] ) ; // this . set ( config ) ; config . config_id = 'definition' ; Ext . data . DatabaseDefinition . superclass . constructor . call ( this , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the target for the event . Unlike { @link #target } this returns the main element for your event . So if you are listening to a tap event on Ext . Viewport . element and you tap on an inner element of Ext . Viewport . element this will return Ext . Viewport . element . [CODESPLIT] function ( selector , maxDepth , returnEl ) { if ( arguments . length === 0 ) { return this . delegatedTarget ; } return selector ? Ext . fly ( this . target ) . findParent ( selector , maxDepth , returnEl ) : ( returnEl ? Ext . get ( this . target ) : this . target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an { [CODESPLIT] function ( action , silent ) { action = Ext . factory ( action , Ext . app . Action ) ; this . getActions ( ) . push ( action ) ; var url = action . getUrl ( ) ; if ( this . getUpdateUrl ( ) ) { // history.pushState({}, action.getTitle(), \"#\" + action.getUrl()); this . setToken ( url ) ; window . location . hash = url ; } if ( silent !== true ) { this . fireEvent ( 'change' , url ) ; } this . setToken ( url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Navigate to the previous active action . This changes the page url . [CODESPLIT] function ( ) { var actions = this . getActions ( ) , previousAction = actions [ actions . length - 2 ] ; if ( previousAction ) { actions . pop ( ) ; previousAction . getController ( ) . getApplication ( ) . redirectTo ( previousAction . getUrl ( ) ) ; } else { actions [ actions . length - 1 ] . getController ( ) . getApplication ( ) . redirectTo ( '' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format a string by replacing all keys between { and } with values from the given dictionary [CODESPLIT] function strformat ( string , dict ) { var formatted = string ; for ( var prop in dict ) { var regexp = new RegExp ( '\\\\{' + prop + '\\\\}' , 'gi' ) ; formatted = formatted . replace ( regexp , dict [ prop ] ) ; } return formatted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of the GrelRequest class . [CODESPLIT] function GrelRequest ( grel ) { var authString ; if ( grel . token ) { authString = grel . token + ':' ; } else { authString = grel . user + ':' + grel . password ; } this . headers = { 'Authorization' : 'Basic ' + new Buffer ( authString ) . toString ( 'base64' ) , 'Accept' : 'application/vnd.github.manifold-preview' , 'User-Agent' : 'Grel' } ; this . grel = grel ; this . content = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private method that handles HTTP responses we get from GitHub . This method will always be executed in the context of a GrelRequest . [CODESPLIT] function handleResponse ( res , data , callback ) { // HTTP 204 doesn't have a response var json = data && JSON . parse ( data ) || { } ; if ( ( res . statusCode >= 200 ) && ( res . statusCode <= 206 ) ) { // Handle a few known responses switch ( json . message ) { case 'Bad credentials' : callback . call ( this , json ) ; break ; default : callback . call ( this , null , json ) ; } } else { callback . call ( this , json ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "split markdown header [CODESPLIT] function splitHeader ( content ) { // New line characters need to handle all operating systems. const lines = content . split ( / \\r?\\n / ) ; if ( lines [ 0 ] !== '---' ) { return { } ; } let i = 1 ; for ( ; i < lines . length - 1 ; ++ i ) { if ( lines [ i ] === '---' ) { break ; } } return { header : lines . slice ( 1 , i + 1 ) . join ( '\\n' ) , content : lines . slice ( i + 1 ) . join ( '\\n' ) , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scrolls to the given location . [CODESPLIT] function ( x , y , animation ) { if ( this . isDestroyed ) { return this ; } //<deprecated product=touch since=2.0> if ( typeof x != 'number' && arguments . length === 1 ) { //<debug warn> Ext . Logger . deprecate ( \"Calling scrollTo() with an object argument is deprecated, \" + \"please pass x and y arguments instead\" , this ) ; //</debug> y = x . y ; x = x . x ; } //</deprecated> var translatable = this . getTranslatable ( ) , position = this . position , positionChanged = false , translationX , translationY ; if ( this . isAxisEnabled ( 'x' ) ) { if ( isNaN ( x ) || typeof x != 'number' ) { x = position . x ; } else { if ( position . x !== x ) { position . x = x ; positionChanged = true ; } } translationX = - x ; } if ( this . isAxisEnabled ( 'y' ) ) { if ( isNaN ( y ) || typeof y != 'number' ) { y = position . y ; } else { if ( position . y !== y ) { position . y = y ; positionChanged = true ; } } translationY = - y ; } if ( positionChanged ) { if ( animation !== undefined && animation !== false ) { translatable . translateAnimated ( translationX , translationY , animation ) ; } else { this . fireEvent ( 'scroll' , this , position . x , position . y ) ; translatable . translate ( translationX , translationY ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scrolls to the end of the scrollable view . [CODESPLIT] function ( animation ) { var size = this . getSize ( ) , cntSize = this . getContainerSize ( ) ; return this . scrollTo ( size . x - cntSize . x , size . y - cntSize . y , animation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change the scroll offset by the given amount . [CODESPLIT] function ( x , y , animation ) { var position = this . position ; x = ( typeof x == 'number' ) ? x + position . x : null ; y = ( typeof y == 'number' ) ? y + position . y : null ; return this . scrollTo ( x , y , animation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new Draggable . [CODESPLIT] function ( config ) { var element ; this . extraConstraint = { } ; this . initialConfig = config ; this . offset = { x : 0 , y : 0 } ; this . listeners = { dragstart : 'onDragStart' , drag : 'onDrag' , dragend : 'onDragEnd' , resize : 'onElementResize' , touchstart : 'onPress' , touchend : 'onRelease' , scope : this } ; if ( config && config . element ) { element = config . element ; delete config . element ; this . setElement ( element ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "addActions - add actions util [CODESPLIT] function addActions ( actions ) { if ( typeof actions === 'string' ) { add ( actions ) ; } else if ( Array . isArray ( actions ) ) { actions . forEach ( addActions ) ; } else if ( typeof actions === 'object' ) { for ( var type in actions ) { add ( type , actions [ type ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "INDEXSPACE FUNCTION : indexspace ( str len ) Generates a linearly spaced index array from a subsequence string . [CODESPLIT] function indexspace ( str , len ) { var x1 , x2 , tmp , inc , arr ; if ( ! isString ( str ) || ! re . test ( str ) ) { throw new Error ( 'indexspace()::invalid input argument. Invalid subsequence syntax. Please consult documentation. Value: `' + str + '`.' ) ; } if ( ! isNonNegativeInteger ( len ) ) { throw new TypeError ( 'indexspace()::invalid input argument. Reference array length must be a nonnegative integer. Value: `' + len + '`.' ) ; } if ( ! len ) { return [ ] ; } str = str . split ( ':' ) ; x1 = str [ 0 ] ; x2 = str [ 1 ] ; if ( str . length === 2 ) { inc = 1 ; } else { inc = parseInt ( str [ 2 ] , 10 ) ; } // Handle zero increment... if ( inc === 0 ) { throw new Error ( 'indexspace()::invalid syntax. Increment must be an integer not equal to 0. Value: `' + inc + '`.' ) ; } // START // // Handle use of 'end' keyword... if ( reEnd . test ( x1 ) ) { tmp = x1 . match ( reMatch ) ; if ( tmp ) { if ( tmp [ 1 ] === '-' ) { x1 = len - 1 - parseInt ( tmp [ 2 ] , 10 ) ; if ( x1 < 0 ) { // WARNING: forgive the user for exceeding the range bounds... x1 = 0 ; } } else { x1 = ( len - 1 ) / parseInt ( tmp [ 2 ] , 10 ) ; x1 = Math . ceil ( x1 ) ; } } else { x1 = len - 1 ; } } else { x1 = parseInt ( x1 , 10 ) ; // Handle empty index... if ( x1 !== x1 ) { // :-?\\d*:-?\\d+ if ( inc < 0 ) { // Max index: x1 = len - 1 ; } else { // Min index: x1 = 0 ; } } // Handle negative index... else if ( x1 < 0 ) { x1 = len + x1 ; // len-x1 if ( x1 < 0 ) { // WARNING: forgive the user for exceeding index bounds... x1 = 0 ; } } // Handle exceeding bounds... else if ( x1 >= len ) { return [ ] ; } } // END // // NOTE: here, we determine an inclusive `end` value; i.e., the last acceptable index value. // Handle use of 'end' keyword... if ( reEnd . test ( x2 ) ) { tmp = x2 . match ( reMatch ) ; if ( tmp ) { if ( tmp [ 1 ] === '-' ) { x2 = len - 1 - parseInt ( tmp [ 2 ] , 10 ) ; if ( x2 < 0 ) { // WARNING: forgive the user for exceeding the range bounds... x2 = 0 ; } } else { x2 = ( len - 1 ) / parseInt ( tmp [ 2 ] , 10 ) ; x2 = Math . ceil ( x2 ) - 1 ; } } else { x2 = len - 1 ; } } else { x2 = parseInt ( x2 , 10 ) ; // Handle empty index... if ( x2 !== x2 ) { // -?\\d*::-?\\d+ if ( inc < 0 ) { // Min index: x2 = 0 ; } else { // Max index: x2 = len - 1 ; } } // Handle negative index... else if ( x2 < 0 ) { x2 = len + x2 ; // len-x2 if ( x2 < 0 ) { // WARNING: forgive the user for exceeding index bounds... x2 = 0 ; } if ( inc > 0 ) { x2 = x2 - 1 ; } } // Handle positive index... else { if ( inc < 0 ) { x2 = x2 + 1 ; } else if ( x2 >= len ) { x2 = len - 1 ; } else { x2 = x2 - 1 ; } } } // INDICES // arr = [ ] ; if ( inc < 0 ) { if ( x2 > x1 ) { return arr ; } while ( x1 >= x2 ) { arr . push ( x1 ) ; x1 += inc ; } } else { if ( x1 > x2 ) { return arr ; } while ( x1 <= x2 ) { arr . push ( x1 ) ; x1 += inc ; } } return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends an event handler to an element . The shorthand version { @link #on } is equivalent . Typically you will use { @link Ext . Element#addListener } directly on an Element in favor of calling this version . @param { String / HTMLElement } el The HTML element or id to assign the event handler to . @param { String } eventName The name of the event to listen for . @param { Function } handler The handler function the event invokes . This function is passed the following parameters : @param { Ext . EventObject } handler . evt The { @link Ext . EventObject EventObject } describing the event . @param { Ext . Element } handler . t The { @link Ext . Element Element } which was the target of the event . Note that this may be filtered by using the delegate option . @param { Object } handler . o The options object from the addListener call . @param { Object } scope ( optional ) The scope ( this reference ) in which the handler function is executed . __Defaults to the Element__ . @param { Object } options ( optional ) An object containing handler configuration properties . This may contain any of the following properties : @param { Object } [ options . scope ] The scope ( this reference ) in which the handler function is executed . __Defaults to the Element__ . @param { String } [ options . delegate ] A simple selector to filter the target or look for a descendant of the target . @param { Boolean } [ options . stopEvent ] true to stop the event . That is stop propagation and prevent the default action . @param { Boolean } [ options . preventDefault ] true to prevent the default action . @param { Boolean } [ options . stopPropagation ] true to prevent event propagation . @param { Boolean } [ options . normalized ] false to pass a browser event to the handler function instead of an Ext . EventObject . @param { Number } [ options . delay ] The number of milliseconds to delay the invocation of the handler after the event fires . @param { Boolean } [ options . single ] true to add a handler to handle just the next firing of the event and then remove itself . @param { Number } [ options . buffer ] Causes the handler to be scheduled to run in an { @link Ext . util . DelayedTask } delayed by the specified number of milliseconds . If the event fires again within that time the original handler is _not_ invoked but the new handler is scheduled in its place . @param { Ext . Element } [ options . target ] Only call the handler if the event was fired on the target Element _not_ if the event was bubbled up from a child node . [CODESPLIT] function ( element , eventName , fn , scope , options ) { //<debug warn> Ext . Logger . deprecate ( \"Ext.EventManager.addListener is deprecated, use addListener() directly from an instance of Ext.Element instead\" , 2 ) ; //</debug> element . on ( eventName , fn , scope , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes an event handler from an element . The shorthand version { [CODESPLIT] function ( element , eventName , fn , scope ) { //<debug warn> Ext . Logger . deprecate ( \"Ext.EventManager.removeListener is deprecated, use removeListener() directly from an instance of Ext.Element instead\" , 2 ) ; //</debug> element . un ( eventName , fn , scope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a listener to be notified when the browser window is resized and provides resize event buffering ( 50 milliseconds ) passes new viewport width and height to handlers . [CODESPLIT] function ( fn , scope , options ) { //<debug warn> Ext . Logger . deprecate ( \"Ext.EventManager.onWindowResize is deprecated, attach listener to Ext.Viewport instead, i.e: Ext.Viewport.on('resize', ...)\" , 2 ) ; //</debug> Ext . Viewport . on ( 'resize' , fn , scope , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string with a specified number of repetitions a given string pattern . The pattern be separated by a different string . [CODESPLIT] function ( pattern , count , sep ) { for ( var buf = [ ] , i = count ; i -- ; ) { buf . push ( pattern ) ; } return buf . join ( sep || '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a file to a server [CODESPLIT] function ( config ) { var options = new FileUploadOptions ( ) ; options . fileKey = config . fileKey || \"file\" ; options . fileName = this . path . substr ( this . path . lastIndexOf ( '/' ) + 1 ) ; options . mimeType = config . mimeType || \"image/jpeg\" ; options . params = config . params || { } ; options . headers = config . headers || { } ; options . chunkMode = config . chunkMode || true ; var fileTransfer = new FileTransfer ( ) ; fileTransfer . upload ( this . path , encodeURI ( config . url ) , config . success , config . failure , options , config . trustAllHosts || false ) ; return fileTransfer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downloads a file from the server saving it into the Local File System [CODESPLIT] function ( config ) { var fileTransfer = new FileTransfer ( ) ; fileTransfer . download ( encodeURI ( config . source ) , this . path , config . success , config . failure , config . trustAllHosts || false , config . options || { } ) ; return fileTransfer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will sort a collection based on the currently configured sorters . [CODESPLIT] function ( property , value , anyMatch , caseSensitive ) { // Support for the simple case of filtering by property/value if ( property ) { if ( Ext . isString ( property ) ) { this . addFilters ( { property : property , value : value , anyMatch : anyMatch , caseSensitive : caseSensitive } ) ; return this . items ; } else { this . addFilters ( property ) ; return this . items ; } } this . items = this . mixins . filterable . filter . call ( this , this . all . slice ( ) ) ; this . updateAfterFilter ( ) ; if ( this . sorted && this . getAutoSort ( ) ) { this . sort ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an item to the collection . @param { String } key [CODESPLIT] function ( key , item ) { var me = this , filtered = this . filtered , sorted = this . sorted , all = this . all , items = this . items , keys = this . keys , indices = this . indices , filterable = this . mixins . filterable , currentLength = items . length , index = currentLength ; if ( arguments . length == 1 ) { item = key ; key = me . getKey ( item ) ; } if ( typeof key != 'undefined' && key !== null ) { if ( typeof me . map [ key ] != 'undefined' ) { return me . replace ( key , item ) ; } me . map [ key ] = item ; } all . push ( item ) ; if ( filtered && this . getAutoFilter ( ) && filterable . isFiltered . call ( me , item ) ) { return null ; } me . length ++ ; if ( sorted && this . getAutoSort ( ) ) { index = this . findInsertionIndex ( items , item ) ; } if ( index !== currentLength ) { this . dirtyIndices = true ; Ext . Array . splice ( keys , index , 0 , key ) ; Ext . Array . splice ( items , index , 0 , item ) ; } else { indices [ key ] = currentLength ; keys . push ( key ) ; items . push ( item ) ; } return item ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces an item in the collection . Fires the { @link #replace } event when complete . @param { String } oldKey [CODESPLIT] function ( oldKey , item ) { var me = this , sorted = me . sorted , presorted = me . presorted , filtered = me . filtered , filterable = me . mixins . filterable , items = me . items , keys = me . keys , all = me . all , map = me . map , returnItem = null , oldItemsLn = items . length , subjectToOptimize = false , oldItem , index , newKey ; if ( arguments . length == 1 ) { item = oldKey ; oldKey = newKey = me . getKey ( item ) ; subjectToOptimize = true ; } else { newKey = me . getKey ( item ) ; } oldItem = map [ oldKey ] ; if ( typeof oldKey == 'undefined' || oldKey === null || typeof oldItem == 'undefined' ) { return me . add ( newKey , item ) ; } me . map [ newKey ] = item ; if ( newKey !== oldKey ) { delete me . map [ oldKey ] ; } if ( sorted && me . getAutoSort ( ) ) { if ( ! subjectToOptimize ) { Ext . Array . remove ( items , oldItem ) ; Ext . Array . remove ( keys , oldKey ) ; } else { var itemsFrom = items . indexOf ( oldItem ) ; } if ( ! presorted ) { Ext . Array . remove ( all , oldItem ) ; all . push ( item ) ; me . dirtyIndices = true ; } else { var allTo = this . findInsertionIndex ( all , item , undefined , true ) , allFrom = all . indexOf ( item ) ; if ( allTo !== allFrom ) { move ( all , allFrom , allTo ) ; me . dirtyIndices = true ; } } if ( filtered && me . getAutoFilter ( ) ) { // If the item is now filtered we check if it was not filtered // before. If that is the case then we subtract from the length if ( filterable . isFiltered . call ( me , item ) ) { if ( oldItemsLn !== items . length ) { me . length -- ; } if ( subjectToOptimize ) { Ext . Array . remove ( items , oldItem ) ; Ext . Array . remove ( keys , oldKey ) ; } return null ; } // If the item was filtered, but now it is not anymore then we // add to the length else if ( oldItemsLn === items . length ) { me . length ++ ; returnItem = item ; } } if ( ! subjectToOptimize ) { index = this . findInsertionIndex ( items , item ) ; Ext . Array . splice ( keys , index , 0 , newKey ) ; Ext . Array . splice ( items , index , 0 , item ) ; } else { index = this . findInsertionIndex ( items , item , undefined , true ) ; move ( keys , itemsFrom , index ) ; move ( items , itemsFrom , index ) ; } } else { if ( filtered ) { if ( me . getAutoFilter ( ) && filterable . isFiltered . call ( me , item ) ) { if ( me . indexOf ( oldItem ) !== - 1 ) { Ext . Array . remove ( items , oldItem ) ; Ext . Array . remove ( keys , oldKey ) ; me . length -- ; me . dirtyIndices = true ; } return null ; } else if ( me . indexOf ( oldItem ) === - 1 ) { items . push ( item ) ; keys . push ( newKey ) ; me . indices [ newKey ] = me . length ; me . length ++ ; return item ; } } index = me . indexOf ( oldItem ) ; keys [ index ] = newKey ; items [ index ] = item ; if ( newKey !== oldKey ) { this . dirtyIndices = true ; } } return returnItem ; function move ( array , from , to ) { if ( to === from ) return ; var target = array [ from ] ; var increment = to < from ? - 1 : 1 ; for ( var k = from ; k != to ; k += increment ) { array [ k ] = array [ k + increment ] ; } array [ to ] = target ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds all elements of an Array or an Object to the collection . [CODESPLIT] function ( addItems ) { var me = this , filtered = me . filtered , sorted = me . sorted , all = me . all , items = me . items , keys = me . keys , map = me . map , autoFilter = me . getAutoFilter ( ) , autoSort = me . getAutoSort ( ) , newKeys = [ ] , newItems = [ ] , filterable = me . mixins . filterable , addedItems = [ ] , ln , key , i , item ; if ( Ext . isObject ( addItems ) ) { for ( key in addItems ) { if ( addItems . hasOwnProperty ( key ) ) { newItems . push ( items [ key ] ) ; newKeys . push ( key ) ; } } } else { newItems = addItems ; ln = addItems . length ; for ( i = 0 ; i < ln ; i ++ ) { newKeys . push ( me . getKey ( addItems [ i ] ) ) ; } } for ( i = 0 ; i < ln ; i ++ ) { key = newKeys [ i ] ; item = newItems [ i ] ; if ( typeof key != 'undefined' && key !== null ) { if ( typeof map [ key ] != 'undefined' ) { me . replace ( key , item ) ; continue ; } map [ key ] = item ; } all . push ( item ) ; if ( filtered && autoFilter && filterable . isFiltered . call ( me , item ) ) { continue ; } me . length ++ ; keys . push ( key ) ; items . push ( item ) ; addedItems . push ( item ) ; } if ( addedItems . length ) { me . dirtyIndices = true ; if ( sorted && autoSort ) { me . sort ( ) ; } return addedItems ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the specified function once for every key in the collection passing each key and its associated item as the first two parameters . [CODESPLIT] function ( fn , scope ) { var keys = this . keys , items = this . items , ln = keys . length , i ; for ( i = 0 ; i < ln ; i ++ ) { fn . call ( scope || window , keys [ i ] , items [ i ] , i , ln ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter by a function . Returns a _new_ collection that has been filtered . The passed function will be called with each object in the collection . If the function returns true the value is included otherwise it is filtered . [CODESPLIT] function ( fn , scope ) { var me = this , newCollection = new this . self ( ) , keys = me . keys , items = me . all , length = items . length , i ; newCollection . getKey = me . getKey ; for ( i = 0 ; i < length ; i ++ ) { if ( fn . call ( scope || me , items [ i ] , me . getKey ( items [ i ] ) ) ) { newCollection . add ( keys [ i ] , items [ i ] ) ; } } return newCollection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts an item at the specified index in the collection . Fires the { [CODESPLIT] function ( index , key , item ) { var me = this , sorted = this . sorted , map = this . map , filtered = this . filtered ; if ( arguments . length == 2 ) { item = key ; key = me . getKey ( item ) ; } if ( index >= me . length || ( sorted && me . getAutoSort ( ) ) ) { return me . add ( key , item ) ; } if ( typeof key != 'undefined' && key !== null ) { if ( typeof map [ key ] != 'undefined' ) { me . replace ( key , item ) ; return false ; } map [ key ] = item ; } this . all . push ( item ) ; if ( filtered && this . getAutoFilter ( ) && this . mixins . filterable . isFiltered . call ( me , item ) ) { return null ; } me . length ++ ; Ext . Array . splice ( me . items , index , 0 , item ) ; Ext . Array . splice ( me . keys , index , 0 , key ) ; me . dirtyIndices = true ; return item ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an item from the collection . [CODESPLIT] function ( item ) { var index = this . items . indexOf ( item ) ; if ( index === - 1 ) { Ext . Array . remove ( this . all , item ) ; if ( typeof this . getKey == 'function' ) { var key = this . getKey ( item ) ; if ( key !== undefined ) { delete this . map [ key ] ; } } return item ; } return this . removeAt ( this . items . indexOf ( item ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all items in the passed array from the collection . [CODESPLIT] function ( items ) { if ( items ) { var ln = items . length , i ; for ( i = 0 ; i < ln ; i ++ ) { this . remove ( items [ i ] ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an item from a specified index in the collection . Fires the { [CODESPLIT] function ( index ) { var me = this , items = me . items , keys = me . keys , all = me . all , item , key ; if ( index < me . length && index >= 0 ) { item = items [ index ] ; key = keys [ index ] ; if ( typeof key != 'undefined' ) { delete me . map [ key ] ; } Ext . Array . erase ( items , index , 1 ) ; Ext . Array . erase ( keys , index , 1 ) ; Ext . Array . remove ( all , item ) ; delete me . indices [ key ] ; me . length -- ; this . dirtyIndices = true ; return item ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns index within the collection of the passed Object . [CODESPLIT] function ( item ) { if ( this . dirtyIndices ) { this . updateIndices ( ) ; } var index = item ? this . indices [ this . getKey ( item ) ] : - 1 ; return ( index === undefined ) ? - 1 : index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the item associated with the passed key OR index . Key has priority over index . This is the equivalent of calling { [CODESPLIT] function ( key ) { var me = this , fromMap = me . map [ key ] , item ; if ( fromMap !== undefined ) { item = fromMap ; } else if ( typeof key == 'number' ) { item = me . items [ key ] ; } return typeof item != 'function' || me . getAllowFunctions ( ) ? item : null ; // for prototype! }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the collection contains the passed Object as an item . [CODESPLIT] function ( item ) { var key = this . getKey ( item ) ; if ( key ) { return this . containsKey ( key ) ; } else { return Ext . Array . contains ( this . items , item ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all items from the collection . Fires the { [CODESPLIT] function ( ) { var me = this ; me . length = 0 ; me . items . length = 0 ; me . keys . length = 0 ; me . all . length = 0 ; me . dirtyIndices = true ; me . indices = { } ; me . map = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a range of items in this collection [CODESPLIT] function ( start , end ) { var me = this , items = me . items , range = [ ] , i ; if ( items . length < 1 ) { return range ; } start = start || 0 ; end = Math . min ( typeof end == 'undefined' ? me . length - 1 : end , me . length - 1 ) ; if ( start <= end ) { for ( i = start ; i <= end ; i ++ ) { range [ range . length ] = items [ i ] ; } } else { for ( i = start ; i >= end ; i -- ) { range [ range . length ] = items [ i ] ; } } return range ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the index of the first matching object in this collection by a function . If the function returns true it is considered a match . [CODESPLIT] function ( fn , scope , start ) { var me = this , keys = me . keys , items = me . items , i = start || 0 , ln = items . length ; for ( ; i < ln ; i ++ ) { if ( fn . call ( scope || me , items [ i ] , keys [ i ] ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a shallow copy of this collection [CODESPLIT] function ( ) { var me = this , copy = new this . self ( ) , keys = me . keys , items = me . items , i = 0 , ln = items . length ; for ( ; i < ln ; i ++ ) { copy . add ( keys [ i ] , items [ i ] ) ; } copy . getKey = me . getKey ; return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the monthText configuration [CODESPLIT] function ( newMonthText , oldMonthText ) { var innerItems = this . getInnerItems , ln = innerItems . length , item , i ; //loop through each of the current items and set the title on the correct slice if ( this . initialized ) { for ( i = 0 ; i < ln ; i ++ ) { item = innerItems [ i ] ; if ( ( typeof item . title == \"string\" && item . title == oldMonthText ) || ( item . title . html == oldMonthText ) ) { item . setTitle ( newMonthText ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the { [CODESPLIT] function ( newDayText , oldDayText ) { var innerItems = this . getInnerItems , ln = innerItems . length , item , i ; //loop through each of the current items and set the title on the correct slice if ( this . initialized ) { for ( i = 0 ; i < ln ; i ++ ) { item = innerItems [ i ] ; if ( ( typeof item . title == \"string\" && item . title == oldDayText ) || ( item . title . html == oldDayText ) ) { item . setTitle ( newDayText ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the yearText configuration [CODESPLIT] function ( yearText ) { var innerItems = this . getInnerItems , ln = innerItems . length , item , i ; //loop through each of the current items and set the title on the correct slice if ( this . initialized ) { for ( i = 0 ; i < ln ; i ++ ) { item = innerItems [ i ] ; if ( item . title == this . yearText ) { item . setTitle ( yearText ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates all slots for all years specified by this component and then sets them on the component [CODESPLIT] function ( ) { var me = this , slotOrder = me . getSlotOrder ( ) , yearsFrom = me . getYearFrom ( ) , yearsTo = me . getYearTo ( ) , years = [ ] , days = [ ] , months = [ ] , reverse = yearsFrom > yearsTo , ln , i , daysInMonth ; while ( yearsFrom ) { years . push ( { text : yearsFrom , value : yearsFrom } ) ; if ( yearsFrom === yearsTo ) { break ; } if ( reverse ) { yearsFrom -- ; } else { yearsFrom ++ ; } } daysInMonth = me . getDaysInMonth ( 1 , new Date ( ) . getFullYear ( ) ) ; for ( i = 0 ; i < daysInMonth ; i ++ ) { days . push ( { text : i + 1 , value : i + 1 } ) ; } for ( i = 0 , ln = Ext . Date . monthNames . length ; i < ln ; i ++ ) { months . push ( { text : Ext . Date . monthNames [ i ] , value : i + 1 } ) ; } var slots = [ ] ; slotOrder . forEach ( function ( item ) { slots . push ( me . createSlot ( item , days , months , years ) ) ; } ) ; me . setSlots ( slots ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a slot config for a specified date . [CODESPLIT] function ( name , days , months , years ) { switch ( name ) { case 'year' : return { name : 'year' , align : 'center' , data : years , title : this . getYearText ( ) , flex : 3 } ; case 'month' : return { name : name , align : 'right' , data : months , title : this . getMonthText ( ) , flex : 4 } ; case 'day' : return { name : 'day' , align : 'center' , data : days , title : this . getDayText ( ) , flex : 2 } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * KADEMLIA TRANSPORT [CODESPLIT] function ( contact , options ) { this . messaging = options . messaging kademlia . RPC . call ( this , contact , options ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A private function for rendering decision [CODESPLIT] function ( user ) { if ( user ) { if ( ! ! ~ this . roles . indexOf ( '*' ) ) { return true ; } else { for ( var userRoleIndex in user . roles ) { for ( var roleIndex in this . roles ) { if ( this . roles [ roleIndex ] === user . roles [ userRoleIndex ] ) { return true ; } } } } } else { return this . isPublic ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates and returns the position values needed for the back button when you are pushing a title . [CODESPLIT] function ( oldLeft , oldTitle , reverse ) { var me = this , barElement = me . element , newLeftElement = me . leftBox . element , titleElement = me . titleComponent . element , minOffset = Math . min ( barElement . getWidth ( ) / 3 , 200 ) , newLeftWidth = newLeftElement . getWidth ( ) , barX = barElement . getX ( ) , barWidth = barElement . getWidth ( ) , titleX = titleElement . getX ( ) , titleLeft = titleElement . getLeft ( ) , titleWidth = titleElement . getWidth ( ) , oldLeftX = oldLeft . x , oldLeftWidth = oldLeft . width , oldLeftLeft = oldLeft . left , useLeft = Ext . browser . is . AndroidStock2 && ! this . getAndroid2Transforms ( ) , newOffset , oldOffset , leftAnims , titleAnims , omega , theta ; theta = barX - oldLeftX - oldLeftWidth ; if ( reverse ) { newOffset = theta ; oldOffset = Math . min ( titleX - oldLeftWidth , minOffset ) ; } else { oldOffset = theta ; newOffset = Math . min ( titleX - barX , minOffset ) ; } if ( useLeft ) { leftAnims = { element : { from : { left : newOffset , opacity : 1 } , to : { left : 0 , opacity : 1 } } } ; } else { leftAnims = { element : { from : { transform : { translateX : newOffset } , opacity : 0 } , to : { transform : { translateX : 0 } , opacity : 1 } } , ghost : { to : { transform : { translateX : oldOffset } , opacity : 0 } } } ; } theta = barX - titleX + newLeftWidth ; if ( ( oldLeftLeft + titleWidth ) > titleX ) { omega = barX - titleX - titleWidth ; } if ( reverse ) { titleElement . setLeft ( 0 ) ; oldOffset = barX + barWidth - titleX - titleWidth ; if ( omega !== undefined ) { newOffset = omega ; } else { newOffset = theta ; } } else { newOffset = barX + barWidth - titleX - titleWidth ; if ( omega !== undefined ) { oldOffset = omega ; } else { oldOffset = theta ; } newOffset = Math . max ( titleLeft , newOffset ) ; } if ( useLeft ) { titleAnims = { element : { from : { left : newOffset , opacity : 1 } , to : { left : titleLeft , opacity : 1 } } } ; } else { titleAnims = { element : { from : { transform : { translateX : newOffset } , opacity : 0 } , to : { transform : { translateX : titleLeft } , opacity : 1 } } , ghost : { to : { transform : { translateX : oldOffset } , opacity : 0 } } } ; } return { left : leftAnims , title : titleAnims , titleLeft : titleLeft } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method used to animate elements . You pass it an element objects for the from and to positions an option onEnd callback called when the animation is over . Normally this method is passed configurations returned from the methods such as #measureTitle ( true ) etc . It is called from the #pushLeftBoxAnimated #pushTitleAnimated #popBackButtonAnimated and #popTitleAnimated methods . [CODESPLIT] function ( element , config , callback ) { var me = this , animation ; //reset the left of the element element . setLeft ( 0 ) ; config = Ext . apply ( config , { element : element , easing : 'ease-in-out' , duration : me . getAnimation ( ) . duration || 250 , preserveEndState : true } ) ; animation = new Ext . fx . Animation ( config ) ; animation . on ( 'animationend' , function ( ) { if ( callback ) { callback . call ( me ) ; } } , me ) ; Ext . Animator . run ( animation ) ; me . activeAnimations . push ( animation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the text needed for the current back button at anytime . [CODESPLIT] function ( ) { var text = this . backButtonStack [ this . backButtonStack . length - 2 ] , useTitleForBackButtonText = this . getUseTitleForBackButtonText ( ) ; if ( ! useTitleForBackButtonText ) { if ( text ) { text = this . getDefaultBackButtonText ( ) ; } } return text ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We override the hidden method because we don t want to remove it from the view using display : none . Instead we just position it off the screen much like the navigation bar proxy . This means that all animations pushing popping etc . all still work when if you hide / show this bar at any time . [CODESPLIT] function ( hidden ) { if ( ! hidden ) { this . element . setStyle ( { position : 'relative' , top : 'auto' , left : 'auto' , width : 'auto' } ) ; } else { this . element . setStyle ( { position : 'absolute' , top : '-1000px' , left : '-1000px' , width : this . element . getWidth ( ) + 'px' } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a proxy element of the passed element and positions it in the same position using absolute positioning . The createNavigationBarProxy method uses this to create proxies of the backButton and the title elements . [CODESPLIT] function ( element ) { var ghost , x , y , left , width ; ghost = element . dom . cloneNode ( true ) ; ghost . id = element . id + '-proxy' ; //insert it into the toolbar element . getParent ( ) . dom . appendChild ( ghost ) ; //set the x/y ghost = Ext . get ( ghost ) ; x = element . getX ( ) ; y = element . getY ( ) ; left = element . getLeft ( ) ; width = element . getWidth ( ) ; ghost . setStyle ( 'position' , 'absolute' ) ; ghost . setX ( x ) ; ghost . setY ( y ) ; ghost . setHeight ( element . getHeight ( ) ) ; ghost . setWidth ( width ) ; return { x : x , y : y , left : left , width : width , ghost : ghost } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A Metalsmith plugin to extract untemplatized file contents . [CODESPLIT] function plugin ( options ) { options = options || { } ; options . key = options . key || 'untemplatized' ; return function ( files , metalsmith , done ) { setImmediate ( done ) ; Object . keys ( files ) . forEach ( function ( file ) { debug ( 'checking file: %s' , file ) ; var data = files [ file ] ; var contents = data . contents . toString ( ) . replace ( / ^\\n+ / g , '' ) ; debug ( 'storing untemplatized content: %s' , file ) ; data [ options . key ] = new Buffer ( contents ) ; } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines a metric that measures latency by last req / res [CODESPLIT] function LatencyMetric ( ) { if ( ! ( this instanceof LatencyMetric ) ) { return new LatencyMetric ( ) } Metric . call ( this ) this . key = 'latency' this . default = [ 0 ] this . hooks = [ { trigger : 'before' , event : 'send' , handler : this . _start } , { trigger : 'before' , event : 'receive' , handler : this . _stop } ] this . _tests = { } setInterval ( this . _expireTimeouts . bind ( this ) , LatencyMetric . TEST_TIMEOUT ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dataType : json others [CODESPLIT] function decodeResult ( contentType , dataType , result ) { if ( dataType == 'json' ) { try { result = JSON . parse ( result ) ; return result ; } catch ( e ) { } } if ( contentType && contentType . indexOf ( 'application/json' ) == 0 ) { try { result = JSON . parse ( result ) ; } catch ( e ) { } } //todo: xml result return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Default map will take the first this . header . length items from the object as the row values [CODESPLIT] function defaultMapFn ( data ) { return Object . keys ( data ) . slice ( 0 , this . headers . length ) . map ( function ( key ) { return data [ key ] } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Schedule a new Job [CODESPLIT] function scheduleJob ( trigger , jobFunc , jobData ) { const job = Job . createJob ( trigger , jobFunc , jobData ) ; const excuteTime = job . excuteTime ( ) ; const id = job . id ; map [ id ] = job ; const element = { id : id , time : excuteTime } ; const curJob = queue . peek ( ) ; if ( ! curJob || excuteTime < curJob . time ) { queue . offer ( element ) ; setTimer ( job ) ; return job . id ; } queue . offer ( element ) ; return job . id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add / override static properties of this class . [CODESPLIT] function ( members ) { var member , name ; //<debug> var className = Ext . getClassName ( this ) ; //</debug> for ( name in members ) { if ( members . hasOwnProperty ( name ) ) { member = members [ name ] ; //<debug> if ( typeof member == 'function' ) { member . displayName = className + '.' + name ; } //</debug> this [ name ] = member ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add methods / properties to the prototype of this class . [CODESPLIT] function ( members ) { var prototype = this . prototype , names = [ ] , name , member ; //<debug> var className = this . $className || '' ; //</debug> for ( name in members ) { if ( members . hasOwnProperty ( name ) ) { member = members [ name ] ; if ( typeof member == 'function' && ! member . $isClass && member !== Ext . emptyFn ) { member . $owner = this ; member . $name = name ; //<debug> member . displayName = className + '#' + name ; //</debug> } prototype [ name ] = member ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override members of this class . Overridden methods can be invoked via { @link Ext . Base#callParent } . [CODESPLIT] function ( members ) { var me = this , enumerables = Ext . enumerables , target = me . prototype , cloneFunction = Ext . Function . clone , currentConfig = target . config , name , index , member , statics , names , previous , newConfig , prop ; if ( arguments . length === 2 ) { name = members ; members = { } ; members [ name ] = arguments [ 1 ] ; enumerables = null ; } do { names = [ ] ; // clean slate for prototype (1st pass) and static (2nd pass) statics = null ; // not needed 1st pass, but needs to be cleared for 2nd pass for ( name in members ) { // hasOwnProperty is checked in the next loop... if ( name == 'statics' ) { statics = members [ name ] ; } else if ( name == 'config' ) { newConfig = members [ name ] ; //<debug error> for ( prop in newConfig ) { if ( ! ( prop in currentConfig ) ) { throw new Error ( \"Attempting to override a non-existant config property. This is not \" + \"supported, you must extend the Class.\" ) ; } } //</debug> me . addConfig ( newConfig , true ) ; } else { names . push ( name ) ; } } if ( enumerables ) { names . push . apply ( names , enumerables ) ; } for ( index = names . length ; index -- ; ) { name = names [ index ] ; if ( members . hasOwnProperty ( name ) ) { var inherited = false ; member = members [ name ] ; if ( typeof member == 'function' && ! member . $className && member !== Ext . emptyFn ) { if ( typeof member . $owner != 'undefined' ) { member = cloneFunction ( member ) ; } //<debug> var className = me . $className ; if ( className ) { member . displayName = className + '#' + name ; } //</debug> member . $owner = me ; member . $name = name ; previous = target [ name ] ; if ( previous == null ) { previous = this [ name ] ; if ( previous ) { inherited = true ; } } if ( previous ) { member . $previous = previous ; } } if ( ! inherited ) { target [ name ] = member ; } else { this [ name ] = member ; } } } target = me ; // 2nd pass is for statics members = statics ; // statics will be null on 2nd pass } while ( members ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<feature classSystem . mixins > Used internally by the mixins pre - processor [CODESPLIT] function ( name , mixinClass ) { var mixin = mixinClass . prototype , prototype = this . prototype , key ; if ( typeof mixin . onClassMixedIn != 'undefined' ) { mixin . onClassMixedIn . call ( mixinClass , this ) ; } if ( ! prototype . hasOwnProperty ( 'mixins' ) ) { if ( 'mixins' in prototype ) { prototype . mixins = Ext . Object . chain ( prototype . mixins ) ; } else { prototype . mixins = { } ; } } for ( key in mixin ) { if ( key === 'mixins' ) { Ext . merge ( prototype . mixins , mixin [ key ] ) ; } else if ( typeof prototype [ key ] == 'undefined' && key != 'mixinId' && key != 'config' ) { prototype [ key ] = mixin [ key ] ; } } //<feature classSystem.config> if ( 'config' in mixin ) { this . addConfig ( mixin . config , false ) ; } //</feature> prototype . mixins [ name ] = mixin ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call the original method that was previously overridden with { @link Ext . Base#override } [CODESPLIT] function ( args ) { var callOverriddenFn = this . callOverridden || this . prototype . callOverridden , method = callOverriddenFn . caller , previousMethod = method && method . $previous ; if ( ! previousMethod ) { return method . $return ; } return previousMethod . apply ( this , args || noArgs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize configuration for this class . a typical example : [CODESPLIT] function ( instanceConfig ) { //<debug> //            if (instanceConfig && instanceConfig.breakOnInitConfig) { //                debugger; //            } //</debug> var configNameCache = Ext . Class . configNameCache , prototype = this . self . prototype , initConfigList = this . initConfigList , initConfigMap = this . initConfigMap , config = new this . configClass , defaultConfig = this . defaultConfig , i , ln , name , value , nameMap , getName ; this . initConfig = Ext . emptyFn ; this . initialConfig = instanceConfig || { } ; if ( instanceConfig ) { Ext . merge ( config , instanceConfig ) ; } this . config = config ; // Optimize initConfigList *once* per class based on the existence of apply* and update* methods // Happens only once during the first instantiation if ( ! prototype . hasOwnProperty ( 'wasInstantiated' ) ) { prototype . wasInstantiated = true ; for ( i = 0 , ln = initConfigList . length ; i < ln ; i ++ ) { name = initConfigList [ i ] ; nameMap = configNameCache [ name ] ; value = defaultConfig [ name ] ; if ( ! ( nameMap . apply in prototype ) && ! ( nameMap . update in prototype ) && prototype [ nameMap . set ] . $isDefault && typeof value != 'object' ) { prototype [ nameMap . internal ] = defaultConfig [ name ] ; initConfigMap [ name ] = false ; Ext . Array . remove ( initConfigList , name ) ; i -- ; ln -- ; } } } if ( instanceConfig ) { initConfigList = initConfigList . slice ( ) ; for ( name in instanceConfig ) { if ( name in defaultConfig && ! initConfigMap [ name ] ) { initConfigList . push ( name ) ; } } } // Point all getters to the initGetters for ( i = 0 , ln = initConfigList . length ; i < ln ; i ++ ) { name = initConfigList [ i ] ; nameMap = configNameCache [ name ] ; this [ nameMap . get ] = this [ nameMap . initGet ] ; } this . beforeInitConfig ( config ) ; for ( i = 0 , ln = initConfigList . length ; i < ln ; i ++ ) { name = initConfigList [ i ] ; nameMap = configNameCache [ name ] ; getName = nameMap . get ; if ( this . hasOwnProperty ( getName ) ) { this [ nameMap . set ] . call ( this , config [ name ] ) ; delete this [ getName ] ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define a new type . [CODESPLIT] function defineType ( type , validator ) { var typeDef ; var regKey ; if ( type instanceof Function ) { validator = _customValidator ( type ) ; type = type . name ; //console.log(\"Custom type\", typeof type, type, validator); } else if ( ! ( validator instanceof Function ) ) { throw TypeException ( 'Validator must be a function for `{{type}}`' , null , null , { type : type } ) ; } typeDef = parseTypeDef ( type ) ; regKey = typeDef . name . toLocaleLowerCase ( ) ; if ( primitives [ regKey ] ) { throw TypeException ( 'Cannot override primitive type `{{type}}`' , null , null , { type : typeDef . name } ) ; } else if ( registry [ regKey ] && ( registry [ regKey ] . validator !== validator ) ) { throw TypeException ( 'Validator conflict for type `{{type}}` ' , null , null , { type : typeDef . name } ) ; } registry [ regKey ] = { type : typeDef . name , validator : validator } ; return validator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Undefine a type . [CODESPLIT] function undefineType ( type ) { var validator ; var typeDef = parseTypeDef ( type ) ; var regKey = typeDef . name . toLocaleLowerCase ( ) ; if ( primitives [ regKey ] ) { throw TypeException ( 'Cannot undefine primitive type `{{type}}`' , null , null , { type : typeDef . name } ) ; } validator = registry [ regKey ] && registry [ regKey ] . validator ; delete registry [ regKey ] ; return validator || false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check value against type [CODESPLIT] function checkType ( type , value , previous , attributeName ) { var typeDef = parseTypeDef ( type ) ; var regKey = typeDef . name . toLocaleLowerCase ( ) ; validator = primitives [ regKey ] || ( registry [ regKey ] && registry [ regKey ] . validator ) ; if ( ! validator ) { throw TypeException ( 'Unknown type `{{type}}`' , null , [ attributeName ] , { type : typeDef . name } ) ; } else if ( typeDef . indexes ) { return arrayValidation ( typeDef , 0 , value , previous , attributeName , validator ) ; } return validator ( value , previous , attributeName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return all defined type names [CODESPLIT] function getDefinedNames ( ) { return Object . keys ( primitives ) . concat ( Object . keys ( registry ) . map ( function ( type ) { return registry [ type ] . type ; } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "============= Validators ============= [CODESPLIT] function arrayValidation ( typeDef , index , value , previous , attributeName , validator ) { var indexInc ; var i ; var ilen ; if ( value === null || value === undefined || typeDef . indexes . length <= index ) { //console.log(\"Validating\", value, index, typeDef); return validator ( value , previous , attributeName ) ; } else if ( typeDef . indexes . length > index ) { //console.log(\"Checking array\", value, index, typeDef); if ( value instanceof Array ) { if ( value . length ) { indexInc = Math . max ( Math . floor ( value . length / VALIDATE_MAX_ARR_INDEX ) , 1 ) ; for ( i = 0 , ilen = value . length ; i < ilen ; i += indexInc ) { arrayValidation ( typeDef , index + 1 , value [ i ] , previous instanceof Array ? previous [ i ] : undefined , attributeName , validator ) ; } return value ; } else if ( previous instanceof Array && previous . length ) { indexInc = Math . max ( Math . floor ( value . length / VALIDATE_MAX_ARR_INDEX ) , 1 ) ; for ( i = 0 , ilen = value . length ; i < ilen ; i += indexInc ) { arrayValidation ( typeDef , index + 1 , null , previous [ i ] , attributeName , validator ) } return value ; } else { return arrayValidation ( typeDef , index + 1 , undefined , undefined , attributeName , validator ) } } } throw TypeException ( 'Invalid array for `{{type}}`' , null , [ attributeName ] , { type : typeDef . name , indexes : typeDef . indexes } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "don t include redundant license or copyright notice [CODESPLIT] function ( comment ) { const isLicense = comment . toLowerCase ( ) . includes ( \"license\" ) || comment . toLowerCase ( ) . includes ( \"copyright\" ) ; if ( isLicense === false ) { return false ; } if ( lastLicense !== comment ) { lastLicense = comment ; return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter / setter [CODESPLIT] function ctor ( k , v ) { if ( k && _ . isString ( k ) && k . indexOf ( 'paths.' ) === 0 ) return get . apply ( null , _ . toArray ( arguments ) ) return v ? set ( k , v ) : get ( k ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get setting key [CODESPLIT] function get ( k ) { if ( ! k ) return _SETTINGS let v = _ . get ( _SETTINGS , k ) if ( ! v ) return if ( _ . isString ( k ) && k . indexOf ( 'paths.' ) !== 0 ) return v let args = _ . drop ( _ . toArray ( arguments ) ) let argsLength = args . unshift ( v ) return path . join . apply ( path , args ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set setting key with val ( merged if already exists and is plain object {} ) [CODESPLIT] function set ( k , v ) { let curr = get ( k ) if ( curr && _ . isPlainObject ( curr ) && _ . isPlainObject ( v ) ) v = _ . mcopy ( curr , v ) if ( k ) _ . set ( _SETTINGS , k , v ) if ( ! k ) _SETTINGS = v return get ( k ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "require src and merge with SETTINGS if exists [CODESPLIT] function load ( src ) { if ( ! src || ! _ . isString ( src ) ) return let file = _ . attempt ( require , src ) if ( ! file || _ . isError ( file ) || ! _ . isPlainObject ( file ) ) return return _ . merge ( _SETTINGS , file ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructor [CODESPLIT] function SipFakeStack ( config ) { if ( ! config . server ) { throw '(SipFakeStack) You need at least to specify a valid IPv4/6 target' ; } this . server = config . server || null ; this . port = config . port || 5060 ; this . transport = config . transport || 'UDP' ; //    this.lport = config.lport || utils.randomPort(); this . lport = config . lport || null ; this . srcHost = config . srcHost ; this . timeout = config . timeout || 8000 ; this . wsPath = config . wsPath || null ; this . domain = config . domain || null ; this . onlyFirst = config . onlyFirst || true ; if ( net . isIPv6 ( config . server ) && ! config . srcHost ) { this . srcHost = utils . randomIP6 ( ) ; } else if ( ! config . srcHost ) { this . srcHost = utils . randomIP ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if size has a unit otherwise appends the passed unit string or the default for this Element . [CODESPLIT] function ( size , units ) { // Size set to a value which means \"auto\" if ( size === \"\" || size == \"auto\" || size === undefined || size === null ) { return size || '' ; } // Otherwise, warn if it's not a valid CSS measurement if ( Ext . isNumber ( size ) || this . numberRe . test ( size ) ) { return size + ( units || this . defaultUnit || 'px' ) ; } else if ( ! this . unitRe . test ( size ) ) { //<debug> Ext . Logger . warn ( \"Warning, size detected (\" + size + \") not a valid property value on Element.addUnits.\" ) ; //</debug> return size || '' ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a number or string representing margin sizes into an object . Supports CSS - style margin declarations ( e . g . 10 10 10 10 10 10 10 and 10 10 10 10 are all valid options and would return the same result ) [CODESPLIT] function ( box ) { if ( typeof box != 'string' ) { box = box . toString ( ) ; } var parts = box . split ( ' ' ) , ln = parts . length ; if ( ln == 1 ) { parts [ 1 ] = parts [ 2 ] = parts [ 3 ] = parts [ 0 ] ; } else if ( ln == 2 ) { parts [ 2 ] = parts [ 0 ] ; parts [ 3 ] = parts [ 1 ] ; } else if ( ln == 3 ) { parts [ 3 ] = parts [ 1 ] ; } return { top : parts [ 0 ] || 0 , right : parts [ 1 ] || 0 , bottom : parts [ 2 ] || 0 , left : parts [ 3 ] || 0 } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a number or string representing margin sizes into an object . Supports CSS - style margin declarations ( e . g . 10 10 10 10 10 10 10 and 10 10 10 10 are all valid options and would return the same result ) [CODESPLIT] function ( box , units ) { var me = this ; box = me . parseBox ( box ) ; return me . addUnits ( box . top , units ) + ' ' + me . addUnits ( box . right , units ) + ' ' + me . addUnits ( box . bottom , units ) + ' ' + me . addUnits ( box . left , units ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a DOM form into a url encoded string [CODESPLIT] function ( form ) { var fElements = form . elements || ( document . forms [ form ] || Ext . getDom ( form ) ) . elements , hasSubmit = false , encoder = encodeURIComponent , name , data = '' , type , hasValue ; Ext . each ( fElements , function ( element ) { name = element . name ; type = element . type ; if ( ! element . disabled && name ) { if ( / select-(one|multiple) / i . test ( type ) ) { Ext . each ( element . options , function ( opt ) { if ( opt . selected ) { hasValue = opt . hasAttribute ? opt . hasAttribute ( 'value' ) : opt . getAttributeNode ( 'value' ) . specified ; data += Ext . String . format ( \"{0}={1}&\" , encoder ( name ) , encoder ( hasValue ? opt . value : opt . text ) ) ; } } ) ; } else if ( ! ( / file|undefined|reset|button / i . test ( type ) ) ) { if ( ! ( / radio|checkbox / i . test ( type ) && ! element . checked ) && ! ( type == 'submit' && hasSubmit ) ) { data += encoder ( name ) + '=' + encoder ( element . value ) + '&' ; hasSubmit = / submit / i . test ( type ) ; } } } } ) ; return data . substr ( 0 , data . length - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the document width [CODESPLIT] function ( ) { //<debug warn> Ext . Logger . deprecate ( \"Ext.Element.getDocumentWidth() is no longer supported. \" + \"Please use Ext.Viewport#getWindowWidth() instead\" , this ) ; //</debug> return Math . max ( ! Ext . isStrict ? document . body . scrollWidth : document . documentElement . scrollWidth , this . getViewportWidth ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the current orientation of the window . This is calculated by determining if the height is greater than the width . [CODESPLIT] function ( ) { //<debug warn> Ext . Logger . deprecate ( \"Ext.Element.getOrientation() is no longer supported. \" + \"Please use Ext.Viewport#getOrientation() instead\" , this ) ; //</debug> if ( Ext . supports . OrientationChange ) { return ( window . orientation == 0 ) ? 'portrait' : 'landscape' ; } return ( window . innerHeight > window . innerWidth ) ? 'portrait' : 'landscape' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new Sortable . [CODESPLIT] function ( el , config ) { config = config || { } ; Ext . apply ( this , config ) ; this . addEvents ( /**\n             * @event sortstart\n             * @param {Ext.Sortable} this\n             * @param {Ext.event.Event} e\n             */ 'sortstart' , /**\n             * @event sortend\n             * @param {Ext.Sortable} this\n             * @param {Ext.event.Event} e\n             */ 'sortend' , /**\n             * @event sortchange\n             * @param {Ext.Sortable} this\n             * @param {Ext.Element} el The Element being dragged.\n             * @param {Number} index The index of the element after the sort change.\n             */ 'sortchange' // not yet implemented. // 'sortupdate', // 'sortreceive', // 'sortremove', // 'sortenter', // 'sortleave', // 'sortactivate', // 'sortdeactivate' ) ; this . el = Ext . get ( el ) ; this . callParent ( ) ; this . mixins . observable . constructor . call ( this ) ; if ( this . direction == 'horizontal' ) { this . horizontal = true ; } else if ( this . direction == 'vertical' ) { this . vertical = true ; } else { this . horizontal = this . vertical = true ; } this . el . addCls ( this . baseCls ) ; this . startEventName = ( this . getDelay ( ) > 0 ) ? 'taphold' : 'tapstart' ; if ( ! this . disabled ) { this . enable ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables sorting for this Sortable . This method is invoked immediately after construction of a Sortable unless the disabled configuration is set to true . [CODESPLIT] function ( ) { this . el . on ( this . startEventName , this . onStart , this , { delegate : this . itemSelector , holdThreshold : this . getDelay ( ) } ) ; this . disabled = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "MOVING SUM // FUNCTION : msum ( arr W [ options ] ) Computes a moving sum over an array . [CODESPLIT] function msum ( arr , W , options ) { var copy = true , clbk , len , sum , dropVal , out , i ; if ( ! isArray ( arr ) ) { throw new TypeError ( 'msum()::invalid input argument. Must provide an array. Value: `' + arr + '`.' ) ; } if ( ! isPositiveInteger ( W ) ) { throw new TypeError ( 'msum()::invalid input argument. Window must be a positive integer. Value: `' + W + '`.' ) ; } if ( arguments . length > 2 ) { if ( ! isObject ( options ) ) { throw new TypeError ( 'msum()::invalid input argument. Options must be an object. Value: `' + options + '`.' ) ; } if ( options . hasOwnProperty ( 'accessor' ) ) { clbk = options . accessor ; if ( ! isFunction ( clbk ) ) { throw new TypeError ( 'msum()::invalid option. Accessor option must be a function. Value: `' + clbk + '`.' ) ; } } if ( options . hasOwnProperty ( 'copy' ) ) { copy = options . copy ; if ( ! isBoolean ( copy ) ) { throw new TypeError ( 'msum()::invalid option. Copy option must be a boolean primitive. Value: `' + copy + '`.' ) ; } } } if ( W > arr . length ) { throw new Error ( 'msum()::invalid input argument. Window cannot exceed the array length.' ) ; } len = arr . length ; sum = 0 ; if ( copy && ! clbk ) { // Case 1: numeric array and return a copy... len = len - W + 1 ; out = new Array ( len ) ; // Calculate the sum for the first window... for ( i = 0 ; i < W ; i ++ ) { sum += arr [ i ] ; } out [ 0 ] = sum ; // Calculate sums for the remaining windows... for ( i = 0 ; i < len - 1 ; i ++ ) { sum += arr [ i + W ] - arr [ i ] ; out [ i + 1 ] = sum ; } return out ; } else if ( clbk ) { if ( copy ) { // Case 2: non-numeric array and return a copy... out = new Array ( len ) ; for ( i = 0 ; i < len ; i ++ ) { out [ i ] = clbk ( arr [ i ] ) ; } } else { // Case 3: non-numeric array and mutate the input array... out = arr ; for ( i = 0 ; i < len ; i ++ ) { out [ i ] = clbk ( arr [ i ] ) ; } } } else { // Case 4: numeric array and mutate the input array... out = arr ; } len = len - W + 1 ; // Calculate the sum for the first window... for ( i = 0 ; i < W ; i ++ ) { sum += out [ i ] ; } dropVal = out [ 0 ] ; out [ 0 ] = sum ; // Calculate sums for the remaining windows... for ( i = 1 ; i < len ; i ++ ) { sum += out [ i + W - 1 ] - dropVal ; dropVal = out [ i ] ; out [ i ] = sum ; } // Trim the output array: out . length = len ; return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take formatted options and creates an Express style req object . Takes an url String or an already parsed ( via . / lib / url . parse ) object . [CODESPLIT] function Request ( ghosttrain , route , url , options ) { // Headers info this . headers = options . headers || { } ; // Allows us to check protocol of client-side requests, // but relative requests won't have a protocol var protocol = 'window' in this ? window . location . protocol : '' ; // Expose URL properties var parsedURL = url . pathname ? url : parseURL ( url , true ) ; this . path = parsedURL . pathname ; this . query = parsedURL . query ; this . protocol = ( parsedURL . protocol || protocol ) . replace ( ':' , '' ) ; this . secure = this . protocol === 'https' ; this . route = route ; this . method = route . method . toUpperCase ( ) ; this . url = this . originalUrl = requestURL ( parsedURL ) ; this . params = route . params ; this . body = options . body || { } ; this . headers = options . headers || { } ; this . xhr = 'xmlhttprequest' === ( this . get ( 'X-Requested-With' ) || '' ) . toLowerCase ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Patch for objects [CODESPLIT] function _compareMaps ( a , b , options ) { debug ( a , b ) ; let alength = a . size === undefined ? a . length : a . size ; let blength = b . size === undefined ? b . length : b . size ; if ( alength === 0 && blength === 0 ) return ops . NOP ; // ops.Map([...b]) and not just ops.Rpl(b) because if b is a map it's not good JSON. if ( alength === 0 || blength === 0 ) return new ops . Map ( [ ... b ] ) ; let patch = [ ] ; if ( ! options . sorted ) { a = Array . from ( a ) . sort ( ( a , b ) => utils . compare ( a , b , options ) ) ; b = Array . from ( b ) . sort ( ( a , b ) => utils . compare ( a , b , options ) ) ; } let ai = 1 , bi = 1 ; let ao = a [ 0 ] , bo = b [ 0 ] let element_options = options . getArrayElementOptions ( ) ; do { let comparison = utils . compare ( ao , bo , options ) ; debug ( \"comparing items\" , ao , bo , comparison ) ; if ( comparison < 0 ) { debug ( 'skip' ) ; ao = a [ ai ++ ] ; } else if ( comparison > 0 ) { debug ( 'insert' ) ; patch . push ( [ options . key ( bo ) , new ops . Ins ( options . value ( bo ) ) ] ) ; bo = b [ bi ++ ] ; } else { if ( options . value ( ao ) !== options . value ( bo ) ) { let element_patch = compare ( options . value ( ao ) , options . value ( bo ) , element_options ) if ( element_patch != ops . NOP ) patch . push ( [ options . key ( bo ) , element_patch ] ) ; } else debug ( 'skip2' ) ; ao = a [ ai ++ ] ; bo = b [ bi ++ ] ; } } while ( ai <= a . length && bi <= b . length ) ; while ( ai <= a . length ) { patch . push ( [ options . key ( ao ) , ops . DEL ] ) ; ao = a [ ai ++ ] ; } while ( bi <= b . length ) { patch . push ( [ options . key ( bo ) , new ops . Ins ( options . value ( bo ) ) ] ) ; bo = b [ bi ++ ] ; } return new ops . Map ( patch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare two object to produce a patch object . [CODESPLIT] function compare ( a , b , options ) { debug ( 'compare %j,%j options: %j' , a , b , options ) ; options = Options . addDefaults ( options ) ; debug ( 'compare - options %j' , options ) ; if ( a === b ) return ops . NOP ; if ( b === undefined ) return ops . DEL ; if ( a === undefined ) return new ops . Rpl ( b ) ; if ( typeof a === 'object' && typeof b === 'object' ) { if ( utils . isArrayLike ( a ) && utils . isArrayLike ( b ) ) { if ( options . map ) { return _compareMaps ( a , b , options ) ; } else { return _compareArrays ( a , b , options ) ; } } else if ( a instanceof Map && b instanceof Map ) { return _compareMaps ( a , b , options ) ; } else if ( a . constructor === b . constructor ) { // This isn't quite right, we can merge objects with a common base class return _compareObjects ( a , b , options ) ; } } return new ops . Rpl ( b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert over - the - wire JSON format back into typed patch object [CODESPLIT] function fromJSON ( object ) { if ( object instanceof ops . Op ) return object ; // If already patch, return it if ( object === undefined ) return ops . NOP ; if ( object . op ) { if ( object . op === ops . Rpl . name ) return new ops . Rpl ( object . data ) ; if ( object . op === ops . Ins . name ) return new ops . Ins ( object . data ) ; else if ( object . op === ops . NOP . name ) return ops . NOP ; else if ( object . op === ops . DEL . name ) return ops . DEL ; else if ( object . op === ops . Mrg . name ) return new ops . Mrg ( utils . map ( object . data , fromJSON ) ) ; else if ( object . op === ops . Map . name ) return new ops . Map ( object . data . map ( ( [ key , op ] ) => [ key , fromJSON ( op ) ] ) ) ; else if ( object . op === ops . Arr . name ) return new ops . Arr ( object . data . map ( ( [ key , op ] ) => [ key , fromJSON ( op ) ] ) ) ; else throw new Error ( 'unknown diff.op ' + object . op ) ; } else { return new ops . Rpl ( object ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts the collection by a single sorter function . [CODESPLIT] function ( sorterFn ) { var me = this , items = me . items , keys = me . keys , length = items . length , temp = [ ] , i ; //first we create a copy of the items array so that we can sort it for ( i = 0 ; i < length ; i ++ ) { temp [ i ] = { key : keys [ i ] , value : items [ i ] , index : i } ; } Ext . Array . sort ( temp , function ( a , b ) { var v = sorterFn ( a . value , b . value ) ; if ( v === 0 ) { v = ( a . index < b . index ? - 1 : 1 ) ; } return v ; } ) ; //copy the temporary array back into the main this.items and this.keys objects for ( i = 0 ; i < length ; i ++ ) { items [ i ] = temp [ i ] . value ; keys [ i ] = temp [ i ] . key ; } me . fireEvent ( 'sort' , me , items , keys ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reorders each of the items based on a mapping from old index to new index . Internally this just translates into a sort . The sort event is fired whenever reordering has occured . [CODESPLIT] function ( mapping ) { var me = this , items = me . items , index = 0 , length = items . length , order = [ ] , remaining = [ ] , oldIndex ; me . suspendEvents ( ) ; //object of {oldPosition: newPosition} reversed to {newPosition: oldPosition} for ( oldIndex in mapping ) { order [ mapping [ oldIndex ] ] = items [ oldIndex ] ; } for ( index = 0 ; index < length ; index ++ ) { if ( mapping [ index ] == undefined ) { remaining . push ( items [ index ] ) ; } } for ( index = 0 ; index < length ; index ++ ) { if ( order [ index ] == undefined ) { order [ index ] = remaining . shift ( ) ; } } me . clear ( ) ; me . addAll ( order ) ; me . resumeEvents ( ) ; me . fireEvent ( 'sort' , me ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TRANSPOSE // FUNCTION : transpose ( matrix [ options ] ) Computes the transpose of a matrix . [CODESPLIT] function transpose ( mat , options ) { /* jshint newcap:false */ var strides , shape , opts , ctor , err , tmp , d ; if ( ! isMatrixLike ( mat ) ) { throw new TypeError ( 'transpose()::invalid input argument. First argument must be a matrix. Value: `' + mat + '`.' ) ; } opts = { } ; if ( arguments . length > 1 ) { err = validate ( opts , options ) ; if ( err ) { throw err ; } } else { opts . copy = true ; } if ( opts . copy ) { // Copy the matrix data to a new typed array: ctor = ctors ( mat . dtype ) ; d = new ctor ( mat . data ) ; // Swap the dimensions: shape = [ mat . shape [ 1 ] , mat . shape [ 0 ] ] ; // Swap the strides: strides = [ mat . strides [ 1 ] , mat . strides [ 0 ] ] ; // Return a new matrix: return new mat . constructor ( d , mat . dtype , shape , mat . offset , strides ) ; } else { // Swap the dimensions... tmp = mat . shape [ 0 ] ; mat . shape [ 0 ] = mat . shape [ 1 ] ; mat . shape [ 1 ] = tmp ; // Swap the strides... tmp = mat . strides [ 0 ] ; mat . strides [ 0 ] = mat . strides [ 1 ] ; mat . strides [ 1 ] = tmp ; // Return the matrix transpose: return mat ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * We use a queue to process events when we must handle the events sequentially [CODESPLIT] function Queue ( q ) { events . EventEmitter . call ( this ) ; var self = this ; this . q = q && q . process ? q : kue . createQueue ( ) ; this . q . process ( 'message' , function ( message , done ) { self . emit ( 'message' , message ) ; done ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke . apply if value is a function otherwise return default value . [CODESPLIT] function apply ( func , args , self ) { return ( typeof func === 'function' ) ? func . apply ( self , array ( args ) ) : func }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Following functions are not executed on import anymore [CODESPLIT] function detectDeviceClass ( ) { var body = document . body ; if ( isMobile . any ( ) ) { body . classList . add ( 'mobile' ) ; } if ( isMobile . Android ( ) ) { body . classList . add ( 'android' ) ; } if ( isTablet . any ( ) ) { body . classList . add ( 'tablet' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function can be triggered on window resize [CODESPLIT] function detectWindowWidth ( ) { var mobileWidth = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : 730 ; var isMobileWidth = window . innerWidth < mobileWidth ; var body = document . body ; if ( isMobileWidth ) { body . classList . add ( 'is-mobile-width' ) ; } else { body . classList . remove ( 'is-mobile-width' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "array of change stamps [CODESPLIT] function ( config , callback , scope ) { var changed = false ; if ( config ) { config . config_id = 'csv' ; Ext . data . CSV . superclass . constructor . call ( this , config ) ; if ( config . v ) { this . v = [ ] ; this . do_add ( config . v ) ; } } if ( this . v === undefined ) { this . v = [ ] ; changed = true ; } this . writeAndCallback ( changed , callback , scope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the schema s property at path is a ref - or an Array of refs - and if yes adds a virtual property suffixed with P which returns a promise to the reference s query result ( s ) . [CODESPLIT] function addVirtualRef ( schema , node , path ) { if ( _ . isArray ( node ) && isRef ( _ . first ( node ) ) ) { schema . virtual ( path + 'P' ) . get ( function ( ) { if ( ! this [ path ] || ! this [ path ] . length ) return Promise . resolve ( [ ] ) ; var model = this . constructor . db . model ( _ . first ( node ) . ref ) ; return findAsync . call ( model , { $or : _ . map ( this [ path ] , function ( id ) { return { _id : id } ; } ) } ) ; } ) ; } else if ( isRef ( node ) ) { schema . virtual ( path + 'P' ) . get ( function ( ) { var model = this . constructor . db . model ( node . ref ) ; return findByIdAsync . call ( model , this [ path ] ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FUNCTIONS // FUNCTION : createTopic ( options ) Creates a new topic . [CODESPLIT] function createTopic ( options ) { var max = Number . MAX_VALUE , duplicates = false ; if ( ! options . hasOwnProperty ( 'max' ) ) { options . max = max ; } else { max = options . max ; } if ( ! options . hasOwnProperty ( 'duplicates' ) ) { options . duplicates = duplicates ; } else { duplicates = options . duplicates ; } if ( ! isInteger ( max ) || max < 0 ) { throw new TypeError ( 'createTopic()::invalid option. Max subscribers must be an integer greater than or equal to 0.' ) ; } if ( typeof duplicates !== 'boolean' ) { throw new TypeError ( 'createTopic()::invalid option. Duplicates flag must be a boolean.' ) ; } return { 'subscribers' : [ ] , 'options' : options } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "loadModule - load module ( theme or plugin ) for app [CODESPLIT] function loadModule ( data , name ) { if ( typeof data !== 'object' ) { return ; } // Run before load module if ( typeof data . willLoad === 'function' ) { data . willLoad ( ) ; } // CSS Style if ( Array . isArray ( data . styles ) ) { data . styles . forEach ( function ( styles ) { theme . add ( styles , name ) ; } ) ; } else if ( typeof data . styles === 'object' ) { theme . add ( data . styles , name ) ; } // Components if ( data . components !== undefined ) { theme . addComponents ( data . components , name ) ; } // Layouts if ( data . layouts !== undefined ) { addLayout ( data . layouts ) ; } // I18n if ( data . i18n !== undefined ) { addTranslation ( data . i18n ) ; } // Redux actions if ( data . actions !== undefined ) { addActions ( data . actions ) ; } // Redux reducers if ( typeof data . reducers === 'function' ) { data . reducers ( ) ; } // Run after load module if ( typeof data . loaded === 'function' ) { data . loaded ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Workarounds based on findings by Jim Driscoll http : // weblogs . java . net / blog / driscoll / archive / 2009 / 09 / 08 / eval - javascript - global - context [CODESPLIT] function ( data ) { if ( data && jQuery . trim ( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window . execScript || function ( data ) { window [ \"eval\" ] . call ( window , data ) ; // jscs:ignore requireDotNotation } ) ( data ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multifunctional method to get and set values of a collection The value / s can optionally be executed if it s a function [CODESPLIT] function ( elems , fn , key , value , chainable , emptyGet , raw ) { var i = 0 , length = elems . length , bulk = key == null ; // Sets many values if ( jQuery . type ( key ) === \"object\" ) { chainable = true ; for ( i in key ) { access ( elems , fn , i , key [ i ] , true , emptyGet , raw ) ; } // Sets one value } else if ( value !== undefined ) { chainable = true ; if ( ! jQuery . isFunction ( value ) ) { raw = true ; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn . call ( elems , value ) ; fn = null ; // ...except when executing function values } else { bulk = fn ; fn = function ( elem , key , value ) { return bulk . call ( jQuery ( elem ) , value ) ; } ; } } if ( fn ) { for ( ; i < length ; i ++ ) { fn ( elems [ i ] , key , raw ? value : value . call ( elems [ i ] , i , fn ( elems [ i ] , key ) ) ) ; } } } return chainable ? elems : // Gets bulk ? fn . call ( elems ) : length ? fn ( elems [ 0 ] , key ) : emptyGet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates over the standard event callback ( as well as the fancy multiple space - separated events change blur callback and jQuery - style event maps { event : callback } ) . [CODESPLIT] function ( iteratee , events , name , callback , opts ) { var i = 0 , names ; if ( name && typeof name === 'object' ) { // Handle event maps. if ( callback !== void 0 && 'context' in opts && opts . context === void 0 ) opts . context = callback ; for ( names = _ . keys ( name ) ; i < names . length ; i ++ ) { events = eventsApi ( iteratee , events , names [ i ] , name [ names [ i ] ] , opts ) ; } } else if ( name && eventSplitter . test ( name ) ) { // Handle space separated event names by delegating them individually. for ( names = name . split ( eventSplitter ) ; i < names . length ; i ++ ) { events = iteratee ( events , names [ i ] , callback , opts ) ; } } else { // Finally, standard events. events = iteratee ( events , name , callback , opts ) ; } return events ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splices insert into array at index at . [CODESPLIT] function ( array , insert , at ) { at = Math . min ( Math . max ( at , 0 ) , array . length ) ; var tail = Array ( array . length - at ) ; var length = insert . length ; for ( var i = 0 ; i < tail . length ; i ++ ) tail [ i ] = array [ i + at ] ; for ( i = 0 ; i < length ; i ++ ) array [ i + at ] = insert [ i ] ; for ( i = 0 ; i < tail . length ; i ++ ) array [ i + length + at ] = tail [ i ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a model or a list of models from the set . [CODESPLIT] function ( models , options ) { options = _ . extend ( { } , options ) ; var singular = ! _ . isArray ( models ) ; models = singular ? [ models ] : _ . clone ( models ) ; var removed = this . _removeModels ( models , options ) ; if ( ! options . silent && removed ) this . trigger ( 'update' , this , options ) ; return singular ? removed [ 0 ] : removed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method called by both remove and set . [CODESPLIT] function ( models , options ) { var removed = [ ] ; for ( var i = 0 ; i < models . length ; i ++ ) { var model = this . get ( models [ i ] ) ; if ( ! model ) continue ; var index = this . indexOf ( model ) ; this . models . splice ( index , 1 ) ; this . length -- ; if ( ! options . silent ) { options . index = index ; model . trigger ( 'remove' , model , this , options ) ; } removed . push ( model ) ; this . _removeReference ( model , options ) ; } return removed . length ? removed : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does the pathname match the root? [CODESPLIT] function ( ) { var path = this . decodeFragment ( this . location . pathname ) ; var root = path . slice ( 0 , this . root . length - 1 ) + '/' ; return root === this . root ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures our PT array is in the correct sorted order ( by startTime ) [CODESPLIT] function ( ) { if ( ! performanceTimelineRequiresSort ) { return ; } // // Measures, which may be in this list, may enter the list in // an unsorted order. For example: // //  1. measure(\"a\") //  2. mark(\"start_mark\") //  3. measure(\"b\", \"start_mark\") //  4. measure(\"c\") //  5. getEntries() // // When calling #5, we should return [a,c,b] because technically the start time // of c is \"0\" (navigationStart), which will occur before b's start time due to the mark. // performanceTimeline . sort ( function ( a , b ) { return a . startTime - b . startTime ; } ) ; performanceTimelineRequiresSort = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cache management ---------------- Returns the template data associated with a template property string . Caches it in the process or retrieves it from the cache if already available . Returns undefined if there is no cacheable template data . [CODESPLIT] function getTemplateData ( templateProp , view , viewOptions ) { var data ; if ( templateProp && _ . isString ( templateProp ) ) { data = templateCache [ templateProp ] ; if ( ! data ) data = _createTemplateCache ( templateProp , view , viewOptions ) ; if ( data . invalid ) data = undefined ; if ( data ) data = _copyCacheEntry ( data ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the template data associated with a given view provided that the template is set to a non - empty string . Otherwise it returns undefined . Manages caching behind the scenes . [CODESPLIT] function getViewTemplateData ( view , viewOptions ) { var data , meta = view . declarativeViews . meta ; if ( ! meta . processed ) { if ( view . template && _ . isString ( view . template ) ) { meta . originalTemplateProp = view . template ; data = getTemplateData ( view . template , view , viewOptions ) ; meta . processed = true ; meta . inGlobalCache = true ; if ( data ) events . trigger ( \"cacheEntry:view:process\" , _copyCacheEntry ( data ) , meta . originalTemplateProp , view , viewOptions ) ; } else { data = undefined ; meta . processed = true ; meta . inGlobalCache = false ; } } else { data = meta . inGlobalCache ? getTemplateData ( meta . originalTemplateProp , view , viewOptions ) : undefined ; } if ( data ) events . trigger ( \"cacheEntry:view:fetch\" , data , meta . originalTemplateProp , view , viewOptions ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears the cache as a whole . [CODESPLIT] function clearCache ( fromMarionette ) { templateCache = { } ; if ( ! fromMarionette && Backbone . Marionette && Backbone . Marionette . TemplateCache ) Backbone . Marionette . TemplateCache . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes one or more cache entries . [CODESPLIT] function clearCachedTemplate ( templateProp ) { var fromMarionette = false , args = _ . toArray ( arguments ) , lastArg = _ . last ( args ) ; // When called from Marionette, or called recursively, the last argument is a \"fromMarionette\" boolean. Splice // it off before proceeding. if ( args . length && _ . isBoolean ( lastArg ) ) fromMarionette = args . pop ( ) ; // Handle multiple template props passed in as a varargs list, or as an array, with recursive calls for each // template property. if ( args . length > 1 ) { _ . each ( args , function ( singleProp ) { clearCachedTemplate ( singleProp , fromMarionette ) ; } ) ; } else if ( _ . isArray ( templateProp ) || _ . isArguments ( templateProp ) ) { _ . each ( templateProp , function ( singleProp ) { clearCachedTemplate ( singleProp , fromMarionette ) ; } ) ; } else { if ( ! templateProp ) throw new GenericError ( \"Missing argument: string identifying the template. The string should be a template selector or the raw HTML of a template, as provided to the template property of a view when the cache entry was created\" ) ; // Dealing with a single templateProp argument. // // Delete the corresponding cache entry. Try to clear it from the Marionette cache as well. The // templateProp must be a string - non-string arguments are quietly ignored. if ( _ . isString ( templateProp ) ) { _clearCachedTemplate ( templateProp ) ; if ( ! fromMarionette && Backbone . Marionette && Backbone . Marionette . TemplateCache ) { try { Backbone . Marionette . TemplateCache . clear ( templateProp ) ; } catch ( err ) { } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the template cache entry associated with a given view provided that a cache entry exists . [CODESPLIT] function clearViewTemplateCache ( view ) { var meta = view . declarativeViews . meta ; if ( meta . processed ) { if ( meta . inGlobalCache ) _clearCachedTemplate ( meta . originalTemplateProp ) ; } else if ( view . template && _ . isString ( view . template ) ) { _clearCachedTemplate ( view . template ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines the default template loader . Accepts a selector string and returns the template node ( usually a <script > or <template > node ) in a jQuery wrapper . [CODESPLIT] function loadTemplate ( templateProperty ) { var $template ; try { $template = $ ( templateProperty ) ; // If the template is not in the DOM, treat the template property as a raw template string instead. That // part is handled in `catch`, and should not be guarded against further errors here. To switch to that // process, just throw an error. if ( ! $ . contains ( document . documentElement , $template [ 0 ] ) ) throw new Error ( ) ; } catch ( err ) { $template = _wrapRawTemplate ( templateProperty ) ; // If the template string cannot be retrieved unaltered even after wrapping it in a script tag, bail out by // throwing a silent error (will be caught, and not propagated further, in _createTemplateCache()). if ( $template . html ( ) !== templateProperty ) throw new Error ( \"Failed to wrap template string in script tag without altering it\" ) ; } return $template ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a raw HTML / template string and wraps it in a script tag ( of type text / x - template ) . In the process it detects el - related data attributes which are contained in an HTML comment and sets them on the script tag . Returns the script element as a jQuery object . [CODESPLIT] function _wrapRawTemplate ( templateString ) { var $wrapper = $ ( \"<script />\" ) . attr ( \"type\" , \"text/x-template\" ) . text ( templateString ) , elDataAttributes = _getEmbeddedElAttributes ( templateString ) ; if ( elDataAttributes ) $wrapper . attr ( elDataAttributes ) ; return $wrapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a raw HTML / template string and looks for el - related data attributes which are contained in a comment . Returns the attributes hash or undefined if no attributes are found . [CODESPLIT] function _getEmbeddedElAttributes ( templateString ) { var elDataAttributes = { } , elDefinitionMatch = rxElDefinitionComment . exec ( templateString ) , elDefinitionComment = elDefinitionMatch && elDefinitionMatch [ 0 ] ; if ( elDefinitionComment ) { _ . each ( rxRegisteredDataAttributes , function ( rxAttributeMatcher , attributeName ) { var match = rxAttributeMatcher . exec ( elDefinitionComment ) , attributeValue = match && match [ 2 ] ; if ( attributeValue ) elDataAttributes [ attributeName ] = attributeValue ; } ) ; } return _ . size ( elDataAttributes ) ? elDataAttributes : undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a copy of a cache entry and returns it . Protects the original cache entry from modification except for the _pluginData property which remains writable and can be accessed from the copy . [CODESPLIT] function _copyCacheEntry ( cacheEntry ) { var copy = _ . clone ( cacheEntry ) ; if ( _ . isObject ( copy . attributes ) ) copy . attributes = _ . clone ( copy . attributes ) ; return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a cache entry for a given template property . [CODESPLIT] function _createTemplateCache ( templateProp , view , viewOptions ) { var $template , data , html , customLoader = Backbone . DeclarativeViews . custom . loadTemplate , defaultLoader = Backbone . DeclarativeViews . defaults . loadTemplate , modifiedDefaultLoader = defaultLoader !== loadTemplate , cacheId = templateProp ; // Load the template try { $template = customLoader ? customLoader ( templateProp , view , viewOptions ) : defaultLoader ( templateProp , view , viewOptions ) ; } catch ( err ) { // Rethrow and exit if the alarm has been raised deliberately, using an error type of Backbone.DeclarativeViews. if ( _isDeclarativeViewsErrorType ( err ) ) throw err ; // Otherwise, continue without having fetched a template. $template = \"\" ; } if ( ( customLoader || modifiedDefaultLoader ) && $template !== \"\" && ! ( $template instanceof Backbone . $ ) ) { throw new CustomizationError ( \"Invalid return value. The \" + ( customLoader ? \"custom\" : \"default\" ) + \" loadTemplate function must return a jQuery instance, but it hasn't\" ) ; } // Create cache entry if ( $template . length ) { // Read the el-related data attributes of the template. data = _getDataAttributes ( $template ) ; html = $template . html ( ) ; templateCache [ cacheId ] = { html : html , compiled : _tryCompileTemplate ( html , $template ) , tagName : data . tagName , className : data . className , id : data . id , attributes : data . attributes , // Data store for plugins. Plugins should create their own namespace in the store, with the plugin name // as key. _pluginData : { } } ; events . trigger ( \"cacheEntry:create\" , templateCache [ cacheId ] , templateProp , view , viewOptions ) ; } else { templateCache [ cacheId ] = { invalid : true } ; } return templateCache [ cacheId ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the compiled template if a custom compiler is set in Backbone . DeclarativeViews . custom . compiler or undefined if no compiler is set . [CODESPLIT] function _tryCompileTemplate ( html , $template ) { var compiled , customCompiler = Backbone . DeclarativeViews . custom . compiler ; if ( customCompiler ) { if ( customCompiler && ! _ . isFunction ( customCompiler ) ) throw new CustomizationError ( \"Invalid custom template compiler set in Backbone.DeclarativeViews.custom.compiler: compiler is not a function\" ) ; try { compiled = customCompiler ( html , $template ) ; } catch ( err ) { throw new CompilerError ( 'An error occurred while compiling the template. The compiler had been passed the HTML string \"' + html + ( $template ? '\" as the first argument, and the corresponding template node, wrapped in a jQuery object, as the second argument.' : '\" as the only argument.' ) + \"\\nOriginal error thrown by the compiler:\\n\" + err . message ) ; } } return compiled ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a name to the list of data attributes which are used and managed by Backbone . Declarative . Views . The name must be passed without the data - prefix but written as in the data attribute ( ie tag - name not tagName ) . [CODESPLIT] function _registerDataAttribute ( name , options ) { var existingNames = _getRegisteredDataAttributeNames ( ) , fullName = \"data-\" + name , type = options && options . isJSON ? \"json\" : \"primitives\" , names = registeredDataAttributes [ type ] ; if ( name . indexOf ( \"data-\" ) === 0 ) throw new CustomizationError ( 'registerDataAttribute(): Illegal attribute name \"' + name + '\", must be registered without \"data-\" prefix' ) ; if ( name === \"html\" || name === \"compiled\" ) throw new CustomizationError ( 'registerDataAttribute(): Cannot register attribute name \"' + name + '\" because it is reserved' ) ; if ( _ . contains ( existingNames , name ) ) throw new CustomizationError ( 'registerDataAttribute(): Cannot register attribute name \"' + name + '\" because it has already been registered' ) ; // Add the name to the list of registered data attributes names . push ( name ) ; registeredDataAttributes [ type ] = _ . uniq ( names ) ; // Create amd store a regex matching the attribute and its value in an HTML/template string, for transfer onto a // wrapper node (see _wrapRawTemplate()) rxRegisteredDataAttributes [ fullName ] = new RegExp ( fullName + \"\\\\s*=\\\\s*(['\\\"])([\\\\s\\\\S]+?)\\\\1\" ) ; // Update the regular expression which tests an HTML/template string and detects a comment containing registered // attributes. rxElDefinitionComment = _createElDefinitionCommentRx ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads registered data attributes of a given element from the DOM and updates an existing jQuery data cache with these values . [CODESPLIT] function _updateJQueryDataCache ( $elem ) { var add = { } , remove = [ ] ; if ( $ . hasData ( $elem [ 0 ] ) ) { // A jQuery data cache exists. Update it for the el properties (and attribute names registered by a plugin). // Primitive data types. Normally, this will read the \"data-tag-name\", \"data-class-name\" and \"data-id\" // attributes. _ . each ( registeredDataAttributes . primitives , function ( attributeName ) { var attributeValue = $elem . attr ( \"data-\" + attributeName ) ; if ( attributeValue === undefined ) { remove . push ( attributeName ) ; } else { add [ toCamelCase ( attributeName ) ] = attributeValue ; } } ) ; // Stringified JSON data. Normally, this just deals with \"data-attributes\". _ . each ( registeredDataAttributes . json , function ( attributeName ) { var attributeValue = $elem . attr ( \"data-\" + attributeName ) ; if ( attributeValue === undefined ) { remove . push ( attributeName ) ; } else { try { add [ toCamelCase ( attributeName ) ] = $ . parseJSON ( attributeValue ) ; } catch ( err ) { remove . push ( attributeName ) ; } } } ) ; if ( remove . length ) $elem . removeData ( remove ) ; if ( _ . size ( add ) ) $elem . data ( add ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers an alternative way to access the cache and set up a custom compiler and loader . Intended for use by plugins . [CODESPLIT] function _registerCacheAlias ( namespaceObject , instanceCachePropertyName ) { namespaceObject . getCachedTemplate = Backbone . DeclarativeViews . getCachedTemplate ; namespaceObject . clearCachedTemplate = Backbone . DeclarativeViews . clearCachedTemplate ; namespaceObject . clearCache = Backbone . DeclarativeViews . clearCache ; namespaceObject . custom = Backbone . DeclarativeViews . custom ; if ( instanceCachePropertyName ) { instanceCacheAliases . push ( instanceCachePropertyName ) ; instanceCacheAliases = _ . unique ( instanceCacheAliases ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if an error belongs to the error types of Backbone . DeclarativeViews . [CODESPLIT] function _isDeclarativeViewsErrorType ( error ) { return error instanceof GenericError || error instanceof TemplateError || error instanceof CompilerError || error instanceof CustomizationError || error instanceof ConfigurationError ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marionette integration ---------------------- [CODESPLIT] function joinMarionette ( ) { if ( Backbone . Marionette && Backbone . Marionette . TemplateCache && ! isMarionetteInitialized ) { originalClearCache = Backbone . Marionette . TemplateCache . clear ; // Custom implementation of Marionette.TemplateCache.clear() // // When the Marionette cache is cleared, the DeclarativeViews cache is cleared as well. This is not technically // necessary, but makes sense. If there is a reason to invalidate a cached template, it applies to all caches. Backbone . Marionette . TemplateCache . clear = function ( ) { if ( arguments . length ) { Backbone . DeclarativeViews . clearCachedTemplate ( arguments , true ) ; } else { Backbone . DeclarativeViews . clearCache ( true ) ; } originalClearCache . apply ( this , arguments ) ; } ; isMarionetteInitialized = true ; // Removed: integration of the Marionette and Backbone.Declarative.Views template loading mechanisms // // Integrating the template loaders turned out to be of little or no benefit, and could potentially have caused // problems with other custom loaders. In detail: // // - Integration saved exactly one DOM access per *template*. Given the limited number of templates in a project, //   the performance gain had often been too small to even be measurable. // // - During testing with just a single template, the net effect was even negative (!) - integration and the //   associated overhead seemed to slow things down. // // - With integration, custom loaders like the one for Marionette/Handlebars had been trickier to use. Load //   order suddenly mattered. The code setting up a custom loader had to be run after integrating //   Backbone.Declarative.Views with Marionette. Otherwise, the custom loader would haven been overwritten, //   breaking the application. // // In a nutshell, loader integration has proven to be more trouble than it is worth. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a custom error type . [CODESPLIT] function createCustomErrorType ( name ) { function CustomError ( message ) { this . message = message ; if ( Error . captureStackTrace ) { Error . captureStackTrace ( this , this . constructor ) ; } else { this . stack = ( new Error ( ) ) . stack ; } } CustomError . prototype = new Error ( ) ; CustomError . prototype . name = name ; CustomError . prototype . constructor = CustomError ; return CustomError ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the currently registered handler for the specified name . Throws an exception if no handler is found . [CODESPLIT] function ( name ) { var config = this . _wreqrHandlers [ name ] ; if ( ! config ) { return ; } return function ( ) { return config . callback . apply ( config . context , arguments ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a named command with the supplied args [CODESPLIT] function ( name ) { name = arguments [ 0 ] ; var args = _ . rest ( arguments ) ; if ( this . hasHandler ( name ) ) { this . getHandler ( name ) . apply ( this , args ) ; } else { this . storage . addCommand ( name , args ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attach the handlers to a given message system type [CODESPLIT] function ( type , hash , context ) { if ( ! hash ) { return ; } context = context || this ; var method = type === \"vent\" ? \"on\" : \"setHandler\" ; _ . each ( hash , function ( fn , eventName ) { this [ type ] [ method ] ( eventName , _ . bind ( fn , context ) ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trigger the dom : refresh event and corresponding onDomRefresh method [CODESPLIT] function triggerDOMRefresh ( ) { if ( view . _isShown && view . _isRendered && Marionette . isNodeAttached ( view . el ) ) { Marionette . triggerMethodOn ( view , 'dom:refresh' , view ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generic looping function [CODESPLIT] function iterateEvents ( target , entity , bindings , functionCallback , stringCallback ) { if ( ! entity || ! bindings ) { return ; } // type-check bindings if ( ! _ . isObject ( bindings ) ) { throw new Marionette . Error ( { message : 'Bindings must be an object or function.' , url : 'marionette.functions.html#marionettebindentityevents' } ) ; } // allow the bindings to be a function bindings = Marionette . _getValue ( bindings , target ) ; // iterate the bindings and bind them _ . each ( bindings , function ( methods , evt ) { // allow for a function as the handler, // or a list of event names as a string if ( _ . isFunction ( methods ) ) { functionCallback ( target , entity , evt , methods ) ; } else { stringCallback ( target , entity , evt , methods ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a callback to be executed . Callbacks added here are guaranteed to execute even if they are added after the run method is called . [CODESPLIT] function ( callback , contextOverride ) { var promise = _ . result ( this . _deferred , 'promise' ) ; this . _callbacks . push ( { cb : callback , ctx : contextOverride } ) ; promise . then ( function ( args ) { if ( contextOverride ) { args . context = contextOverride ; } callback . call ( args . context , args . options ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Displays a backbone view instance inside of the region . Handles calling the render method for you . Reads content directly from the el attribute . Also calls an optional onShow and onDestroy method on your view just after showing or just before destroying the view respectively . The preventDestroy option can be used to prevent a view from the old view being destroyed on show . The forceShow option can be used to force a view to be re - rendered if it s already shown in the region . [CODESPLIT] function ( view , options ) { if ( ! this . _ensureElement ( ) ) { return ; } this . _ensureViewIsIntact ( view ) ; Marionette . MonitorDOMRefresh ( view ) ; var showOptions = options || { } ; var isDifferentView = view !== this . currentView ; var preventDestroy = ! ! showOptions . preventDestroy ; var forceShow = ! ! showOptions . forceShow ; // We are only changing the view if there is a current view to change to begin with var isChangingView = ! ! this . currentView ; // Only destroy the current view if we don't want to `preventDestroy` and if // the view given in the first argument is different than `currentView` var _shouldDestroyView = isDifferentView && ! preventDestroy ; // Only show the view given in the first argument if it is different than // the current view or if we want to re-show the view. Note that if // `_shouldDestroyView` is true, then `_shouldShowView` is also necessarily true. var _shouldShowView = isDifferentView || forceShow ; if ( isChangingView ) { this . triggerMethod ( 'before:swapOut' , this . currentView , this , options ) ; } if ( this . currentView && isDifferentView ) { delete this . currentView . _parent ; } if ( _shouldDestroyView ) { this . empty ( ) ; // A `destroy` event is attached to the clean up manually removed views. // We need to detach this event when a new view is going to be shown as it // is no longer relevant. } else if ( isChangingView && _shouldShowView ) { this . currentView . off ( 'destroy' , this . empty , this ) ; } if ( _shouldShowView ) { // We need to listen for if a view is destroyed // in a way other than through the region. // If this happens we need to remove the reference // to the currentView since once a view has been destroyed // we can not reuse it. view . once ( 'destroy' , this . empty , this ) ; // make this region the view's parent, // It's important that this parent binding happens before rendering // so that any events the child may trigger during render can also be // triggered on the child's ancestor views view . _parent = this ; this . _renderView ( view ) ; if ( isChangingView ) { this . triggerMethod ( 'before:swap' , view , this , options ) ; } this . triggerMethod ( 'before:show' , view , this , options ) ; Marionette . triggerMethodOn ( view , 'before:show' , view , this , options ) ; if ( isChangingView ) { this . triggerMethod ( 'swapOut' , this . currentView , this , options ) ; } // An array of views that we're about to display var attachedRegion = Marionette . isNodeAttached ( this . el ) ; // The views that we're about to attach to the document // It's important that we prevent _getNestedViews from being executed unnecessarily // as it's a potentially-slow method var displayedViews = [ ] ; var attachOptions = _ . extend ( { triggerBeforeAttach : this . triggerBeforeAttach , triggerAttach : this . triggerAttach } , showOptions ) ; if ( attachedRegion && attachOptions . triggerBeforeAttach ) { displayedViews = this . _displayedViews ( view ) ; this . _triggerAttach ( displayedViews , 'before:' ) ; } this . attachHtml ( view ) ; this . currentView = view ; if ( attachedRegion && attachOptions . triggerAttach ) { displayedViews = this . _displayedViews ( view ) ; this . _triggerAttach ( displayedViews ) ; } if ( isChangingView ) { this . triggerMethod ( 'swap' , view , this , options ) ; } this . triggerMethod ( 'show' , view , this , options ) ; Marionette . triggerMethodOn ( view , 'show' , view , this , options ) ; return this ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Destroy the current view if there is one . If there is no current view it does nothing and returns immediately . [CODESPLIT] function ( options ) { var view = this . currentView ; var emptyOptions = options || { } ; var preventDestroy = ! ! emptyOptions . preventDestroy ; // If there is no view in the region // we should not remove anything if ( ! view ) { return this ; } view . off ( 'destroy' , this . empty , this ) ; this . triggerMethod ( 'before:empty' , view ) ; if ( ! preventDestroy ) { this . _destroyView ( ) ; } this . triggerMethod ( 'empty' , view ) ; // Remove region pointer to the currentView delete this . currentView ; if ( preventDestroy ) { this . $el . contents ( ) . detach ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "call destroy or remove depending on which is found on the view ( if showing a raw Backbone view or a Marionette View ) [CODESPLIT] function ( ) { var view = this . currentView ; if ( view . isDestroyed ) { return ; } if ( ! view . supportsDestroyLifecycle ) { Marionette . triggerMethodOn ( view , 'before:destroy' , view ) ; } if ( view . destroy ) { view . destroy ( ) ; } else { view . remove ( ) ; // appending isDestroyed to raw Backbone View allows regions // to throw a ViewDestroyedError for this view view . isDestroyed = true ; } if ( ! view . supportsDestroyLifecycle ) { Marionette . triggerMethodOn ( view , 'destroy' , view ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build an instance of a region by passing in a configuration object and a default region class to use if none is specified in the config . The config object should either be a string as a jQuery DOM selector a Region class directly or an object literal that specifies a selector a custom regionClass and any options to be supplied to the region : js { selector : #foo regionClass : MyCustomRegion allowMissingEl : false } [CODESPLIT] function ( regionConfig , DefaultRegionClass ) { if ( _ . isString ( regionConfig ) ) { return this . _buildRegionFromSelector ( regionConfig , DefaultRegionClass ) ; } if ( regionConfig . selector || regionConfig . el || regionConfig . regionClass ) { return this . _buildRegionFromObject ( regionConfig , DefaultRegionClass ) ; } if ( _ . isFunction ( regionConfig ) ) { return this . _buildRegionFromRegionClass ( regionConfig ) ; } throw new Marionette . Error ( { message : 'Improper region configuration type.' , url : 'marionette.region.html#region-configuration-types' } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the region from a configuration object js { selector : #foo regionClass : FooRegion allowMissingEl : false } [CODESPLIT] function ( regionConfig , DefaultRegionClass ) { var RegionClass = regionConfig . regionClass || DefaultRegionClass ; var options = _ . omit ( regionConfig , 'selector' , 'regionClass' ) ; if ( regionConfig . selector && ! options . el ) { options . el = regionConfig . selector ; } return new RegionClass ( options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add multiple regions using an object literal or a function that returns an object literal where each key becomes the region name and each value is the region definition . [CODESPLIT] function ( regionDefinitions , defaults ) { regionDefinitions = Marionette . _getValue ( regionDefinitions , this , arguments ) ; return _ . reduce ( regionDefinitions , function ( regions , definition , name ) { if ( _ . isString ( definition ) ) { definition = { selector : definition } ; } if ( definition . selector ) { definition = _ . defaults ( { } , definition , defaults ) ; } regions [ name ] = this . addRegion ( name , definition ) ; return regions ; } , { } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an individual region to the region manager and return the region instance [CODESPLIT] function ( name , definition ) { var region ; if ( definition instanceof Marionette . Region ) { region = definition ; } else { region = Marionette . Region . buildRegion ( definition , Marionette . Region ) ; } this . triggerMethod ( 'before:add:region' , name , region ) ; region . _parent = this ; this . _store ( name , region ) ; this . triggerMethod ( 'add:region' , name , region ) ; return region ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Empty all regions in the region manager and remove them [CODESPLIT] function ( ) { var regions = this . getRegions ( ) ; _ . each ( this . _regions , function ( region , name ) { this . _remove ( name , region ) ; } , this ) ; return regions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "internal method to remove a region [CODESPLIT] function ( name , region ) { this . triggerMethod ( 'before:remove:region' , name , region ) ; region . empty ( ) ; region . stopListening ( ) ; delete region . _parent ; delete this . _regions [ name ] ; this . length -- ; this . triggerMethod ( 'remove:region' , name , region ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the specified template by id . Either retrieves the cached version or loads it from the DOM . [CODESPLIT] function ( templateId , options ) { var cachedTemplate = this . templateCaches [ templateId ] ; if ( ! cachedTemplate ) { cachedTemplate = new Marionette . TemplateCache ( templateId ) ; this . templateCaches [ templateId ] = cachedTemplate ; } return cachedTemplate . load ( options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear templates from the cache . If no arguments are specified clears all templates : clear () If arguments are specified clears each of the specified templates from the cache : clear ( #t1 #t2 ... ) [CODESPLIT] function ( ) { var i ; var args = _ . toArray ( arguments ) ; var length = args . length ; if ( length > 0 ) { for ( i = 0 ; i < length ; i ++ ) { delete this . templateCaches [ args [ i ] ] ; } } else { this . templateCaches = { } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to load the template [CODESPLIT] function ( options ) { // Guard clause to prevent loading this template more than once if ( this . compiledTemplate ) { return this . compiledTemplate ; } // Load the template and compile it var template = this . loadTemplate ( this . templateId , options ) ; this . compiledTemplate = this . compileTemplate ( template , options ) ; return this . compiledTemplate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load a template from the DOM by default . Override this method to provide your own template retrieval For asynchronous loading with AMD / RequireJS consider using a template - loader plugin as described here : https : // github . com / marionettejs / backbone . marionette / wiki / Using - marionette - with - requirejs [CODESPLIT] function ( templateId , options ) { var $template = Backbone . $ ( templateId ) ; if ( ! $template . length ) { throw new Marionette . Error ( { name : 'NoTemplateError' , message : 'Could not find template: \"' + templateId + '\"' } ) ; } return $template . html ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render a template with data . The template parameter is passed to the TemplateCache object to retrieve the template function . Override this method to provide your own custom rendering and template handling for all of Marionette . [CODESPLIT] function ( template , data ) { if ( ! template ) { throw new Marionette . Error ( { name : 'TemplateNotFoundError' , message : 'Cannot render the template since its false, null or undefined.' } ) ; } var templateFunc = _ . isFunction ( template ) ? template : Marionette . TemplateCache . get ( template ) ; return templateFunc ( data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mix in template helper methods . Looks for a templateHelpers attribute which can either be an object literal or a function that returns an object literal . All methods and attributes from this object are copies to the object passed in . [CODESPLIT] function ( target ) { target = target || { } ; var templateHelpers = this . getOption ( 'templateHelpers' ) ; templateHelpers = Marionette . _getValue ( templateHelpers , this ) ; return _ . extend ( target , templateHelpers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "normalize the keys of passed hash with the views ui selectors . { [CODESPLIT] function ( hash ) { var uiBindings = _ . result ( this , '_uiBindings' ) ; return Marionette . normalizeUIKeys ( hash , uiBindings || _ . result ( this , 'ui' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "normalize the values of passed hash with the views ui selectors . { foo : [CODESPLIT] function ( hash , properties ) { var ui = _ . result ( this , 'ui' ) ; var uiBindings = _ . result ( this , '_uiBindings' ) ; return Marionette . normalizeUIValues ( hash , uiBindings || ui , properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure triggers to forward DOM events to view events . triggers : { click . foo : do : foo } [CODESPLIT] function ( ) { if ( ! this . triggers ) { return ; } // Allow `triggers` to be configured as a function var triggers = this . normalizeUIKeys ( _ . result ( this , 'triggers' ) ) ; // Configure the triggers, prevent default // action and stop propagation of DOM events return _ . reduce ( triggers , function ( events , value , key ) { events [ key ] = this . _buildViewTrigger ( value ) ; return events ; } , { } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overriding Backbone . View s delegateEvents to handle the triggers modelEvents and collectionEvents configuration [CODESPLIT] function ( events ) { this . _delegateDOMEvents ( events ) ; this . bindEntityEvents ( this . model , this . getOption ( 'modelEvents' ) ) ; this . bindEntityEvents ( this . collection , this . getOption ( 'collectionEvents' ) ) ; _ . each ( this . _behaviors , function ( behavior ) { behavior . bindEntityEvents ( this . model , behavior . getOption ( 'modelEvents' ) ) ; behavior . bindEntityEvents ( this . collection , behavior . getOption ( 'collectionEvents' ) ) ; } , this ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "internal method to delegate DOM events and triggers [CODESPLIT] function ( eventsArg ) { var events = Marionette . _getValue ( eventsArg || this . events , this ) ; // normalize ui keys events = this . normalizeUIKeys ( events ) ; if ( _ . isUndefined ( eventsArg ) ) { this . events = events ; } var combinedEvents = { } ; // look up if this view has behavior events var behaviorEvents = _ . result ( this , 'behaviorEvents' ) || { } ; var triggers = this . configureTriggers ( ) ; var behaviorTriggers = _ . result ( this , 'behaviorTriggers' ) || { } ; // behavior events will be overriden by view events and or triggers _ . extend ( combinedEvents , behaviorEvents , events , triggers , behaviorTriggers ) ; Backbone . View . prototype . delegateEvents . call ( this , combinedEvents ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overriding Backbone . View s undelegateEvents to handle unbinding the triggers modelEvents and collectionEvents config [CODESPLIT] function ( ) { Backbone . View . prototype . undelegateEvents . apply ( this , arguments ) ; this . unbindEntityEvents ( this . model , this . getOption ( 'modelEvents' ) ) ; this . unbindEntityEvents ( this . collection , this . getOption ( 'collectionEvents' ) ) ; _ . each ( this . _behaviors , function ( behavior ) { behavior . unbindEntityEvents ( this . model , behavior . getOption ( 'modelEvents' ) ) ; behavior . unbindEntityEvents ( this . collection , behavior . getOption ( 'collectionEvents' ) ) ; } , this ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Default destroy implementation for removing a view from the DOM and unbinding it . Regions will call this method for you . You can specify an onDestroy method in your view to add custom code that is called after the view is destroyed . [CODESPLIT] function ( ) { if ( this . isDestroyed ) { return this ; } var args = _ . toArray ( arguments ) ; this . triggerMethod . apply ( this , [ 'before:destroy' ] . concat ( args ) ) ; // mark as destroyed before doing the actual destroy, to // prevent infinite loops within \"destroy\" event handlers // that are trying to destroy other views this . isDestroyed = true ; this . triggerMethod . apply ( this , [ 'destroy' ] . concat ( args ) ) ; // unbind UI elements this . unbindUIElements ( ) ; this . isRendered = false ; // remove the view from the DOM this . remove ( ) ; // Call destroy on each behavior after // destroying the view. // This unbinds event listeners // that behaviors have registered for. _ . invoke ( this . _behaviors , 'destroy' , args ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method binds the elements specified in the ui hash inside the view s code with the associated jQuery selectors . [CODESPLIT] function ( ) { if ( ! this . ui ) { return ; } // store the ui hash in _uiBindings so they can be reset later // and so re-rendering the view will be able to find the bindings if ( ! this . _uiBindings ) { this . _uiBindings = this . ui ; } // get the bindings result, as a function or otherwise var bindings = _ . result ( this , '_uiBindings' ) ; // empty the ui so we don't have anything to start with this . ui = { } ; // bind each of the selectors _ . each ( bindings , function ( selector , key ) { this . ui [ key ] = this . $ ( selector ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to create an event handler for a given triggerDef like click : foo [CODESPLIT] function ( triggerDef ) { var options = _ . defaults ( { } , triggerDef , { preventDefault : true , stopPropagation : true } ) ; var eventName = _ . isObject ( triggerDef ) ? options . event : triggerDef ; return function ( e ) { if ( e ) { if ( e . preventDefault && options . preventDefault ) { e . preventDefault ( ) ; } if ( e . stopPropagation && options . stopPropagation ) { e . stopPropagation ( ) ; } } var args = { view : this , model : this . model , collection : this . collection } ; this . triggerMethod ( eventName , args ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "import the triggerMethod to trigger events with corresponding methods if the method exists [CODESPLIT] function ( ) { var ret = Marionette . _triggerMethod ( this , arguments ) ; this . _triggerEventOnBehaviors ( arguments ) ; this . _triggerEventOnParentLayout ( arguments [ 0 ] , _ . rest ( arguments ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of every nested view within this view [CODESPLIT] function ( ) { var children = this . _getImmediateChildren ( ) ; if ( ! children . length ) { return children ; } return _ . reduce ( children , function ( memo , view ) { if ( ! view . _getNestedViews ) { return memo ; } return memo . concat ( view . _getNestedViews ( ) ) ; } , children ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walk the _parent tree until we find a layout view ( if one exists ) . Returns the parent layout view hierarchically closest to this view . [CODESPLIT] function ( ) { var parent = this . _parent ; while ( parent ) { if ( parent instanceof Marionette . LayoutView ) { return parent ; } parent = parent . _parent ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the model or collection for the view . If a model is found the view s serializeModel is called . If a collection is found each model in the collection is serialized by calling the view s serializeCollection and put into an items array in the resulting data . If both are found defaults to the model . You can override the serializeData method in your own view definition to provide custom serialization for your view s data . [CODESPLIT] function ( ) { if ( ! this . model && ! this . collection ) { return { } ; } var args = [ this . model || this . collection ] ; if ( arguments . length ) { args . push . apply ( args , arguments ) ; } if ( this . model ) { return this . serializeModel . apply ( this , args ) ; } else { return { items : this . serializeCollection . apply ( this , args ) } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to render the template with the serialized data and template helpers via the Marionette . Renderer object . Throws an UndefinedTemplateError error if the template is any falsely value but literal false . [CODESPLIT] function ( ) { var template = this . getTemplate ( ) ; // Allow template-less item views if ( template === false ) { return ; } if ( ! template ) { throw new Marionette . Error ( { name : 'UndefinedTemplateError' , message : 'Cannot render the template since it is null or undefined.' } ) ; } // Add in entity data and template helpers var data = this . mixinTemplateHelpers ( this . serializeData ( ) ) ; // Render and add to el var html = Marionette . Renderer . render ( template , data , this ) ; this . attachElContent ( html ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "constructor option to pass { sort : false } to prevent the CollectionView from maintaining the sorted order of the collection . This will fallback onto appending childView s to the end . option to pass { comparator : compFunction () } to allow the CollectionView to use a custom sort order for the collection . [CODESPLIT] function ( options ) { this . once ( 'render' , this . _initialEvents ) ; this . _initChildViewStorage ( ) ; Marionette . View . apply ( this , arguments ) ; this . on ( { 'before:show' : this . _onBeforeShowCalled , 'show' : this . _onShowCalled , 'before:attach' : this . _onBeforeAttachCalled , 'attach' : this . _onAttachCalled } ) ; this . initRenderBuffer ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configured the initial events that the collection view binds to . [CODESPLIT] function ( ) { if ( this . collection ) { this . listenTo ( this . collection , 'add' , this . _onCollectionAdd ) ; this . listenTo ( this . collection , 'remove' , this . _onCollectionRemove ) ; this . listenTo ( this . collection , 'reset' , this . render ) ; if ( this . getOption ( 'sort' ) ) { this . listenTo ( this . collection , 'sort' , this . _sortViews ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle a child added to the collection [CODESPLIT] function ( child , collection , opts ) { // `index` is present when adding with `at` since BB 1.2; indexOf fallback for < 1.2 var index = opts . at !== undefined && ( opts . index || collection . indexOf ( child ) ) ; // When filtered or when there is no initial index, calculate index. if ( this . getOption ( 'filter' ) || index === false ) { index = _ . indexOf ( this . _filteredSortedModels ( index ) , child ) ; } if ( this . _shouldAddChild ( child , index ) ) { this . destroyEmptyView ( ) ; var ChildView = this . getChildView ( child ) ; this . addChild ( child , ChildView , index ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reorder DOM after sorting . When your element s rendering do not use their index you can pass reorderOnSort : true to only reorder the DOM after a sort instead of rendering all the collectionView [CODESPLIT] function ( ) { var children = this . children ; var models = this . _filteredSortedModels ( ) ; if ( ! models . length && this . _showingEmptyView ) { return this ; } var anyModelsAdded = _ . some ( models , function ( model ) { return ! children . findByModel ( model ) ; } ) ; // If there are any new models added due to filtering // We need to add child views // So render as normal if ( anyModelsAdded ) { this . render ( ) ; } else { // get the DOM nodes in the same order as the models var elsToReorder = _ . map ( models , function ( model , index ) { var view = children . findByModel ( model ) ; view . _index = index ; return view . el ; } ) ; // find the views that were children before but arent in this new ordering var filteredOutViews = children . filter ( function ( view ) { return ! _ . contains ( elsToReorder , view . el ) ; } ) ; this . triggerMethod ( 'before:reorder' ) ; // since append moves elements that are already in the DOM, // appending the elements will effectively reorder them this . _appendReorderedChildren ( elsToReorder ) ; // remove any views that have been filtered out _ . each ( filteredOutViews , this . removeChildView , this ) ; this . checkEmpty ( ) ; this . triggerMethod ( 'reorder' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method . This checks for any changes in the order of the collection . If the index of any view doesn t match it will render . [CODESPLIT] function ( ) { var models = this . _filteredSortedModels ( ) ; // check for any changes in sort order of views var orderChanged = _ . find ( models , function ( item , index ) { var view = this . children . findByModel ( item ) ; return ! view || view . _index !== index ; } , this ) ; if ( orderChanged ) { this . resortView ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method . Separated so that CompositeView can have more control over events being triggered around the rendering process [CODESPLIT] function ( ) { this . destroyEmptyView ( ) ; this . destroyChildren ( { checkEmpty : false } ) ; if ( this . isEmpty ( this . collection ) ) { this . showEmptyView ( ) ; } else { this . triggerMethod ( 'before:render:collection' , this ) ; this . startBuffering ( ) ; this . showCollection ( ) ; this . endBuffering ( ) ; this . triggerMethod ( 'render:collection' , this ) ; // If we have shown children and none have passed the filter, show the empty view if ( this . children . isEmpty ( ) && this . getOption ( 'filter' ) ) { this . showEmptyView ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to loop through collection and show each child view . [CODESPLIT] function ( ) { var ChildView ; var models = this . _filteredSortedModels ( ) ; _ . each ( models , function ( child , index ) { ChildView = this . getChildView ( child ) ; this . addChild ( child , ChildView , index ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow the collection to be sorted by a custom view comparator [CODESPLIT] function ( addedAt ) { var viewComparator = this . getViewComparator ( ) ; var models = this . collection . models ; addedAt = Math . min ( Math . max ( addedAt , 0 ) , models . length - 1 ) ; if ( viewComparator ) { var addedModel ; // Preserve `at` location, even for a sorted view if ( addedAt ) { addedModel = models [ addedAt ] ; models = models . slice ( 0 , addedAt ) . concat ( models . slice ( addedAt + 1 ) ) ; } models = this . _sortModelsBy ( models , viewComparator ) ; if ( addedModel ) { models . splice ( addedAt , 0 , addedModel ) ; } } // Filter after sorting in case the filter uses the index if ( this . getOption ( 'filter' ) ) { models = _ . filter ( models , function ( model , index ) { return this . _shouldAddChild ( model , index ) ; } , this ) ; } return models ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to show an empty view in place of a collection of child views when the collection is empty [CODESPLIT] function ( ) { var EmptyView = this . getEmptyView ( ) ; if ( EmptyView && ! this . _showingEmptyView ) { this . triggerMethod ( 'before:render:empty' ) ; this . _showingEmptyView = true ; var model = new Backbone . Model ( ) ; this . addEmptyView ( model , EmptyView ) ; this . triggerMethod ( 'render:empty' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render and show the emptyView . Similar to addChild method but add : child events are not fired and the event from emptyView are not forwarded [CODESPLIT] function ( child , EmptyView ) { // Only trigger attach if already shown, attached, and not buffering, otherwise endBuffer() or // Region#show() handles this. var canTriggerAttach = this . _isShown && ! this . isBuffering && Marionette . isNodeAttached ( this . el ) ; var nestedViews ; // get the emptyViewOptions, falling back to childViewOptions var emptyViewOptions = this . getOption ( 'emptyViewOptions' ) || this . getOption ( 'childViewOptions' ) ; if ( _ . isFunction ( emptyViewOptions ) ) { emptyViewOptions = emptyViewOptions . call ( this , child , this . _emptyViewIndex ) ; } // build the empty view var view = this . buildChildView ( child , EmptyView , emptyViewOptions ) ; view . _parent = this ; // Proxy emptyView events this . proxyChildEvents ( view ) ; view . once ( 'render' , function ( ) { // trigger the 'before:show' event on `view` if the collection view has already been shown if ( this . _isShown ) { Marionette . triggerMethodOn ( view , 'before:show' , view ) ; } // Trigger `before:attach` following `render` to avoid adding logic and event triggers // to public method `renderChildView()`. if ( canTriggerAttach && this . _triggerBeforeAttach ) { nestedViews = this . _getViewAndNested ( view ) ; this . _triggerMethodMany ( nestedViews , this , 'before:attach' ) ; } } , this ) ; // Store the `emptyView` like a `childView` so we can properly remove and/or close it later this . children . add ( view ) ; this . renderChildView ( view , this . _emptyViewIndex ) ; // Trigger `attach` if ( canTriggerAttach && this . _triggerAttach ) { nestedViews = this . _getViewAndNested ( view ) ; this . _triggerMethodMany ( nestedViews , this , 'attach' ) ; } // call the 'show' method if the collection view has already been shown if ( this . _isShown ) { Marionette . triggerMethodOn ( view , 'show' , view ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render the child s view and add it to the HTML for the collection view at a given index . This will also update the indices of later views in the collection in order to keep the children in sync with the collection . [CODESPLIT] function ( child , ChildView , index ) { var childViewOptions = this . getOption ( 'childViewOptions' ) ; childViewOptions = Marionette . _getValue ( childViewOptions , this , [ child , index ] ) ; var view = this . buildChildView ( child , ChildView , childViewOptions ) ; // increment indices of views after this one this . _updateIndices ( view , true , index ) ; this . triggerMethod ( 'before:add:child' , view ) ; this . _addChildView ( view , index ) ; this . triggerMethod ( 'add:child' , view ) ; view . _parent = this ; return view ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method . This decrements or increments the indices of views after the added / removed view to keep in sync with the collection . [CODESPLIT] function ( view , increment , index ) { if ( ! this . getOption ( 'sort' ) ) { return ; } if ( increment ) { // assign the index to the view view . _index = index ; } // update the indexes of views after this one this . children . each ( function ( laterView ) { if ( laterView . _index >= view . _index ) { laterView . _index += increment ? 1 : - 1 ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal Method . Add the view to children and render it at the given index . [CODESPLIT] function ( view , index ) { // Only trigger attach if already shown, attached, and not buffering, otherwise endBuffer() or // Region#show() handles this. var canTriggerAttach = this . _isShown && ! this . isBuffering && Marionette . isNodeAttached ( this . el ) ; var nestedViews ; // set up the child view event forwarding this . proxyChildEvents ( view ) ; view . once ( 'render' , function ( ) { // trigger the 'before:show' event on `view` if the collection view has already been shown if ( this . _isShown && ! this . isBuffering ) { Marionette . triggerMethodOn ( view , 'before:show' , view ) ; } // Trigger `before:attach` following `render` to avoid adding logic and event triggers // to public method `renderChildView()`. if ( canTriggerAttach && this . _triggerBeforeAttach ) { nestedViews = this . _getViewAndNested ( view ) ; this . _triggerMethodMany ( nestedViews , this , 'before:attach' ) ; } } , this ) ; // Store the child view itself so we can properly remove and/or destroy it later this . children . add ( view ) ; this . renderChildView ( view , index ) ; // Trigger `attach` if ( canTriggerAttach && this . _triggerAttach ) { nestedViews = this . _getViewAndNested ( view ) ; this . _triggerMethodMany ( nestedViews , this , 'attach' ) ; } // Trigger `show` if ( this . _isShown && ! this . isBuffering ) { Marionette . triggerMethodOn ( view , 'show' , view ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "render the child view [CODESPLIT] function ( view , index ) { if ( ! view . supportsRenderLifecycle ) { Marionette . triggerMethodOn ( view , 'before:render' , view ) ; } view . render ( ) ; if ( ! view . supportsRenderLifecycle ) { Marionette . triggerMethodOn ( view , 'render' , view ) ; } this . attachHtml ( this , view , index ) ; return view ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a childView for a model in the collection . [CODESPLIT] function ( child , ChildViewClass , childViewOptions ) { var options = _ . extend ( { model : child } , childViewOptions ) ; var childView = new ChildViewClass ( options ) ; Marionette . MonitorDOMRefresh ( childView ) ; return childView ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the child view and destroy it . This function also updates the indices of later views in the collection in order to keep the children in sync with the collection . [CODESPLIT] function ( view ) { if ( ! view ) { return view ; } this . triggerMethod ( 'before:remove:child' , view ) ; if ( ! view . supportsDestroyLifecycle ) { Marionette . triggerMethodOn ( view , 'before:destroy' , view ) ; } // call 'destroy' or 'remove', depending on which is found if ( view . destroy ) { view . destroy ( ) ; } else { view . remove ( ) ; } if ( ! view . supportsDestroyLifecycle ) { Marionette . triggerMethodOn ( view , 'destroy' , view ) ; } delete view . _parent ; this . stopListening ( view ) ; this . children . remove ( view ) ; this . triggerMethod ( 'remove:child' , view ) ; // decrement the index of views after this one this . _updateIndices ( view , false ) ; return view ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a fragment buffer from the currently buffered children [CODESPLIT] function ( ) { var elBuffer = document . createDocumentFragment ( ) ; _ . each ( this . _bufferedChildren , function ( b ) { elBuffer . appendChild ( b . el ) ; } ) ; return elBuffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append the HTML to the collection s el . Override this method to do something other than . append . [CODESPLIT] function ( collectionView , childView , index ) { if ( collectionView . isBuffering ) { // buffering happens on reset events and initial renders // in order to reduce the number of inserts into the // document, which are expensive. collectionView . _bufferedChildren . splice ( index , 0 , childView ) ; } else { // If we've already rendered the main collection, append // the new child into the correct order if we need to. Otherwise // append to the end. if ( ! collectionView . _insertBefore ( childView , index ) ) { collectionView . _insertAfter ( childView ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method . Check whether we need to insert the view into the correct position . [CODESPLIT] function ( childView , index ) { var currentView ; var findPosition = this . getOption ( 'sort' ) && ( index < this . children . length - 1 ) ; if ( findPosition ) { // Find the view after this one currentView = this . children . find ( function ( view ) { return view . _index === index + 1 ; } ) ; } if ( currentView ) { currentView . $el . before ( childView . el ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle cleanup and other destroying needs for the collection of views [CODESPLIT] function ( ) { if ( this . isDestroyed ) { return this ; } this . triggerMethod ( 'before:destroy:collection' ) ; this . destroyChildren ( { checkEmpty : false } ) ; this . triggerMethod ( 'destroy:collection' ) ; return Marionette . View . prototype . destroy . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Destroy the child views that this collection view is holding on to if any [CODESPLIT] function ( options ) { var destroyOptions = options || { } ; var shouldCheckEmpty = true ; var childViews = this . children . map ( _ . identity ) ; if ( ! _ . isUndefined ( destroyOptions . checkEmpty ) ) { shouldCheckEmpty = destroyOptions . checkEmpty ; } this . children . each ( this . removeChildView , this ) ; if ( shouldCheckEmpty ) { this . checkEmpty ( ) ; } return childViews ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given child should be shown Return false otherwise The filter will be passed ( child index collection ) Where child is the given model index is the index of that model in the collection collection is the collection referenced by this CollectionView [CODESPLIT] function ( child , index ) { var filter = this . getOption ( 'filter' ) ; return ! _ . isFunction ( filter ) || filter . call ( this , child , index , this . collection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set up the child view event forwarding . Uses a childview : prefix in front of all forwarded events . [CODESPLIT] function ( view ) { var prefix = this . getOption ( 'childViewEventPrefix' ) ; // Forward all child view events through the parent, // prepending \"childview:\" to the event name this . listenTo ( view , 'all' , function ( ) { var args = _ . toArray ( arguments ) ; var rootEvent = args [ 0 ] ; var childEvents = this . normalizeMethods ( _ . result ( this , 'childEvents' ) ) ; args [ 0 ] = prefix + ':' + rootEvent ; args . splice ( 1 , 0 , view ) ; // call collectionView childEvent if defined if ( typeof childEvents !== 'undefined' && _ . isFunction ( childEvents [ rootEvent ] ) ) { childEvents [ rootEvent ] . apply ( this , args . slice ( 1 ) ) ; } this . triggerMethod . apply ( this , args ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configured the initial events that the composite view binds to . Override this method to prevent the initial events or to add your own initial events . [CODESPLIT] function ( ) { // Bind only after composite view is rendered to avoid adding child views // to nonexistent childViewContainer if ( this . collection ) { this . listenTo ( this . collection , 'add' , this . _onCollectionAdd ) ; this . listenTo ( this . collection , 'remove' , this . _onCollectionRemove ) ; this . listenTo ( this . collection , 'reset' , this . _renderChildren ) ; if ( this . getOption ( 'sort' ) ) { this . listenTo ( this . collection , 'sort' , this . _sortViews ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the model for the view . You can override the serializeData method in your own view definition to provide custom serialization for your view s data . [CODESPLIT] function ( ) { var data = { } ; if ( this . model ) { data = _ . partial ( this . serializeModel , this . model ) . apply ( this , arguments ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders the model and the collection . [CODESPLIT] function ( ) { this . _ensureViewIsIntact ( ) ; this . _isRendering = true ; this . resetChildViewContainer ( ) ; this . triggerMethod ( 'before:render' , this ) ; this . _renderTemplate ( ) ; this . _renderChildren ( ) ; this . _isRendering = false ; this . isRendered = true ; this . triggerMethod ( 'render' , this ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render the root template that the children views are appended to [CODESPLIT] function ( ) { var data = { } ; data = this . serializeData ( ) ; data = this . mixinTemplateHelpers ( data ) ; this . triggerMethod ( 'before:render:template' ) ; var template = this . getTemplate ( ) ; var html = Marionette . Renderer . render ( template , data , this ) ; this . attachElContent ( html ) ; // the ui bindings is done here and not at the end of render since they // will not be available until after the model is rendered, but should be // available before the collection is rendered. this . bindUIElements ( ) ; this . triggerMethod ( 'render:template' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to ensure an $childViewContainer exists for the attachHtml method to use . [CODESPLIT] function ( containerView , childView ) { if ( ! ! containerView . $childViewContainer ) { return containerView . $childViewContainer ; } var container ; var childViewContainer = Marionette . getOption ( containerView , 'childViewContainer' ) ; if ( childViewContainer ) { var selector = Marionette . _getValue ( childViewContainer , containerView ) ; if ( selector . charAt ( 0 ) === '@' && containerView . ui ) { container = containerView . ui [ selector . substr ( 4 ) ] ; } else { container = containerView . $ ( selector ) ; } if ( container . length <= 0 ) { throw new Marionette . Error ( { name : 'ChildViewContainerMissingError' , message : 'The specified \"childViewContainer\" was not found: ' + containerView . childViewContainer } ) ; } } else { container = containerView . $el ; } containerView . $childViewContainer = container ; return container ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure the regions are available when the initialize method is called . [CODESPLIT] function ( options ) { options = options || { } ; this . _firstRender = true ; this . _initializeRegions ( options ) ; Marionette . ItemView . call ( this , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LayoutView s render will use the existing region objects the first time it is called . Subsequent calls will destroy the views that the regions are showing and then reset the el for the regions to the newly rendered DOM elements . [CODESPLIT] function ( ) { this . _ensureViewIsIntact ( ) ; if ( this . _firstRender ) { // if this is the first render, don't do anything to // reset the regions this . _firstRender = false ; } else { // If this is not the first render call, then we need to // re-initialize the `el` for each region this . _reInitializeRegions ( ) ; } return Marionette . ItemView . prototype . render . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle destroying regions and then destroy the view itself . [CODESPLIT] function ( ) { if ( this . isDestroyed ) { return this ; } // #2134: remove parent element before destroying the child views, so // removing the child views doesn't retrigger repaints if ( this . getOption ( 'destroyImmediate' ) === true ) { this . $el . remove ( ) ; } this . regionManager . destroy ( ) ; return Marionette . ItemView . prototype . destroy . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "internal method to build regions [CODESPLIT] function ( regions ) { var defaults = { regionClass : this . getOption ( 'regionClass' ) , parentEl : _ . partial ( _ . result , this , 'el' ) } ; return this . regionManager . addRegions ( regions , defaults ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to initialize the regions that have been defined in a regions attribute on this layoutView . [CODESPLIT] function ( options ) { var regions ; this . _initRegionManager ( ) ; regions = Marionette . _getValue ( this . regions , this , [ options ] ) || { } ; // Enable users to define `regions` as instance options. var regionOptions = this . getOption . call ( options , 'regions' ) ; // enable region options to be a function regionOptions = Marionette . _getValue ( regionOptions , this , [ options ] ) ; _ . extend ( regions , regionOptions ) ; // Normalize region selectors hash to allow // a user to use the @ui. syntax. regions = this . normalizeUIValues ( regions , [ 'selector' , 'el' ] ) ; this . addRegions ( regions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to initialize the region manager and all regions in it [CODESPLIT] function ( ) { this . regionManager = this . getRegionManager ( ) ; this . regionManager . _parent = this ; this . listenTo ( this . regionManager , 'before:add:region' , function ( name ) { this . triggerMethod ( 'before:add:region' , name ) ; } ) ; this . listenTo ( this . regionManager , 'add:region' , function ( name , region ) { this [ name ] = region ; this . triggerMethod ( 'add:region' , name , region ) ; } ) ; this . listenTo ( this . regionManager , 'before:remove:region' , function ( name ) { this . triggerMethod ( 'before:remove:region' , name ) ; } ) ; this . listenTo ( this . regionManager , 'remove:region' , function ( name , region ) { delete this [ name ] ; this . triggerMethod ( 'remove:region' , name , region ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes care of getting the behavior class given options and a key . If a user passes in options . behaviorClass default to using that . Otherwise delegate the lookup to the users behaviorsLookup implementation . [CODESPLIT] function ( options , key ) { if ( options . behaviorClass ) { return options . behaviorClass ; } // Get behavior class can be either a flat object or a method return Marionette . _getValue ( Behaviors . behaviorsLookup , this , [ options , key ] ) [ key ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate over the behaviors object for each behavior instantiate it and get its grouped behaviors . [CODESPLIT] function ( view , behaviors ) { return _ . chain ( behaviors ) . map ( function ( options , key ) { var BehaviorClass = Behaviors . getBehaviorClass ( options , key ) ; var behavior = new BehaviorClass ( options , view ) ; var nestedBehaviors = Behaviors . parseBehaviors ( view , _ . result ( behavior , 'behaviors' ) ) ; return [ behavior ] . concat ( nestedBehaviors ) ; } ) . flatten ( ) . value ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap view internal methods so that they delegate to behaviors . For example onDestroy should trigger destroy on all of the behaviors and then destroy itself . i . e . view . delegateEvents = _ . partial ( methods . delegateEvents view . delegateEvents behaviors ) ; [CODESPLIT] function ( view , behaviors , methodNames ) { _ . each ( methodNames , function ( methodName ) { view [ methodName ] = _ . partial ( methods [ methodName ] , view [ methodName ] , behaviors ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to build all trigger handlers for a given behavior [CODESPLIT] function ( behavior , i ) { var triggersHash = _ . clone ( _ . result ( behavior , 'triggers' ) ) || { } ; triggersHash = Marionette . normalizeUIKeys ( triggersHash , getBehaviorsUI ( behavior ) ) ; _ . each ( triggersHash , _ . bind ( this . _setHandlerForBehavior , this , behavior , i ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to create and assign the trigger handler for a given behavior [CODESPLIT] function ( behavior , i , eventName , trigger ) { // Unique identifier for the `this._triggers` hash var triggerKey = trigger . replace ( / ^\\S+ / , function ( triggerName ) { return triggerName + '.' + 'behaviortriggers' + i ; } ) ; this . _triggers [ triggerKey ] = this . _view . _buildViewTrigger ( eventName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "process the route event and trigger the onRoute method call if it exists [CODESPLIT] function ( routeName , routeArgs ) { // make sure an onRoute before trying to call it if ( _ . isFunction ( this . onRoute ) ) { // find the path that matches the current route var routePath = _ . invert ( this . getOption ( 'appRoutes' ) ) [ routeName ] ; this . onRoute ( routeName , routePath , routeArgs ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a module attached to the application [CODESPLIT] function ( moduleNames , moduleDefinition ) { // Overwrite the module class if the user specifies one var ModuleClass = Marionette . Module . getClass ( moduleDefinition ) ; var args = _ . toArray ( arguments ) ; args . unshift ( this ) ; // see the Marionette.Module object for more information return ModuleClass . create . apply ( ModuleClass , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to initialize the regions that have been defined in a regions attribute on the application instance [CODESPLIT] function ( options ) { var regions = _ . isFunction ( this . regions ) ? this . regions ( options ) : this . regions || { } ; this . _initRegionManager ( ) ; // Enable users to define `regions` in instance options. var optionRegions = Marionette . getOption ( options , 'regions' ) ; // Enable region options to be a function if ( _ . isFunction ( optionRegions ) ) { optionRegions = optionRegions . call ( this , options ) ; } // Overwrite current regions with those passed in options _ . extend ( regions , optionRegions ) ; this . addRegions ( regions ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to set up the region manager [CODESPLIT] function ( ) { this . _regionManager = this . getRegionManager ( ) ; this . _regionManager . _parent = this ; this . listenTo ( this . _regionManager , 'before:add:region' , function ( ) { Marionette . _triggerMethod ( this , 'before:add:region' , arguments ) ; } ) ; this . listenTo ( this . _regionManager , 'add:region' , function ( name , region ) { this [ name ] = region ; Marionette . _triggerMethod ( this , 'add:region' , arguments ) ; } ) ; this . listenTo ( this . _regionManager , 'before:remove:region' , function ( ) { Marionette . _triggerMethod ( this , 'before:remove:region' , arguments ) ; } ) ; this . listenTo ( this . _regionManager , 'remove:region' , function ( name ) { delete this [ name ] ; Marionette . _triggerMethod ( this , 'remove:region' , arguments ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to setup the Wreqr . radio channel [CODESPLIT] function ( ) { this . channelName = _ . result ( this , 'channelName' ) || 'global' ; this . channel = _ . result ( this , 'channel' ) || Backbone . Wreqr . radio . channel ( this . channelName ) ; this . vent = _ . result ( this , 'vent' ) || this . channel . vent ; this . commands = _ . result ( this , 'commands' ) || this . channel . commands ; this . reqres = _ . result ( this , 'reqres' ) || this . channel . reqres ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop this module by running its finalizers and then stop all of the sub - modules for this module [CODESPLIT] function ( ) { // if we are not initialized, don't bother finalizing if ( ! this . _isInitialized ) { return ; } this . _isInitialized = false ; this . triggerMethod ( 'before:stop' ) ; // stop the sub-modules; depth-first, to make sure the // sub-modules are stopped / finalized before parents _ . invoke ( this . submodules , 'stop' ) ; // run the finalizers this . _finalizerCallbacks . run ( undefined , this ) ; // reset the initializers and finalizers this . _initializerCallbacks . reset ( ) ; this . _finalizerCallbacks . reset ( ) ; this . triggerMethod ( 'stop' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method : run the module definition function with the correct arguments [CODESPLIT] function ( definition , customArgs ) { // If there is no definition short circut the method. if ( ! definition ) { return ; } // build the correct list of arguments for the module definition var args = _ . flatten ( [ this , this . app , Backbone , Marionette , Backbone . $ , _ , customArgs ] ) ; definition . apply ( this , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a module hanging off the app parameter as the parent object . [CODESPLIT] function ( app , moduleNames , moduleDefinition ) { var module = app ; // get the custom args passed in after the module definition and // get rid of the module name and definition function var customArgs = _ . drop ( arguments , 3 ) ; // Split the module names and get the number of submodules. // i.e. an example module name of `Doge.Wow.Amaze` would // then have the potential for 3 module definitions. moduleNames = moduleNames . split ( '.' ) ; var length = moduleNames . length ; // store the module definition for the last module in the chain var moduleDefinitions = [ ] ; moduleDefinitions [ length - 1 ] = moduleDefinition ; // Loop through all the parts of the module definition _ . each ( moduleNames , function ( moduleName , i ) { var parentModule = module ; module = this . _getModule ( parentModule , moduleName , app , moduleDefinition ) ; this . _addModuleDefinition ( parentModule , module , moduleDefinitions [ i ] , customArgs ) ; } , this ) ; // Return the last module in the definition chain return module ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "## Module Classes Module classes can be used as an alternative to the define pattern . The extend function of a Module is identical to the extend functions on other Backbone and Marionette classes . This allows module lifecyle events like onStart and onStop to be called directly . [CODESPLIT] function ( moduleDefinition ) { var ModuleClass = Marionette . Module ; if ( ! moduleDefinition ) { return ModuleClass ; } // If all of the module's functionality is defined inside its class, // then the class can be passed in directly. `MyApp.module(\"Foo\", FooModule)`. if ( moduleDefinition . prototype instanceof ModuleClass ) { return moduleDefinition ; } return moduleDefinition . moduleClass || ModuleClass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the module definition and add a startWithParent initializer function . This is complicated because module definitions are heavily overloaded and support an anonymous function module class or options object [CODESPLIT] function ( parentModule , module , def , args ) { var fn = this . _getDefine ( def ) ; var startWithParent = this . _getStartWithParent ( def , module ) ; if ( fn ) { module . addDefinition ( fn , args ) ; } this . _addStartWithParent ( parentModule , module , startWithParent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns function signature name [CODESPLIT] function _sigName ( src ) { if ( ! _ . isFunction ( src ) ) return '' let ret = _ . trim ( _ . replace ( src . toString ( ) , 'function' , '' ) ) ret = ret . substr ( 0 , ret . indexOf ( '(' ) ) return ret || '' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests a { @link Ext . device . filesystem . FileSystem } instance . [CODESPLIT] function ( config ) { if ( ! config . success ) { Ext . Logger . error ( 'Ext.device.filesystem#requestFileSystem: You must specify a `success` callback.' ) ; return null ; } var me = this ; var successCallback = function ( fs ) { var fileSystem = Ext . create ( 'Ext.device.filesystem.FileSystem' , fs ) ; config . success . call ( config . scope || me , fileSystem ) ; } ; window . requestFileSystem ( config . type , config . size , successCallback , config . failure || Ext . emptyFn ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the name of the entry excluding the path leading to it . [CODESPLIT] function ( ) { var components = this . path . split ( '/' ) ; for ( var i = components . length - 1 ; i >= 0 ; -- i ) { if ( components [ i ] . length > 0 ) { return components [ i ] ; } } return '/' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves the entry to a different location on the file system . [CODESPLIT] function ( config ) { if ( config . parent == null ) { Ext . Logger . error ( 'Ext.device.filesystem.Entry#moveTo: You must specify a new `parent` of the entry.' ) ; return null ; } var me = this ; this . getEntry ( { options : config . options || { } , success : function ( sourceEntry ) { config . parent . getEntry ( { options : config . options || { } , success : function ( destinationEntry ) { if ( config . copy ) { sourceEntry . copyTo ( destinationEntry , config . newName , function ( entry ) { config . success . call ( config . scope || me , entry . isDirectory ? Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , entry . fullPath , me . fileSystem ) : Ext . create ( 'Ext.device.filesystem.FileEntry' , entry . fullPath , me . fileSystem ) ) ; } , config . failure ) ; } else { sourceEntry . moveTo ( destinationEntry , config . newName , function ( entry ) { config . success . call ( config . scope || me , entry . isDirectory ? Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , entry . fullPath , me . fileSystem ) : Ext . create ( 'Ext.device.filesystem.FileEntry' , entry . fullPath , me . fileSystem ) ) ; } , config . failure ) ; } } , failure : config . failure } ) ; } , failure : config . failure } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the entry from the file system . [CODESPLIT] function ( config ) { this . getEntry ( { success : function ( entry ) { if ( config . recursively && this . directory ) { entry . removeRecursively ( config . success , config . failure ) } else { entry . remove ( config . success , config . failure ) } } , failure : config . failure } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up the parent directory containing the entry . [CODESPLIT] function ( config ) { if ( ! config . success ) { Ext . Logger . error ( 'Ext.device.filesystem.Entry#getParent: You must specify a `success` callback.' ) ; return null ; } var me = this ; this . getEntry ( { options : config . options || { } , success : function ( entry ) { entry . getParent ( function ( parentEntry ) { config . success . call ( config . scope || me , parentEntry . isDirectory ? Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , parentEntry . fullPath , me . fileSystem ) : Ext . create ( 'Ext.device.filesystem.FileEntry' , parentEntry . fullPath , me . fileSystem ) ) } , config . failure ) } , failure : config . failure } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests a Directory from the Local File System [CODESPLIT] function ( config ) { var me = this ; var callback = config . success ; if ( ( config . options && config . options . create ) && this . path ) { var folders = this . path . split ( \"/\" ) ; if ( folders [ 0 ] == '.' || folders [ 0 ] == '' ) { folders = folders . slice ( 1 ) ; } var recursiveCreation = function ( dirEntry ) { if ( folders . length ) { dirEntry . getDirectory ( folders . shift ( ) , config . options , recursiveCreation , config . failure ) ; } else { callback ( dirEntry ) ; } } ; recursiveCreation ( this . fileSystem . fs . root ) ; } else { this . fileSystem . fs . root . getDirectory ( this . path , config . options , function ( directory ) { config . success . call ( config . scope || me , directory ) ; } , config . failure ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lists all the entries in the directory . [CODESPLIT] function ( config ) { if ( ! config . success ) { Ext . Logger . error ( 'Ext.device.filesystem.DirectoryEntry#readEntries: You must specify a `success` callback.' ) ; return null ; } var me = this ; this . getEntry ( { success : function ( dirEntry ) { var directoryReader = dirEntry . createReader ( ) ; directoryReader . readEntries ( function ( entryInfos ) { var entries = [ ] , i = 0 , len = entryInfos . length ; for ( ; i < len ; i ++ ) { entryInfo = entryInfos [ i ] ; entries [ i ] = entryInfo . isDirectory ? Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , entryInfo . fullPath , me . fileSystem ) : Ext . create ( 'Ext.device.filesystem.FileEntry' , entryInfo . fullPath , me . fileSystem ) ; } config . success . call ( config . scope || this , entries ) ; } , function ( error ) { if ( config . failure ) { config . failure . call ( config . scope || this , error ) ; } } ) ; } , failure : config . failure } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Works the same way as { [CODESPLIT] function ( config ) { if ( config . path == null ) { Ext . Logger . error ( 'Ext.device.filesystem.DirectoryEntry#getFile: You must specify a `path` of the file.' ) ; return null ; } var me = this ; var fullPath = this . path + config . path ; var directoryEntry = Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , fullPath , this . fileSystem ) ; directoryEntry . getEntry ( { success : function ( ) { config . success . call ( config . scope || me , directoryEntry ) ; } , options : config . options || { } , failure : config . failure } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests a File Handle from the Local File System [CODESPLIT] function ( config ) { var me = this ; var originalConfig = Ext . applyIf ( { } , config ) ; if ( this . fileSystem ) { var failure = function ( evt ) { if ( ( config . options && config . options . create ) && Ext . isString ( this . path ) ) { var folders = this . path . split ( \"/\" ) ; if ( folders [ 0 ] == '.' || folders [ 0 ] == '' ) { folders = folders . slice ( 1 ) ; } if ( folders . length > 1 && ! config . recursive === true ) { folders . pop ( ) ; var dirEntry = Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , folders . join ( \"/\" ) , me . fileSystem ) ; dirEntry . getEntry ( { options : config . options , success : function ( ) { originalConfig . recursive = true ; me . getEntry ( originalConfig ) ; } , failure : config . failure } ) ; } else { if ( config . failure ) { config . failure . call ( config . scope || me , evt ) ; } } } else { if ( config . failure ) { config . failure . call ( config . scope || me , evt ) ; } } } ; this . fileSystem . fs . root . getFile ( this . path , config . options || null , function ( fileEntry ) { fileEntry . file ( function ( file ) { me . length = file . size ; originalConfig . success . call ( config . scope || me , fileEntry ) ; } , function ( error ) { failure . call ( config . scope || me , error ) ; } ) ; } , function ( error ) { failure . call ( config . scope || me , error ) ; } ) ; } else { config . failure ( { code : - 1 , message : \"FileSystem not Initialized\" } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the byte offset into the file at which the next read / write will occur . [CODESPLIT] function ( config ) { if ( config . offset == null ) { Ext . Logger . error ( 'Ext.device.filesystem.FileEntry#seek: You must specify an `offset` in the file.' ) ; return null ; } this . offset = config . offset || 0 ; if ( config . success ) { config . success . call ( config . scope || this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the data from the file starting at the file offset . [CODESPLIT] function ( config ) { var me = this ; this . getEntry ( { success : function ( fileEntry ) { fileEntry . file ( function ( file ) { if ( Ext . isNumber ( config . length ) ) { if ( Ext . isFunction ( file . slice ) ) { file = file . slice ( me . offset , config . length ) ; } else { if ( config . failure ) { config . failure . call ( config . scope || me , { code : - 2 , message : \"File missing slice functionality\" } ) ; } return ; } } var reader = new FileReader ( ) ; reader . onloadend = function ( evt ) { config . success . call ( config . scope || me , evt . target . result ) ; } ; reader . onerror = function ( error ) { config . failure . call ( config . scope || me , error ) ; } ; if ( config . reader ) { reader = Ext . applyIf ( reader , config . reader ) ; } config . encoding = config . encoding || \"UTF8\" ; switch ( config . type ) { default : case \"text\" : reader . readAsText ( file , config . encoding ) ; break ; case \"dataURL\" : reader . readAsDataURL ( file ) ; break ; case \"binaryString\" : reader . readAsBinaryString ( file ) ; break ; case \"arrayBuffer\" : reader . readAsArrayBuffer ( file ) ; break ; } } , function ( error ) { config . failure . call ( config . scope || me , error ) } ) ; } , failure : function ( error ) { config . failure . call ( config . scope || me , error ) } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Truncates or extends the file to the specified size in bytes . If the file is extended the added bytes are null bytes . [CODESPLIT] function ( config ) { if ( config . size == null ) { Ext . Logger . error ( 'Ext.device.filesystem.FileEntry#write: You must specify a `size` of the file.' ) ; return null ; } var me = this ; //noinspection JSValidateTypes this . getEntry ( { success : function ( fileEntry ) { fileEntry . createWriter ( function ( writer ) { writer . truncate ( config . size ) ; config . success . call ( config . scope || me , me ) ; } , function ( error ) { config . failure . call ( config . scope || me , error ) } ) } , failure : function ( error ) { config . failure . call ( config . scope || me , error ) } } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sorts keys for better readablity [CODESPLIT] function ( obj ) { const keys = _ . sortBy ( _ . keys ( obj ) , function ( key ) { return key ; } ) ; return _ . zipObject ( keys , _ . map ( keys , function ( key ) { return obj [ key ] ; } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "all dependencies done [CODESPLIT] function ( err ) { if ( err ) return done ( err ) ; var ret ; if ( typeof leave == 'function' ) { try { ret = leave . call ( this , child , parent ) ; } catch ( err ) { return done ( err ) ; } } done ( null , ret ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multi - Key LRU cache . [CODESPLIT] function MultiKeyCache ( options ) { options = options || { } ; var self = this ; var dispose = options . dispose ; options . dispose = function ( key , value ) { self . _dispose ( key ) ; if ( dispose ) { dispose ( key , value ) ; } } ; this . cache = new LRU ( options ) ; this . _keyMap = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NOTE : the this context will be determined at the time the curried function receives its ** final ** argument . [CODESPLIT] function curry ( len , f ) { for ( var _len = arguments . length , initArgs = Array ( _len > 2 ? _len - 2 : 0 ) , _key = 2 ; _key < _len ; _key ++ ) { initArgs [ _key - 2 ] = arguments [ _key ] ; } var _ref = function ( ) { switch ( true ) { case _extractHiddenClass ( len ) === 'Function' : var args = f == null ? [ ] : [ f ] . concat ( initArgs ) ; return [ len , len . length , args ] ; case _extractHiddenClass ( len ) === 'Number' : return [ f , len , initArgs ] ; default : throw new TypeError ( 'Unrecognized arguments ' + len + ' and ' + f + ' to function curry.' ) ; } } ( ) , _ref2 = _slicedToArray ( _ref , 3 ) , fn = _ref2 [ 0 ] , arity = _ref2 [ 1 ] , fnArgs = _ref2 [ 2 ] ; if ( ! fn ) { return function ( fn ) { for ( var _len2 = arguments . length , args = Array ( _len2 > 1 ? _len2 - 1 : 0 ) , _key2 = 1 ; _key2 < _len2 ; _key2 ++ ) { args [ _key2 - 1 ] = arguments [ _key2 ] ; } return curry . apply ( this , [ arity , fn ] . concat ( args ) ) ; } ; } var helper = function helper ( args ) { return function ( ) { for ( var _len3 = arguments . length , rest = Array ( _len3 ) , _key3 = 0 ; _key3 < _len3 ; _key3 ++ ) { rest [ _key3 ] = arguments [ _key3 ] ; } return currier . call ( this , arity , fn , [ ] . concat ( _toConsumableArray ( args ) , rest ) ) ; } ; } ; var currier = function currier ( length , f , args ) { if ( args . length >= length ) { // ES 6 classes and built-ins, real or polyfilled, throw a TypeError if you try to call them // as a function. try { return f . apply ( this , args ) ; } catch ( e ) { if ( e instanceof TypeError ) { return _applyConstructor ( f , args ) ; } else { throw e ; } } } else { return helper ( args ) ; } } ; return currier . call ( this , arity , fn , fnArgs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debounce :: Number - > ( * - > Null ) - > Number Delay in milliseconds . Returns the timer ID so caller can cancel [CODESPLIT] function debounce ( n , immed , f ) { var _ref3 = function ( ) { switch ( _extractHiddenClass ( immed ) ) { case 'Boolean' : return [ f , immed ] ; case 'Function' : return [ immed , false ] ; default : throw new TypeError ( 'Unrecognized arguments ' + immed + ' and ' + f + ' to function debounce.' ) ; } } ( ) , _ref4 = _slicedToArray ( _ref3 , 2 ) , fn = _ref4 [ 0 ] , now = _ref4 [ 1 ] ; var timer = null ; return function ( ) { var _this = this ; for ( var _len4 = arguments . length , args = Array ( _len4 ) , _key4 = 0 ; _key4 < _len4 ; _key4 ++ ) { args [ _key4 ] = arguments [ _key4 ] ; } if ( timer === null && now ) { fn . apply ( this , args ) ; } clearTimeout ( timer ) ; timer = setTimeout ( function ( ) { return fn . apply ( _this , args ) ; } , n ) ; return timer ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pipe Forward function composition . [CODESPLIT] function pipe ( ) { for ( var _len6 = arguments . length , fs = Array ( _len6 ) , _key6 = 0 ; _key6 < _len6 ; _key6 ++ ) { fs [ _key6 ] = arguments [ _key6 ] ; } return function ( ) { var _this3 = this ; var first = fs . shift ( ) ; for ( var _len7 = arguments . length , args = Array ( _len7 ) , _key7 = 0 ; _key7 < _len7 ; _key7 ++ ) { args [ _key7 ] = arguments [ _key7 ] ; } return fs . reduce ( function ( acc , f ) { return f . call ( _this3 , acc ) ; } , first . apply ( this , args ) ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "denodeify :: ( * - > * ) - > ( * - > Promise * ) Turns a callback - accepting function into one that returns a Promise . [CODESPLIT] function denodeify ( fn ) { var length = fn . length > 0 ? fn . length - 1 : 0 ; var f = function f ( ) { var _this4 = this ; for ( var _len8 = arguments . length , args = Array ( _len8 ) , _key8 = 0 ; _key8 < _len8 ; _key8 ++ ) { args [ _key8 ] = arguments [ _key8 ] ; } return new Promise ( function ( resolve , reject ) { fn . apply ( _this4 , [ ] . concat ( args , [ function ( err ) { for ( var _len9 = arguments . length , rest = Array ( _len9 > 1 ? _len9 - 1 : 0 ) , _key9 = 1 ; _key9 < _len9 ; _key9 ++ ) { rest [ _key9 - 1 ] = arguments [ _key9 ] ; } if ( err ) { reject ( err ) ; } var result = void 0 ; switch ( rest . length ) { case 0 : result = true ; break ; case 1 : result = rest [ 0 ] ; break ; default : result = rest ; break ; } resolve ( result ) ; } ] ) ) ; } ) ; } ; return length ? curry ( length , f ) : f ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "trampoline :: ( * - > * ) - > ( * - > * ) [CODESPLIT] function trampoline ( fn ) { return curry ( fn . length , function ( ) { for ( var _len10 = arguments . length , args = Array ( _len10 ) , _key10 = 0 ; _key10 < _len10 ; _key10 ++ ) { args [ _key10 ] = arguments [ _key10 ] ; } var result = fn . apply ( this , args ) ; while ( _extractHiddenClass ( result ) === 'Function' ) { result = result ( ) ; } return result ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a batch of { @link Ext . data . Operation Operations } in the order specified by { @link #batchOrder } . Used internally by { @link Ext . data . Store } s { @link Ext . data . Store#sync sync } method . Example usage : [CODESPLIT] function ( options , /* deprecated */ listeners ) { var me = this , params = options . params , useBatch = me . getBatchActions ( ) , model = me . getModel ( ) , batch , records ; if ( options . operations === undefined ) { // the old-style (operations, listeners) signature was called // so convert to the single options argument syntax options = { operations : options , listeners : listeners } ; // <debug warn> Ext . Logger . deprecate ( 'Passes old-style signature to Proxy.batch (operations, listeners). Please convert to single options argument syntax.' ) ; // </debug> } if ( options . batch && options . batch . isBatch ) { batch = options . batch ; } else { batch = new Ext . data . Batch ( options . batch || { } ) ; } batch . setProxy ( me ) ; batch . on ( 'complete' , Ext . bind ( me . onBatchComplete , me , [ options ] , 0 ) ) ; if ( options . listeners ) { batch . on ( options . listeners ) ; } Ext . each ( me . getBatchOrder ( ) . split ( ',' ) , function ( action ) { records = options . operations [ action ] ; if ( records ) { if ( useBatch ) { var operationOptions = { action : action , records : records , model : model } ; if ( params ) { operationOptions . params = params ; } batch . add ( new Ext . data . Operation ( operationOptions ) ) ; } else { Ext . each ( records , function ( record ) { var operationOptions = { action : action , records : [ record ] , model : model } ; if ( params ) { operationOptions . params = params ; } batch . add ( new Ext . data . Operation ( operationOptions ) ) ; } ) ; } } } , me ) ; batch . start ( ) ; return batch ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a raw HTML string for a template . A comment containing the el configuration can be inserted into it . [CODESPLIT] function createRawHtml ( createTemplateFn , templateLanguage , elCommentConfig , dataAttributes ) { // Construct the HTML string var comment = elCommentConfig . noComment ? \"\" : \"<!-- \" + elCommentConfig . createContent ( dataAttributes ) + \" -->\" , insertion = elCommentConfig . among ? comment : \"\" , isLeading = ! elCommentConfig . trailing && ! elCommentConfig . among , isTrailing = elCommentConfig . trailing , baseTemplate = createTemplateFn ( templateLanguage , insertion ) ; return isLeading ? comment + baseTemplate : isTrailing ? baseTemplate + comment : baseTemplate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the content of a complex template . It should contain as many pitfalls for correct processing as possible . [CODESPLIT] function createComplexTemplate ( templateLanguage , options ) { var t = getTemplateLanguageConstructs ( templateLanguage ) , indent = options && options . indentation || \"\" , insert = options && options . insertion || \"\" , lines = [ '<!-- top-level comment (single line) -->' , '<!--' , '  top-level' , '  comment' , '  (multi-line)' , '-->' , t . if , '<p>This is a %%paragraph' , 'Some random %%text&& with different line breaks.<br><br/><br />' , t . else , '<h1 class=\"header\">This is a %%header&&</h1>    ' , t . endIf , t . if , '</p>' , t . endIf , insert , 'Some top-level %%text&&, not wrapped in a tag.<br><br/><br />' , '<!-- comment containing a <div> tag -->' , \"<\" + \"script>alert( 'foo' );</\" + \"script>\" , '<p class=\"significantWhitespaceExpected\">' , '  some text  </p>' , '<%%tagName&& %%attrs&&>lorem ipsum</%%tagName&&>' , '<p><h1>Invalid nesting</h1></p>' , t . partial , '<dl class=\"%%dl_class&&\">' , '  ' + t . loop , '  <dt class=\"dtclass\">%%dd_name&&</dt>' , '  <dd class=\"ddclass\">%%dd_content&&</dd>' , '  ' + t . endLoop , '</dl>' ] , innerContent = _ . map ( lines , function ( line ) { return indent + line ; } ) . join ( \"\\n\" ) ; return innerContent . replace ( / %% / g , t . startDelimiter ) . replace ( / && / g , t . endDelimiter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the language constructs for a given template language for use in template creation . [CODESPLIT] function getTemplateLanguageConstructs ( templateLanguage ) { var constructs ; switch ( templateLanguage . toLowerCase ( ) ) { case \"handlebars\" : constructs = { startDelimiter : \"{{\" , endDelimiter : \"}}\" , if : \"{{#if isActive}}\" , else : \"{{else}}\" , endIf : \"{{/if}}\" , loop : \"{{#each looped as |value index|}}\" , endLoop : \"{{/each}}\" , partial : '{{> userMessage tagName=\"h2\" }}' } ; break ; case \"ejs\" : constructs = { startDelimiter : \"<%= \" , endDelimiter : \" %>\" , if : \"<% if (isActive) { %>\" , else : \"<% } else { %>\" , endIf : \"<% } %>\" , loop : \"<% looped.forEach(function(item) { %>\" , endLoop : \"<% }); %>\" , partial : \"<%- include('user/show', {user: user}); %>\" } ; break ; case \"es6\" : constructs = { startDelimiter : \"${\" , endDelimiter : \"}\" , if : \"\" , else : \"\" , endIf : \"\" , loop : \"\" , endLoop : \"\" , partial : \"\" } ; break ; default : throw new Error ( 'Unsupported template language \"' + templateLanguage + '\"' ) ; } return constructs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define a new model prototype . [CODESPLIT] function defineModel ( modelType , options ) { var primaryAttributes ; var attributes ; var prototype ; var staticProto ; var ModelConstructor ; var typeName ; var namespace ; if ( types . isValidType ( modelType ) . indexes ) { throw ModelException ( 'Model type cannot be an array `{{type}}`' , null , null , { type : String ( modelType ) } ) ; } else if ( models [ modelType ] ) { throw ModelException ( 'Model already defined `{{type}}`' , null , null , { type : String ( modelType ) } ) ; } options = options || { } ; primaryAttributes = [ ] ; namespace = _getNamespace ( modelType ) ; typeName = _getTypeName ( modelType ) ; attributes = _prepareAttributes ( options . attributes || { } , primaryAttributes ) ; prototype = _preparePrototype ( options . methods || { } , primaryAttributes , modelType , namespace , typeName ) ; staticProto = _prepareStaticProto ( options . staticMethods || { } , primaryAttributes , options . attributes , prototype . _type ) ; ModelConstructor = Function ( 'Model, events, attributes' , 'return function ' + typeName + 'Model(data) { ' + 'if (!(this instanceof ' + typeName + 'Model)){' + 'return new ' + typeName + 'Model(data);' + '}' + ( attributes ? 'Object.defineProperties(this, attributes);' : '' ) + 'events.emit(\"create\", data);' + 'Model.call(this, data);' + ' }' ) ( Model , events , attributes ) ; util . inherits ( ModelConstructor , Model ) ; Object . defineProperties ( ModelConstructor . prototype , prototype ) ; Object . defineProperties ( ModelConstructor , staticProto ) ; if ( ! types . isDefined ( modelType ) ) { types . define ( modelType , options . typeValidator || _modelTypeValidator ( ModelConstructor ) ) ; } // assign models [ modelType ] = ModelConstructor ; events . emit ( 'define' , { modelType : modelType , namespace : namespace , typeName : typeName , attributes : attributes , constructor : ModelConstructor , options : options } ) ; // Freeze model API for ( var attr in attributes ) { Object . freeze ( attributes [ attr ] ) ; } if ( options . attributes ) { Object . freeze ( options . attributes ) ; // freeze declared attributes } if ( attributes ) { Object . freeze ( attributes ) ; // freeze attributes list } Object . freeze ( primaryAttributes ) ; // freeze primary attributes //Object.freeze(ModelConstructor.prototype);  // do not freeze to allow extensions return ModelConstructor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Base Model function constructor [CODESPLIT] function Model ( data ) { var attributes = this . __proto__ . constructor . attributes ; var i , ilen ; var dirty = false ; Object . defineProperties ( this , { _id : { configurable : false , enumerable : true , writable : false , value : ++ uniqueId } , _isDirty : { configurable : false , enumerable : true , get : function isDirty ( ) { return dirty ; } , set : function isDirty ( d ) { dirty = d ; if ( ! d && this . _previousData ) { this . _previousData = undefined ; } } } , _isNew : { configurable : false , enumerable : true , get : function isNewModel ( ) { var newModel = false ; var attrValue ; if ( this . _primaryAttributes ) { for ( i = 0 , ilen = this . _primaryAttributes . length ; i < ilen && ! newModel ; ++ i ) { attrValue = this [ this . _primaryAttributes [ i ] ] ; if ( ( attrValue === undefined ) || ( attrValue === null ) ) { newModel = true ; } } } return newModel ; } } } ) ; if ( attributes ) { Object . defineProperties ( this , attributes ) ; Object . defineProperty ( this , '_data' , { configurable : false , enumerable : false , writable : false , value : _defaultData ( attributes ) } ) ; } if ( Array . isArray ( data ) ) { for ( i = 0 , ilen = data . length ; i < ilen ; ++ i ) { if ( this . _primaryAttributes [ i ] ) { this [ this . _primaryAttributes [ i ] ] = data [ i ] ; } } } else if ( data ) { this . fromJSON ( data ) ; } this . _isDirty = false ; // overwrite... }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of Point [CODESPLIT] function Point ( masterApikey , feedID , streamID ) { /** @private */ this . masterApiKey = masterApikey ; /** @private */ this . feedID = feedID . toString ( ) ; /** @private */ this . streamID = streamID . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Truncate a string and add an ellipsis ( ... ) to the end if it exceeds the specified length . [CODESPLIT] function ( value , len , word ) { if ( value && value . length > len ) { if ( word ) { var vs = value . substr ( 0 , len - 2 ) , index = Math . max ( vs . lastIndexOf ( ' ' ) , vs . lastIndexOf ( '.' ) , vs . lastIndexOf ( '!' ) , vs . lastIndexOf ( '?' ) ) ; if ( index != - 1 && index >= ( len - 15 ) ) { return vs . substr ( 0 , index ) + \"...\" ; } } return value . substr ( 0 , len - 3 ) + \"...\" ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pads the left side of a string with a specified character . This is especially useful for normalizing number and date strings . Example usage : [CODESPLIT] function ( val , size , ch ) { var result = String ( val ) ; ch = ch || \" \" ; while ( result . length < size ) { result = ch + result ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens . Each token must be unique and must increment in the format { 0 } { 1 } etc . Example usage : [CODESPLIT] function ( format ) { var args = Ext . toArray ( arguments , 1 ) ; return format . replace ( Ext . util . Format . formatRe , function ( m , i ) { return args [ i ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert certain characters ( & < > and ) to their HTML character equivalents for literal display in web pages . [CODESPLIT] function ( value ) { return ! value ? value : String ( value ) . replace ( / & / g , \"&amp;\" ) . replace ( / > / g , \"&gt;\" ) . replace ( / < / g , \"&lt;\" ) . replace ( / \" / g , \"&quot;\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a value into a formatted date using the specified format pattern . Note that this uses the native Javascript Date . parse () method and is therefore subject to its idiosyncrasies . Most formats assume the local timezone unless specified . One notable exception is YYYY - MM - DD ( note the dashes ) which is typically interpreted in UTC and can cause date shifting . [CODESPLIT] function ( value , format ) { var date = value ; if ( ! value ) { return \"\" ; } if ( ! Ext . isDate ( value ) ) { date = new Date ( Date . parse ( value ) ) ; if ( isNaN ( date ) ) { // Dates with ISO 8601 format are not well supported by mobile devices, this can work around the issue. if ( this . iso8601TestRe . test ( value ) ) { // Fix for older android browsers to properly implement ISO 8601 formatted dates with timezone if ( Ext . os . is . Android && Ext . os . version . isLessThan ( \"3.0\" ) ) { /**\n                         * This code is modified from the following source: <https://github.com/csnover/js-iso8601>\n                         * © 2011 Colin Snover <http://zetafleet.com>\n                         * Released under MIT license.\n                         */ var potentialUndefinedKeys = [ 1 , 4 , 5 , 6 , 7 , 10 , 11 ] ; var dateParsed , minutesOffset = 0 ; // Capture Groups // 1 YYYY (optional) // 2 MM // 3 DD // 4 HH // 5 mm (optional) // 6 ss (optional) // 7 msec (optional) // 8 Z (optional) // 9 ± (optional) // 10 tzHH (optional) // 11 tzmm (optional) if ( ( dateParsed = / ^(\\d{4}|[+\\-]\\d{6})(?:-(\\d{2})(?:-(\\d{2}))?)?(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{3}))?)?(?:(Z)|([+\\-])(\\d{2})(?::(\\d{2}))?)?)?$ / . exec ( value ) ) ) { //Set any undefined values needed for Date to 0 for ( var i = 0 , k ; ( k = potentialUndefinedKeys [ i ] ) ; ++ i ) { dateParsed [ k ] = + dateParsed [ k ] || 0 ; } // Fix undefined month and decrement dateParsed [ 2 ] = ( + dateParsed [ 2 ] || 1 ) - 1 ; //fix undefined days dateParsed [ 3 ] = + dateParsed [ 3 ] || 1 ; // Correct for timezone if ( dateParsed [ 8 ] !== 'Z' && dateParsed [ 9 ] !== undefined ) { minutesOffset = dateParsed [ 10 ] * 60 + dateParsed [ 11 ] ; if ( dateParsed [ 9 ] === '+' ) { minutesOffset = 0 - minutesOffset ; } } // Calculate valid date date = new Date ( Date . UTC ( dateParsed [ 1 ] , dateParsed [ 2 ] , dateParsed [ 3 ] , dateParsed [ 4 ] , dateParsed [ 5 ] + minutesOffset , dateParsed [ 6 ] , dateParsed [ 7 ] ) ) ; } } else { date = value . split ( this . iso8601SplitRe ) ; date = new Date ( date [ 0 ] , date [ 1 ] - 1 , date [ 2 ] , date [ 3 ] , date [ 4 ] , date [ 5 ] ) ; } } } if ( isNaN ( date ) ) { // Dates with the format \"2012-01-20\" fail, but \"2012/01/20\" work in some browsers. We'll try and // get around that. date = new Date ( Date . parse ( value . replace ( this . dashesRe , \"/\" ) ) ) ; //<debug> if ( isNaN ( date ) ) { Ext . Logger . error ( \"Cannot parse the passed value \" + value + \" into a valid date\" ) ; } //</debug> } value = date ; } return Ext . Date . format ( value , format || Ext . util . Format . defaultDateFormat ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates this container with the new active item . [CODESPLIT] function ( tabBar , newTab ) { var oldActiveItem = this . getActiveItem ( ) , newActiveItem ; this . setActiveItem ( tabBar . indexOf ( newTab ) ) ; newActiveItem = this . getActiveItem ( ) ; return this . forcedChange || oldActiveItem !== newActiveItem ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { [CODESPLIT] function ( config ) { if ( config === true ) { config = { } ; } if ( config ) { Ext . applyIf ( config , { ui : this . getUi ( ) , docked : this . getTabBarPosition ( ) } ) ; } return Ext . factory ( config , Ext . tab . Bar , this . getTabBar ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new LineSegment out of two points . [CODESPLIT] function ( point1 , point2 ) { var Point = Ext . util . Point ; this . point1 = Point . from ( point1 ) ; this . point2 = Point . from ( point2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the point where two lines intersect . [CODESPLIT] function ( lineSegment ) { var point1 = this . point1 , point2 = this . point2 , point3 = lineSegment . point1 , point4 = lineSegment . point2 , x1 = point1 . x , x2 = point2 . x , x3 = point3 . x , x4 = point4 . x , y1 = point1 . y , y2 = point2 . y , y3 = point3 . y , y4 = point4 . y , d = ( x1 - x2 ) * ( y3 - y4 ) - ( y1 - y2 ) * ( x3 - x4 ) , xi , yi ; if ( d == 0 ) { return null ; } xi = ( ( x3 - x4 ) * ( x1 * y2 - y1 * x2 ) - ( x1 - x2 ) * ( x3 * y4 - y3 * x4 ) ) / d ; yi = ( ( y3 - y4 ) * ( x1 * y2 - y1 * x2 ) - ( y1 - y2 ) * ( x3 * y4 - y3 * x4 ) ) / d ; if ( xi < Math . min ( x1 , x2 ) || xi > Math . max ( x1 , x2 ) || xi < Math . min ( x3 , x4 ) || xi > Math . max ( x3 , x4 ) || yi < Math . min ( y1 , y2 ) || yi > Math . max ( y1 , y2 ) || yi < Math . min ( y3 , y4 ) || yi > Math . max ( y3 , y4 ) ) { return null ; } return new Ext . util . Point ( xi , yi ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FUNCTION NAME // FUNCTION : functionName ( fcn ) Returns the name of a function . [CODESPLIT] function functionName ( fcn ) { var name ; if ( ! isFunction ( fcn ) ) { throw new TypeError ( 'invalid input argument. Must provide a function. Value: `' + fcn + '`.' ) ; } if ( isString ( fcn . name ) ) { name = fcn . name ; } else { name = RE . exec ( fcn . toString ( ) ) [ 1 ] ; } return ( name === '' ) ? 'anonymous' : name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Class that interprets command line commands using commander . [CODESPLIT] function ( ) { // Defines all the commands with commander. program . version ( env . version ) . description ( 'Tool for generating random numbers from a seed' ) . option ( '-s, --seed <seed>' , 'specify the seed' , Math . random ( ) ) . option ( '-d, --decimal' , 'generates a random decimal number' , false ) . option ( '-r, --range <a>,<b>' , 'generates a random integer in the range inclusive' , this . range ) . parse ( process . argv ) ; // Calls the method that will check the commands // the user has entered. this . switchFunction ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public stuff Constructor [CODESPLIT] function SteroidsSocket ( options ) { var finalTarget ; if ( options . target && net . isIPv6 ( options . target ) ) { finalTarget = normalize6 ( options . target ) ; } else { finalTarget = options . target ; } this . target = finalTarget ; this . port = options . port || 80 ; this . transport = options . transport || 'TCP' ; this . lport = options . lport || null ; this . timeout = options . timeout || 8000 ; this . allowHalfOpen = options . allowHalfOpen || null ; this . wsProto = options . wsProto || 'sip' ; this . wsPath = options . wsPath || null ; // We init the socket in the send function to be able // to detect timeouts using UDP (no \"received\" or similar event) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The libraries don t support any close function so we need this to emulate it . [CODESPLIT] function timeoutCb ( ) { if ( ! received ) { self . emit ( 'error' , { type : 'socket: timeout' , data : 'Connection problem: No response' } ) ; } // Websockets Node module doen't support any close function, we're using the client // https://github.com/Worlize/WebSocket-Node/blob/master/lib/WebSocketClient.js // So we need this var to \"emulate\" it and avoid returning multiple errors wsError = true ; // We're closing the socket manually, so we need this to avoid errors self . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "String real width [CODESPLIT] function realWidth ( str ) { if ( str == null ) return 0 ; str = stripANSI ( str ) ; return str . length + ( stripEmoji ( str ) . match ( / [^\\x00-\\xff] / g ) || [ ] ) . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main [CODESPLIT] function PC ( source , config ) { if ( source == null ) return ; this . config = { prefix : '' , suffix : '' , placeholder : ' ' , columnSeparation : ' ' , rowSeparation : \"\\n\" , rowSplitSymbol : \"\\n\" , columnSplitSymbol : \"\\t\" } ; this . _STATS = { originalSource : source , source : null , formatted : null , rows : 0 , columns : 0 , maxWidth : [ ] , width : [ ] , align : [ ] } ; this . params ( config ) ; this . parseSource ( ) ; this . AnalyticAlignment ( ) ; this . format ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursivley copy a folder to a given destination if there are conflicts prompt the user . [CODESPLIT] function ( source , destination ) { gulp . src ( source ) . pipe ( conflict ( destination ) ) . pipe ( gulp . dest ( destination ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively copy a template folder to a given destination and apply a template context object for using <% = token % > delimiters and {{ = token }} for filename delimiters ( windows restriction ) . [CODESPLIT] function ( source , destination , context , opts ) { if ( ! opts ) opts = { force : true } ; this . mkdirP ( destination ) ; var files = fs . readdirSync ( source ) ; for ( var i = 0 ; i < files . length ; i ++ ) { var sourceFile = path . join ( source , files [ i ] ) ; var destinationFile = path . join ( destination , files [ i ] ) ; if ( this . isDirectory ( sourceFile ) ) { this . templateDirSync ( sourceFile , destinationFile , context , opts ) ; } else { if ( fs . existsSync ( destinationFile ) && ! opts . force ) { console . log ( 'skipping existing file: ' + files [ i ] ) ; } else { this . templateFileSync ( sourceFile , destinationFile , context ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy a and apply a lodash template to a file based on a given context . The filename can include a {{ = token }} for template delimiters ( windows restriction ) . [CODESPLIT] function ( source , destination , context ) { // To avoid issues with windows use a custom delimiter for file names if ( destination . indexOf ( '{{-' ) !== - 1 ) { _ . templateSettings . escape = / \\{\\{-(.*?)\\}\\} / g ; destination = _ . template ( destination , context ) ; } var content = fs . readFileSync ( source , 'utf8' ) . toString ( ) ; var indexContent = _ . template ( content , context ) ; fs . writeFileSync ( destination , indexContent , 'utf8' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shortcut for copying a folder and it s contents recursively to a given destination if the source does not exist it will do nothing . [CODESPLIT] function ( source , destination ) { if ( ! fs . existsSync ( destination ) ) mkdir ( '-p' , destination ) ; cp ( '-R' , source , destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add assignable properties for tracking . [CODESPLIT] function ( tracker , propList ) { var trackingData = tracker [ trackingKeyName ] ; propList . forEach ( function ( name ) { Object . defineProperty ( tracker , name , { enumerable : true , configurable : true , get : function ( ) { return trackingData . object [ name ] ; } , set : function ( x ) { trackingData . actions . push ( { key : name , set : x , } ) ; trackingData . object [ name ] = x ; } , } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add callable methods for tracking . [CODESPLIT] function ( tracker , methodList ) { var trackingData = tracker [ trackingKeyName ] ; methodList . forEach ( function ( name ) { tracker [ name ] = function ( ) { var context = this ; var argsArray = Array . prototype . slice . call ( arguments ) ; // Only record actions called directly on the tracker. if ( this === tracker ) { // Forwarded call should operate on original object. context = trackingData . object ; trackingData . actions . push ( { key : name , arguments : argsArray , } ) ; } return trackingData . object [ name ] . apply ( context , argsArray ) ; } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find all existing properties and methods in the object . [CODESPLIT] function ( object ) { var propList = [ ] ; var methodList = [ ] ; for ( var k in object ) { if ( typeof object [ k ] === \"function\" ) { methodList . push ( k ) ; } else { propList . push ( k ) ; } } return { propList : propList , methodList : methodList , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JCM constructor should not be async delay until first operation [CODESPLIT] function ( config , callback , scope ) { // Ext . data . utilities . check ( 'SyncProxy' , 'constructor' , 'config' , config , [ 'store' , 'database_name' , 'key' ] ) ; // Ext . data . SyncProxy . superclass . constructor . call ( this , config ) ; this . store = config . store ; // // System Name // this . store . readValue ( 'Sencha.Sync.system_name' , function ( system_name ) { config . system_name = system_name || Ext . data . UUIDGenerator . generate ( ) ; this . store . writeValue ( 'Sencha.Sync.system_name' , config . system_name , function ( ) { // // Load Configuration // Ext . data . utilities . apply ( this , [ 'readConfig_DatabaseDefinition' , 'readConfig_CSV' , 'readConfig_Generator' ] , [ config ] , function ( ) { if ( this . definition . system_name === undefined ) { this . definition . set ( { system_name : Ext . data . UUIDGenerator . generate ( ) } ) ; } console . log ( \"SyncProxy - Opened database '\" + config . key + \"/\" + config . database_name + \"/\" + config . datastore_name + \"'\" ) if ( callback ) { callback . call ( scope , this ) } } , this ) ; } , this ) ; } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Installing a new content . [CODESPLIT] function ( content ) { content = trim ( content ) ; if ( this . mounted ) { invoke ( this , [ Constants . BLOCK , 'setMountedContent' ] , content ) ; } else { dom . contentNode ( this ) . innerHTML = content ; this . upgrade ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Getting object properties . [CODESPLIT] function ( ) { const props = dom . attrs . toObject ( this ) ; const xprops = this . xprops ; const eprops = get ( xtag , [ 'tags' , this [ Constants . TAGNAME ] , 'accessors' ] , { } ) ; for ( let prop in eprops ) { if ( xprops . hasOwnProperty ( prop ) && eprops . hasOwnProperty ( prop ) && ! BLOCK_COMMON_ACCESSORS . hasOwnProperty ( prop ) ) { props [ prop ] = this [ prop ] ; } } dom . attrs . typeConversion ( props , xprops ) ; return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cloning a node . [CODESPLIT] function ( deep ) { // not to clone the contents const node = dom . cloneNode ( this , false ) ; dom . upgrade ( node ) ; node [ Constants . TMPL ] = this [ Constants . TMPL ] ; node [ Constants . INSERTED ] = false ; if ( deep ) { node . content = this . content ; } // ??? // if ('checked' in this) clone.checked = this.checked; return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialization of the element . [CODESPLIT] function blockInit ( node ) { if ( ! node [ Constants . TAGNAME ] ) { node [ Constants . INSERTED ] = false ; node [ Constants . TAGNAME ] = node . tagName . toLowerCase ( ) ; node [ Constants . TMPL ] = { } ; node [ Constants . UID ] = uniqueId ( ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creating an item . [CODESPLIT] function blockCreate ( node ) { if ( node . hasChildNodes ( ) ) { Array . prototype . forEach . call ( node . querySelectorAll ( 'script[type=\"text/x-template\"][ref],template[ref]' ) , tmplCompileIterator , node ) ; } node [ Constants . BLOCK ] = new XBElement ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( key === 'lifecycle' ) { return mergeWith ( objValue , srcValue , lifecycleCustomizer ) ; } if ( key === 'events' ) { return mergeWith ( objValue , srcValue , eventsCustomizer ) ; } if ( key === 'accessors' ) { return mergeWith ( objValue , srcValue , accessorsCustomizer ) ; } if ( key === 'methods' ) { checkOverriddenMethods ( objValue , srcValue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inheritance events set property changes . [CODESPLIT] function accessorsCustomizer ( objValue , srcValue ) { const objSetter = get ( objValue , 'set' ) ; const srcSetter = get ( srcValue , 'set' ) ; return merge ( { } , objValue , srcValue , { set : wrap ( objSetter , wrap ( srcSetter , wrapperFunction ) ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ) } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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><script>...</script><div>not found</div></xb-test> if ( isScriptContent ) { lazy ( blockCreateLazy , this ) ; } else { blockCreate ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; } , \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "计算 md5 [CODESPLIT] function md5 ( buffer ) { var hash = crypto . createHash ( 'md5' ) ; return hash . update ( buffer ) . digest ( 'hex' ) . slice ( 0 , 10 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "创建一个正则表达式 [CODESPLIT] function createPattern ( pattern , flags ) { pattern = pattern . replace ( / [\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|] / g , \"\\\\$&\" ) ; return flags ? new RegExp ( pattern , flags ) : new RegExp ( pattern ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "纠正依赖的格式 [CODESPLIT] function correctDependencies ( file , dependencies , correct ) { if ( ! correct ) { return ; } for ( var i = dependencies . length - 1 ; i >= 0 ; i -- ) { correct ( file , dependencies [ i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取 html 文件的依赖 [CODESPLIT] function ( options ) { var me = this ; return me . custom ( function ( file , callback ) { htmlDependencies ( file , me , options ) ; callback ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取 css 文件的依赖 [CODESPLIT] function ( options ) { var me = this ; return me . custom ( function ( file , callback ) { cssDependencies ( file , me , options ) ; callback ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取 amd 文件的依赖 [CODESPLIT] function ( options ) { var me = this ; return me . custom ( function ( file , callback ) { amdDependencies ( file , me , options ) ; callback ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; } } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) /**\n   * Wraps getNearestContacts with telemetry\n   * #getNearestContacts\n   * @returns {Array} shortlist\n   */ 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 ) } /**\n   * Uses the transport telemetry to compare two nodes\n   * #_compare\n   * @param {kad.Contact} contactA\n   * @param {kad.Contact} contactB\n   * @returns {Number}\n   */ 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 } /**\n   * Uses a profile scorecard to calculate the probability of success\n   * #getSuccessProbability\n   * @param {Object} score\n   * @returns {Number}\n   */ TelemetryRouter . getSuccessProbability = function ( score ) { return ( score . reliability + score . availability + score . latency ) / 3 } return TelemetryRouter }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; /**\n\t* FUNCTION: quantile( p )\n\t*\tEvaluates the quantile function for a triangular distribution.\n\t*\n\t* @private\n\t* @param {Number} p - input value\n\t* @returns {Number} evaluated quantile function\n\t*/ 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 ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; } } } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; /**\n   * Create the logger method for each level. Set it up in the constructor\n   * to properly lock in the context.\n   */ Object . keys ( levels ) . forEach ( function ( level ) { logger [ level ] = function ( ) { return logger . write ( levels [ level ] , arguments ) ; } ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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' ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ] = { } ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter factory [CODESPLIT] function ( token ) { var filter = { val : '' , opts : [ ] , type : 'filter' } token . filters . push ( filter ) ; return filter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"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 }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) }", "target": 1, "target_options": ["no_match", "match"]}
{"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' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add watchify args [CODESPLIT] function prewatch ( theOptions ) { if ( config . watch ) { return _ . defaults ( theOptions , watchify . args ) ; } return theOptions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 } ` ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ] ) ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a new fake salesforce id [CODESPLIT] function ( ) { var idStr = '' + sforce . db . id ++ ; return sforce . db . _idTemplate . substring ( 0 , 18 - idStr . length ) + idStr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 , } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( '<a name=\"{0}\" style=\"color:#333;\"></a>' , anchor ) ) ; // Add contents item html . push ( fm ( '<div style=\"padding-left:{0}em;\"><a href=\"#{2}\" style=\"text-decoration:none;\">{1}</a></div>' , index * 1.5 , order . slice ( 0 , index + 1 ) . join ( '.' ) + ' ' + hash [ index ] , anchor ) ) ; } ) ; var $contentsWrap = $ ( fm ( [ '<div style=\"{0}\">' , '<div style=\"text-align: center;height:22px;line-height:22px;\">' , '<b>Contents</b> <a href=\"javascript:;\">hide</a>' , '</div>' , '<div>{1}</div>' , '</div>' ] . 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' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add to Top link for mark h [CODESPLIT] function addTop ( $ , top ) { console . log ( 'addTop' , top ) ; $ ( top . join ( ',' ) ) . each ( function ( i , obj ) { //$(obj).append(' <a href=\"#\" style=\"display:none;font-size: 12px;color: #333;\">Top</a>'); $ ( obj ) . prepend ( [ '<div style=\"position: relative;width: 1px;\">' , '<a href=\"javascript:;\" style=\"position:absolute;width:1.2em;left:-1.2em;font-size:0.8em;display:inline-block;visibility:hidden;color:#333;text-align:left;text-decoration: none;\">' , '&#10022;</a>' , '</div>' ] . 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 ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get transaction from XHR options . [CODESPLIT] function ( options ) { return options && options . getTid ? Ext . direct . Manager . getTransaction ( options . getTid ( ) ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 = [ ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Work with options here [CODESPLIT] function inlineBlockFix ( decl ) { var origRule = decl . parent ; origRule . append ( { prop : '*display' , value : 'inline' } , { prop : '*zoom' , value : '1' } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ] /**\n   * Wraps _open with telemetry hooks setup\n   * #_open\n   * @param {Function} callback\n   */ 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 }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a random value from an array [CODESPLIT] function getRandomArrValue ( arr , min = 0 , max = arr . length - 1 ) { return arr [ getRandomInt ( min , max ) ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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.' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 + '.' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 }", "target": 1, "target_options": ["no_match", "match"]}
{"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 } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trying autodetect and import key [CODESPLIT] function ( key , data ) { // [\\S\\s]* matches zero or more of any character if ( / ^[\\S\\s]*-----BEGIN RSA PRIVATE KEY-----\\s*(?=(([A-Za-z0-9+/=]+\\s*)+))\\1-----END RSA PRIVATE KEY-----[\\S\\s]*$ / g . test ( data ) ) { module . exports . privateImport ( key , data ) ; return true ; } if ( / ^[\\S\\s]*-----BEGIN RSA PUBLIC KEY-----\\s*(?=(([A-Za-z0-9+/=]+\\s*)+))\\1-----END RSA PUBLIC KEY-----[\\S\\s]*$ / g . test ( data ) ) { module . exports . publicImport ( key , data ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"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 ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logs a message to help with debugging . [CODESPLIT] function ( message , priority , callerId ) { if ( ! this . getEnabled ( ) ) { return this ; } var statics = Logger , priorities = statics . priorities , priorityValue = priorities [ priority ] , caller = this . log . caller , callerDisplayName = '' , writers = this . getWriters ( ) , event , i , originalCaller ; if ( ! priority ) { priority = 'info' ; } if ( priorities [ this . getMinPriority ( ) ] > priorityValue ) { return this ; } if ( ! callerId ) { callerId = 1 ; } if ( Ext . isArray ( message ) ) { message = message . join ( \" \" ) ; } else { message = String ( message ) ; } if ( typeof callerId == 'number' ) { i = callerId ; do { i -- ; caller = caller . caller ; if ( ! caller ) { break ; } if ( ! originalCaller ) { originalCaller = caller . caller ; } if ( i <= 0 && caller . displayName ) { break ; } } while ( caller !== originalCaller ) ; callerDisplayName = Ext . getDisplayName ( caller ) ; } else { caller = caller . caller ; callerDisplayName = Ext . getDisplayName ( callerId ) + '#' + caller . $name ; } event = { time : Ext . Date . now ( ) , priority : priorityValue , priorityName : priority , message : message , caller : caller , callerDisplayName : callerDisplayName } ; for ( i in writers ) { if ( writers . hasOwnProperty ( i ) ) { writers [ i ] . write ( Ext . merge ( { } , event ) ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shortcut to read a template file apply a context and write it to a new file . // todo refactor template utilities from .. / util . js to lib / template . js [CODESPLIT] function writeTemplateFileSync ( source , context , destination ) { var templateContent = fs . readFileSync ( source , 'utf8' ) ; var templateResult ; try { templateResult = _ . template ( templateContent , context ) ; } catch ( error ) { console . error ( 'templateFileSync() error with source' , source , ' and ' , destination ) ; console . error ( error ) ; } fs . writeFileSync ( destination , templateResult ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shortcut to apply a template context and return the result // todo refactor template utilities from .. / util . js to lib / template . js [CODESPLIT] function templateSync ( content , context ) { var templateResult ; try { templateResult = _ . template ( content , context ) ; } catch ( error ) { console . error ( 'templateSync() error with source' , content , 'or content' , context ) ; console . error ( error ) ; } return templateResult ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shortcut to copy a file Synchronously [CODESPLIT] function copyFileSync ( source , destination ) { if ( validateFileSync ( source ) ) { fs . writeFileSync ( destination , fs . readFileSync ( source ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If there are any files in the source folder that are a match copy them to the destination . [CODESPLIT] function copyFilesMatchSync ( match , source , destination ) { fs . readdirSync ( source ) . forEach ( function eachTemplate ( filename ) { var sourceFile = path . join ( source , filename ) ; var destinationFile = path . join ( destination , filename ) ; if ( match . test ( path . basename ( filename ) ) ) { fs . writeFileSync ( destinationFile , fs . readFileSync ( sourceFile ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy any number files that are a match to a regex to a given destination . If there are any files in the destination that are also a match replace them . [CODESPLIT] function replaceMatchFilesSync ( match , source , destination ) { unlinkFilesMatchSync ( match , destination ) ; copyFilesMatchSync ( match , source , destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If there are any files in the location folder that are a match remove them . [CODESPLIT] function unlinkFilesMatchSync ( match , location ) { fs . readdirSync ( location ) . forEach ( function eachTemplate ( filename ) { if ( match . test ( path . basename ( filename ) ) ) { var filePath = path . join ( location , filename ) ; if ( validateFileSync ( filePath ) ) { fs . unlinkSync ( filePath ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate if a given path has a valid directory is it doesn t console . error with an optional custom message . [CODESPLIT] function validateDirectorySync ( path , errorMessage ) { errorMessage = errorMessage || 'Error validateDirectorySync() the directory path is not valid ' + path ; var isValid = existsDirectorySync ( path ) ; if ( ! isValid ) { console . error ( errorMessage ) ; } return isValid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate if a given path has a valid file is it doesn t console . error with an optional custom message . [CODESPLIT] function validateFileSync ( path , errorMessage ) { errorMessage = errorMessage || 'Error validateFileSync() the file path is not valid ' + path ; var isValid = existsFileSync ( path ) ; if ( ! isValid ) { console . error ( errorMessage ) ; } return isValid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find all subdirectories of the base recursively . [CODESPLIT] function subDirectoriesWithFile ( base , filename ) { var result = [ ] ; if ( fs . existsSync ( base ) && fs . statSync ( base ) . isDirectory ( ) ) { if ( fs . existsSync ( path . join ( base , filename ) ) ) { result . push ( base ) ; } fs . readdirSync ( base ) . forEach ( function ( subdir ) { result . push . apply ( result , subDirectoriesWithFile ( path . join ( base , subdir ) , filename ) ) ; } ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match the path defined by path elements where some may be RegExp . When there is more than one candidate prefer the one with greatest interger value . [CODESPLIT] function maximisePath ( ) { // Ensure each element in the path exists, // where it is a regex, match it and replace the element with a string var elements = Array . prototype . slice . call ( arguments ) ; for ( var i = 1 ; i < elements . length ; i ++ ) { // the directory is elements 0 .. i-1 joined var directory = path . resolve ( path . join . apply ( path , elements . slice ( 0 , i ) ) ) ; // no directory implies failure if ( ! fs . existsSync ( directory ) ) { return null ; } // regex element is matched else if ( ( typeof elements [ i ] !== 'string' ) && ( 'test' in elements [ i ] ) ) { var matches = resolveDirMatches ( directory , elements [ i ] ) ; // no match implies failure, else use the item with the highest numeric index if ( matches . length === 0 ) { return null ; } else { elements [ i ] = matches [ 0 ] ; } } // anything else is cast to string else { elements [ i ] = String ( elements [ i ] ) ; } } // now join them all together // do a final check to make sure it exists var result = path . resolve ( elements . join ( path . sep ) ) ; return fs . existsSync ( result ) && result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a given directory find all files that match the result will be sorted with highest numeric index first . [CODESPLIT] function resolveDirMatches ( directory , match ) { if ( validateDirectorySync ( directory ) ) { return fs . readdirSync ( directory ) . filter ( function eachDirectoryItem ( item ) { var resolved = path . resolve ( path . join ( directory , item ) ) ; return match . test ( item ) && fs . statSync ( resolved ) . isDirectory ( ) ; } ) . sort ( compareHigher ) ; } else { return [ ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rank a vs b based on any numeric component in their string . [CODESPLIT] function compareHigher ( a , b ) { var numA = parseFloat ( / [\\d\\.]+$ / . exec ( a ) [ 0 ] ) ; var numB = parseFloat ( / [\\d\\.]+$ / . exec ( b ) [ 0 ] ) ; if ( isNaN ( numA ) || ( numB > numA ) ) { return + 1 ; } else if ( isNaN ( numB ) || ( numA > numB ) ) { return - 1 ; } else { return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pick the first existing directory from any of the given arguments . [CODESPLIT] function reduceDirectories ( ) { return Array . prototype . slice . call ( arguments ) . map ( function ( candidate ) { return path . normalize ( candidate ) ; } ) . filter ( function ( candidate ) { return fs . existsSync ( candidate ) && fs . statSync ( candidate ) . isDirectory ( ) ; } ) . shift ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a menu for a given side of the Viewport . [CODESPLIT] function ( menu , config ) { var me = this ; config = config || { } ; // Temporary workaround for body shifting issue if ( Ext . os . is . iOS && ! this . hasiOSOrientationFix ) { this . hasiOSOrientationFix = true ; this . on ( 'orientationchange' , function ( ) { window . scrollTo ( 0 , 0 ) ; } , this ) ; } if ( ! menu ) { //<debug error> Ext . Logger . error ( \"You must specify a side to dock the menu.\" ) ; //</debug> return ; } if ( ! config . side ) { //<debug error> Ext . Logger . error ( \"You must specify a side to dock the menu.\" ) ; //</debug> return ; } if ( [ 'left' , 'right' , 'top' , 'bottom' ] . indexOf ( config . side ) == - 1 ) { //<debug error> Ext . Logger . error ( \"You must specify a valid side (left, right, top or botom) to dock the menu.\" ) ; //</debug> return ; } var menus = me . getMenus ( ) ; if ( ! menus ) { menus = { } ; } // Add a listener to show this menu on swipe if ( ! me . addedSwipeListener ) { me . addedSwipeListener = true ; me . element . on ( { tap : me . onTap , swipestart : me . onSwipeStart , edgeswipestart : me . onEdgeSwipeStart , edgeswipe : me . onEdgeSwipe , edgeswipeend : me . onEdgeSwipeEnd , scope : me } ) ; // Add BB10 webworks API for swipe down. if ( window . blackberry ) { var toggleMenu = function ( ) { var menus = me . getMenus ( ) , menu = menus [ 'top' ] ; if ( ! menu ) { return ; } if ( menu . isHidden ( ) ) { me . showMenu ( 'top' ) ; } else { me . hideMenu ( 'top' ) ; } } ; if ( blackberry . app && blackberry . app . event && blackberry . app . event . onSwipeDown ) { blackberry . app . event . onSwipeDown ( toggleMenu ) ; // PlayBook } else if ( blackberry . event && blackberry . event . addEventListener ) { blackberry . event . addEventListener ( \"swipedown\" , toggleMenu ) ; // BB10 } } } menus [ config . side ] = menu ; menu . $reveal = Boolean ( config . reveal ) ; menu . $cover = config . cover !== false && ! menu . $reveal ; menu . $side = config . side ; me . fixMenuSize ( menu , config . side ) ; if ( config . side == 'left' ) { menu . setLeft ( 0 ) ; menu . setRight ( null ) ; menu . setTop ( 0 ) ; menu . setBottom ( 0 ) ; } else if ( config . side == 'right' ) { menu . setLeft ( null ) ; menu . setRight ( 0 ) ; menu . setTop ( 0 ) ; menu . setBottom ( 0 ) ; } else if ( config . side == 'top' ) { menu . setLeft ( 0 ) ; menu . setRight ( 0 ) ; menu . setTop ( 0 ) ; menu . setBottom ( null ) ; } else if ( config . side == 'bottom' ) { menu . setLeft ( 0 ) ; menu . setRight ( 0 ) ; menu . setTop ( null ) ; menu . setBottom ( 0 ) ; } me . setMenus ( menus ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a menu from a specified side . [CODESPLIT] function ( side ) { var menus = this . getMenus ( ) || { } , menu = menus [ side ] ; if ( menu ) this . hideMenu ( side ) ; delete menus [ side ] ; this . setMenus ( menus ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shows a menu specified by the menu s side . [CODESPLIT] function ( side ) { var menus = this . getMenus ( ) , menu = menus [ side ] , before , after , viewportBefore , viewportAfter ; if ( ! menu || menu . isAnimating ) { return ; } this . hideOtherMenus ( side ) ; before = { translateX : 0 , translateY : 0 } ; after = { translateX : 0 , translateY : 0 } ; viewportBefore = { translateX : 0 , translateY : 0 } ; viewportAfter = { translateX : 0 , translateY : 0 } ; if ( menu . $reveal ) { Ext . getBody ( ) . insertFirst ( menu . element ) ; } else { Ext . Viewport . add ( menu ) ; } menu . show ( ) ; menu . addCls ( 'x-' + side ) ; var size = ( side == 'left' || side == 'right' ) ? menu . element . getWidth ( ) : menu . element . getHeight ( ) ; if ( side == 'left' ) { before . translateX = - size ; viewportAfter . translateX = size ; } else if ( side == 'right' ) { before . translateX = size ; viewportAfter . translateX = - size ; } else if ( side == 'top' ) { before . translateY = - size ; viewportAfter . translateY = size ; } else if ( side == 'bottom' ) { before . translateY = size ; viewportAfter . translateY = - size ; } if ( menu . $reveal ) { if ( Ext . browser . getPreferredTranslationMethod ( ) != 'scrollposition' ) { menu . translate ( 0 , 0 ) ; } } else { menu . translate ( before . translateX , before . translateY ) ; } if ( menu . $cover ) { menu . getTranslatable ( ) . on ( 'animationend' , function ( ) { menu . isAnimating = false ; } , this , { single : true } ) ; menu . translate ( after . translateX , after . translateY , { preserveEndState : true , duration : 200 } ) ; } else { this . translate ( viewportBefore . translateX , viewportBefore . translateY ) ; this . getTranslatable ( ) . on ( 'animationend' , function ( ) { menu . isAnimating = false ; } , this , { single : true } ) ; this . translate ( viewportAfter . translateX , viewportAfter . translateY , { preserveEndState : true , duration : 200 } ) ; } // Make the menu as animating menu . isAnimating = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hides a menu specified by the menu s side . [CODESPLIT] function ( side , animate ) { var menus = this . getMenus ( ) , menu = menus [ side ] , after , viewportAfter , size ; animate = ( animate === false ) ? false : true ; if ( ! menu || ( menu . isHidden ( ) || menu . isAnimating ) ) { return ; } after = { translateX : 0 , translateY : 0 } ; viewportAfter = { translateX : 0 , translateY : 0 } ; size = ( side == 'left' || side == 'right' ) ? menu . element . getWidth ( ) : menu . element . getHeight ( ) ; if ( side == 'left' ) { after . translateX = - size ; } else if ( side == 'right' ) { after . translateX = size ; } else if ( side == 'top' ) { after . translateY = - size ; } else if ( side == 'bottom' ) { after . translateY = size ; } if ( menu . $cover ) { if ( animate ) { menu . getTranslatable ( ) . on ( 'animationend' , function ( ) { menu . isAnimating = false ; menu . hide ( ) ; } , this , { single : true } ) ; menu . translate ( after . translateX , after . translateY , { preserveEndState : true , duration : 200 } ) ; } else { menu . translate ( after . translateX , after . translateY ) ; menu . hide ( ) } } else { if ( animate ) { this . getTranslatable ( ) . on ( 'animationend' , function ( ) { menu . isAnimating = false ; menu . hide ( ) ; } , this , { single : true } ) ; this . translate ( viewportAfter . translateX , viewportAfter . translateY , { preserveEndState : true , duration : 200 } ) ; } else { this . translate ( viewportAfter . translateX , viewportAfter . translateY ) ; menu . hide ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hides all menus except for the side specified [CODESPLIT] function ( side , animation ) { var menus = this . getMenus ( ) ; for ( var menu in menus ) { if ( side != menu ) { this . hideMenu ( menu , animation ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Toggles the menu specified by side [CODESPLIT] function ( side ) { var menus = this . getMenus ( ) , menu ; if ( menus [ side ] ) { menu = menus [ side ] ; if ( menu . isHidden ( ) ) { this . showMenu ( side ) ; } else { this . hideMenu ( side ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : add transports parents / * measurer . prototype . transport = function ( measurement ) { var self = this ; [CODESPLIT] function timer ( options ) { if ( _ . isFunction ( options ) ) { options = { out : options } ; } options = options || { } ; this . _out = options . out || _ . stderr ; this . _times = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the Hiera module . [CODESPLIT] function init ( adapter , config ) { if ( ! fs ) { var Adapter = require ( './adapters/' + adapter ) ; fs = new Adapter ( config ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the Hiera hierarchy . [CODESPLIT] function getHierarchy ( cb ) { getConfig ( function ( err , config ) { if ( err ) { cb ( err ) ; return ; } cb ( null , config [ ':hierarchy' ] ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Hiera backend configurations . [CODESPLIT] function getBackends ( cb ) { getConfig ( function ( err , config ) { if ( err ) { cb ( err ) ; return ; } cb ( null , config [ ':backends' ] ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets configuration for a specific backend . [CODESPLIT] function getBackendConfig ( backend , cb ) { getConfig ( function ( err , config ) { if ( err ) { cb ( err ) ; return ; } cb ( null , config [ ':' + backend ] ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves data from a Hiera file . [CODESPLIT] function getFile ( backend , file , cb ) { getBackendConfig ( backend , function ( err , config ) { file = [ config [ ':datadir' ] , '/' , file ] . join ( '' ) ; fs . readFile ( file , cb ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves data to a Hiera file . [CODESPLIT] function saveFile ( backend , file , data , cb ) { cb = typeof ( cb ) === 'function' ? cb : function ( ) { } ; getBackendConfig ( backend , function ( err , config ) { var datadir = config [ ':datadir' ] ; file = path . join ( datadir , file ) ; fs . writeFile ( file , data , cb ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for hierarchy overrides for a given file . [CODESPLIT] function getOverrides ( backend , file , cb ) { async . parallel ( [ function hierarchy ( cb ) { getHierarchy ( cb ) ; } , function backendConfig ( cb ) { getBackendConfig ( backend , cb ) ; } ] , function ( err , results ) { var hierarchy , datadir , filename , tasks , pos , searchHierarchy , tasks ; hierarchy = results [ 0 ] ; datadir = results [ 1 ] [ ':datadir' ] ; filename = file . remove ( '.' + backend ) ; tasks = [ ] ; // remove the file's matching hierarchy pos = hierarchy . findIndex ( filename ) ; searchHierarchy = hierarchy . to ( pos ) ; getFile ( backend , file , function ( err , data ) { var sourceData ; if ( err ) { cb ( err ) ; return ; } sourceData = yaml . safeLoad ( data ) ; // setup hierarchy search tasks _ . each ( searchHierarchy , function ( hierarchy ) { tasks . push ( hierarchy + '.' + backend ) ; } ) ; async . map ( tasks , function ( f , cb ) { // get data for each file in the hierarchy // TODO: support magic hiera vars getFile ( backend , f , function ( err , data ) { cb ( null , { file : f , data : yaml . safeLoad ( data ) } ) ; } ) ; } , function ( err , comparisonData ) { var list = { } ; if ( err ) { cb ( err ) ; return ; } _ . each ( sourceData , function ( key , value ) { _ . each ( comparisonData , function ( set ) { _ . each ( set . data , function ( cKey , cValue ) { if ( cKey === key ) { list [ cKey ] = { file : set . file , value : cValue } ; } } ) ; if ( list [ key ] ) { // already exists return false ; } } ) ; } ) ; cb ( null , list ) ; } ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when a key has been pressed in the <input > [CODESPLIT] function ( me , e ) { // getValue to ensure that we are in sync with the dom var value = me . getValue ( ) , // allows value to be zero but not undefined or null (other falsey values) valueValid = value !== undefined && value !== null && value !== \"\" ; this [ valueValid ? 'showClearIcon' : 'hideClearIcon' ] ( ) ; if ( e . browserEvent . keyCode === 13 ) { me . fireAction ( 'action' , [ me , e ] , 'doAction' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Module [CODESPLIT] function parse ( session , file ) { if ( ! this . match ( file ) ) { return ; } var fn = util . require ( file ) ; fn ( session . suite , session ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PDF // FUNCTION : pdf ( x [ opts ] ) Evaluates the probability density function ( PDF ) for a Normal distribution . [CODESPLIT] function pdf ( x , options ) { /* jshint newcap:false */ var opts = { } , ctor , err , out , dt , d ; if ( arguments . length > 1 ) { err = validate ( opts , options ) ; if ( err ) { throw err ; } } opts . mu = typeof opts . mu !== 'undefined' ? opts . mu : 0 ; opts . sigma = typeof opts . sigma !== 'undefined' ? opts . sigma : 1 ; if ( isNumber ( x ) ) { return pdf1 ( x , opts . mu , opts . sigma ) ; } if ( isMatrixLike ( x ) ) { if ( opts . copy !== false ) { dt = opts . dtype || 'float64' ; ctor = ctors ( dt ) ; if ( ctor === null ) { throw new Error ( 'pdf()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + dt + '`.' ) ; } // Create an output matrix: d = new ctor ( x . length ) ; out = matrix ( d , x . shape , dt ) ; } else { out = x ; } return pdf5 ( out , x , opts . mu , opts . sigma ) ; } if ( isTypedArrayLike ( x ) ) { if ( opts . copy === false ) { out = x ; } else { dt = opts . dtype || 'float64' ; ctor = ctors ( dt ) ; if ( ctor === null ) { throw new Error ( 'pdf()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + dt + '`.' ) ; } out = new ctor ( x . length ) ; } return pdf6 ( out , x , opts . mu , opts . sigma ) ; } if ( isArrayLike ( x ) ) { // Handle deepset first... if ( opts . path ) { opts . sep = opts . sep || '.' ; return pdf4 ( x , opts . mu , opts . sigma , opts . path , opts . sep ) ; } // Handle regular and accessor arrays next... if ( opts . copy === false ) { out = x ; } else if ( opts . dtype ) { ctor = ctors ( opts . dtype ) ; if ( ctor === null ) { throw new TypeError ( 'pdf()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + opts . dtype + '`.' ) ; } out = new ctor ( x . length ) ; } else { out = new Array ( x . length ) ; } if ( opts . accessor ) { return pdf3 ( out , x , opts . mu , opts . sigma , opts . accessor ) ; } return pdf2 ( out , x , opts . mu , opts . sigma ) ; } return NaN ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wrap async success callback [CODESPLIT] function done ( result , callback ) { if ( ! _ . isFunction ( callback ) ) return process . nextTick ( function ( ) { callback ( null , result ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wrap async error callback [CODESPLIT] function fail ( err , callback ) { if ( ! _ . isFunction ( callback ) ) return let uError = new Error ( 'Unknown Error' ) err = err ? _ . isError ( err ) ? err : _ . isString ( err ) ? new Error ( err ) : uError : uError process . nextTick ( function ( ) { callback ( err ) } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wrap callback [CODESPLIT] function cb ( callback ) { callback = _ . isArguments ( callback ) ? acb ( callback ) : callback return function ( err , result ) { if ( err ) return fail ( err , callback ) done ( result , callback ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reverse scans args for [ Function ] || null - > used for grabbing callback from dynamic args returns first arg that is typeof function from right to left [CODESPLIT] function acb ( args ) { args = _ . toArray ( args ) return _ . find ( _ . reverse ( args ) , function ( arg ) { return _ . isFunction ( arg ) } ) || function ( ) { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We create this method because root is now a config so getRoot is already defined but in the old data package getRoot was passed a data argument and it would return the data inside of the root property . This method handles both cases . [CODESPLIT] function ( data ) { var fieldsCollection = this . getModel ( ) . getFields ( ) ; /*\n         * We check here whether the fields are dirty since the last read.\n         * This works around an issue when a Model is used for both a Tree and another\n         * source, because the tree decorates the model with extra fields and it causes\n         * issues because the readers aren't notified.\n         */ if ( fieldsCollection . isDirty ) { this . buildExtractors ( true ) ; delete fieldsCollection . isDirty ; } if ( this . rootAccessor ) { return this . rootAccessor . call ( this , data ) ; } else { return data ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "> Check any of values exists on arr . [CODESPLIT] function arrIncludes ( arr , values ) { if ( ! Array . isArray ( values ) ) { return inArray ( arr , values ) } var len = values . length ; var i = - 1 ; while ( i ++ < len ) { var j = inArray ( arr , values [ i ] ) ; if ( j ) { return j } } return false }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! function - arguments <https : // github . com / tunnckoCore / function - arguments > [CODESPLIT] function functionArguments ( fn ) { if ( typeof fn !== 'function' ) { throw new TypeError ( 'function-arguments expect a function' ) } if ( fn . length === 0 ) { return [ ] } // from https://github.com/jrburke/requirejs var reComments = / (\\/\\*([\\s\\S]*?)\\*\\/|([^:]|^)\\/\\/(.*)$) / mg ; var fnToStr = Function . prototype . toString ; var fnStr = fnToStr . call ( fn ) ; fnStr = fnStr . replace ( reComments , '' ) || fnStr ; fnStr = fnStr . slice ( 0 , fnStr . indexOf ( '{' ) ) ; var open = fnStr . indexOf ( '(' ) ; var close = fnStr . indexOf ( ')' ) ; open = open >= 0 ? open + 1 : 0 ; close = close > 0 ? close : fnStr . indexOf ( '=' ) ; fnStr = fnStr . slice ( open , close ) ; fnStr = '(' + fnStr + ')' ; var match = fnStr . match ( / \\(([\\s\\S]*)\\) / ) ; return match ? match [ 1 ] . split ( ',' ) . map ( function ( param ) { return param . trim ( ) } ) : [ ] }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "> Trying to guess is fn asynchronous function or not . But not [ is - callback - function ] [] be aware of that diff . [CODESPLIT] function isAsyncFunction ( fn , names , strict ) { if ( typeof fn !== 'function' ) { throw new TypeError ( 'is-async-function expect a function' ) } strict = typeof names === 'boolean' ? names : strict ; strict = typeof strict === 'boolean' ? strict : true ; names = typeof names === 'boolean' ? null : names ; names = Array . isArray ( names ) ? names : index ( names ) ; names = names . length ? names : index$8 ; var idx = index$6 ( names , index$10 ( fn ) ) ; return strict ? Boolean ( idx ) : idx }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! redolent <https : // github . com / tunnckoCore / redolent > [CODESPLIT] function redolent ( fn , opts ) { if ( typeof fn !== 'function' ) { throw new TypeError ( 'redolent: expect `fn` to be a function' ) } opts = index$2 ( { context : this , Promise : Promize } , opts ) ; opts . Promise = register ( opts ) ; // we can't test that here, because some // of our devDeps has some Promise library, // so it's loaded by `native-or-another` automatically /* istanbul ignore next */ if ( typeof opts . Promise !== 'function' ) { var msg = 'no native Promise support nor other promise were found' ; throw new TypeError ( 'redolent: ' + msg ) } return function ( ) { opts . context = this || opts . context ; opts . args = index ( opts . args ) . concat ( index$1 ( arguments ) ) ; var promise = new opts . Promise ( function ( resolve , reject ) { var called = false ; function done ( er , res ) { called = true ; if ( er ) { return reject ( er ) } if ( arguments . length > 2 ) { res = index$1 ( arguments , 1 ) ; } return resolve ( res ) } var isAsyncFn = index$5 ( fn ) ; opts . args = isAsyncFn ? opts . args . concat ( done ) : opts . args ; var syncResult = fn . apply ( opts . context , opts . args ) ; var xPromise = isPromise ( syncResult , opts . Promise ) ; var hasPromiseReturn = isAsyncFn && ! called && xPromise ; if ( ( ! isAsyncFn && ! called ) || hasPromiseReturn ) { resolve ( syncResult ) ; return } if ( isAsyncFn && ! xPromise && syncResult !== undefined ) { var msg = 'Asynchronous functions can only return a Promise or invoke a callback' ; reject ( new Error ( 'redolent: ' + msg ) ) ; } } ) ; return normalize ( promise , opts . Promise ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * istanbul ignore next [CODESPLIT] function isPromise ( val , Promize$$1 ) { return val instanceof Promize$$1 || ( val !== null && typeof val === 'object' && typeof val . then === 'function' && typeof val . catch === 'function' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns result object with props containing each _ . url [ key ] invoked result [CODESPLIT] function all ( src ) { let ret = { } _ . forIn ( exports , ( v , k ) => { if ( ! _ . isFunction ( v ) || _ . includes ( ALL_EXCLUDE_KEYS , k ) ) return ret [ k ] = _ . attempt ( v , src ) } ) return ret }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cleans url to be properly formatted [CODESPLIT] function clean ( src ) { let pidx = src . indexOf ( 'http' ) if ( pidx > 0 ) src = src . substr ( pidx ) return src ? pidx >= 0 || src . indexOf ( '//' ) >= 0 ? src : '/' + src : '' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return json query object [CODESPLIT] function jquery ( src ) { src = clean ( src ) ; let params = { } let match = null if ( ! url || ! _ . isString ( src ) ) return params while ( match = REGX_QUERY_OBJECT . exec ( src ) ) { params [ match [ 1 ] ] = match [ 2 ] } return params }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "VALIDATE // FUNCTION : validate ( opts options ) Validates function options . [CODESPLIT] function validate ( opts , options ) { if ( ! isObject ( options ) ) { return new TypeError ( 'transpose()::invalid input argument. Options argument must be an object. Value: `' + options + '`.' ) ; } if ( options . hasOwnProperty ( 'copy' ) ) { opts . copy = options . copy ; if ( ! isBoolean ( opts . copy ) ) { return new TypeError ( 'transpose()::invalid option. Copy option must be a boolean primitive. Option: `' + opts . copy + '`.' ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A module that represents a componentTabs object a componentTab is a page composition tool . [CODESPLIT] function ( el , options ) { events . EventEmitter . call ( this ) ; this . el = el ; this . options = extend ( { } , this . options ) ; extend ( this . options , options ) ; this . showTab = this . _show ; this . _init ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms the properties in an object to an encoded URI query string . <b > Note< / b > : works best if the object is in the format of { propertyName : propertyValue propertyName2 : propertyValue2 . . } [CODESPLIT] function toURI ( obj , dontEncode ) { const arr = [ ] ; let paramVal ; if ( isObject ( obj ) && ! isArray ( obj ) ) { Object . keys ( obj ) . forEach ( ( val ) => { if ( isArray ( obj [ val ] ) ) { paramVal = ` ${ obj [ val ] . join ( ',' ) } ` ; } else { paramVal = obj [ val ] ; } if ( dontEncode ) { arr . push ( ` ${ val } ${ paramVal } ` ) ; } else { arr . push ( ` ${ encodeURIComponent ( val ) } ${ encodeURIComponent ( paramVal ) } ` ) ; } } ) ; } return arr . join ( '&' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes an object s properties into JSON string then URI encoded [CODESPLIT] function toParam ( obj , dontEncode ) { const arr = [ ] ; let vals ; if ( isObject ( obj ) && ! isArray ( obj ) ) { Object . keys ( obj ) . forEach ( ( val ) => { if ( isArray ( obj [ val ] ) ) { vals = ` ${ obj [ val ] . map ( v => ( isNaN ( v ) ? ` ${ v } ` : v ) ) . join ( ',' ) } ` ; } else { vals = isNaN ( obj [ val ] ) ? ` ${ obj [ val ] } ` : obj [ val ] ; } arr . push ( ` ${ val } ${ vals } ` ) ; } ) ; if ( dontEncode ) { return ` ${ arr . join ( ',' ) } ` ; } return encodeURIComponent ( ` ${ arr . join ( ',' ) } ` ) ; } return '' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Watches for the current position and calls the callback when successful depending on the specified { @link #frequency } . [CODESPLIT] function ( config ) { var defaultConfig = Ext . device . geolocation . Abstract . prototype . config ; config = Ext . applyIf ( config , { maximumAge : defaultConfig . maximumAge , frequency : defaultConfig . frequency , allowHighAccuracy : defaultConfig . allowHighAccuracy , timeout : defaultConfig . timeout } ) ; // <debug> if ( ! config . callback ) { Ext . Logger . warn ( 'You need to specify a `callback` function for #watchPosition' ) ; } // </debug> return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the x y coordinates specified by the anchor position on the element . [CODESPLIT] function ( anchor , local , size ) { //<debug warn> Ext . Logger . deprecate ( \"getAnchorXY() is no longer available for Ext.Element. Please see Ext.Component#showBy() \" + \"to do anchoring at Component level instead\" , this ) ; //</debug> //Passing a different size is useful for pre-calculating anchors, //especially for anchored animations that change the el size. anchor = ( anchor || \"tl\" ) . toLowerCase ( ) ; size = size || { } ; var me = this , vp = me . dom == document . body || me . dom == document , width = size . width || vp ? window . innerWidth : me . getWidth ( ) , height = size . height || vp ? window . innerHeight : me . getHeight ( ) , xy , rnd = Math . round , myXY = me . getXY ( ) , extraX = vp ? 0 : ! local ? myXY [ 0 ] : 0 , extraY = vp ? 0 : ! local ? myXY [ 1 ] : 0 , hash = { c : [ rnd ( width * 0.5 ) , rnd ( height * 0.5 ) ] , t : [ rnd ( width * 0.5 ) , 0 ] , l : [ 0 , rnd ( height * 0.5 ) ] , r : [ width , rnd ( height * 0.5 ) ] , b : [ rnd ( width * 0.5 ) , height ] , tl : [ 0 , 0 ] , bl : [ 0 , height ] , br : [ width , height ] , tr : [ width , 0 ] } ; xy = hash [ anchor ] ; return [ xy [ 0 ] + extraX , xy [ 1 ] + extraY ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the x y coordinates to align this element with another element . [CODESPLIT] function ( el , position , offsets , local ) { //<debug warn> Ext . Logger . deprecate ( \"getAlignToXY() is no longer available for Ext.Element. Please see Ext.Component#showBy() \" + \"to do anchoring at Component level instead\" , this ) ; //</debug> local = ! ! local ; el = Ext . get ( el ) ; //<debug> if ( ! el || ! el . dom ) { throw new Error ( \"Element.alignToXY with an element that doesn't exist\" ) ; } //</debug> offsets = offsets || [ 0 , 0 ] ; if ( ! position || position == '?' ) { position = 'tl-bl?' ; } else if ( ! ( / - / ) . test ( position ) && position !== \"\" ) { position = 'tl-' + position ; } position = position . toLowerCase ( ) ; var me = this , matches = position . match ( this . alignToRe ) , dw = window . innerWidth , dh = window . innerHeight , p1 = \"\" , p2 = \"\" , a1 , a2 , x , y , swapX , swapY , p1x , p1y , p2x , p2y , width , height , region , constrain ; if ( ! matches ) { throw \"Element.alignTo with an invalid alignment \" + position ; } p1 = matches [ 1 ] ; p2 = matches [ 2 ] ; constrain = ! ! matches [ 3 ] ; //Subtract the aligned el's internal xy from the target's offset xy //plus custom offset to get the aligned el's new offset xy a1 = me . getAnchorXY ( p1 , true ) ; a2 = el . getAnchorXY ( p2 , local ) ; x = a2 [ 0 ] - a1 [ 0 ] + offsets [ 0 ] ; y = a2 [ 1 ] - a1 [ 1 ] + offsets [ 1 ] ; if ( constrain ) { width = me . getWidth ( ) ; height = me . getHeight ( ) ; region = el . getPageBox ( ) ; //If we are at a viewport boundary and the aligned el is anchored on a target border that is //perpendicular to the vp border, allow the aligned el to slide on that border, //otherwise swap the aligned el to the opposite border of the target. p1y = p1 . charAt ( 0 ) ; p1x = p1 . charAt ( p1 . length - 1 ) ; p2y = p2 . charAt ( 0 ) ; p2x = p2 . charAt ( p2 . length - 1 ) ; swapY = ( ( p1y == \"t\" && p2y == \"b\" ) || ( p1y == \"b\" && p2y == \"t\" ) ) ; swapX = ( ( p1x == \"r\" && p2x == \"l\" ) || ( p1x == \"l\" && p2x == \"r\" ) ) ; if ( x + width > dw ) { x = swapX ? region . left - width : dw - width ; } if ( x < 0 ) { x = swapX ? region . right : 0 ; } if ( y + height > dh ) { y = swapY ? region . top - height : dh - height ; } if ( y < 0 ) { y = swapY ? region . bottom : 0 ; } } return [ x , y ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an item to the collection . Fires the { @link #event - add } event when complete . @param { String } key The key to associate with the item or the new item . [CODESPLIT] function ( key , obj ) { var me = this , myObj = obj , myKey = key , old ; if ( arguments . length == 1 ) { myObj = myKey ; myKey = me . getKey ( myObj ) ; } if ( typeof myKey != 'undefined' && myKey !== null ) { old = me . map [ myKey ] ; if ( typeof old != 'undefined' ) { return me . replace ( myKey , myObj ) ; } me . map [ myKey ] = myObj ; } me . length ++ ; me . items . push ( myObj ) ; me . keys . push ( myKey ) ; me . fireEvent ( 'add' , me . length - 1 , myObj , myKey ) ; return myObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces an item in the collection . Fires the { @link #event - replace } event when complete . @param { String } key The key associated with the item to replace or the replacement item . [CODESPLIT] function ( key , o ) { var me = this , old , index ; if ( arguments . length == 1 ) { o = arguments [ 0 ] ; key = me . getKey ( o ) ; } old = me . map [ key ] ; if ( typeof key == 'undefined' || key === null || typeof old == 'undefined' ) { return me . add ( key , o ) ; } index = me . indexOfKey ( key ) ; me . items [ index ] = o ; me . map [ key ] = o ; me . fireEvent ( 'replace' , key , old , o ) ; return o ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds all elements of an Array or an Object to the collection . [CODESPLIT] function ( objs ) { var me = this , i = 0 , args , len , key ; if ( arguments . length > 1 || Ext . isArray ( objs ) ) { args = arguments . length > 1 ? arguments : objs ; for ( len = args . length ; i < len ; i ++ ) { me . add ( args [ i ] ) ; } } else { for ( key in objs ) { if ( objs . hasOwnProperty ( key ) ) { if ( me . allowFunctions || typeof objs [ key ] != 'function' ) { me . add ( key , objs [ key ] ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the specified function once for every item in the collection . [CODESPLIT] function ( fn , scope ) { var items = [ ] . concat ( this . items ) , // each safe for removal i = 0 , len = items . length , item ; for ( ; i < len ; i ++ ) { item = items [ i ] ; if ( fn . call ( scope || item , item , i , len ) === false ) { break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts an item at the specified index in the collection . Fires the { [CODESPLIT] function ( index , key , obj ) { var me = this , myKey = key , myObj = obj ; if ( arguments . length == 2 ) { myObj = myKey ; myKey = me . getKey ( myObj ) ; } if ( me . containsKey ( myKey ) ) { me . suspendEvents ( ) ; me . removeAtKey ( myKey ) ; me . resumeEvents ( ) ; } if ( index >= me . length ) { return me . add ( myKey , myObj ) ; } me . length ++ ; Ext . Array . splice ( me . items , index , 0 , myObj ) ; if ( typeof myKey != 'undefined' && myKey !== null ) { me . map [ myKey ] = myObj ; } Ext . Array . splice ( me . keys , index , 0 , myKey ) ; me . fireEvent ( 'add' , index , myObj , myKey ) ; return myObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all items from the collection . Fires the { [CODESPLIT] function ( ) { var me = this ; me . length = 0 ; me . items = [ ] ; me . keys = [ ] ; me . map = { } ; me . fireEvent ( 'clear' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters the objects in this collection by a set of { @link Ext . util . Filter Filter } s or by a single property / value pair with optional parameters for substring matching and case sensitivity . See { @link Ext . util . Filter Filter } for an example of using Filter objects ( preferred ) . Alternatively MixedCollection can be easily filtered by property like this : [CODESPLIT] function ( property , value , anyMatch , caseSensitive ) { var filters = [ ] , filterFn ; //support for the simple case of filtering by property/value if ( Ext . isString ( property ) ) { filters . push ( Ext . create ( 'Ext.util.Filter' , { property : property , value : value , anyMatch : anyMatch , caseSensitive : caseSensitive } ) ) ; } else if ( Ext . isArray ( property ) || property instanceof Ext . util . Filter ) { filters = filters . concat ( property ) ; } //at this point we have an array of zero or more Ext.util.Filter objects to filter with, //so here we construct a function that combines these filters by ANDing them together filterFn = function ( record ) { var isMatch = true , length = filters . length , i ; for ( i = 0 ; i < length ; i ++ ) { var filter = filters [ i ] , fn = filter . getFilterFn ( ) , scope = filter . getScope ( ) ; isMatch = isMatch && fn . call ( scope , record ) ; } return isMatch ; } ; return this . filterBy ( filterFn ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Usage : captain create_user [CODESPLIT] function create_user ( options ) { options = options || { } ; var success = options . success || function ( ) { terminal . exit ( '\\nUser created!\\n\\n' ) ; } , error = options . error || function ( err ) { terminal . abort ( 'Failed to created user' , err ) ; } ; program . prompt ( 'username: ' , function ( username ) { program . password ( 'password: ' , '*' , function ( password ) { program . password ( 'confirm password: ' , '*' , function ( password2 ) { if ( password != password2 ) { terminal . abort ( 'Password do not match, bailing out.' ) ; } program . prompt ( 'email: ' , function ( email ) { var body = { username : username , password : password , email : email } , db = require ( 'captain-core/lib/db' ) ; db . users . create ( body , function ( err ) { if ( err ) { error ( err ) ; } else { success ( ) ; } } ) ; } ) ; } ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Usage : captain syncdb [ -- force ] [CODESPLIT] function syncdb ( ) { function _syncdb ( drop ) { var db = require ( 'captain-core/lib/db' ) ; db . syncDB ( { complete : function ( err ) { if ( err ) { terminal . abort ( 'Failed syncing' , err ) ; } else { terminal . exit ( '\\nAll done\\n\\n' ) ; } } , progress : function ( script , file ) { console . log ( 'Executing:' , file ) ; if ( program . verbose ) { console . log ( '========\\n%s\\n' , script ) ; } } , drop : drop } ) ; } if ( program . drop ) { if ( ! program . force ) { program . prompt ( 'This will drop all databases, are you sure you want to proceed? (y/N): ' , function ( answer ) { if ( ! ! answer . match ( / y|yes|arrr / i ) ) { fn ( true ) ; } else { terminal . exit ( 'Exiting.' ) ; } } ) ; } else { _syncdb ( true ) ; } } else { _syncdb ( false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Usage : captain load_data <path > [CODESPLIT] function load_data ( filename ) { var files = [ ] , db = require ( 'captain-core/lib/db' ) ; if ( filename === true ) { program . help ( ) ; } if ( helpers . isDirectory ( filename ) ) { fs . readdirSync ( filename ) . forEach ( function ( file ) { files . push ( join ( filename , file ) ) ; } ) ; } else { files . push ( filename ) ; } async . series ( files . map ( db . load ) , function ( err ) { if ( err ) { terminal . abort ( 'Failed loading data' , err ) ; } else { terminal . exit ( '\\nAll done.\\n\\n' ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Usage : captain init <name > [ -- force ] [CODESPLIT] function init ( target ) { function create_project ( name , uri ) { console . log ( ) ; console . log ( terminal . cyan ( 'Creating project: ' ) + name ) ; console . log ( ) ; // Creating dirs helpers . dirs ( name , [ 'cache' , 'media' , 'logs' , 'themes' ] ) ; // Copying files helpers . copyR ( [ join ( 'themes' , 'default' ) ] , name ) ; // Creating files var templates = helpers . files ( { name : name , uri : uri } ) ; Object . keys ( templates ) . forEach ( function ( key ) { var p = join ( name , key ) , dir = dirname ( key ) ; if ( dir != '.' ) { helpers . mkdir ( join ( name , dir ) ) ; } helpers . write ( p , templates [ key ] ) ; } ) ; } if ( target === true ) { program . help ( ) ; } function _init ( ) { console . log ( ) ; console . log ( terminal . cyan ( 'Initializing project: ' ) + target ) ; // Testing connection prompt_uri ( function ( uri ) { console . info ( terminal . cyan ( 'Connection successful!' ) ) ; console . log ( ) ; console . info ( terminal . cyan ( 'Creating database schema...' ) ) ; // Creating projects files create_project ( target , uri ) ; // Synchronizing database var db = require ( 'captain-core/lib/db' ) ; var conf = require ( 'captain-core' ) . conf ; conf . reload ( join ( cwd , target ) ) ; db . syncDB ( { uri : uri , complete : function ( err ) { if ( err ) { terminal . abort ( err ) ; } console . log ( ) ; console . info ( terminal . cyan ( 'Done!' ) ) ; console . log ( ) ; console . info ( terminal . cyan ( 'Creating first user...' ) ) ; console . log ( ) ; // Creating user create_user ( { no_commit : true , success : function ( ) { // Instructions console . log ( ) ; console . info ( terminal . cyan ( 'Done!' ) ) ; console . log ( ) ; console . info ( terminal . cyan ( 'Now run:' ) ) ; console . log ( helpers . pad ( 'cd ' + target ) ) ; console . log ( helpers . pad ( 'captain run' ) ) ; terminal . exit ( '' ) ; } } ) ; } } ) ; } ) ; } if ( helpers . exists ( target ) && ! helpers . isEmptyDirectory ( target ) && ! program . force ) { program . prompt ( 'Directory not empty, force create? (y/n): ' , function ( answer ) { var forceCreate = ! ! answer . match ( / y|yes|arrr / i ) ; if ( forceCreate ) { _init ( ) ; } else { terminal . abort ( 'Cowardly refusing to init project in a non-empty directory' ) ; } } ) ; } else { _init ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Usage : captain themes [CODESPLIT] function themes ( ) { var themes = fs . readdirSync ( join ( PROJECT_ROOT , 'themes' ) ) ; console . log ( terminal . cyan ( 'Available themes:' ) ) ; console . log ( themes . map ( helpers . pad ) . join ( helpers . EOL ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Usage : captain theme <theme > [CODESPLIT] function theme ( target ) { if ( target === true ) { program . help ( ) ; } if ( helpers . isCaptainProject ( ) ) { helpers . copyR ( [ join ( 'themes' , target ) ] , '.' ) ; } else { terminal . abort ( 'Not a Captain project' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Usage : captain run [ -- watch ] [ -- fork ] [CODESPLIT] function run ( ) { process . env [ 'NODE_PATH' ] = resolve ( PROJECT_ROOT , '..' ) ; helpers . countUsers ( function ( err , count ) { if ( err ) { throw err ; } if ( count > 0 ) { _run ( ) ; } else { terminal . abort ( 'You need to create at least one user with `captain create_user`' ) ; } } ) ; function _run ( ) { // TODO: Put this in settings var logs = join ( cwd , 'logs' ) , out = fs . openSync ( join ( logs , 'out.log' ) , 'a' ) , err = fs . openSync ( join ( logs , 'err.log' ) , 'a' ) ; if ( helpers . isCaptainProject ( ) ) { var bin = program . watch ? resolve ( PROJECT_ROOT , 'node_modules' , '.bin' , 'node-dev' ) : 'node' ; var options = program . fork ? { stdio : [ 'ignore' , out , err ] , detached : true } : { stdio : 'inherit' } ; var child = spawn ( bin , [ join ( cwd , 'index.js' ) ] , options ) ; var conf = require ( 'captain-core' ) . conf ; console . log ( terminal . cyan ( 'Your application is running at: ' ) + 'http://%s:%d' , conf . host , conf . port ) ; if ( program . fork ) { // TODO: Put this in settings fs . writeFileSync ( join ( cwd , 'node.pid' ) , String ( child . pid ) ) ; child . unref ( ) ; } } else { terminal . abort ( 'Not a Captain project' ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests a { @link Ext . device . filesystem . FileSystem } instance . [CODESPLIT] function ( config ) { if ( ! config . success ) { Ext . Logger . error ( 'Ext.device.filesystem#requestFileSystem: You must specify a `success` callback.' ) ; return null ; } Ext . device . Communicator . send ( { command : 'FileSystem#requestFileSystem' , callbacks : { success : function ( id ) { var fileSystem = Ext . create ( 'Ext.device.filesystem.FileSystem' , id ) ; config . success . call ( config . scope || this , fileSystem ) ; } , failure : function ( error ) { if ( config . failure ) { config . failure . call ( config . scope || this , error ) ; } } } , scope : config . scope || this } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the entry from the file system . [CODESPLIT] function ( config ) { Ext . device . Communicator . send ( { command : 'FileSystem#remove' , path : this . path , fileSystemId : this . fileSystem . id , recursively : config . recursively , callbacks : { success : function ( ) { if ( config . success ) { config . success . call ( config . scope || this ) ; } } , failure : function ( error ) { if ( config . failure ) { config . failure . call ( config . scope || this , error ) ; } } } , scope : config . scope || this } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lists all the entries in the directory . [CODESPLIT] function ( config ) { if ( ! config . success ) { Ext . Logger . error ( 'Ext.device.filesystem.DirectoryEntry#readEntries: You must specify a `success` callback.' ) ; return null ; } var me = this ; Ext . device . Communicator . send ( { command : 'FileSystem#readEntries' , path : this . path , fileSystemId : this . fileSystem . id , callbacks : { success : function ( entryInfos ) { var entries = entryInfos . map ( function ( entryInfo ) { return entryInfo . directory ? Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , entryInfo . path , me . fileSystem ) : Ext . create ( 'Ext.device.filesystem.FileEntry' , entryInfo . path , me . fileSystem ) ; } ) ; config . success . call ( config . scope || this , entries ) ; } , failure : function ( error ) { if ( config . failure ) { config . failure . call ( config . scope || this , error ) ; } } } , scope : config . scope || this } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates or looks up a file . [CODESPLIT] function ( config ) { if ( config . path == null ) { Ext . Logger . error ( 'Ext.device.filesystem.DirectoryEntry#getFile: You must specify a `path` of the file.' ) ; return null ; } if ( config . options == null ) { config . options = { } ; } var me = this ; Ext . device . Communicator . send ( { command : 'FileSystem#getEntry' , path : this . path , fileSystemId : this . fileSystem . id , newPath : config . path , directory : config . directory , create : config . options . create , exclusive : config . options . exclusive , callbacks : { success : function ( path ) { if ( config . success ) { var entry = config . directory ? Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , path , me . fileSystem ) : Ext . create ( 'Ext.device.filesystem.FileEntry' , path , me . fileSystem ) ; config . success . call ( config . scope || this , entry ) ; } } , failure : function ( error ) { if ( config . failure ) { config . failure . call ( config . scope || this , error ) ; } } } , scope : config . scope || this } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the data from the file starting at the file offset . [CODESPLIT] function ( config ) { var me = this ; Ext . device . Communicator . send ( { command : 'FileSystem#read' , path : this . path , fileSystemId : this . fileSystem . id , offset : this . offset , length : config . length , callbacks : { success : function ( result ) { me . offset = result . offset ; if ( config . success ) { config . success . call ( config . scope || this , result . data ) ; } } , failure : function ( error ) { if ( config . failure ) { config . failure . call ( config . scope || this , error ) ; } } } , scope : config . scope || this } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate if element s DOM node has text [CODESPLIT] function toHaveText ( ) { return { compare : function compare ( element , text ) { var regexp = text instanceof RegExp ? text : new RegExp ( text , 'ig' ) ; var pass = element . getDOMNode ( ) . textContent . match ( regexp ) ; var message = pass ? 'Text \"' + text + '\" is found within an element' : 'Text \"' + text + '\" is not found within an element' ; return { pass : pass , message : message } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We create complex instance arrays and objects in beforeInitialize so that we can use these inside of the initConfig process . [CODESPLIT] function ( ) { var me = this , container = me . container , baseCls = me . getBaseCls ( ) , scrollable , scrollViewElement , pinnedHeader ; Ext . apply ( me , { listItems : [ ] , headerItems : [ ] , updatedItems : [ ] , headerMap : [ ] , scrollDockItems : { top : [ ] , bottom : [ ] } } ) ; // We determine the translation methods for headers and items within this List based // on the best strategy for the device this . translationMethod = Ext . browser . is . AndroidStock2 ? 'cssposition' : 'csstransform' ; // Create the inner container that will actually hold all the list items if ( ! container ) { container = me . container = Ext . factory ( { xtype : 'container' , scrollable : { scroller : { autoRefresh : ! me . getInfinite ( ) , direction : 'vertical' } } } ) ; } // We add the container after creating it manually because when you add the container, // the items config is initialized. When this happens, any scrollDock items will be added, // which in turn tries to add these items to the container me . add ( container ) ; // We make this List's scrollable the inner containers scrollable scrollable = container . getScrollable ( ) ; scrollViewElement = me . scrollViewElement = scrollable . getElement ( ) ; me . scrollElement = scrollable . getScroller ( ) . getElement ( ) ; me . setScrollable ( scrollable ) ; me . scrollableBehavior = container . getScrollableBehavior ( ) ; // Create the pinnedHeader instance thats being used when grouping is enabled // and insert it into the scrollElement pinnedHeader = me . pinnedHeader = Ext . factory ( { xtype : 'listitemheader' , html : '&nbsp;' , translatable : { translationMethod : this . translationMethod } , cls : [ baseCls + '-header' , baseCls + '-header-swap' ] } ) ; pinnedHeader . translate ( 0 , - 10000 ) ; pinnedHeader . $position = - 10000 ; scrollViewElement . insertFirst ( pinnedHeader . renderElement ) ; // We want to intercept any translate calls made on the scroller to perform specific list logic me . bind ( scrollable . getScroller ( ) . getTranslatable ( ) , 'doTranslate' , 'onTranslate' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We override DataView s initialize method with an empty function [CODESPLIT] function ( ) { var me = this , container = me . container , scrollViewElement = me . scrollViewElement , indexBar = me . getIndexBar ( ) , triggerEvent = me . getTriggerEvent ( ) , triggerCtEvent = me . getTriggerCtEvent ( ) ; if ( indexBar ) { scrollViewElement . appendChild ( indexBar . renderElement ) ; } if ( triggerEvent ) { me . on ( triggerEvent , me . onItemTrigger , me ) ; } if ( triggerCtEvent ) { me . on ( triggerCtEvent , me . onContainerTrigger , me ) ; } container . element . on ( { delegate : '.' + me . getBaseCls ( ) + '-disclosure' , tap : 'handleItemDisclosure' , scope : me } ) ; container . element . on ( { resize : 'onContainerResize' , scope : me } ) ; // Android 2.x not a direct child container . innerElement . on ( { touchstart : 'onItemTouchStart' , touchend : 'onItemTouchEnd' , tap : 'onItemTap' , taphold : 'onItemTapHold' , singletap : 'onItemSingleTap' , doubletap : 'onItemDoubleTap' , swipe : 'onItemSwipe' , delegate : '.' + Ext . baseCSSPrefix + 'list-item' , scope : me } ) ; if ( me . getStore ( ) ) { me . refresh ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an item at the specified index . [CODESPLIT] function ( index ) { var listItems = this . listItems , ln = listItems . length , i , listItem ; for ( i = 0 ; i < ln ; i ++ ) { listItem = listItems [ i ] ; if ( listItem . $dataIndex == index ) { return listItem ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "apply to the selection model to maintain visual UI cues [CODESPLIT] function ( me , index , target , record , e ) { if ( ! ( this . getPreventSelectionOnDisclose ( ) && Ext . fly ( e . target ) . hasCls ( this . getBaseCls ( ) + '-disclosure' ) ) ) { this . callParent ( arguments ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "arg1 = host ( optional ) arg2 = port ( optional ) arg3 = files ( required ) [CODESPLIT] function notify ( arg1 , arg2 , arg3 ) { var argsLength = arguments . length ; return new P ( function ( resolve , reject ) { var filesCsv = null ; var requestUrl = null ; var host = null ; var port = null ; var files = null ; if ( argsLength === 3 ) { host = arg1 ; port = arg2 ; files = arg3 ; } else if ( argsLength === 2 ) { host = DEFAULT_HOST ; port = arg1 ; files = arg2 ; } else if ( argsLength === 1 ) { host = DEFAULT_HOST ; port = DEFAULT_PORT ; files = arg1 ; } requestUrl = 'http://' + host + ':' + port + '/changed?files=' ; if ( host == null || port == null || files == null ) { return reject ( new Error ( 'host, port and files are all required fields!' ) ) ; } // one file if ( _ . isString ( files ) ) { filesCsv = files ; } else if ( _ . isArray ( files ) ) { filesCsv = files . join ( ',' ) ; } else { return reject ( new Error ( 'files must be a string or an array of strings!' ) ) ; } requestUrl += filesCsv ; console . log ( requestUrl ) ; request . get ( requestUrl , function ( err , response , body ) { if ( err !== null ) { return reject ( err ) ; } else { return resolve ( { response : response , body : body } ) ; } } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the configuration for the loader . This should be called right after ext - ( debug ) . js is included in the page and before Ext . onReady . i . e : [CODESPLIT] function ( name , value ) { if ( Ext . isObject ( name ) && arguments . length === 1 ) { Ext . merge ( this . config , name ) ; } else { this . config [ name ] = ( Ext . isObject ( value ) ) ? Ext . merge ( this . config [ name ] , value ) : value ; } setPathCount += 1 ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translates a className to a file path by adding the the proper prefix and converting the . s to / s . For example : [CODESPLIT] function ( className ) { var path = '' , paths = this . config . paths , prefix = this . getPrefix ( className ) ; if ( prefix . length > 0 ) { if ( prefix === className ) { return paths [ prefix ] ; } path = paths [ prefix ] ; className = className . substring ( prefix . length + 1 ) ; } if ( path . length > 0 ) { path += '/' ; } return path . replace ( / \\/\\.\\/ / g , '/' ) + className . replace ( / \\. / g , \"/\" ) + '.js' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Explicitly exclude files from being loaded . Useful when used in conjunction with a broad include expression . Can be chained with more require and exclude methods eg : [CODESPLIT] function ( excludes ) { var me = this ; return { require : function ( expressions , fn , scope ) { return me . require ( expressions , fn , scope , excludes ) ; } , syncRequire : function ( expressions , fn , scope ) { return me . syncRequire ( expressions , fn , scope , excludes ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inject a script element to document s head call onLoad and onError accordingly [CODESPLIT] function ( url , onLoad , onError , scope , charset ) { var script = document . createElement ( 'script' ) , me = this , onLoadFn = function ( ) { me . cleanupScriptElement ( script ) ; onLoad . call ( scope ) ; } , onErrorFn = function ( ) { me . cleanupScriptElement ( script ) ; onError . call ( scope ) ; } ; script . type = 'text/javascript' ; script . src = url ; script . onload = onLoadFn ; script . onerror = onErrorFn ; script . onreadystatechange = function ( ) { if ( this . readyState === 'loaded' || this . readyState === 'complete' ) { onLoadFn ( ) ; } } ; if ( charset ) { script . charset = charset ; } this . documentHead . appendChild ( script ) ; return script ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load a script file supports both asynchronous and synchronous approaches [CODESPLIT] function ( url , onLoad , onError , scope , synchronous ) { var me = this , isFileLoaded = this . isFileLoaded , scriptElements = this . scriptElements , noCacheUrl = url + ( this . getConfig ( 'disableCaching' ) ? ( '?' + this . getConfig ( 'disableCachingParam' ) + '=' + Ext . Date . now ( ) ) : '' ) , xhr , status , content , onScriptError ; if ( isFileLoaded [ url ] ) { return this ; } scope = scope || this ; this . isLoading = true ; if ( ! synchronous ) { onScriptError = function ( ) { //<debug error> onError . call ( scope , \"Failed loading '\" + url + \"', please verify that the file exists\" , synchronous ) ; //</debug> } ; if ( ! Ext . isReady && Ext . onDocumentReady ) { Ext . onDocumentReady ( function ( ) { if ( ! isFileLoaded [ url ] ) { scriptElements [ url ] = me . injectScriptElement ( noCacheUrl , onLoad , onScriptError , scope ) ; } } ) ; } else { scriptElements [ url ] = this . injectScriptElement ( noCacheUrl , onLoad , onScriptError , scope ) ; } } else { if ( typeof XMLHttpRequest != 'undefined' ) { xhr = new XMLHttpRequest ( ) ; } else { xhr = new ActiveXObject ( 'Microsoft.XMLHTTP' ) ; } try { xhr . open ( 'GET' , noCacheUrl , false ) ; xhr . send ( null ) ; } catch ( e ) { //<debug error> onError . call ( this , \"Failed loading synchronously via XHR: '\" + url + \"'; It's likely that the file is either \" + \"being loaded from a different domain or from the local file system whereby cross origin \" + \"requests are not allowed due to security reasons. Use asynchronous loading with \" + \"Ext.require instead.\" , synchronous ) ; //</debug> } status = ( xhr . status == 1223 ) ? 204 : xhr . status ; content = xhr . responseText ; if ( ( status >= 200 && status < 300 ) || status == 304 || ( status == 0 && content . length > 0 ) ) { // Debugger friendly, file names are still shown even though they're eval'ed code // Breakpoints work on both Firebug and Chrome's Web Inspector Ext . globalEval ( content + \"\\n//@ sourceURL=\" + url ) ; onLoad . call ( scope ) ; } else { //<debug> onError . call ( this , \"Failed loading synchronously via XHR: '\" + url + \"'; please \" + \"verify that the file exists. \" + \"XHR status code: \" + status , synchronous ) ; //</debug> } // Prevent potential IE memory leak xhr = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "documented above [CODESPLIT] function ( ) { var syncModeEnabled = this . syncModeEnabled ; if ( ! syncModeEnabled ) { this . syncModeEnabled = true ; } this . require . apply ( this , arguments ) ; if ( ! syncModeEnabled ) { this . syncModeEnabled = false ; } this . refreshQueue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "documented above [CODESPLIT] function ( expressions , fn , scope , excludes ) { var excluded = { } , included = { } , queue = this . queue , classNameToFilePathMap = this . classNameToFilePathMap , isClassFileLoaded = this . isClassFileLoaded , excludedClassNames = [ ] , possibleClassNames = [ ] , classNames = [ ] , references = [ ] , callback , syncModeEnabled , filePath , expression , exclude , className , possibleClassName , i , j , ln , subLn ; if ( excludes ) { excludes = arrayFrom ( excludes ) ; for ( i = 0 , ln = excludes . length ; i < ln ; i ++ ) { exclude = excludes [ i ] ; if ( typeof exclude == 'string' && exclude . length > 0 ) { excludedClassNames = Manager . getNamesByExpression ( exclude ) ; for ( j = 0 , subLn = excludedClassNames . length ; j < subLn ; j ++ ) { excluded [ excludedClassNames [ j ] ] = true ; } } } } expressions = arrayFrom ( expressions ) ; if ( fn ) { if ( fn . length > 0 ) { callback = function ( ) { var classes = [ ] , i , ln , name ; for ( i = 0 , ln = references . length ; i < ln ; i ++ ) { name = references [ i ] ; classes . push ( Manager . get ( name ) ) ; } return fn . apply ( this , classes ) ; } ; } else { callback = fn ; } } else { callback = Ext . emptyFn ; } scope = scope || Ext . global ; for ( i = 0 , ln = expressions . length ; i < ln ; i ++ ) { expression = expressions [ i ] ; if ( typeof expression == 'string' && expression . length > 0 ) { possibleClassNames = Manager . getNamesByExpression ( expression ) ; subLn = possibleClassNames . length ; for ( j = 0 ; j < subLn ; j ++ ) { possibleClassName = possibleClassNames [ j ] ; if ( excluded [ possibleClassName ] !== true ) { references . push ( possibleClassName ) ; if ( ! Manager . isCreated ( possibleClassName ) && ! included [ possibleClassName ] /* && !this.requiresMap.hasOwnProperty(possibleClassName)*/ ) { included [ possibleClassName ] = true ; classNames . push ( possibleClassName ) ; } } } } } // If the dynamic dependency feature is not being used, throw an error // if the dependencies are not defined if ( classNames . length > 0 ) { if ( ! this . config . enabled ) { throw new Error ( \"Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. \" + \"Missing required class\" + ( ( classNames . length > 1 ) ? \"es\" : \"\" ) + \": \" + classNames . join ( ', ' ) ) ; } } else { callback . call ( scope ) ; return this ; } syncModeEnabled = this . syncModeEnabled ; if ( ! syncModeEnabled ) { queue . push ( { requires : classNames . slice ( ) , // this array will be modified as the queue is processed, // so we need a copy of it callback : callback , scope : scope } ) ; } ln = classNames . length ; for ( i = 0 ; i < ln ; i ++ ) { className = classNames [ i ] ; filePath = this . getPath ( className ) ; // If we are synchronously loading a file that has already been asynchronously loaded before // we need to destroy the script tag and revert the count // This file will then be forced loaded in synchronous if ( syncModeEnabled && isClassFileLoaded . hasOwnProperty ( className ) ) { this . numPendingFiles -- ; this . removeScriptElement ( filePath ) ; delete isClassFileLoaded [ className ] ; } if ( ! isClassFileLoaded . hasOwnProperty ( className ) ) { isClassFileLoaded [ className ] = false ; classNameToFilePathMap [ className ] = filePath ; this . numPendingFiles ++ ; this . loadScriptFile ( filePath , pass ( this . onFileLoaded , [ className , filePath ] , this ) , pass ( this . onFileLoadError , [ className , filePath ] ) , this , syncModeEnabled ) ; } } if ( syncModeEnabled ) { callback . call ( scope ) ; if ( ln === 1 ) { return Manager . get ( className ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaceable function to handle rendering [CODESPLIT] async function ( fname , attrs ) { let partialDirs ; if ( typeof module . exports . configuration . partialDirs === 'undefined' || ! module . exports . configuration . partialDirs || module . exports . configuration . partialDirs . length <= 0 ) { partialDirs = [ __dirname ] ; } else { partialDirs = module . exports . configuration . partialDirs ; } var partialFound = await globfs . findAsync ( partialDirs , fname ) ; if ( ! partialFound ) throw new Error ( ` ${ fname } ${ util . inspect ( partialDirs ) } ` ) ; // Pick the first partial found partialFound = partialFound [ 0 ] ; // console.log(`module.exports.configuration renderPartial ${partialFound}`); if ( ! partialFound ) throw new Error ( ` ${ fname } ${ util . inspect ( partialDirs ) } ` ) ; var partialFname = path . join ( partialFound . basedir , partialFound . path ) ; var stats = await fs . stat ( partialFname ) ; if ( ! stats . isFile ( ) ) { throw new Error ( ` ${ fname } ${ partialFname } ` ) ; } var partialText = await fs . readFile ( partialFname , 'utf8' ) ; if ( / \\.ejs$ / i . test ( partialFname ) ) { try { return ejs . render ( partialText , attrs ) ; } catch ( e ) { throw new Error ( ` ${ fname } ${ e } ` ) ; } } /* else if (/\\.literal$/i.test(partialFname)) {\n            try {\n                const t = literal(partialText);\n                return t(attrs);\n            } catch (e) {\n                throw new Error(`Literal rendering of ${fname} failed because of ${e}`);\n            }\n        } */ else if ( / \\.html$ / i . test ( partialFname ) ) { // NOTE: The partialBody gets lost in this case return partialText ; } else { throw new Error ( \"No rendering support for ${fname}\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats the data for each record before sending it to the server . This method should be overridden to format the data in a way that differs from the default . [CODESPLIT] function ( record ) { var me = this , fields = record . getFields ( ) , idProperty = record . getIdProperty ( ) , uniqueIdStrategy = me . getUniqueIdStrategy ( ) , data = { } , name , value ; fields . each ( function ( field ) { if ( field . getPersist ( ) ) { name = field . getName ( ) ; if ( name === idProperty && ! uniqueIdStrategy ) { return ; } value = record . get ( name ) ; if ( field . getType ( ) . type == 'date' ) { value = me . writeDate ( field , value ) ; } data [ name ] = value ; } } , me ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an Ext . Direct Provider and creates the proxy or stub methods to execute server - side methods . If the provider is not already connected it will auto - connect . [CODESPLIT] function ( provider ) { var me = this , args = Ext . toArray ( arguments ) , i = 0 , ln ; if ( args . length > 1 ) { for ( ln = args . length ; i < ln ; ++ i ) { me . addProvider ( args [ i ] ) ; } return ; } // if provider has not already been instantiated if ( ! provider . isProvider ) { provider = Ext . create ( 'direct.' + provider . type + 'provider' , provider ) ; } me . providers . add ( provider ) ; provider . on ( 'data' , me . onProviderData , me ) ; if ( ! provider . isConnected ( ) ) { provider . connect ( ) ; } return provider ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the provider . [CODESPLIT] function ( provider ) { var me = this , providers = me . providers ; provider = provider . isProvider ? provider : providers . get ( provider ) ; if ( provider ) { provider . un ( 'data' , me . onProviderData , me ) ; providers . remove ( provider ) ; return provider ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a direct function . It may be passed in a string format for example : MyApp . Person . read . [CODESPLIT] function ( fn ) { if ( Ext . isString ( fn ) ) { var parts = fn . split ( '.' ) , i = 0 , ln = parts . length , current = window ; while ( current && i < ln ) { current = current [ parts [ i ] ] ; ++ i ; } fn = Ext . isFunction ( current ) ? current : null ; } return fn || null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a new Application instance . [CODESPLIT] function ( config ) { config = config || { } ; Ext . applyIf ( config , { application : this } ) ; this . initConfig ( config ) ; //it's common to pass in functions to an application but because they are not predictable config names they //aren't ordinarily placed onto this so we need to do it manually for ( var key in config ) { this [ key ] = config [ key ] ; } // <deprecated product=touch since=2.0> if ( config . autoCreateViewport ) { Ext . Logger . deprecate ( '[Ext.app.Application] autoCreateViewport has been deprecated in Sencha Touch 2. Please implement a ' + 'launch function on your Application instead and use Ext.create(\"MyApp.view.Main\") to create your initial UI.' ) ; } // </deprecated> //<debug> Ext . Loader . setConfig ( { enabled : true } ) ; //</debug> Ext . require ( this . getRequires ( ) , function ( ) { if ( this . getEnableLoader ( ) !== false ) { Ext . require ( this . getProfiles ( ) , this . onProfilesLoaded , this ) ; } } , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dispatches a given { [CODESPLIT] function ( action , addToHistory ) { action = action || { } ; Ext . applyIf ( action , { application : this } ) ; action = Ext . factory ( action , Ext . app . Action ) ; if ( action ) { var profile = this . getCurrentProfile ( ) , profileNS = profile ? profile . getNamespace ( ) : undefined , controller = this . getController ( action . getController ( ) , profileNS ) ; if ( controller ) { if ( addToHistory !== false ) { this . getHistory ( ) . add ( action , true ) ; } controller . execute ( action ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Redirects the browser to the given url . This only affects the url after the # . You can pass in either a String or a Model instance - if a Model instance is defined its { [CODESPLIT] function ( url ) { if ( Ext . data && Ext . data . Model && url instanceof Ext . data . Model ) { var record = url ; url = record . toUrl ( ) ; } var decoded = this . getRouter ( ) . recognize ( url ) ; if ( decoded ) { decoded . url = url ; if ( record ) { decoded . data = { } ; decoded . data . record = record ; } return this . dispatch ( decoded ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Controller instance for the given controller name . [CODESPLIT] function ( name , profileName ) { var instances = this . getControllerInstances ( ) , appName = this . getName ( ) , format = Ext . String . format , topLevelName ; if ( name instanceof Ext . app . Controller ) { return name ; } if ( instances [ name ] ) { return instances [ name ] ; } else { topLevelName = format ( \"{0}.controller.{1}\" , appName , name ) ; profileName = format ( \"{0}.controller.{1}.{2}\" , appName , profileName , name ) ; return instances [ profileName ] || instances [ topLevelName ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes the { [CODESPLIT] function ( masked ) { var isVisible = true , currentMask ; if ( masked === false ) { masked = true ; isVisible = false ; } currentMask = Ext . factory ( masked , Ext . Mask , this . getMasked ( ) ) ; if ( currentMask ) { this . add ( currentMask ) ; currentMask . setHidden ( ! isVisible ) ; } return currentMask ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize layout and event listeners the very first time an item is added [CODESPLIT] function ( ) { delete this . onItemAdd ; if ( this . innerHtmlElement && ! this . getHtml ( ) ) { this . innerHtmlElement . destroy ( ) ; delete this . innerHtmlElement ; } this . on ( 'innerstatechange' , 'onItemInnerStateChange' , this , { delegate : '> component' } ) ; return this . onItemAdd . apply ( this , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "< / debug > [CODESPLIT] function ( ) { var layout = this . layout ; if ( ! layout ) { layout = this . link ( '_layout' , this . link ( 'layout' , Ext . factory ( this . _layout || 'default' , Ext . layout . Default , null , 'layout' ) ) ) ; layout . setContainer ( this ) ; } return layout ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds one or more Components to this Container . Example : [CODESPLIT] function ( newItems ) { var me = this , i , ln , item , newActiveItem ; if ( Ext . isArray ( newItems ) ) { for ( i = 0 , ln = newItems . length ; i < ln ; i ++ ) { item = me . factoryItem ( newItems [ i ] ) ; this . doAdd ( item ) ; if ( ! newActiveItem && ! this . getActiveItem ( ) && this . innerItems . length > 0 && item . isInnerItem ( ) ) { newActiveItem = item ; } } } else { item = me . factoryItem ( newItems ) ; this . doAdd ( item ) ; if ( ! newActiveItem && ! this . getActiveItem ( ) && this . innerItems . length > 0 && item . isInnerItem ( ) ) { newActiveItem = item ; } } if ( newActiveItem ) { this . setActiveItem ( newActiveItem ) ; } return item ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes an item from this Container optionally destroying it . [CODESPLIT] function ( item , destroy ) { var me = this , index = me . indexOf ( item ) , innerItems = me . getInnerItems ( ) ; if ( destroy === undefined ) { destroy = me . getAutoDestroy ( ) ; } if ( index !== - 1 ) { if ( ! me . removingAll && innerItems . length > 1 && item === me . getActiveItem ( ) ) { me . on ( { activeitemchange : 'doRemove' , scope : me , single : true , order : 'after' , args : [ item , index , destroy ] } ) ; me . doResetActiveItem ( innerItems . indexOf ( item ) ) ; } else { me . doRemove ( item , index , destroy ) ; if ( innerItems . length === 0 ) { me . setActiveItem ( null ) ; } } } return me ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all items currently in the Container optionally destroying them all . [CODESPLIT] function ( destroy , everything ) { var items = this . items , ln = items . length , i = 0 , item ; if ( typeof destroy != 'boolean' ) { destroy = this . getAutoDestroy ( ) ; } everything = Boolean ( everything ) ; // removingAll flag is used so we don't unnecessarily change activeItem while removing all items. this . removingAll = true ; for ( ; i < ln ; i ++ ) { item = items . getAt ( i ) ; if ( item && ( everything || item . isInnerItem ( ) ) ) { this . doRemove ( item , i , destroy ) ; i -- ; ln -- ; } } this . setActiveItem ( null ) ; this . removingAll = false ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a child Component at the given index . For example here s how we can add a new item making it the first child Component of this Container : [CODESPLIT] function ( index , item ) { var me = this , i ; //<debug error> if ( typeof index != 'number' ) { Ext . Logger . error ( \"Invalid index of '\" + index + \"', must be a valid number\" ) ; } //</debug> if ( Ext . isArray ( item ) ) { for ( i = item . length - 1 ; i >= 0 ; i -- ) { me . insert ( index , item [ i ] ) ; } return me ; } item = this . factoryItem ( item ) ; this . doInsert ( index , item ) ; return item ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all the { [CODESPLIT] function ( ) { var items = this . getItems ( ) . items , dockedItems = [ ] , ln = items . length , item , i ; for ( i = 0 ; i < ln ; i ++ ) { item = items [ i ] ; if ( item . isDocked ( ) ) { dockedItems . push ( item ) ; } } return dockedItems ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Animates to the supplied activeItem with a specified animation . Currently this only works with a Card layout . This passed animation will override any default animations on the container for a single card switch . The animation will be destroyed when complete . [CODESPLIT] function ( activeItem , animation ) { var layout = this . getLayout ( ) , defaultAnimation ; if ( this . activeItemAnimation ) { this . activeItemAnimation . destroy ( ) ; } this . activeItemAnimation = animation = new Ext . fx . layout . Card ( animation ) ; if ( animation && layout . isCard ) { animation . setLayout ( layout ) ; defaultAnimation = layout . getAnimation ( ) ; if ( defaultAnimation ) { defaultAnimation . disable ( ) ; } animation . on ( 'animationend' , function ( ) { if ( defaultAnimation ) { defaultAnimation . enable ( ) ; } animation . destroy ( ) ; } , this ) ; } return this . setActiveItem ( activeItem ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used by ComponentQuery to retrieve all of the items which can potentially be considered a child of this Container . This should be overridden by components which have child items that are not contained in items . For example dockedItems menu etc [CODESPLIT] function ( deep ) { var items = this . getItems ( ) . items . slice ( ) , ln = items . length , i , item ; if ( deep ) { for ( i = 0 ; i < ln ; i ++ ) { item = items [ i ] ; if ( item . getRefItems ) { items = items . concat ( item . getRefItems ( true ) ) ; } } } return items ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Examines this container s { @link #property - items } property and gets a direct child component of this container . @param { String / Number } component This parameter may be any of the following : [CODESPLIT] function ( component ) { if ( Ext . isObject ( component ) ) { component = component . getItemId ( ) ; } return this . getItems ( ) . get ( component ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a docked item of this container using a reference id or an index of its location in { [CODESPLIT] function ( component ) { if ( Ext . isObject ( component ) ) { component = component . getItemId ( ) ; } var dockedItems = this . getDockedItems ( ) , ln = dockedItems . length , item , i ; if ( Ext . isNumber ( component ) ) { return dockedItems [ component ] ; } for ( i = 0 ; i < ln ; i ++ ) { item = dockedItems [ i ] ; if ( item . id == component ) { return item ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "< / deprecated > [CODESPLIT] function ( ) { var me = this , modal = me . getModal ( ) ; if ( modal ) { modal . destroy ( ) ; } me . removeAll ( true , true ) ; me . unlink ( '_scrollable' ) ; Ext . destroy ( me . items ) ; me . callSuper ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "callback ( isok err ) [CODESPLIT] function exportProtobuf ( pkgname , obj , callback ) { var lstexport = [ ] ; var lstreq = [ ] ; var lstres = [ ] ; if ( Array . isArray ( obj ) ) { var str = 'package ' + pkgname + ';\\r\\n\\r\\n' ; for ( var i = 0 ; i < obj . length ; ++ i ) { if ( obj [ i ] . type == 'message' ) { if ( base . isResMsg ( obj [ i ] . name ) ) { lstres . push ( { name : obj [ i ] . name , comment : obj [ i ] . comment } ) ; } else if ( base . isReqMsg ( obj [ i ] . name ) ) { lstreq . push ( { name : obj [ i ] . name , comment : obj [ i ] . comment } ) ; } } } str += exportEnumMsgID ( lstreq , base . getGlobalObj ( 'REQ_MSGID_BEGIN' , obj ) . val . val , lstres , base . getGlobalObj ( 'RES_MSGID_BEGIN' , obj ) . val . val ) ; for ( var i = 0 ; i < obj . length ; ++ i ) { if ( obj [ i ] . type == 'message' ) { lstexport = exportMember ( obj [ i ] , lstexport , obj ) ; } } for ( var i = 0 ; i < lstexport . length ; ++ i ) { var co = base . getGlobalObj ( lstexport [ i ] , obj ) ; if ( co . type == 'enum' ) { var cs = exportEnum ( co , callback , obj ) ; if ( cs == undefined ) { return ; } str += cs + '\\r\\n' ; } else { var cs = exportMsg ( co , callback , obj ) ; if ( cs == undefined ) { return ; } str += cs + '\\r\\n' ; } } for ( var i = 0 ; i < obj . length ; ++ i ) { if ( obj [ i ] . type == 'message' ) { var cs = exportMsg ( obj [ i ] , callback , obj ) ; if ( cs == undefined ) { return ; } str += cs + '\\r\\n' ; } } return str ; } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "There is - ms - user - select CSS property for IE10 but it seems it works only in desktop browser . So we need to prevent selection event . [CODESPLIT] function ( e ) { var srcElement = e . srcElement . nodeName . toUpperCase ( ) , selectableElements = [ 'INPUT' , 'TEXTAREA' ] ; if ( selectableElements . indexOf ( srcElement ) == - 1 ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether or not the passed number is within a desired range . If the number is already within the range it is returned otherwise the min or max value is returned depending on which side of the range is exceeded . Note that this method returns the constrained value but does not change the current number . [CODESPLIT] function ( number , min , max ) { number = parseFloat ( number ) ; if ( ! isNaN ( min ) ) { number = Math . max ( number , min ) ; } if ( ! isNaN ( max ) ) { number = Math . min ( number , max ) ; } return number ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Snaps the passed number between stopping points based upon a passed increment value . [CODESPLIT] function ( value , increment , minValue , maxValue ) { var newValue = value , m ; if ( ! ( increment && value ) ) { return value ; } m = value % increment ; if ( m !== 0 ) { newValue -= m ; if ( m * 2 >= increment ) { newValue += increment ; } else if ( m * 2 < - increment ) { newValue -= increment ; } } return Ext . Number . constrain ( newValue , minValue , maxValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats a number using fixed - point notation [CODESPLIT] function ( value , precision ) { if ( isToFixedBroken ) { precision = precision || 0 ; var pow = Math . pow ( 10 , precision ) ; return ( Math . round ( value * pow ) / pow ) . toFixed ( precision ) ; } return value . toFixed ( precision ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extend object [CODESPLIT] function _extend ( target , source ) { var keys = Object . keys ( source ) ; for ( var i = 0 ; i < keys . length ; i ++ ) { target [ keys [ i ] ] = source [ keys [ i ] ] ; } return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "simple logger middleware [CODESPLIT] function logger ( req , res , next ) { if ( req . url . substr ( 0 , 2 ) === \"/r\" ) { console . log ( req . method , decodeURIComponent ( req . url ) , req . body ? JSON . stringify ( req . body ) : \"\" ) ; } next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "simple string to native - type conversion middleware [CODESPLIT] function typeConvert ( obj , onlyDate ) { var i , res ; if ( typeof obj === \"object\" ) { for ( i in obj ) { if ( obj . hasOwnProperty ( i ) ) { obj [ i ] = typeConvert ( obj [ i ] , onlyDate ) ; } } } else if ( typeof obj === \"string\" ) { if ( ! onlyDate && obj . match ( / ^([0-9.]+|true|false|undefined|null)$ / ) ) { obj = eval ( obj ) ; } else { res = obj . match ( / ^\"?(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z)\"?$ / ) ; if ( res ) { obj = new Date ( res [ 1 ] ) ; } } } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "middleware that executes typeconvert on the query and the body [CODESPLIT] function typeConvertMiddleware ( req , res , next ) { typeConvert ( req . params ) ; typeConvert ( req . body , true ) ; next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "store manager [CODESPLIT] function StoreManager ( options ) { var stores = { } ; this . get = function ( name ) { if ( ! stores [ name ] ) { stores [ name ] = options . store ( name ) ; } return stores [ name ] ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the rest server [CODESPLIT] function createServer ( options ) { var server , stores ; // convenience method to define a restify route function defineRoute ( method , route , handler ) { server [ method ] ( route , function ( req , res ) { var store = stores . get ( req . params . resource ) ; delete req . params . resource ; handler ( req , store , function ( error , docs ) { if ( error ) { res . status ( 500 ) ; res . end ( error ) ; } else if ( ! docs ) { res . status ( 404 ) ; res . end ( \"Not found\" ) ; } else { res . json ( docs ) ; } } ) ; } ) ; } // convenience method to create a routing URL function routeURL ( ) { var prefix = options . prefix || \"\" , args = [ \"/\" + prefix , \":resource\" ] . concat ( Array . prototype . slice . call ( arguments ) ) ; return path . join . apply ( path , args ) ; } // create password salt and hash function createPasswordHash ( object ) { if ( ! object ) return object ; var password = object . password ; if ( password ) { delete object . password ; object . passwordSalt = sha1 ( Math . random ( ) . toString ( ) ) ; object . passwordHash = sha1 ( \"restify-magic\" + object . passwordSalt + password ) ; } return object ; } // ensure non-empty options options = options || { } ; // the store manager options . store = options . store || defaultStore ( ) ; stores = new StoreManager ( options ) ; // create and configure the server server = options . server || restify . createServer ( ) ; server . use ( restify . plugins . acceptParser ( server . acceptable ) ) . use ( restify . plugins . fullResponse ( ) ) . use ( restify . plugins . queryParser ( ) ) . use ( restify . plugins . bodyParser ( { mapParams : false } ) ) . use ( typeConvertMiddleware ) . use ( restify . plugins . gzipResponse ( ) ) . pre ( restify . pre . sanitizePath ( ) ) ; if ( options . debug ) { server . use ( logger ) ; } if ( options . middleware ) { options . middleware . forEach ( function ( middleware ) { server . use ( middleware ) ; } ) ; } // GET defineRoute ( \"get\" , routeURL ( ) , function ( req , store , cb ) { var password = req . params . password ; if ( ! password ) { return store . find ( req . params ) . sort ( { _created : 1 } ) . exec ( cb ) ; } // password to hash delete req . params . password ; store . findOne ( req . params ) . exec ( function ( err , record ) { if ( err ) { cb ( err ) ; } else if ( sha1 ( \"restify-magic\" + record . passwordSalt + password ) !== record . passwordHash ) { cb ( undefined , [ ] ) ; } else { cb ( undefined , record ) ; } } ) ; } ) ; // GET with id defineRoute ( \"get\" , routeURL ( \":_id\" ) , function ( req , store , cb ) { store . findOne ( req . params , cb ) ; } ) ; // POST defineRoute ( \"post\" , routeURL ( ) , function ( req , store , cb ) { createPasswordHash ( req . body ) ; req . body . _updated = new Date ( ) ; if ( Object . keys ( req . params ) . length > 0 ) { store . update ( req . params , req . body , { multi : true , upsert : true } , cb ) ; } else { req . body . _created = req . body . _updated ; store . insert ( req . body , cb ) ; } } ) ; // POST with id defineRoute ( \"post\" , routeURL ( \":_id\" ) , function ( req , store , cb ) { createPasswordHash ( req . body ) ; req . body . _updated = new Date ( ) ; store . update ( req . params , req . body , { } , cb ) ; } ) ; // PUT defineRoute ( \"put\" , routeURL ( ) , function ( req , store , cb ) { createPasswordHash ( req . body ) ; req . body . _updated = new Date ( ) ; store . update ( req . params , req . body , { multi : true } , cb ) ; } ) ; // PUT with id defineRoute ( \"put\" , routeURL ( \":_id\" ) , function ( req , store , cb ) { createPasswordHash ( req . body ) ; req . body . _updated = new Date ( ) ; store . update ( req . params , req . body , { } , cb ) ; } ) ; // DELETE with id defineRoute ( \"del\" , routeURL ( \":_id\" ) , function ( req , store , cb ) { store . remove ( req . params , { } , cb ) ; } ) ; return server ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convenience method to define a restify route [CODESPLIT] function defineRoute ( method , route , handler ) { server [ method ] ( route , function ( req , res ) { var store = stores . get ( req . params . resource ) ; delete req . params . resource ; handler ( req , store , function ( error , docs ) { if ( error ) { res . status ( 500 ) ; res . end ( error ) ; } else if ( ! docs ) { res . status ( 404 ) ; res . end ( \"Not found\" ) ; } else { res . json ( docs ) ; } } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convenience method to create a routing URL [CODESPLIT] function routeURL ( ) { var prefix = options . prefix || \"\" , args = [ \"/\" + prefix , \":resource\" ] . concat ( Array . prototype . slice . call ( arguments ) ) ; return path . join . apply ( path , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create password salt and hash [CODESPLIT] function createPasswordHash ( object ) { if ( ! object ) return object ; var password = object . password ; if ( password ) { delete object . password ; object . passwordSalt = sha1 ( Math . random ( ) . toString ( ) ) ; object . passwordHash = sha1 ( \"restify-magic\" + object . passwordSalt + password ) ; } return object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A non recursive way to resolve our json schema to the create query . [CODESPLIT] function ( json , typeSpecification , array ) { var keys , current = json , nested = [ ] , nestedKeys = [ ] , levels = [ ] , query = 'COLUMN_CREATE(' , root = true , curNest = '' , curItem , item = 0 , level = 0 ; while ( current ) { keys = Object . keys ( current ) ; var len = keys . length ; var _l ; var deepestLevel = 1 ; for ( var i = 0 ; i < len ; ++ i ) { if ( ( _l = current [ keys [ i ] ] ) === null || _l === undefined ) { continue ; } if ( typeof ( _l ) === 'object' ) { // skip empty objects, we do not store them, // this needs us to set NULL instead if ( ! Object . keys ( _l ) . length ) { _l = null ; if ( ! typeSpecification ) { query += '\\'' + keys [ i ] . replace ( / \\\\ / g , '\\\\\\\\' ) . replace ( / \\u0008 / g , '\\\\b' ) . replace ( / ' / g , '\\\\\\'' ) . replace ( / \\u0000 / g , '\\\\0' ) + '\\', NULL, ' ; } else { query += '?, NULL, ' ; array . push ( keys [ i ] ) ; } continue ; } nested . push ( _l ) ; nestedKeys . push ( keys [ i ] ) ; if ( curItem !== item ) { curItem = item ; ++ level ; levels . push ( { level : level - 1 , nestSep : curNest + ')' } ) ; } else { levels . push ( { level : level - 1 , nestSep : ')' } ) ; } //save nesting level } else { var queryType = typeof ( _l ) ; if ( ! typeSpecification ) { query += '\\'' + keys [ i ] . replace ( / \\\\ / g , '\\\\\\\\' ) . replace ( / \\u0008 / g , '\\\\b' ) . replace ( / ' / g , '\\\\\\'' ) . replace ( / \\u0000 / g , '\\\\0' ) + '\\', ' ; } else { query += '?, ' ; array . push ( keys [ i ] ) ; } switch ( queryType ) { case 'boolean' : query += ( ( _l === true ) ? 1 : 0 ) + ' AS unsigned integer, ' ; break ; case 'number' : query += _l + ' AS double, ' ; break ; default : if ( ! typeSpecification ) { query += '\\'' + _l . replace ( / \\\\ / g , '\\\\\\\\' ) . replace ( / \\u0008 / g , '\\\\b' ) . replace ( / ' / g , '\\\\\\'' ) . replace ( / \\u0000 / g , '\\\\0' ) + '\\', ' ; } else { query += '?, ' ; array . push ( _l ) ; } break ; } } } if ( root ) { root = false ; } else { if ( level === 0 ) query = query . substring ( 0 , query . length - 2 ) + curNest + ', ' ; } if ( nested . length !== 0 ) { if ( ! typeSpecification ) { query += '\\'' + nestedKeys . pop ( ) . replace ( / \\\\ / g , '\\\\\\\\' ) . replace ( / \\u0008 / g , '\\\\b' ) . replace ( / ' / g , '\\\\\\'' ) . replace ( / \\u0000 / g , '\\\\0' ) + '\\', COLUMN_CREATE(' ; } else { query += '?, COLUMN_CREATE(' ; array . push ( nestedKeys . pop ( ) ) ; } } else { query = query . substring ( 0 , query . length - 2 ) ; } current = nested . pop ( ) ; ++ item ; //restore nesting level level = levels . pop ( ) || 0 ; if ( level ) { curNest = level . nestSep ; level = level . level ; } deepestLevel = level + 1 ; } query += ')' ; return query ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method allows you to decorate a Record s prototype to implement the NodeInterface . This adds a set of methods new events new properties and new fields on every Record with the same Model as the passed Record . [CODESPLIT] function ( record ) { if ( ! record . isNode ) { // Apply the methods and fields to the prototype var mgr = Ext . data . ModelManager , modelName = record . modelName , modelClass = mgr . getModel ( modelName ) , newFields = [ ] , i , newField , len ; // Start by adding the NodeInterface methods to the Model's prototype modelClass . override ( this . getPrototypeBody ( ) ) ; newFields = this . applyFields ( modelClass , [ { name : 'parentId' , type : 'string' , defaultValue : null } , { name : 'index' , type : 'int' , defaultValue : 0 } , { name : 'depth' , type : 'int' , defaultValue : 0 , persist : false } , { name : 'expanded' , type : 'bool' , defaultValue : false , persist : false } , { name : 'expandable' , type : 'bool' , defaultValue : true , persist : false } , { name : 'checked' , type : 'auto' , defaultValue : null } , { name : 'leaf' , type : 'bool' , defaultValue : false , persist : false } , { name : 'cls' , type : 'string' , defaultValue : null , persist : false } , { name : 'iconCls' , type : 'string' , defaultValue : null , persist : false } , { name : 'root' , type : 'boolean' , defaultValue : false , persist : false } , { name : 'isLast' , type : 'boolean' , defaultValue : false , persist : false } , { name : 'isFirst' , type : 'boolean' , defaultValue : false , persist : false } , { name : 'allowDrop' , type : 'boolean' , defaultValue : true , persist : false } , { name : 'allowDrag' , type : 'boolean' , defaultValue : true , persist : false } , { name : 'loaded' , type : 'boolean' , defaultValue : false , persist : false } , { name : 'loading' , type : 'boolean' , defaultValue : false , persist : false } , { name : 'href' , type : 'string' , defaultValue : null , persist : false } , { name : 'hrefTarget' , type : 'string' , defaultValue : null , persist : false } , { name : 'qtip' , type : 'string' , defaultValue : null , persist : false } , { name : 'qtitle' , type : 'string' , defaultValue : null , persist : false } ] ) ; len = newFields . length ; // We set a dirty flag on the fields collection of the model. Any reader that // will read in data for this model will update their extractor functions. modelClass . getFields ( ) . isDirty = true ; // Set default values for ( i = 0 ; i < len ; ++ i ) { newField = newFields [ i ] ; if ( record . get ( newField . getName ( ) ) === undefined ) { record . data [ newField . getName ( ) ] = newField . getDefaultValue ( ) ; } } } if ( ! record . isDecorated ) { record . isDecorated = true ; Ext . applyIf ( record , { firstChild : null , lastChild : null , parentNode : null , previousSibling : null , nextSibling : null , childNodes : [ ] } ) ; record . enableBubble ( [ /**\n                     * @event append\n                     * Fires when a new child node is appended.\n                     * @param {Ext.data.NodeInterface} this This node.\n                     * @param {Ext.data.NodeInterface} node The newly appended node.\n                     * @param {Number} index The index of the newly appended node.\n                     */ \"append\" , /**\n                     * @event remove\n                     * Fires when a child node is removed.\n                     * @param {Ext.data.NodeInterface} this This node.\n                     * @param {Ext.data.NodeInterface} node The removed node.\n                     */ \"remove\" , /**\n                     * @event move\n                     * Fires when this node is moved to a new location in the tree.\n                     * @param {Ext.data.NodeInterface} this This node.\n                     * @param {Ext.data.NodeInterface} oldParent The old parent of this node.\n                     * @param {Ext.data.NodeInterface} newParent The new parent of this node.\n                     * @param {Number} index The index it was moved to.\n                     */ \"move\" , /**\n                     * @event insert\n                     * Fires when a new child node is inserted.\n                     * @param {Ext.data.NodeInterface} this This node.\n                     * @param {Ext.data.NodeInterface} node The child node inserted.\n                     * @param {Ext.data.NodeInterface} refNode The child node the node was inserted before.\n                     */ \"insert\" , /**\n                     * @event beforeappend\n                     * Fires before a new child is appended, return `false` to cancel the append.\n                     * @param {Ext.data.NodeInterface} this This node.\n                     * @param {Ext.data.NodeInterface} node The child node to be appended.\n                     */ \"beforeappend\" , /**\n                     * @event beforeremove\n                     * Fires before a child is removed, return `false` to cancel the remove.\n                     * @param {Ext.data.NodeInterface} this This node.\n                     * @param {Ext.data.NodeInterface} node The child node to be removed.\n                     */ \"beforeremove\" , /**\n                     * @event beforemove\n                     * Fires before this node is moved to a new location in the tree. Return `false` to cancel the move.\n                     * @param {Ext.data.NodeInterface} this This node.\n                     * @param {Ext.data.NodeInterface} oldParent The parent of this node.\n                     * @param {Ext.data.NodeInterface} newParent The new parent this node is moving to.\n                     * @param {Number} index The index it is being moved to.\n                     */ \"beforemove\" , /**\n                      * @event beforeinsert\n                      * Fires before a new child is inserted, return false to cancel the insert.\n                      * @param {Ext.data.NodeInterface} this This node\n                      * @param {Ext.data.NodeInterface} node The child node to be inserted\n                      * @param {Ext.data.NodeInterface} refNode The child node the node is being inserted before\n                      */ \"beforeinsert\" , /**\n                     * @event expand\n                     * Fires when this node is expanded.\n                     * @param {Ext.data.NodeInterface} this The expanding node.\n                     */ \"expand\" , /**\n                     * @event collapse\n                     * Fires when this node is collapsed.\n                     * @param {Ext.data.NodeInterface} this The collapsing node.\n                     */ \"collapse\" , /**\n                     * @event beforeexpand\n                     * Fires before this node is expanded.\n                     * @param {Ext.data.NodeInterface} this The expanding node.\n                     */ \"beforeexpand\" , /**\n                     * @event beforecollapse\n                     * Fires before this node is collapsed.\n                     * @param {Ext.data.NodeInterface} this The collapsing node.\n                     */ \"beforecollapse\" , /**\n                     * @event sort\n                     * Fires when this node's childNodes are sorted.\n                     * @param {Ext.data.NodeInterface} this This node.\n                     * @param {Ext.data.NodeInterface[]} childNodes The childNodes of this node.\n                     */ \"sort\" , 'load' ] ) ; } return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that the passed object is an instance of a Record with the NodeInterface applied [CODESPLIT] function ( node ) { if ( Ext . isObject ( node ) && ! node . isModel ) { node = Ext . data . ModelManager . create ( node , this . modelName ) ; } // Make sure the node implements the node interface return Ext . data . NodeInterface . decorate ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates general data of this node like isFirst isLast depth . This method is internally called after a node is moved . This shouldn t have to be called by the developer unless they are creating custom Tree plugins . [CODESPLIT] function ( silent ) { var me = this , parentNode = me . parentNode , isFirst = ( ! parentNode ? true : parentNode . firstChild == me ) , isLast = ( ! parentNode ? true : parentNode . lastChild == me ) , depth = 0 , parent = me , children = me . childNodes , ln = children . length , i ; while ( parent . parentNode ) { ++ depth ; parent = parent . parentNode ; } me . beginEdit ( ) ; me . set ( { isFirst : isFirst , isLast : isLast , depth : depth , index : parentNode ? parentNode . indexOf ( me ) : 0 , parentId : parentNode ? parentNode . getId ( ) : null } ) ; me . endEdit ( silent ) ; if ( silent ) { me . commit ( silent ) ; } for ( i = 0 ; i < ln ; i ++ ) { children [ i ] . updateInfo ( silent ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert node ( s ) as the last child node of this node . [CODESPLIT] function ( node , suppressEvents , suppressNodeUpdate ) { var me = this , i , ln , index , oldParent , ps ; // if passed an array or multiple args do them one by one if ( Ext . isArray ( node ) ) { for ( i = 0 , ln = node . length ; i < ln ; i ++ ) { me . appendChild ( node [ i ] , suppressEvents , suppressNodeUpdate ) ; } } else { // Make sure it is a record node = me . createNode ( node ) ; if ( suppressEvents !== true && me . fireEvent ( \"beforeappend\" , me , node ) === false ) { return false ; } index = me . childNodes . length ; oldParent = node . parentNode ; // it's a move, make sure we move it cleanly if ( oldParent ) { if ( suppressEvents !== true && node . fireEvent ( \"beforemove\" , node , oldParent , me , index ) === false ) { return false ; } oldParent . removeChild ( node , null , false , true ) ; } index = me . childNodes . length ; if ( index === 0 ) { me . setFirstChild ( node ) ; } me . childNodes . push ( node ) ; node . parentNode = me ; node . nextSibling = null ; me . setLastChild ( node ) ; ps = me . childNodes [ index - 1 ] ; if ( ps ) { node . previousSibling = ps ; ps . nextSibling = node ; ps . updateInfo ( suppressNodeUpdate ) ; } else { node . previousSibling = null ; } node . updateInfo ( suppressNodeUpdate ) ; // As soon as we append a child to this node, we are loaded if ( ! me . isLoaded ( ) ) { me . set ( 'loaded' , true ) ; } // If this node didn't have any childnodes before, update myself else if ( me . childNodes . length === 1 ) { me . set ( 'loaded' , me . isLoaded ( ) ) ; } if ( suppressEvents !== true ) { me . fireEvent ( \"append\" , me , node , index ) ; if ( oldParent ) { node . fireEvent ( \"move\" , node , oldParent , me , index ) ; } } return node ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a child node from this node . [CODESPLIT] function ( node , destroy , suppressEvents , suppressNodeUpdate ) { var me = this , index = me . indexOf ( node ) ; if ( index == - 1 || ( suppressEvents !== true && me . fireEvent ( \"beforeremove\" , me , node ) === false ) ) { return false ; } // remove it from childNodes collection Ext . Array . erase ( me . childNodes , index , 1 ) ; // update child refs if ( me . firstChild == node ) { me . setFirstChild ( node . nextSibling ) ; } if ( me . lastChild == node ) { me . setLastChild ( node . previousSibling ) ; } if ( suppressEvents !== true ) { me . fireEvent ( \"remove\" , me , node ) ; } // update siblings if ( node . previousSibling ) { node . previousSibling . nextSibling = node . nextSibling ; node . previousSibling . updateInfo ( suppressNodeUpdate ) ; } if ( node . nextSibling ) { node . nextSibling . previousSibling = node . previousSibling ; node . nextSibling . updateInfo ( suppressNodeUpdate ) ; } // If this node suddenly doesn't have childnodes anymore, update myself if ( ! me . childNodes . length ) { me . set ( 'loaded' , me . isLoaded ( ) ) ; } if ( destroy ) { node . destroy ( true ) ; } else { node . clear ( ) ; } return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a copy ( clone ) of this Node . [CODESPLIT] function ( newId , deep ) { var me = this , result = me . callOverridden ( arguments ) , len = me . childNodes ? me . childNodes . length : 0 , i ; // Move child nodes across to the copy if required if ( deep ) { for ( i = 0 ; i < len ; i ++ ) { result . appendChild ( me . childNodes [ i ] . copy ( true ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear the node . [CODESPLIT] function ( destroy ) { var me = this ; // clear any references from the node me . parentNode = me . previousSibling = me . nextSibling = null ; if ( destroy ) { me . firstChild = me . lastChild = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Destroys the node . [CODESPLIT] function ( silent ) { /*\n                     * Silent is to be used in a number of cases\n                     * 1) When setRoot is called.\n                     * 2) When destroy on the tree is called\n                     * 3) For destroying child nodes on a node\n                     */ var me = this , options = me . destroyOptions ; if ( silent === true ) { me . clear ( true ) ; Ext . each ( me . childNodes , function ( n ) { n . destroy ( true ) ; } ) ; me . childNodes = null ; delete me . destroyOptions ; me . callOverridden ( [ options ] ) ; } else { me . destroyOptions = silent ; // overridden method will be called, since remove will end up calling destroy(true); me . remove ( true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the first node before the second node in this nodes childNodes collection . [CODESPLIT] function ( node , refNode , suppressEvents ) { var me = this , index = me . indexOf ( refNode ) , oldParent = node . parentNode , refIndex = index , ps ; if ( ! refNode ) { // like standard Dom, refNode can be null for append return me . appendChild ( node ) ; } // nothing to do if ( node == refNode ) { return false ; } // Make sure it is a record with the NodeInterface node = me . createNode ( node ) ; if ( suppressEvents !== true && me . fireEvent ( \"beforeinsert\" , me , node , refNode ) === false ) { return false ; } // when moving internally, indexes will change after remove if ( oldParent == me && me . indexOf ( node ) < index ) { refIndex -- ; } // it's a move, make sure we move it cleanly if ( oldParent ) { if ( suppressEvents !== true && node . fireEvent ( \"beforemove\" , node , oldParent , me , index , refNode ) === false ) { return false ; } oldParent . removeChild ( node ) ; } if ( refIndex === 0 ) { me . setFirstChild ( node ) ; } Ext . Array . splice ( me . childNodes , refIndex , 0 , node ) ; node . parentNode = me ; node . nextSibling = refNode ; refNode . previousSibling = node ; ps = me . childNodes [ refIndex - 1 ] ; if ( ps ) { node . previousSibling = ps ; ps . nextSibling = node ; ps . updateInfo ( ) ; } else { node . previousSibling = null ; } node . updateInfo ( ) ; if ( ! me . isLoaded ( ) ) { me . set ( 'loaded' , true ) ; } // If this node didn't have any childnodes before, update myself else if ( me . childNodes . length === 1 ) { me . set ( 'loaded' , me . isLoaded ( ) ) ; } if ( suppressEvents !== true ) { me . fireEvent ( \"insert\" , me , node , refNode ) ; if ( oldParent ) { node . fireEvent ( \"move\" , node , oldParent , me , refIndex , refNode ) ; } } return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes this node from its parent . [CODESPLIT] function ( destroy , suppressEvents ) { var parentNode = this . parentNode ; if ( parentNode ) { parentNode . removeChild ( this , destroy , suppressEvents , true ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all child nodes from this node . [CODESPLIT] function ( destroy , suppressEvents ) { var cn = this . childNodes , n ; while ( ( n = cn [ 0 ] ) ) { this . removeChild ( n , destroy , suppressEvents ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts this nodes children using the supplied sort function . [CODESPLIT] function ( sortFn , recursive , suppressEvent ) { var cs = this . childNodes , ln = cs . length , i , n ; if ( ln > 0 ) { Ext . Array . sort ( cs , sortFn ) ; for ( i = 0 ; i < ln ; i ++ ) { n = cs [ i ] ; n . previousSibling = cs [ i - 1 ] ; n . nextSibling = cs [ i + 1 ] ; if ( i === 0 ) { this . setFirstChild ( n ) ; } if ( i == ln - 1 ) { this . setLastChild ( n ) ; } n . updateInfo ( suppressEvent ) ; if ( recursive && ! n . isLeaf ( ) ) { n . sort ( sortFn , true , true ) ; } } this . notifyStores ( 'afterEdit' , [ 'sorted' ] , { sorted : 'sorted' } ) ; if ( suppressEvent !== true ) { this . fireEvent ( 'sort' , this , cs ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expand this node . [CODESPLIT] function ( recursive , callback , scope ) { var me = this ; if ( ! me . isLeaf ( ) ) { if ( me . isLoading ( ) ) { me . on ( 'expand' , function ( ) { me . expand ( recursive , callback , scope ) ; } , me , { single : true } ) ; } else { if ( ! me . isExpanded ( ) ) { // The TreeStore actually listens for the beforeexpand method and checks // whether we have to asynchronously load the children from the server // first. Thats why we pass a callback function to the event that the // store can call once it has loaded and parsed all the children. me . fireAction ( 'expand' , [ this ] , function ( ) { me . set ( 'expanded' , true ) ; Ext . callback ( callback , scope || me , [ me . childNodes ] ) ; } ) ; } else { Ext . callback ( callback , scope || me , [ me . childNodes ] ) ; } } } else { Ext . callback ( callback , scope || me ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collapse this node . [CODESPLIT] function ( recursive , callback , scope ) { var me = this ; // First we start by checking if this node is a parent if ( ! me . isLeaf ( ) && me . isExpanded ( ) ) { this . fireAction ( 'collapse' , [ me ] , function ( ) { me . set ( 'expanded' , false ) ; Ext . callback ( callback , scope || me , [ me . childNodes ] ) ; } ) ; } else { Ext . callback ( callback , scope || me , [ me . childNodes ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "call the next target function ( s ) if possible when appropriate [CODESPLIT] function ( ) { if ( head . open === 0 && head . next ) { // advance the head, if possible head = head . next ; } head . open = head . open || 0 ; head . callbacks = head . callbacks || [ false ] ; var dispatchInternal = function ( fnIndex ) { head . open += 1 ; setImmediate ( function ( ) { var opts = makeOpts ( head . opts [ fnIndex ] ) ; if ( errorCount > 0 ) { return ; } var handleError = function ( err ) { errorCount += 1 ; opts . onError ( err , errorCount ) ; } ; var callback = function ( err ) { setImmediate ( function ( ) { if ( head . callbacks [ fnIndex ] ) { handleError ( new Error ( 'function called back twice!' ) ) ; } head . callbacks [ fnIndex ] = true ; if ( err ) { handleError ( err ) ; } head . open -= 1 ; setImmediate ( dispatch ) ; } ) ; } ; if ( opts . wrapWithTry ) { try { head . fns [ fnIndex ] ( callback ) ; } catch ( err ) { head . open -= 1 ; handleError ( err ) ; } } else { head . fns [ fnIndex ] ( callback ) ; } } ) ; } ; for ( head . fnIndex = head . fnIndex || 0 ; head . fnIndex < head . fns . length ; head . fnIndex += 1 ) { dispatchInternal ( head . fnIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set the next fn allowing the tail to advance [CODESPLIT] function ( nextTargetFn , fnOpt ) { tail . next = { fns : [ nextTargetFn ] , opts : [ fnOpt ] } ; tail = tail . next ; dispatch ( ) ; return controller ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@description This is the deployor system [CODESPLIT] function Deployor ( options ) { this . options = _assign ( { } , Deployor . defaults , options ) // TODO move this Object . keys ( this . options ) . forEach ( function ( key ) { process . env [ snakeCase ( key ) . toUpperCase ( ) ] = this . options [ key ] } . bind ( this ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Repaints the whole page . This fixes frequently encountered painting issues in mobile Safari . [CODESPLIT] function ( ) { var mask = Ext . getBody ( ) . createChild ( { cls : Ext . baseCSSPrefix + 'mask ' + Ext . baseCSSPrefix + 'mask-transparent' } ) ; setTimeout ( function ( ) { mask . destroy ( ) ; } , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates unique ids . If the element is passes and it already has an id it is unchanged . [CODESPLIT] function ( el , prefix ) { if ( el && el . id ) { return el . id ; } el = Ext . getDom ( el ) || { } ; if ( el === document || el === document . documentElement ) { el . id = 'ext-app' ; } else if ( el === document . body ) { el . id = 'ext-body' ; } else if ( el === window ) { el . id = 'ext-window' ; } el . id = el . id || ( ( prefix || 'ext-' ) + ( ++ Ext . idSeed ) ) ; return el . id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the current document body as an { [CODESPLIT] function ( ) { if ( ! Ext . documentBodyElement ) { if ( ! document . body ) { throw new Error ( \"[Ext.getBody] document.body does not exist at this point\" ) ; } Ext . documentBodyElement = Ext . get ( document . body ) ; } return Ext . documentBodyElement ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the current document head as an { [CODESPLIT] function ( ) { if ( ! Ext . documentHeadElement ) { Ext . documentHeadElement = Ext . get ( document . head || document . getElementsByTagName ( 'head' ) [ 0 ] ) ; } return Ext . documentHeadElement ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies a set of named properties from the source object to the destination object . [CODESPLIT] function ( dest , source , names , usePrototypeKeys ) { if ( typeof names == 'string' ) { names = names . split ( / [,;\\s] / ) ; } Ext . each ( names , function ( name ) { if ( usePrototypeKeys || source . hasOwnProperty ( name ) ) { dest [ name ] = source [ name ] ; } } , this ) ; return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to destroy any objects passed to it by removing all event listeners removing them from the DOM ( if applicable ) and calling their destroy functions ( if available ) . This method is primarily intended for arguments of type { [CODESPLIT] function ( ) { var args = arguments , ln = args . length , i , item ; for ( i = 0 ; i < ln ; i ++ ) { item = args [ i ] ; if ( item ) { if ( Ext . isArray ( item ) ) { this . destroy . apply ( this , item ) ; } else if ( Ext . isFunction ( item . destroy ) ) { item . destroy ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the dom node for the passed String ( id ) dom node or Ext . Element . Here are some examples : [CODESPLIT] function ( el ) { if ( ! el || ! document ) { return null ; } return el . dom ? el . dom : ( typeof el == 'string' ? document . getElementById ( el ) : el ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes this element from the document removes all DOM event listeners and deletes the cache reference . All DOM event listeners are removed from this element . [CODESPLIT] function ( node ) { if ( node && node . parentNode && node . tagName != 'BODY' ) { Ext . get ( node ) . clearListeners ( ) ; node . parentNode . removeChild ( node ) ; delete Ext . cache [ node . id ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ext . setup () is the entry - point to initialize a Sencha Touch application . Note that if your application makes use of MVC architecture use { @link Ext#application } instead . [CODESPLIT] function ( config ) { var defaultSetupConfig = Ext . defaultSetupConfig , emptyFn = Ext . emptyFn , onReady = config . onReady || emptyFn , onUpdated = config . onUpdated || emptyFn , scope = config . scope , requires = Ext . Array . from ( config . requires ) , extOnReady = Ext . onReady , head = Ext . getHead ( ) , callback , viewport , precomposed ; Ext . setup = function ( ) { throw new Error ( \"Ext.setup has already been called before\" ) ; } ; delete config . requires ; delete config . onReady ; delete config . onUpdated ; delete config . scope ; Ext . require ( [ 'Ext.event.Dispatcher' ] ) ; callback = function ( ) { var listeners = Ext . setupListeners , ln = listeners . length , i , listener ; delete Ext . setupListeners ; Ext . isSetup = true ; for ( i = 0 ; i < ln ; i ++ ) { listener = listeners [ i ] ; listener . fn . call ( listener . scope ) ; } Ext . onReady = extOnReady ; Ext . onReady ( onReady , scope ) ; } ; Ext . onUpdated = onUpdated ; Ext . onReady = function ( fn , scope ) { var origin = onReady ; onReady = function ( ) { origin ( ) ; Ext . onReady ( fn , scope ) ; } ; } ; config = Ext . merge ( { } , defaultSetupConfig , config ) ; Ext . onDocumentReady ( function ( ) { Ext . factoryConfig ( config , function ( data ) { Ext . event . Dispatcher . getInstance ( ) . setPublishers ( data . eventPublishers ) ; if ( data . logger ) { Ext . Logger = data . logger ; } if ( data . animator ) { Ext . Animator = data . animator ; } if ( data . viewport ) { Ext . Viewport = viewport = data . viewport ; if ( ! scope ) { scope = viewport ; } Ext . require ( requires , function ( ) { Ext . Viewport . on ( 'ready' , callback , null , { single : true } ) ; } ) ; } else { Ext . require ( requires , callback ) ; } } ) ; if ( ! Ext . microloaded && navigator . userAgent . match ( / IEMobile\\/10\\.0 / ) ) { var msViewportStyle = document . createElement ( \"style\" ) ; msViewportStyle . appendChild ( document . createTextNode ( \"@media screen and (orientation: portrait) {\" + \"@-ms-viewport {width: 320px !important;}\" + \"}\" + \"@media screen and (orientation: landscape) {\" + \"@-ms-viewport {width: 560px !important;}\" + \"}\" ) ) ; head . appendChild ( msViewportStyle ) ; } } ) ; function addMeta ( name , content ) { var meta = document . createElement ( 'meta' ) ; meta . setAttribute ( 'name' , name ) ; meta . setAttribute ( 'content' , content ) ; head . append ( meta ) ; } function addIcon ( href , sizes , precomposed ) { var link = document . createElement ( 'link' ) ; link . setAttribute ( 'rel' , 'apple-touch-icon' + ( precomposed ? '-precomposed' : '' ) ) ; link . setAttribute ( 'href' , href ) ; if ( sizes ) { link . setAttribute ( 'sizes' , sizes ) ; } head . append ( link ) ; } function addStartupImage ( href , media ) { var link = document . createElement ( 'link' ) ; link . setAttribute ( 'rel' , 'apple-touch-startup-image' ) ; link . setAttribute ( 'href' , href ) ; if ( media ) { link . setAttribute ( 'media' , media ) ; } head . append ( link ) ; } var icon = config . icon , isIconPrecomposed = Boolean ( config . isIconPrecomposed ) , startupImage = config . startupImage || { } , statusBarStyle = config . statusBarStyle || 'black' , devicePixelRatio = window . devicePixelRatio || 1 ; if ( navigator . standalone ) { addMeta ( 'viewport' , 'width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' ) ; } else { addMeta ( 'viewport' , 'initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, minimum-ui' ) ; } addMeta ( 'apple-mobile-web-app-capable' , 'yes' ) ; addMeta ( 'apple-touch-fullscreen' , 'yes' ) ; if ( Ext . browser . is . ie ) { addMeta ( 'msapplication-tap-highlight' , 'no' ) ; } // status bar style if ( statusBarStyle ) { addMeta ( 'apple-mobile-web-app-status-bar-style' , statusBarStyle ) ; } if ( Ext . isString ( icon ) ) { icon = { 57 : icon , 72 : icon , 114 : icon , 144 : icon } ; } else if ( ! icon ) { icon = { } ; } //<deprecated product=touch since=2.0.1> if ( 'phoneStartupScreen' in config ) { //<debug warn> Ext . Logger . deprecate ( \"[Ext.setup()] 'phoneStartupScreen' config is deprecated, please use 'startupImage' \" + \"config instead. Refer to the latest API docs for more details\" ) ; //</debug> config [ '320x460' ] = config . phoneStartupScreen ; } if ( 'tabletStartupScreen' in config ) { //<debug warn> Ext . Logger . deprecate ( \"[Ext.setup()] 'tabletStartupScreen' config is deprecated, please use 'startupImage' \" + \"config instead. Refer to the latest API docs for more details\" ) ; //</debug> config [ '768x1004' ] = config . tabletStartupScreen ; } if ( 'glossOnIcon' in config ) { //<debug warn> Ext . Logger . deprecate ( \"[Ext.setup()] 'glossOnIcon' config is deprecated, please use 'isIconPrecomposed' \" + \"config instead. Refer to the latest API docs for more details\" ) ; //</debug> isIconPrecomposed = Boolean ( config . glossOnIcon ) ; } //</deprecated> if ( Ext . os . is . iPad ) { if ( devicePixelRatio >= 2 ) { // Retina iPad - Landscape if ( '1496x2048' in startupImage ) { addStartupImage ( startupImage [ '1496x2048' ] , '(orientation: landscape)' ) ; } // Retina iPad - Portrait if ( '1536x2008' in startupImage ) { addStartupImage ( startupImage [ '1536x2008' ] , '(orientation: portrait)' ) ; } // Retina iPad if ( '144' in icon ) { addIcon ( icon [ '144' ] , '144x144' , isIconPrecomposed ) ; } } else { // Non-Retina iPad - Landscape if ( '748x1024' in startupImage ) { addStartupImage ( startupImage [ '748x1024' ] , '(orientation: landscape)' ) ; } // Non-Retina iPad - Portrait if ( '768x1004' in startupImage ) { addStartupImage ( startupImage [ '768x1004' ] , '(orientation: portrait)' ) ; } // Non-Retina iPad if ( '72' in icon ) { addIcon ( icon [ '72' ] , '72x72' , isIconPrecomposed ) ; } } } else { // Retina iPhone, iPod touch with iOS version >= 4.3 if ( devicePixelRatio >= 2 && Ext . os . version . gtEq ( '4.3' ) ) { if ( Ext . os . is . iPhone5 ) { addStartupImage ( startupImage [ '640x1096' ] ) ; } else { addStartupImage ( startupImage [ '640x920' ] ) ; } // Retina iPhone and iPod touch if ( '114' in icon ) { addIcon ( icon [ '114' ] , '114x114' , isIconPrecomposed ) ; } } else { addStartupImage ( startupImage [ '320x460' ] ) ; // Non-Retina iPhone, iPod touch, and Android devices if ( '57' in icon ) { addIcon ( icon [ '57' ] , null , isIconPrecomposed ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@member Ext @method application [CODESPLIT] function ( config ) { var appName = config . name , onReady , scope , requires ; if ( ! config ) { config = { } ; } if ( ! Ext . Loader . config . paths [ appName ] ) { Ext . Loader . setPath ( appName , config . appFolder || 'app' ) ; } requires = Ext . Array . from ( config . requires ) ; config . requires = [ 'Ext.app.Application' ] ; onReady = config . onReady ; scope = config . scope ; config . onReady = function ( ) { config . requires = requires ; new Ext . app . Application ( config ) ; if ( onReady ) { onReady . call ( scope ) ; } } ; Ext . setup ( config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A global factory method to instantiate a class from a config object . For example these two calls are equivalent : [CODESPLIT] function ( config , classReference , instance , aliasNamespace ) { var manager = Ext . ClassManager , newInstance ; // If config is falsy or a valid instance, destroy the current instance // (if it exists) and replace with the new one if ( ! config || config . isInstance ) { if ( instance && instance !== config ) { instance . destroy ( ) ; } return config ; } if ( aliasNamespace ) { // If config is a string value, treat it as an alias if ( typeof config == 'string' ) { return manager . instantiateByAlias ( aliasNamespace + '.' + config ) ; } // Same if 'type' is given in config else if ( Ext . isObject ( config ) && 'type' in config ) { return manager . instantiateByAlias ( aliasNamespace + '.' + config . type , config ) ; } } if ( config === true ) { return instance || manager . instantiate ( classReference ) ; } //<debug error> if ( ! Ext . isObject ( config ) ) { Ext . Logger . error ( \"Invalid config, must be a valid config object\" ) ; } //</debug> if ( 'xtype' in config ) { newInstance = manager . instantiateByAlias ( 'widget.' + config . xtype , config ) ; } else if ( 'xclass' in config ) { newInstance = manager . instantiate ( config . xclass , config ) ; } if ( newInstance ) { if ( instance ) { instance . destroy ( ) ; } return newInstance ; } if ( instance ) { return instance . setConfig ( config ) ; } return manager . instantiate ( classReference , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<debug > Useful snippet to show an exact narrowed - down list of top - level Components that are not yet destroyed . [CODESPLIT] function ( ) { var map = Ext . ComponentManager . all . map , leaks = [ ] , parent ; Ext . Object . each ( map , function ( id , component ) { while ( ( parent = component . getParent ( ) ) && map . hasOwnProperty ( parent . getId ( ) ) ) { component = parent ; } if ( leaks . indexOf ( component ) === - 1 ) { leaks . push ( component ) ; } } ) ; console . log ( leaks ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Msutache Instance Methods [CODESPLIT] function addAction ( name , fn ) { if ( typeof name === \"object\" && fn == null ) { _ . each ( name , function ( fn , n ) { this . addAction ( n , fn ) ; } , this ) ; return this ; } if ( typeof name !== \"string\" || name === \"\" ) throw new Error ( \"Expecting non-empty string for action name.\" ) ; if ( typeof fn !== \"function\" ) throw new Error ( \"Expecting function for action.\" ) ; if ( this . _actions == null ) this . _actions = { } ; if ( this . _actions [ name ] == null ) this . _actions [ name ] = [ ] ; if ( ! ~ this . _actions [ name ] . indexOf ( fn ) ) this . _actions [ name ] . push ( fn ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * options : { credentials : { username : ... password : ... token : ... } repo : git@github . com : user / repo . git } [CODESPLIT] function ( options ) { this . options = options ; this . headers = { 'User-Agent' : 'request/grunt-github-release-asset' } ; var authStr ; if ( options . credentials ) { if ( options . credentials . token ) { authStr = options . credentials . token + ':' + '' ; } else if ( options . credentials . username && options . credentials . password ) { authStr = options . credentials . username + ':' + options . credentials . password ; } } if ( ! authStr ) { throw new Error ( 'Please supply a token or username & password to authorize yourself.' ) ; } this . headers [ 'Authorization' ] = 'Basic ' + ( new Buffer ( authStr ) . toString ( 'base64' ) ) try { this . repoPath = options . repo . split ( ':' ) [ 1 ] . split ( '.' ) . slice ( 0 , - 1 ) . join ( '.' ) . toLowerCase ( ) ; } catch ( err ) { throw new Error ( 'Repository url isn\\'t provided or isn\\'t valid.' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Curried function deriving new array values by applying provided function to each item / index of provided array . Optionally a dot - notation formatted string may be provided for item property access . [CODESPLIT] function map ( fn , list ) { var end = list . length var idx = - 1 var out = [ ] while ( ++ idx < end ) { out . push ( ( typeof fn === 'string' ) ? selectn ( fn , list [ idx ] ) : fn ( list [ idx ] ) ) } return out }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ISFINITE // FUNCTION : isfinite ( arr ) Computes for each array element whether an element is a finite number . [CODESPLIT] function isfinite ( arr ) { if ( ! Array . isArray ( arr ) ) { throw new TypeError ( 'isfinite()::invalid input argument. Must provide an array.' ) ; } var len = arr . length , out = new Array ( len ) , val ; for ( var i = 0 ; i < len ; i ++ ) { out [ i ] = 0 ; val = arr [ i ] ; if ( typeof val === 'number' && val === val && val < pinf && val > ninf ) { out [ i ] = 1 ; } } return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "~~~~~ CHILD PROCESS ~~~~~~ child_process . exec ( command [ options ] [ callback ] ) [CODESPLIT] function exec ( options , callback ) { return cmd ( _ . assign ( options , { type : 'exec' } ) , _ . cb ( callback ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "child_process . execFile ( file [ args ] [ options ] [ callback ] ) [CODESPLIT] function execFile ( options , callback ) { return cmd ( _ . assign ( options , { type : 'execFile' } ) , _ . cb ( callback ) ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "runs exec or exexfile modules . writePaths : { cmd : node args : [ test modules . writePaths ] switches : { dest : _ . path . join ( TEMP_PATH paths . json ) } } [CODESPLIT] function cmd ( options , callback ) { let opts = _ . merge ( { } , DEFAULTS , options ) let { cmd = '' , type = '' , args = [ ] , switches = { } } = opts type = type && _ . isString ( type ) && _ . includes ( [ 'exec' , 'execFile' ] , type ) ? type : 'exec' args = args && _ . isArray ( args ) ? args : [ ] switches = switches && _ . isPlainObject ( switches ) ? _ . merge ( switches , _ . omit ( JARGV || { } , [ '_' ] ) ) || { } : { } let method = _ . get ( cproc , type ) if ( ! cmd || ! _ . isString ( cmd ) ) return _ . fail ( 'Invalid cmd' , callback ) if ( ! _ . isFunction ( method ) ) return _ . fail ( 'Invalid type' , callback ) _ . forIn ( switches , ( v , k ) => { if ( ! v && ! k ) return let arg = v && k ? ` ${ k } ${ v } ` : ` ${ k || v } ` if ( arg ) args . push ( arg ) } ) args = _ . compact ( args ) let isExec = type === 'exec' _ . assign ( opts , { args : args } ) opts = _ . omit ( opts , [ 'type' , 'switches' ] ) // exec does not take args argument like execFile // -> must join args with ' ' and append to cmd prop to create command if ( isExec ) cmd = _ . join ( [ cmd , _ . join ( args , ' ' ) ] , ' ' ) let cb = ( err , stdout , stderr ) => { if ( err ) return _ . fail ( err , callback ) _ . done ( { stdout : stdout , stderr : stderr } , callback ) } const child = isExec ? _ . attempt ( method , cmd , opts , cb ) : _ . attempt ( method , cmd , args , opts , cb ) return child //return _handleChild(child, _.cb(callback)) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "handles newly created child process via cproc . exec OR cprop . execFile ** child . on ( close ( code ) = > {} ) is basically the only event that is called ** use stdout / stderr to handle fail / done on close event !!! [CODESPLIT] function _handleChild ( child , callback ) { if ( ! child ) return _ . fail ( 'Invalid child process' , callback ) if ( _ . isError ( child ) ) return _ . fail ( child , callback ) let stdout = '' let stderr = '' child . stdout . on ( 'data' , function ( data ) { stdout += data } ) child . stderr . on ( 'data' , function ( data ) { stderr += data } ) child . on ( 'close' , function ( code ) { return _ . done ( stdout || stderr , callback ) } ) child . on ( 'disconnect' , function ( err ) { } ) child . on ( 'error' , function ( err ) { } ) child . on ( 'exit' , function ( code , signal ) { } ) child . on ( 'message' , function ( message , sendHandle ) { } ) return child }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "QUERY // FUNCTION : query ( data options clbk ) Queries an endpoint . [CODESPLIT] function query ( data , options , clbk ) { var opts ; // Extract request options: opts = getOpts ( options ) ; // Set the query endpoint: opts . path = getPath ( options ) ; // Get the request data: data = getData ( data ) ; opts . headers [ 'Content-Length' ] = data . length ; // Make the request: request ( opts , data , done ) ; /**\n\t* FUNCTION: done( error, response, data )\n\t*\tCallback invoked after completing request.\n\t*\n\t* @private\n\t* @param {Error|Null} error - error object\n\t* @param {Object} response - HTTP response object\n\t* @param {Object} data - response data\n\t* @returns {Void}\n\t*/ function done ( error , response , data ) { if ( error ) { return clbk ( error ) ; } debug ( 'Request successfully completed.' ) ; clbk ( null , data ) ; } // end FUNCTION done() }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FUNCTION : done ( error response data ) Callback invoked after completing request . [CODESPLIT] function done ( error , response , data ) { if ( error ) { return clbk ( error ) ; } debug ( 'Request successfully completed.' ) ; clbk ( null , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helpers [CODESPLIT] function getDigest ( cfg ) { var ha1 , ha2 , response ; ha1 = crypto . createHash ( 'md5' ) . update ( cfg . fromExt + ':' + cfg . realm + ':' + cfg . pass ) . digest ( 'hex' ) ; ha2 = crypto . createHash ( 'md5' ) . update ( cfg . meth + ':' + cfg . authUri ) . digest ( 'hex' ) ; //    console.log(cfg); //    console.log('HA1: ' + cfg.fromExt + ':' + cfg.realm + ':' + cfg.pass) //    console.log('HA1MD5:'+ ha1); //    console.log('HA2: ' + cfg.meth + ':' + cfg.authUri); //    console.log('HA2MD5:'+ ha2); response = crypto . createHash ( 'md5' ) . update ( ha1 + ':' + cfg . nonce + ':' + ha2 ) . digest ( 'hex' ) ; //    console.log('response: ' + ha1 + ':' + cfg.nonce + ':' + ha2); //    console.log('responseMD5: ' + response ); return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helper method for deprecating a property [CODESPLIT] function ( property , obj , newProperty ) { if ( config . hasOwnProperty ( property ) ) { if ( obj ) { config [ obj ] = config [ obj ] || { } ; config [ obj ] [ ( newProperty ) ? newProperty : property ] = config [ obj ] [ ( newProperty ) ? newProperty : property ] || config [ property ] ; } else { config [ newProperty ] = config [ property ] ; } delete config [ property ] ; //<debug warn> Ext . Logger . deprecate ( \"'\" + property + \"' config is deprecated, use the '\" + ( ( obj ) ? obj + \".\" : \"\" ) + ( ( newProperty ) ? newProperty : property ) + \"' config instead\" , 2 ) ; //</debug> } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Version 0 . 1 . 0 Create Store Objects [CODESPLIT] function Store ( name , items ) { if ( ! name ) { throw new Error ( 'Please give the store a name!' ) ; } this . name = name ; this . items = items || { } ; this . type = 'object' ; this . setType ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "join an array [CODESPLIT] function node ( content , type , name , indent ) { this . type = type ; if ( name ) this . name = name ; this . content = content ; if ( indent ) { this . indent = indent ; // to use same indentation as source code if ( ~ eol . indexOf ( indent [ 0 ] ) ) { delete this . indent ; } } var loc = location ( ) ; var bol = loc . start . column == 1 ; if ( bol ) this . bol = true ; this . line = loc . start . line ; this . column = loc . start . column ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "flatten an array and join it [CODESPLIT] function f ( arr ) { if ( arr ) { var merged = [ ] ; return merged . concat . apply ( merged , arr ) . join ( \"\" ) } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "configureStore - create redux - store [CODESPLIT] function configureStore ( onComplete ) { // Apply middlewares var middlewares = [ thunk ] ; events . emit ( 'middlewaresWillApply' , middlewares ) ; if ( __DEV__ && ! ! window . navigator . userAgent ) { middlewares . push ( createLogger ( { collapsed : true , duration : true , } ) ) ; } // Create store var storeCreator = applyMiddleware . apply ( null , middlewares ) ( createStore ) ; var result = { } ; // {store: <created store>} events . emit ( 'storeWillCreate' , storeCreator , reducers , onComplete , result ) ; if ( result . store === undefined ) { result . store = storeCreator ( reducers ) ; setTimeout ( onComplete , 0 ) ; } global . reduxStore = result . store ; return reduxStore ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new Droppable . [CODESPLIT] function ( el , config ) { var me = this ; config = config || { } ; Ext . apply ( me , config ) ; /**\n         * @event dropactivate\n         * @param {Ext.util.Droppable} this\n         * @param {Ext.util.Draggable} draggable\n         * @param {Ext.event.Event} e\n         */ /**\n         * @event dropdeactivate\n         * @param {Ext.util.Droppable} this\n         * @param {Ext.util.Draggable} draggable\n         * @param {Ext.event.Event} e\n         */ /**\n         * @event dropenter\n         * @param {Ext.util.Droppable} this\n         * @param {Ext.util.Draggable} draggable\n         * @param {Ext.event.Event} e\n         */ /**\n         * @event dropleave\n         * @param {Ext.util.Droppable} this\n         * @param {Ext.util.Draggable} draggable\n         * @param {Ext.event.Event} e\n         */ /**\n         * @event drop\n         * @param {Ext.util.Droppable} this\n         * @param {Ext.util.Draggable} draggable\n         * @param {Ext.event.Event} e\n         */ me . el = Ext . get ( el ) ; me . callParent ( ) ; me . mixins . observable . constructor . call ( me ) ; if ( ! me . disabled ) { me . enable ( ) ; } me . el . addCls ( me . baseCls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable the Droppable target . This is invoked immediately after constructing a Droppable if the disabled parameter is NOT set to true . [CODESPLIT] function ( ) { if ( ! this . mgr ) { this . mgr = Ext . util . Observable . observe ( Ext . util . Draggable ) ; } this . mgr . on ( { dragstart : this . onDragStart , scope : this } ) ; this . disabled = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FORMAT returns formatted / path / to / file . js - > path . to . file [CODESPLIT] function ns ( rootpath , src ) { return _ . compact ( src . replace ( rootpath , '' ) . split ( path . sep ) ) . join ( '.' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return rel path of namespace ( ns - > parent . folder . item ) [CODESPLIT] function nspath ( ) { let src = _ . join ( _ . filter ( _ . toArray ( arguments ) , function ( arg ) { return arg && _ . isString ( arg ) } ) , '.' ) if ( ! src ) return '' return _ . replace ( src , REGX_DOTS , '/' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns forward - slashed rel path ( only use for better visual logging ) [CODESPLIT] function diff ( rootpath , src ) { return _ . isString ( rootpath ) && _ . isString ( src ) ? src . replace ( rootpath , '' ) . split ( path . sep ) . join ( '/' ) : '' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns rel path of src from root [CODESPLIT] function rel ( root , src , sep ) { if ( ! root || ! _ . isString ( root ) || ! src || ! _ . isString ( src ) ) return let root_split = root . split ( path . sep ) , src_split = src . split ( path . sep ) return _ . join ( _ . difference ( src_split , root_split ) , sep || '/' ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns rel appended to dest root [CODESPLIT] function rebase ( root , src , dest ) { let relp = rel ( root , src ) return relp ? path . join ( dest , relp ) : '' }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PUBLIC API : You can override these methods in a subclass to provide alternative compiled forms for name lookup and buffering semantics [CODESPLIT] function ( parent , name , type ) { if ( JavaScriptCompiler . RESERVED_WORDS [ name ] || name . indexOf ( '-' ) !== - 1 || ! isNaN ( name ) ) { return parent + \"['\" + name + \"']\" ; } else if ( / ^[0-9]+$ / . test ( name ) ) { return parent + \"[\" + name + \"]\" ; } else { return parent + \".\" + name ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "END PUBLIC API [CODESPLIT] function ( environment , options ) { this . environment = environment ; this . options = options || { } ; this . preamble ( ) ; this . stackSlot = 0 ; this . stackVars = [ ] ; this . registers = { list : [ ] } ; this . compileChildren ( environment , options ) ; Handlebars . log ( Handlebars . logger . DEBUG , environment . disassemble ( ) + \"\\n\\n\" ) ; var opcodes = environment . opcodes , opcode , name , declareName , declareVal ; this . i = 0 ; for ( l = opcodes . length ; this . i < l ; this . i ++ ) { opcode = this . nextOpcode ( 0 ) ; if ( opcode [ 0 ] === 'DECLARE' ) { this . i = this . i + 2 ; this [ opcode [ 1 ] ] = opcode [ 2 ] ; } else { this . i = this . i + opcode [ 1 ] . length ; this [ opcode [ 0 ] ] . apply ( this , opcode [ 1 ] ) ; } } return this . createFunction ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 0 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; var _handlebarsRuntime = __webpack_require__ ( 2 ) ; var _handlebarsRuntime2 = _interopRequireDefault ( _handlebarsRuntime ) ; // Compiler imports var _handlebarsCompilerAst = __webpack_require__ ( 21 ) ; var _handlebarsCompilerAst2 = _interopRequireDefault ( _handlebarsCompilerAst ) ; var _handlebarsCompilerBase = __webpack_require__ ( 22 ) ; var _handlebarsCompilerCompiler = __webpack_require__ ( 27 ) ; var _handlebarsCompilerJavascriptCompiler = __webpack_require__ ( 28 ) ; var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault ( _handlebarsCompilerJavascriptCompiler ) ; var _handlebarsCompilerVisitor = __webpack_require__ ( 25 ) ; var _handlebarsCompilerVisitor2 = _interopRequireDefault ( _handlebarsCompilerVisitor ) ; var _handlebarsNoConflict = __webpack_require__ ( 20 ) ; var _handlebarsNoConflict2 = _interopRequireDefault ( _handlebarsNoConflict ) ; var _create = _handlebarsRuntime2 [ 'default' ] . create ; function create ( ) { var hb = _create ( ) ; hb . compile = function ( input , options ) { return _handlebarsCompilerCompiler . compile ( input , options , hb ) ; } ; hb . precompile = function ( input , options ) { return _handlebarsCompilerCompiler . precompile ( input , options , hb ) ; } ; hb . AST = _handlebarsCompilerAst2 [ 'default' ] ; hb . Compiler = _handlebarsCompilerCompiler . Compiler ; hb . JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2 [ 'default' ] ; hb . Parser = _handlebarsCompilerBase . parser ; hb . parse = _handlebarsCompilerBase . parse ; return hb ; } var inst = create ( ) ; inst . create = create ; _handlebarsNoConflict2 [ 'default' ] ( inst ) ; inst . Visitor = _handlebarsCompilerVisitor2 [ 'default' ] ; inst [ 'default' ] = inst ; exports [ 'default' ] = inst ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 1 [CODESPLIT] function ( module , exports ) { \"use strict\" ; exports [ \"default\" ] = function ( obj ) { return obj && obj . __esModule ? obj : { \"default\" : obj } ; } ; exports . __esModule = true ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 2 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireWildcard = __webpack_require__ ( 3 ) [ 'default' ] ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; var _handlebarsBase = __webpack_require__ ( 4 ) ; var base = _interopRequireWildcard ( _handlebarsBase ) ; // Each of these augment the Handlebars object. No need to setup here. // (This is done to easily share code between commonjs and browse envs) var _handlebarsSafeString = __webpack_require__ ( 18 ) ; var _handlebarsSafeString2 = _interopRequireDefault ( _handlebarsSafeString ) ; var _handlebarsException = __webpack_require__ ( 6 ) ; var _handlebarsException2 = _interopRequireDefault ( _handlebarsException ) ; var _handlebarsUtils = __webpack_require__ ( 5 ) ; var Utils = _interopRequireWildcard ( _handlebarsUtils ) ; var _handlebarsRuntime = __webpack_require__ ( 19 ) ; var runtime = _interopRequireWildcard ( _handlebarsRuntime ) ; var _handlebarsNoConflict = __webpack_require__ ( 20 ) ; var _handlebarsNoConflict2 = _interopRequireDefault ( _handlebarsNoConflict ) ; // For compatibility and usage outside of module systems, make the Handlebars object a namespace function create ( ) { var hb = new base . HandlebarsEnvironment ( ) ; Utils . extend ( hb , base ) ; hb . SafeString = _handlebarsSafeString2 [ 'default' ] ; hb . Exception = _handlebarsException2 [ 'default' ] ; hb . Utils = Utils ; hb . escapeExpression = Utils . escapeExpression ; hb . VM = runtime ; hb . template = function ( spec ) { return runtime . template ( spec , hb ) ; } ; return hb ; } var inst = create ( ) ; inst . create = create ; _handlebarsNoConflict2 [ 'default' ] ( inst ) ; inst [ 'default' ] = inst ; exports [ 'default' ] = inst ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 3 [CODESPLIT] function ( module , exports ) { \"use strict\" ; exports [ \"default\" ] = function ( obj ) { if ( obj && obj . __esModule ) { return obj ; } else { var newObj = { } ; if ( obj != null ) { for ( var key in obj ) { if ( Object . prototype . hasOwnProperty . call ( obj , key ) ) newObj [ key ] = obj [ key ] ; } } newObj [ \"default\" ] = obj ; return newObj ; } } ; exports . __esModule = true ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 4 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; exports . HandlebarsEnvironment = HandlebarsEnvironment ; var _utils = __webpack_require__ ( 5 ) ; var _exception = __webpack_require__ ( 6 ) ; var _exception2 = _interopRequireDefault ( _exception ) ; var _helpers = __webpack_require__ ( 7 ) ; var _decorators = __webpack_require__ ( 15 ) ; var _logger = __webpack_require__ ( 17 ) ; var _logger2 = _interopRequireDefault ( _logger ) ; var VERSION = '4.0.5' ; exports . VERSION = VERSION ; var COMPILER_REVISION = 7 ; exports . COMPILER_REVISION = COMPILER_REVISION ; var REVISION_CHANGES = { 1 : '<= 1.0.rc.2' , // 1.0.rc.2 is actually rev2 but doesn't report it 2 : '== 1.0.0-rc.3' , 3 : '== 1.0.0-rc.4' , 4 : '== 1.x.x' , 5 : '== 2.0.0-alpha.x' , 6 : '>= 2.0.0-beta.1' , 7 : '>= 4.0.0' } ; exports . REVISION_CHANGES = REVISION_CHANGES ; var objectType = '[object Object]' ; function HandlebarsEnvironment ( helpers , partials , decorators ) { this . helpers = helpers || { } ; this . partials = partials || { } ; this . decorators = decorators || { } ; _helpers . registerDefaultHelpers ( this ) ; _decorators . registerDefaultDecorators ( this ) ; } HandlebarsEnvironment . prototype = { constructor : HandlebarsEnvironment , logger : _logger2 [ 'default' ] , log : _logger2 [ 'default' ] . log , registerHelper : function registerHelper ( name , fn ) { if ( _utils . toString . call ( name ) === objectType ) { if ( fn ) { throw new _exception2 [ 'default' ] ( 'Arg not supported with multiple helpers' ) ; } _utils . extend ( this . helpers , name ) ; } else { this . helpers [ name ] = fn ; } } , unregisterHelper : function unregisterHelper ( name ) { delete this . helpers [ name ] ; } , registerPartial : function registerPartial ( name , partial ) { if ( _utils . toString . call ( name ) === objectType ) { _utils . extend ( this . partials , name ) ; } else { if ( typeof partial === 'undefined' ) { throw new _exception2 [ 'default' ] ( 'Attempting to register a partial called \"' + name + '\" as undefined' ) ; } this . partials [ name ] = partial ; } } , unregisterPartial : function unregisterPartial ( name ) { delete this . partials [ name ] ; } , registerDecorator : function registerDecorator ( name , fn ) { if ( _utils . toString . call ( name ) === objectType ) { if ( fn ) { throw new _exception2 [ 'default' ] ( 'Arg not supported with multiple decorators' ) ; } _utils . extend ( this . decorators , name ) ; } else { this . decorators [ name ] = fn ; } } , unregisterDecorator : function unregisterDecorator ( name ) { delete this . decorators [ name ] ; } } ; var log = _logger2 [ 'default' ] . log ; exports . log = log ; exports . createFrame = _utils . createFrame ; exports . logger = _logger2 [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 7 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; exports . registerDefaultHelpers = registerDefaultHelpers ; var _helpersBlockHelperMissing = __webpack_require__ ( 8 ) ; var _helpersBlockHelperMissing2 = _interopRequireDefault ( _helpersBlockHelperMissing ) ; var _helpersEach = __webpack_require__ ( 9 ) ; var _helpersEach2 = _interopRequireDefault ( _helpersEach ) ; var _helpersHelperMissing = __webpack_require__ ( 10 ) ; var _helpersHelperMissing2 = _interopRequireDefault ( _helpersHelperMissing ) ; var _helpersIf = __webpack_require__ ( 11 ) ; var _helpersIf2 = _interopRequireDefault ( _helpersIf ) ; var _helpersLog = __webpack_require__ ( 12 ) ; var _helpersLog2 = _interopRequireDefault ( _helpersLog ) ; var _helpersLookup = __webpack_require__ ( 13 ) ; var _helpersLookup2 = _interopRequireDefault ( _helpersLookup ) ; var _helpersWith = __webpack_require__ ( 14 ) ; var _helpersWith2 = _interopRequireDefault ( _helpersWith ) ; function registerDefaultHelpers ( instance ) { _helpersBlockHelperMissing2 [ 'default' ] ( instance ) ; _helpersEach2 [ 'default' ] ( instance ) ; _helpersHelperMissing2 [ 'default' ] ( instance ) ; _helpersIf2 [ 'default' ] ( instance ) ; _helpersLog2 [ 'default' ] ( instance ) ; _helpersLookup2 [ 'default' ] ( instance ) ; _helpersWith2 [ 'default' ] ( instance ) ; } /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 8 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; exports . __esModule = true ; var _utils = __webpack_require__ ( 5 ) ; exports [ 'default' ] = function ( instance ) { instance . registerHelper ( 'blockHelperMissing' , function ( context , options ) { var inverse = options . inverse , fn = options . fn ; if ( context === true ) { return fn ( this ) ; } else if ( context === false || context == null ) { return inverse ( this ) ; } else if ( _utils . isArray ( context ) ) { if ( context . length > 0 ) { if ( options . ids ) { options . ids = [ options . name ] ; } return instance . helpers . each ( context , options ) ; } else { return inverse ( this ) ; } } else { if ( options . data && options . ids ) { var data = _utils . createFrame ( options . data ) ; data . contextPath = _utils . appendContextPath ( options . data . contextPath , options . name ) ; options = { data : data } ; } return fn ( context , options ) ; } } ) ; } ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 9 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; var _utils = __webpack_require__ ( 5 ) ; var _exception = __webpack_require__ ( 6 ) ; var _exception2 = _interopRequireDefault ( _exception ) ; exports [ 'default' ] = function ( instance ) { instance . registerHelper ( 'each' , function ( context , options ) { if ( ! options ) { throw new _exception2 [ 'default' ] ( 'Must pass iterator to #each' ) ; } var fn = options . fn , inverse = options . inverse , i = 0 , ret = '' , data = undefined , contextPath = undefined ; if ( options . data && options . ids ) { contextPath = _utils . appendContextPath ( options . data . contextPath , options . ids [ 0 ] ) + '.' ; } if ( _utils . isFunction ( context ) ) { context = context . call ( this ) ; } if ( options . data ) { data = _utils . createFrame ( options . data ) ; } function execIteration ( field , index , last ) { if ( data ) { data . key = field ; data . index = index ; data . first = index === 0 ; data . last = ! ! last ; if ( contextPath ) { data . contextPath = contextPath + field ; } } ret = ret + fn ( context [ field ] , { data : data , blockParams : _utils . blockParams ( [ context [ field ] , field ] , [ contextPath + field , null ] ) } ) ; } if ( context && typeof context === 'object' ) { if ( _utils . isArray ( context ) ) { for ( var j = context . length ; i < j ; i ++ ) { if ( i in context ) { execIteration ( i , i , i === context . length - 1 ) ; } } } else { var priorKey = undefined ; for ( var key in context ) { if ( context . hasOwnProperty ( key ) ) { // We're running the iterations one step out of sync so we can detect // the last iteration without have to scan the object twice and create // an itermediate keys array. if ( priorKey !== undefined ) { execIteration ( priorKey , i - 1 ) ; } priorKey = key ; i ++ ; } } if ( priorKey !== undefined ) { execIteration ( priorKey , i - 1 , true ) ; } } } if ( i === 0 ) { ret = inverse ( this ) ; } return ret ; } ) ; } ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 10 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; var _exception = __webpack_require__ ( 6 ) ; var _exception2 = _interopRequireDefault ( _exception ) ; exports [ 'default' ] = function ( instance ) { instance . registerHelper ( 'helperMissing' , function ( ) /* [args, ]options */ { if ( arguments . length === 1 ) { // A missing field in a {{foo}} construct. return undefined ; } else { // Someone is actually trying to call something, blow up. throw new _exception2 [ 'default' ] ( 'Missing helper: \"' + arguments [ arguments . length - 1 ] . name + '\"' ) ; } } ) ; } ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 11 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; exports . __esModule = true ; var _utils = __webpack_require__ ( 5 ) ; exports [ 'default' ] = function ( instance ) { instance . registerHelper ( 'if' , function ( conditional , options ) { if ( _utils . isFunction ( conditional ) ) { conditional = conditional . call ( this ) ; } // Default behavior is to render the positive path if the value is truthy and not empty. // The `includeZero` option may be set to treat the condtional as purely not empty based on the // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative. if ( ! options . hash . includeZero && ! conditional || _utils . isEmpty ( conditional ) ) { return options . inverse ( this ) ; } else { return options . fn ( this ) ; } } ) ; instance . registerHelper ( 'unless' , function ( conditional , options ) { return instance . helpers [ 'if' ] . call ( this , conditional , { fn : options . inverse , inverse : options . fn , hash : options . hash } ) ; } ) ; } ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 12 [CODESPLIT] function ( module , exports ) { 'use strict' ; exports . __esModule = true ; exports [ 'default' ] = function ( instance ) { instance . registerHelper ( 'log' , function ( ) /* message, options */ { var args = [ undefined ] , options = arguments [ arguments . length - 1 ] ; for ( var i = 0 ; i < arguments . length - 1 ; i ++ ) { args . push ( arguments [ i ] ) ; } var level = 1 ; if ( options . hash . level != null ) { level = options . hash . level ; } else if ( options . data && options . data . level != null ) { level = options . data . level ; } args [ 0 ] = level ; instance . log . apply ( instance , args ) ; } ) ; } ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 13 [CODESPLIT] function ( module , exports ) { 'use strict' ; exports . __esModule = true ; exports [ 'default' ] = function ( instance ) { instance . registerHelper ( 'lookup' , function ( obj , field ) { return obj && obj [ field ] ; } ) ; } ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 14 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; exports . __esModule = true ; var _utils = __webpack_require__ ( 5 ) ; exports [ 'default' ] = function ( instance ) { instance . registerHelper ( 'with' , function ( context , options ) { if ( _utils . isFunction ( context ) ) { context = context . call ( this ) ; } var fn = options . fn ; if ( ! _utils . isEmpty ( context ) ) { var data = options . data ; if ( options . data && options . ids ) { data = _utils . createFrame ( options . data ) ; data . contextPath = _utils . appendContextPath ( options . data . contextPath , options . ids [ 0 ] ) ; } return fn ( context , { data : data , blockParams : _utils . blockParams ( [ context ] , [ data && data . contextPath ] ) } ) ; } else { return options . inverse ( this ) ; } } ) ; } ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 15 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; exports . registerDefaultDecorators = registerDefaultDecorators ; var _decoratorsInline = __webpack_require__ ( 16 ) ; var _decoratorsInline2 = _interopRequireDefault ( _decoratorsInline ) ; function registerDefaultDecorators ( instance ) { _decoratorsInline2 [ 'default' ] ( instance ) ; } /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 16 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; exports . __esModule = true ; var _utils = __webpack_require__ ( 5 ) ; exports [ 'default' ] = function ( instance ) { instance . registerDecorator ( 'inline' , function ( fn , props , container , options ) { var ret = fn ; if ( ! props . partials ) { props . partials = { } ; ret = function ( context , options ) { // Create a new partials stack frame prior to exec. var original = container . partials ; container . partials = _utils . extend ( { } , original , props . partials ) ; var ret = fn ( context , options ) ; container . partials = original ; return ret ; } ; } props . partials [ options . args [ 0 ] ] = options . fn ; return ret ; } ) ; } ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 17 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; exports . __esModule = true ; var _utils = __webpack_require__ ( 5 ) ; var logger = { methodMap : [ 'debug' , 'info' , 'warn' , 'error' ] , level : 'info' , // Maps a given level value to the `methodMap` indexes above. lookupLevel : function lookupLevel ( level ) { if ( typeof level === 'string' ) { var levelMap = _utils . indexOf ( logger . methodMap , level . toLowerCase ( ) ) ; if ( levelMap >= 0 ) { level = levelMap ; } else { level = parseInt ( level , 10 ) ; } } return level ; } , // Can be overridden in the host environment log : function log ( level ) { level = logger . lookupLevel ( level ) ; if ( typeof console !== 'undefined' && logger . lookupLevel ( logger . level ) <= level ) { var method = logger . methodMap [ level ] ; if ( ! console [ method ] ) { // eslint-disable-line no-console method = 'log' ; } for ( var _len = arguments . length , message = Array ( _len > 1 ? _len - 1 : 0 ) , _key = 1 ; _key < _len ; _key ++ ) { message [ _key - 1 ] = arguments [ _key ] ; } console [ method ] . apply ( console , message ) ; // eslint-disable-line no-console } } } ; exports [ 'default' ] = logger ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a given level value to the methodMap indexes above . [CODESPLIT] function lookupLevel ( level ) { if ( typeof level === 'string' ) { var levelMap = _utils . indexOf ( logger . methodMap , level . toLowerCase ( ) ) ; if ( levelMap >= 0 ) { level = levelMap ; } else { level = parseInt ( level , 10 ) ; } } return level ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Can be overridden in the host environment [CODESPLIT] function log ( level ) { level = logger . lookupLevel ( level ) ; if ( typeof console !== 'undefined' && logger . lookupLevel ( logger . level ) <= level ) { var method = logger . methodMap [ level ] ; if ( ! console [ method ] ) { // eslint-disable-line no-console method = 'log' ; } for ( var _len = arguments . length , message = Array ( _len > 1 ? _len - 1 : 0 ) , _key = 1 ; _key < _len ; _key ++ ) { message [ _key - 1 ] = arguments [ _key ] ; } console [ method ] . apply ( console , message ) ; // eslint-disable-line no-console } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 18 [CODESPLIT] function ( module , exports ) { // Build out our basic SafeString type 'use strict' ; exports . __esModule = true ; function SafeString ( string ) { this . string = string ; } SafeString . prototype . toString = SafeString . prototype . toHTML = function ( ) { return '' + this . string ; } ; exports [ 'default' ] = SafeString ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 19 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireWildcard = __webpack_require__ ( 3 ) [ 'default' ] ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; exports . checkRevision = checkRevision ; exports . template = template ; exports . wrapProgram = wrapProgram ; exports . resolvePartial = resolvePartial ; exports . invokePartial = invokePartial ; exports . noop = noop ; var _utils = __webpack_require__ ( 5 ) ; var Utils = _interopRequireWildcard ( _utils ) ; var _exception = __webpack_require__ ( 6 ) ; var _exception2 = _interopRequireDefault ( _exception ) ; var _base = __webpack_require__ ( 4 ) ; function checkRevision ( compilerInfo ) { var compilerRevision = compilerInfo && compilerInfo [ 0 ] || 1 , currentRevision = _base . COMPILER_REVISION ; if ( compilerRevision !== currentRevision ) { if ( compilerRevision < currentRevision ) { var runtimeVersions = _base . REVISION_CHANGES [ currentRevision ] , compilerVersions = _base . REVISION_CHANGES [ compilerRevision ] ; throw new _exception2 [ 'default' ] ( 'Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').' ) ; } else { // Use the embedded version info since the runtime doesn't know about this revision yet throw new _exception2 [ 'default' ] ( 'Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo [ 1 ] + ').' ) ; } } } function template ( templateSpec , env ) { /* istanbul ignore next */ if ( ! env ) { throw new _exception2 [ 'default' ] ( 'No environment passed to template' ) ; } if ( ! templateSpec || ! templateSpec . main ) { throw new _exception2 [ 'default' ] ( 'Unknown template object: ' + typeof templateSpec ) ; } templateSpec . main . decorator = templateSpec . main_d ; // Note: Using env.VM references rather than local var references throughout this section to allow // for external users to override these as psuedo-supported APIs. env . VM . checkRevision ( templateSpec . compiler ) ; function invokePartialWrapper ( partial , context , options ) { if ( options . hash ) { context = Utils . extend ( { } , context , options . hash ) ; if ( options . ids ) { options . ids [ 0 ] = true ; } } partial = env . VM . resolvePartial . call ( this , partial , context , options ) ; var result = env . VM . invokePartial . call ( this , partial , context , options ) ; if ( result == null && env . compile ) { options . partials [ options . name ] = env . compile ( partial , templateSpec . compilerOptions , env ) ; result = options . partials [ options . name ] ( context , options ) ; } if ( result != null ) { if ( options . indent ) { var lines = result . split ( '\\n' ) ; for ( var i = 0 , l = lines . length ; i < l ; i ++ ) { if ( ! lines [ i ] && i + 1 === l ) { break ; } lines [ i ] = options . indent + lines [ i ] ; } result = lines . join ( '\\n' ) ; } return result ; } else { throw new _exception2 [ 'default' ] ( 'The partial ' + options . name + ' could not be compiled when running in runtime-only mode' ) ; } } // Just add water var container = { strict : function strict ( obj , name ) { if ( ! ( name in obj ) ) { throw new _exception2 [ 'default' ] ( '\"' + name + '\" not defined in ' + obj ) ; } return obj [ name ] ; } , lookup : function lookup ( depths , name ) { var len = depths . length ; for ( var i = 0 ; i < len ; i ++ ) { if ( depths [ i ] && depths [ i ] [ name ] != null ) { return depths [ i ] [ name ] ; } } } , lambda : function lambda ( current , context ) { return typeof current === 'function' ? current . call ( context ) : current ; } , escapeExpression : Utils . escapeExpression , invokePartial : invokePartialWrapper , fn : function fn ( i ) { var ret = templateSpec [ i ] ; ret . decorator = templateSpec [ i + '_d' ] ; return ret ; } , programs : [ ] , program : function program ( i , data , declaredBlockParams , blockParams , depths ) { var programWrapper = this . programs [ i ] , fn = this . fn ( i ) ; if ( data || depths || blockParams || declaredBlockParams ) { programWrapper = wrapProgram ( this , i , fn , data , declaredBlockParams , blockParams , depths ) ; } else if ( ! programWrapper ) { programWrapper = this . programs [ i ] = wrapProgram ( this , i , fn ) ; } return programWrapper ; } , data : function data ( value , depth ) { while ( value && depth -- ) { value = value . _parent ; } return value ; } , merge : function merge ( param , common ) { var obj = param || common ; if ( param && common && param !== common ) { obj = Utils . extend ( { } , common , param ) ; } return obj ; } , noop : env . VM . noop , compilerInfo : templateSpec . compiler } ; function ret ( context ) { var options = arguments . length <= 1 || arguments [ 1 ] === undefined ? { } : arguments [ 1 ] ; var data = options . data ; ret . _setup ( options ) ; if ( ! options . partial && templateSpec . useData ) { data = initData ( context , data ) ; } var depths = undefined , blockParams = templateSpec . useBlockParams ? [ ] : undefined ; if ( templateSpec . useDepths ) { if ( options . depths ) { depths = context !== options . depths [ 0 ] ? [ context ] . concat ( options . depths ) : options . depths ; } else { depths = [ context ] ; } } function main ( context /*, options*/ ) { return '' + templateSpec . main ( container , context , container . helpers , container . partials , data , blockParams , depths ) ; } main = executeDecorators ( templateSpec . main , main , container , options . depths || [ ] , data , blockParams ) ; return main ( context , options ) ; } ret . isTop = true ; ret . _setup = function ( options ) { if ( ! options . partial ) { container . helpers = container . merge ( options . helpers , env . helpers ) ; if ( templateSpec . usePartial ) { container . partials = container . merge ( options . partials , env . partials ) ; } if ( templateSpec . usePartial || templateSpec . useDecorators ) { container . decorators = container . merge ( options . decorators , env . decorators ) ; } } else { container . helpers = options . helpers ; container . partials = options . partials ; container . decorators = options . decorators ; } } ; ret . _child = function ( i , data , blockParams , depths ) { if ( templateSpec . useBlockParams && ! blockParams ) { throw new _exception2 [ 'default' ] ( 'must pass block params' ) ; } if ( templateSpec . useDepths && ! depths ) { throw new _exception2 [ 'default' ] ( 'must pass parent depths' ) ; } return wrapProgram ( container , i , templateSpec [ i ] , data , 0 , blockParams , depths ) ; } ; return ret ; } function wrapProgram ( container , i , fn , data , declaredBlockParams , blockParams , depths ) { function prog ( context ) { var options = arguments . length <= 1 || arguments [ 1 ] === undefined ? { } : arguments [ 1 ] ; var currentDepths = depths ; if ( depths && context !== depths [ 0 ] ) { currentDepths = [ context ] . concat ( depths ) ; } return fn ( container , context , container . helpers , container . partials , options . data || data , blockParams && [ options . blockParams ] . concat ( blockParams ) , currentDepths ) ; } prog = executeDecorators ( fn , prog , container , depths , data , blockParams ) ; prog . program = i ; prog . depth = depths ? depths . length : 0 ; prog . blockParams = declaredBlockParams || 0 ; return prog ; } function resolvePartial ( partial , context , options ) { if ( ! partial ) { if ( options . name === '@partial-block' ) { partial = options . data [ 'partial-block' ] ; } else { partial = options . partials [ options . name ] ; } } else if ( ! partial . call && ! options . name ) { // This is a dynamic partial that returned a string options . name = partial ; partial = options . partials [ partial ] ; } return partial ; } function invokePartial ( partial , context , options ) { options . partial = true ; if ( options . ids ) { options . data . contextPath = options . ids [ 0 ] || options . data . contextPath ; } var partialBlock = undefined ; if ( options . fn && options . fn !== noop ) { options . data = _base . createFrame ( options . data ) ; partialBlock = options . data [ 'partial-block' ] = options . fn ; if ( partialBlock . partials ) { options . partials = Utils . extend ( { } , options . partials , partialBlock . partials ) ; } } if ( partial === undefined && partialBlock ) { partial = partialBlock ; } if ( partial === undefined ) { throw new _exception2 [ 'default' ] ( 'The partial ' + options . name + ' could not be found' ) ; } else if ( partial instanceof Function ) { return partial ( context , options ) ; } } function noop ( ) { return '' ; } function initData ( context , data ) { if ( ! data || ! ( 'root' in data ) ) { data = data ? _base . createFrame ( data ) : { } ; data . root = context ; } return data ; } function executeDecorators ( fn , prog , container , depths , data , blockParams ) { if ( fn . decorator ) { var props = { } ; prog = fn . decorator ( prog , props , container , depths && depths [ 0 ] , data , blockParams , depths ) ; Utils . extend ( prog , props ) ; } return prog ; } /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 20 [CODESPLIT] function ( module , exports ) { /* WEBPACK VAR INJECTION */ ( function ( global ) { /* global window */ 'use strict' ; exports . __esModule = true ; exports [ 'default' ] = function ( Handlebars ) { /* istanbul ignore next */ var root = typeof global !== 'undefined' ? global : window , $Handlebars = root . Handlebars ; /* istanbul ignore next */ Handlebars . noConflict = function ( ) { if ( root . Handlebars === Handlebars ) { root . Handlebars = $Handlebars ; } return Handlebars ; } ; } ; module . exports = exports [ 'default' ] ; /* WEBPACK VAR INJECTION */ } . call ( exports , ( function ( ) { return this ; } ( ) ) ) ) /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 21 [CODESPLIT] function ( module , exports ) { 'use strict' ; exports . __esModule = true ; var AST = { // Public API used to evaluate derived attributes regarding AST nodes helpers : { // a mustache is definitely a helper if: // * it is an eligible helper, and // * it has at least one parameter or hash segment helperExpression : function helperExpression ( node ) { return node . type === 'SubExpression' || ( node . type === 'MustacheStatement' || node . type === 'BlockStatement' ) && ! ! ( node . params && node . params . length || node . hash ) ; } , scopedId : function scopedId ( path ) { return ( / ^\\.|this\\b / . test ( path . original ) ) ; } , // an ID is simple if it only has one part, and that part is not // `..` or `this`. simpleId : function simpleId ( path ) { return path . parts . length === 1 && ! AST . helpers . scopedId ( path ) && ! path . depth ; } } } ; // Must be exported as an object rather than the root of the module as the jison lexer // must modify the object to operate properly. exports [ 'default' ] = AST ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a mustache is definitely a helper if : * it is an eligible helper and * it has at least one parameter or hash segment [CODESPLIT] function helperExpression ( node ) { return node . type === 'SubExpression' || ( node . type === 'MustacheStatement' || node . type === 'BlockStatement' ) && ! ! ( node . params && node . params . length || node . hash ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "an ID is simple if it only has one part and that part is not .. or this . [CODESPLIT] function simpleId ( path ) { return path . parts . length === 1 && ! AST . helpers . scopedId ( path ) && ! path . depth ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 22 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; var _interopRequireWildcard = __webpack_require__ ( 3 ) [ 'default' ] ; exports . __esModule = true ; exports . parse = parse ; var _parser = __webpack_require__ ( 23 ) ; var _parser2 = _interopRequireDefault ( _parser ) ; var _whitespaceControl = __webpack_require__ ( 24 ) ; var _whitespaceControl2 = _interopRequireDefault ( _whitespaceControl ) ; var _helpers = __webpack_require__ ( 26 ) ; var Helpers = _interopRequireWildcard ( _helpers ) ; var _utils = __webpack_require__ ( 5 ) ; exports . parser = _parser2 [ 'default' ] ; var yy = { } ; _utils . extend ( yy , Helpers ) ; function parse ( input , options ) { // Just return if an already-compiled AST was passed in. if ( input . type === 'Program' ) { return input ; } _parser2 [ 'default' ] . yy = yy ; // Altering the shared object here, but this is ok as parser is a sync operation yy . locInfo = function ( locInfo ) { return new yy . SourceLocation ( options && options . srcName , locInfo ) ; } ; var strip = new _whitespaceControl2 [ 'default' ] ( options ) ; return strip . accept ( _parser2 [ 'default' ] . parse ( input ) ) ; } /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 24 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; var _visitor = __webpack_require__ ( 25 ) ; var _visitor2 = _interopRequireDefault ( _visitor ) ; function WhitespaceControl ( ) { var options = arguments . length <= 0 || arguments [ 0 ] === undefined ? { } : arguments [ 0 ] ; this . options = options ; } WhitespaceControl . prototype = new _visitor2 [ 'default' ] ( ) ; WhitespaceControl . prototype . Program = function ( program ) { var doStandalone = ! this . options . ignoreStandalone ; var isRoot = ! this . isRootSeen ; this . isRootSeen = true ; var body = program . body ; for ( var i = 0 , l = body . length ; i < l ; i ++ ) { var current = body [ i ] , strip = this . accept ( current ) ; if ( ! strip ) { continue ; } var _isPrevWhitespace = isPrevWhitespace ( body , i , isRoot ) , _isNextWhitespace = isNextWhitespace ( body , i , isRoot ) , openStandalone = strip . openStandalone && _isPrevWhitespace , closeStandalone = strip . closeStandalone && _isNextWhitespace , inlineStandalone = strip . inlineStandalone && _isPrevWhitespace && _isNextWhitespace ; if ( strip . close ) { omitRight ( body , i , true ) ; } if ( strip . open ) { omitLeft ( body , i , true ) ; } if ( doStandalone && inlineStandalone ) { omitRight ( body , i ) ; if ( omitLeft ( body , i ) ) { // If we are on a standalone node, save the indent info for partials if ( current . type === 'PartialStatement' ) { // Pull out the whitespace from the final line current . indent = / ([ \\t]+$) / . exec ( body [ i - 1 ] . original ) [ 1 ] ; } } } if ( doStandalone && openStandalone ) { omitRight ( ( current . program || current . inverse ) . body ) ; // Strip out the previous content node if it's whitespace only omitLeft ( body , i ) ; } if ( doStandalone && closeStandalone ) { // Always strip the next node omitRight ( body , i ) ; omitLeft ( ( current . inverse || current . program ) . body ) ; } } return program ; } ; WhitespaceControl . prototype . BlockStatement = WhitespaceControl . prototype . DecoratorBlock = WhitespaceControl . prototype . PartialBlockStatement = function ( block ) { this . accept ( block . program ) ; this . accept ( block . inverse ) ; // Find the inverse program that is involed with whitespace stripping. var program = block . program || block . inverse , inverse = block . program && block . inverse , firstInverse = inverse , lastInverse = inverse ; if ( inverse && inverse . chained ) { firstInverse = inverse . body [ 0 ] . program ; // Walk the inverse chain to find the last inverse that is actually in the chain. while ( lastInverse . chained ) { lastInverse = lastInverse . body [ lastInverse . body . length - 1 ] . program ; } } var strip = { open : block . openStrip . open , close : block . closeStrip . close , // Determine the standalone candiacy. Basically flag our content as being possibly standalone // so our parent can determine if we actually are standalone openStandalone : isNextWhitespace ( program . body ) , closeStandalone : isPrevWhitespace ( ( firstInverse || program ) . body ) } ; if ( block . openStrip . close ) { omitRight ( program . body , null , true ) ; } if ( inverse ) { var inverseStrip = block . inverseStrip ; if ( inverseStrip . open ) { omitLeft ( program . body , null , true ) ; } if ( inverseStrip . close ) { omitRight ( firstInverse . body , null , true ) ; } if ( block . closeStrip . open ) { omitLeft ( lastInverse . body , null , true ) ; } // Find standalone else statments if ( ! this . options . ignoreStandalone && isPrevWhitespace ( program . body ) && isNextWhitespace ( firstInverse . body ) ) { omitLeft ( program . body ) ; omitRight ( firstInverse . body ) ; } } else if ( block . closeStrip . open ) { omitLeft ( program . body , null , true ) ; } return strip ; } ; WhitespaceControl . prototype . Decorator = WhitespaceControl . prototype . MustacheStatement = function ( mustache ) { return mustache . strip ; } ; WhitespaceControl . prototype . PartialStatement = WhitespaceControl . prototype . CommentStatement = function ( node ) { /* istanbul ignore next */ var strip = node . strip || { } ; return { inlineStandalone : true , open : strip . open , close : strip . close } ; } ; function isPrevWhitespace ( body , i , isRoot ) { if ( i === undefined ) { i = body . length ; } // Nodes that end with newlines are considered whitespace (but are special // cased for strip operations) var prev = body [ i - 1 ] , sibling = body [ i - 2 ] ; if ( ! prev ) { return isRoot ; } if ( prev . type === 'ContentStatement' ) { return ( sibling || ! isRoot ? / \\r?\\n\\s*?$ / : / (^|\\r?\\n)\\s*?$ / ) . test ( prev . original ) ; } } function isNextWhitespace ( body , i , isRoot ) { if ( i === undefined ) { i = - 1 ; } var next = body [ i + 1 ] , sibling = body [ i + 2 ] ; if ( ! next ) { return isRoot ; } if ( next . type === 'ContentStatement' ) { return ( sibling || ! isRoot ? / ^\\s*?\\r?\\n / : / ^\\s*?(\\r?\\n|$) / ) . test ( next . original ) ; } } // Marks the node to the right of the position as omitted. // I.e. {{foo}}' ' will mark the ' ' node as omitted. // // If i is undefined, then the first child will be marked as such. // // If mulitple is truthy then all whitespace will be stripped out until non-whitespace // content is met. function omitRight ( body , i , multiple ) { var current = body [ i == null ? 0 : i + 1 ] ; if ( ! current || current . type !== 'ContentStatement' || ! multiple && current . rightStripped ) { return ; } var original = current . value ; current . value = current . value . replace ( multiple ? / ^\\s+ / : / ^[ \\t]*\\r?\\n? / , '' ) ; current . rightStripped = current . value !== original ; } // Marks the node to the left of the position as omitted. // I.e. ' '{{foo}} will mark the ' ' node as omitted. // // If i is undefined then the last child will be marked as such. // // If mulitple is truthy then all whitespace will be stripped out until non-whitespace // content is met. function omitLeft ( body , i , multiple ) { var current = body [ i == null ? body . length - 1 : i - 1 ] ; if ( ! current || current . type !== 'ContentStatement' || ! multiple && current . leftStripped ) { return ; } // We omit the last node if it's whitespace only and not preceeded by a non-content node. var original = current . value ; current . value = current . value . replace ( multiple ? / \\s+$ / : / [ \\t]+$ / , '' ) ; current . leftStripped = current . value !== original ; return current . leftStripped ; } exports [ 'default' ] = WhitespaceControl ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 25 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; var _exception = __webpack_require__ ( 6 ) ; var _exception2 = _interopRequireDefault ( _exception ) ; function Visitor ( ) { this . parents = [ ] ; } Visitor . prototype = { constructor : Visitor , mutating : false , // Visits a given value. If mutating, will replace the value if necessary. acceptKey : function acceptKey ( node , name ) { var value = this . accept ( node [ name ] ) ; if ( this . mutating ) { // Hacky sanity check: This may have a few false positives for type for the helper // methods but will generally do the right thing without a lot of overhead. if ( value && ! Visitor . prototype [ value . type ] ) { throw new _exception2 [ 'default' ] ( 'Unexpected node type \"' + value . type + '\" found when accepting ' + name + ' on ' + node . type ) ; } node [ name ] = value ; } } , // Performs an accept operation with added sanity check to ensure // required keys are not removed. acceptRequired : function acceptRequired ( node , name ) { this . acceptKey ( node , name ) ; if ( ! node [ name ] ) { throw new _exception2 [ 'default' ] ( node . type + ' requires ' + name ) ; } } , // Traverses a given array. If mutating, empty respnses will be removed // for child elements. acceptArray : function acceptArray ( array ) { for ( var i = 0 , l = array . length ; i < l ; i ++ ) { this . acceptKey ( array , i ) ; if ( ! array [ i ] ) { array . splice ( i , 1 ) ; i -- ; l -- ; } } } , accept : function accept ( object ) { if ( ! object ) { return ; } /* istanbul ignore next: Sanity code */ if ( ! this [ object . type ] ) { throw new _exception2 [ 'default' ] ( 'Unknown type: ' + object . type , object ) ; } if ( this . current ) { this . parents . unshift ( this . current ) ; } this . current = object ; var ret = this [ object . type ] ( object ) ; this . current = this . parents . shift ( ) ; if ( ! this . mutating || ret ) { return ret ; } else if ( ret !== false ) { return object ; } } , Program : function Program ( program ) { this . acceptArray ( program . body ) ; } , MustacheStatement : visitSubExpression , Decorator : visitSubExpression , BlockStatement : visitBlock , DecoratorBlock : visitBlock , PartialStatement : visitPartial , PartialBlockStatement : function PartialBlockStatement ( partial ) { visitPartial . call ( this , partial ) ; this . acceptKey ( partial , 'program' ) ; } , ContentStatement : function ContentStatement ( ) /* content */ { } , CommentStatement : function CommentStatement ( ) /* comment */ { } , SubExpression : visitSubExpression , PathExpression : function PathExpression ( ) /* path */ { } , StringLiteral : function StringLiteral ( ) /* string */ { } , NumberLiteral : function NumberLiteral ( ) /* number */ { } , BooleanLiteral : function BooleanLiteral ( ) /* bool */ { } , UndefinedLiteral : function UndefinedLiteral ( ) /* literal */ { } , NullLiteral : function NullLiteral ( ) /* literal */ { } , Hash : function Hash ( hash ) { this . acceptArray ( hash . pairs ) ; } , HashPair : function HashPair ( pair ) { this . acceptRequired ( pair , 'value' ) ; } } ; function visitSubExpression ( mustache ) { this . acceptRequired ( mustache , 'path' ) ; this . acceptArray ( mustache . params ) ; this . acceptKey ( mustache , 'hash' ) ; } function visitBlock ( block ) { visitSubExpression . call ( this , block ) ; this . acceptKey ( block , 'program' ) ; this . acceptKey ( block , 'inverse' ) ; } function visitPartial ( partial ) { this . acceptRequired ( partial , 'name' ) ; this . acceptArray ( partial . params ) ; this . acceptKey ( partial , 'hash' ) ; } exports [ 'default' ] = Visitor ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a given value . If mutating will replace the value if necessary . [CODESPLIT] function acceptKey ( node , name ) { var value = this . accept ( node [ name ] ) ; if ( this . mutating ) { // Hacky sanity check: This may have a few false positives for type for the helper // methods but will generally do the right thing without a lot of overhead. if ( value && ! Visitor . prototype [ value . type ] ) { throw new _exception2 [ 'default' ] ( 'Unexpected node type \"' + value . type + '\" found when accepting ' + name + ' on ' + node . type ) ; } node [ name ] = value ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an accept operation with added sanity check to ensure required keys are not removed . [CODESPLIT] function acceptRequired ( node , name ) { this . acceptKey ( node , name ) ; if ( ! node [ name ] ) { throw new _exception2 [ 'default' ] ( node . type + ' requires ' + name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Traverses a given array . If mutating empty respnses will be removed for child elements . [CODESPLIT] function acceptArray ( array ) { for ( var i = 0 , l = array . length ; i < l ; i ++ ) { this . acceptKey ( array , i ) ; if ( ! array [ i ] ) { array . splice ( i , 1 ) ; i -- ; l -- ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 26 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; exports . SourceLocation = SourceLocation ; exports . id = id ; exports . stripFlags = stripFlags ; exports . stripComment = stripComment ; exports . preparePath = preparePath ; exports . prepareMustache = prepareMustache ; exports . prepareRawBlock = prepareRawBlock ; exports . prepareBlock = prepareBlock ; exports . prepareProgram = prepareProgram ; exports . preparePartialBlock = preparePartialBlock ; var _exception = __webpack_require__ ( 6 ) ; var _exception2 = _interopRequireDefault ( _exception ) ; function validateClose ( open , close ) { close = close . path ? close . path . original : close ; if ( open . path . original !== close ) { var errorNode = { loc : open . path . loc } ; throw new _exception2 [ 'default' ] ( open . path . original + \" doesn't match \" + close , errorNode ) ; } } function SourceLocation ( source , locInfo ) { this . source = source ; this . start = { line : locInfo . first_line , column : locInfo . first_column } ; this . end = { line : locInfo . last_line , column : locInfo . last_column } ; } function id ( token ) { if ( / ^\\[.*\\]$ / . test ( token ) ) { return token . substr ( 1 , token . length - 2 ) ; } else { return token ; } } function stripFlags ( open , close ) { return { open : open . charAt ( 2 ) === '~' , close : close . charAt ( close . length - 3 ) === '~' } ; } function stripComment ( comment ) { return comment . replace ( / ^\\{\\{~?\\!-?-? / , '' ) . replace ( / -?-?~?\\}\\}$ / , '' ) ; } function preparePath ( data , parts , loc ) { loc = this . locInfo ( loc ) ; var original = data ? '@' : '' , dig = [ ] , depth = 0 , depthString = '' ; for ( var i = 0 , l = parts . length ; i < l ; i ++ ) { var part = parts [ i ] . part , // If we have [] syntax then we do not treat path references as operators, // i.e. foo.[this] resolves to approximately context.foo['this'] isLiteral = parts [ i ] . original !== part ; original += ( parts [ i ] . separator || '' ) + part ; if ( ! isLiteral && ( part === '..' || part === '.' || part === 'this' ) ) { if ( dig . length > 0 ) { throw new _exception2 [ 'default' ] ( 'Invalid path: ' + original , { loc : loc } ) ; } else if ( part === '..' ) { depth ++ ; depthString += '../' ; } } else { dig . push ( part ) ; } } return { type : 'PathExpression' , data : data , depth : depth , parts : dig , original : original , loc : loc } ; } function prepareMustache ( path , params , hash , open , strip , locInfo ) { // Must use charAt to support IE pre-10 var escapeFlag = open . charAt ( 3 ) || open . charAt ( 2 ) , escaped = escapeFlag !== '{' && escapeFlag !== '&' ; var decorator = / \\* / . test ( open ) ; return { type : decorator ? 'Decorator' : 'MustacheStatement' , path : path , params : params , hash : hash , escaped : escaped , strip : strip , loc : this . locInfo ( locInfo ) } ; } function prepareRawBlock ( openRawBlock , contents , close , locInfo ) { validateClose ( openRawBlock , close ) ; locInfo = this . locInfo ( locInfo ) ; var program = { type : 'Program' , body : contents , strip : { } , loc : locInfo } ; return { type : 'BlockStatement' , path : openRawBlock . path , params : openRawBlock . params , hash : openRawBlock . hash , program : program , openStrip : { } , inverseStrip : { } , closeStrip : { } , loc : locInfo } ; } function prepareBlock ( openBlock , program , inverseAndProgram , close , inverted , locInfo ) { if ( close && close . path ) { validateClose ( openBlock , close ) ; } var decorator = / \\* / . test ( openBlock . open ) ; program . blockParams = openBlock . blockParams ; var inverse = undefined , inverseStrip = undefined ; if ( inverseAndProgram ) { if ( decorator ) { throw new _exception2 [ 'default' ] ( 'Unexpected inverse block on decorator' , inverseAndProgram ) ; } if ( inverseAndProgram . chain ) { inverseAndProgram . program . body [ 0 ] . closeStrip = close . strip ; } inverseStrip = inverseAndProgram . strip ; inverse = inverseAndProgram . program ; } if ( inverted ) { inverted = inverse ; inverse = program ; program = inverted ; } return { type : decorator ? 'DecoratorBlock' : 'BlockStatement' , path : openBlock . path , params : openBlock . params , hash : openBlock . hash , program : program , inverse : inverse , openStrip : openBlock . strip , inverseStrip : inverseStrip , closeStrip : close && close . strip , loc : this . locInfo ( locInfo ) } ; } function prepareProgram ( statements , loc ) { if ( ! loc && statements . length ) { var firstLoc = statements [ 0 ] . loc , lastLoc = statements [ statements . length - 1 ] . loc ; /* istanbul ignore else */ if ( firstLoc && lastLoc ) { loc = { source : firstLoc . source , start : { line : firstLoc . start . line , column : firstLoc . start . column } , end : { line : lastLoc . end . line , column : lastLoc . end . column } } ; } } return { type : 'Program' , body : statements , strip : { } , loc : loc } ; } function preparePartialBlock ( open , program , close , locInfo ) { validateClose ( open , close ) ; return { type : 'PartialBlockStatement' , name : open . path , params : open . params , hash : open . hash , program : program , openStrip : open . strip , closeStrip : close && close . strip , loc : this . locInfo ( locInfo ) } ; } /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 27 [CODESPLIT] function ( module , exports , __webpack_require__ ) { /* eslint-disable new-cap */ 'use strict' ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; exports . Compiler = Compiler ; exports . precompile = precompile ; exports . compile = compile ; var _exception = __webpack_require__ ( 6 ) ; var _exception2 = _interopRequireDefault ( _exception ) ; var _utils = __webpack_require__ ( 5 ) ; var _ast = __webpack_require__ ( 21 ) ; var _ast2 = _interopRequireDefault ( _ast ) ; var slice = [ ] . slice ; function Compiler ( ) { } // the foundHelper register will disambiguate helper lookup from finding a // function in a context. This is necessary for mustache compatibility, which // requires that context functions in blocks are evaluated by blockHelperMissing, // and then proceed as if the resulting value was provided to blockHelperMissing. Compiler . prototype = { compiler : Compiler , equals : function equals ( other ) { var len = this . opcodes . length ; if ( other . opcodes . length !== len ) { return false ; } for ( var i = 0 ; i < len ; i ++ ) { var opcode = this . opcodes [ i ] , otherOpcode = other . opcodes [ i ] ; if ( opcode . opcode !== otherOpcode . opcode || ! argEquals ( opcode . args , otherOpcode . args ) ) { return false ; } } // We know that length is the same between the two arrays because they are directly tied // to the opcode behavior above. len = this . children . length ; for ( var i = 0 ; i < len ; i ++ ) { if ( ! this . children [ i ] . equals ( other . children [ i ] ) ) { return false ; } } return true ; } , guid : 0 , compile : function compile ( program , options ) { this . sourceNode = [ ] ; this . opcodes = [ ] ; this . children = [ ] ; this . options = options ; this . stringParams = options . stringParams ; this . trackIds = options . trackIds ; options . blockParams = options . blockParams || [ ] ; // These changes will propagate to the other compiler components var knownHelpers = options . knownHelpers ; options . knownHelpers = { 'helperMissing' : true , 'blockHelperMissing' : true , 'each' : true , 'if' : true , 'unless' : true , 'with' : true , 'log' : true , 'lookup' : true } ; if ( knownHelpers ) { for ( var _name in knownHelpers ) { /* istanbul ignore else */ if ( _name in knownHelpers ) { options . knownHelpers [ _name ] = knownHelpers [ _name ] ; } } } return this . accept ( program ) ; } , compileProgram : function compileProgram ( program ) { var childCompiler = new this . compiler ( ) , // eslint-disable-line new-cap result = childCompiler . compile ( program , this . options ) , guid = this . guid ++ ; this . usePartial = this . usePartial || result . usePartial ; this . children [ guid ] = result ; this . useDepths = this . useDepths || result . useDepths ; return guid ; } , accept : function accept ( node ) { /* istanbul ignore next: Sanity code */ if ( ! this [ node . type ] ) { throw new _exception2 [ 'default' ] ( 'Unknown type: ' + node . type , node ) ; } this . sourceNode . unshift ( node ) ; var ret = this [ node . type ] ( node ) ; this . sourceNode . shift ( ) ; return ret ; } , Program : function Program ( program ) { this . options . blockParams . unshift ( program . blockParams ) ; var body = program . body , bodyLength = body . length ; for ( var i = 0 ; i < bodyLength ; i ++ ) { this . accept ( body [ i ] ) ; } this . options . blockParams . shift ( ) ; this . isSimple = bodyLength === 1 ; this . blockParams = program . blockParams ? program . blockParams . length : 0 ; return this ; } , BlockStatement : function BlockStatement ( block ) { transformLiteralToPath ( block ) ; var program = block . program , inverse = block . inverse ; program = program && this . compileProgram ( program ) ; inverse = inverse && this . compileProgram ( inverse ) ; var type = this . classifySexpr ( block ) ; if ( type === 'helper' ) { this . helperSexpr ( block , program , inverse ) ; } else if ( type === 'simple' ) { this . simpleSexpr ( block ) ; // now that the simple mustache is resolved, we need to // evaluate it by executing `blockHelperMissing` this . opcode ( 'pushProgram' , program ) ; this . opcode ( 'pushProgram' , inverse ) ; this . opcode ( 'emptyHash' ) ; this . opcode ( 'blockValue' , block . path . original ) ; } else { this . ambiguousSexpr ( block , program , inverse ) ; // now that the simple mustache is resolved, we need to // evaluate it by executing `blockHelperMissing` this . opcode ( 'pushProgram' , program ) ; this . opcode ( 'pushProgram' , inverse ) ; this . opcode ( 'emptyHash' ) ; this . opcode ( 'ambiguousBlockValue' ) ; } this . opcode ( 'append' ) ; } , DecoratorBlock : function DecoratorBlock ( decorator ) { var program = decorator . program && this . compileProgram ( decorator . program ) ; var params = this . setupFullMustacheParams ( decorator , program , undefined ) , path = decorator . path ; this . useDecorators = true ; this . opcode ( 'registerDecorator' , params . length , path . original ) ; } , PartialStatement : function PartialStatement ( partial ) { this . usePartial = true ; var program = partial . program ; if ( program ) { program = this . compileProgram ( partial . program ) ; } var params = partial . params ; if ( params . length > 1 ) { throw new _exception2 [ 'default' ] ( 'Unsupported number of partial arguments: ' + params . length , partial ) ; } else if ( ! params . length ) { if ( this . options . explicitPartialContext ) { this . opcode ( 'pushLiteral' , 'undefined' ) ; } else { params . push ( { type : 'PathExpression' , parts : [ ] , depth : 0 } ) ; } } var partialName = partial . name . original , isDynamic = partial . name . type === 'SubExpression' ; if ( isDynamic ) { this . accept ( partial . name ) ; } this . setupFullMustacheParams ( partial , program , undefined , true ) ; var indent = partial . indent || '' ; if ( this . options . preventIndent && indent ) { this . opcode ( 'appendContent' , indent ) ; indent = '' ; } this . opcode ( 'invokePartial' , isDynamic , partialName , indent ) ; this . opcode ( 'append' ) ; } , PartialBlockStatement : function PartialBlockStatement ( partialBlock ) { this . PartialStatement ( partialBlock ) ; } , MustacheStatement : function MustacheStatement ( mustache ) { this . SubExpression ( mustache ) ; if ( mustache . escaped && ! this . options . noEscape ) { this . opcode ( 'appendEscaped' ) ; } else { this . opcode ( 'append' ) ; } } , Decorator : function Decorator ( decorator ) { this . DecoratorBlock ( decorator ) ; } , ContentStatement : function ContentStatement ( content ) { if ( content . value ) { this . opcode ( 'appendContent' , content . value ) ; } } , CommentStatement : function CommentStatement ( ) { } , SubExpression : function SubExpression ( sexpr ) { transformLiteralToPath ( sexpr ) ; var type = this . classifySexpr ( sexpr ) ; if ( type === 'simple' ) { this . simpleSexpr ( sexpr ) ; } else if ( type === 'helper' ) { this . helperSexpr ( sexpr ) ; } else { this . ambiguousSexpr ( sexpr ) ; } } , ambiguousSexpr : function ambiguousSexpr ( sexpr , program , inverse ) { var path = sexpr . path , name = path . parts [ 0 ] , isBlock = program != null || inverse != null ; this . opcode ( 'getContext' , path . depth ) ; this . opcode ( 'pushProgram' , program ) ; this . opcode ( 'pushProgram' , inverse ) ; path . strict = true ; this . accept ( path ) ; this . opcode ( 'invokeAmbiguous' , name , isBlock ) ; } , simpleSexpr : function simpleSexpr ( sexpr ) { var path = sexpr . path ; path . strict = true ; this . accept ( path ) ; this . opcode ( 'resolvePossibleLambda' ) ; } , helperSexpr : function helperSexpr ( sexpr , program , inverse ) { var params = this . setupFullMustacheParams ( sexpr , program , inverse ) , path = sexpr . path , name = path . parts [ 0 ] ; if ( this . options . knownHelpers [ name ] ) { this . opcode ( 'invokeKnownHelper' , params . length , name ) ; } else if ( this . options . knownHelpersOnly ) { throw new _exception2 [ 'default' ] ( 'You specified knownHelpersOnly, but used the unknown helper ' + name , sexpr ) ; } else { path . strict = true ; path . falsy = true ; this . accept ( path ) ; this . opcode ( 'invokeHelper' , params . length , path . original , _ast2 [ 'default' ] . helpers . simpleId ( path ) ) ; } } , PathExpression : function PathExpression ( path ) { this . addDepth ( path . depth ) ; this . opcode ( 'getContext' , path . depth ) ; var name = path . parts [ 0 ] , scoped = _ast2 [ 'default' ] . helpers . scopedId ( path ) , blockParamId = ! path . depth && ! scoped && this . blockParamIndex ( name ) ; if ( blockParamId ) { this . opcode ( 'lookupBlockParam' , blockParamId , path . parts ) ; } else if ( ! name ) { // Context reference, i.e. `{{foo .}}` or `{{foo ..}}` this . opcode ( 'pushContext' ) ; } else if ( path . data ) { this . options . data = true ; this . opcode ( 'lookupData' , path . depth , path . parts , path . strict ) ; } else { this . opcode ( 'lookupOnContext' , path . parts , path . falsy , path . strict , scoped ) ; } } , StringLiteral : function StringLiteral ( string ) { this . opcode ( 'pushString' , string . value ) ; } , NumberLiteral : function NumberLiteral ( number ) { this . opcode ( 'pushLiteral' , number . value ) ; } , BooleanLiteral : function BooleanLiteral ( bool ) { this . opcode ( 'pushLiteral' , bool . value ) ; } , UndefinedLiteral : function UndefinedLiteral ( ) { this . opcode ( 'pushLiteral' , 'undefined' ) ; } , NullLiteral : function NullLiteral ( ) { this . opcode ( 'pushLiteral' , 'null' ) ; } , Hash : function Hash ( hash ) { var pairs = hash . pairs , i = 0 , l = pairs . length ; this . opcode ( 'pushHash' ) ; for ( ; i < l ; i ++ ) { this . pushParam ( pairs [ i ] . value ) ; } while ( i -- ) { this . opcode ( 'assignToHash' , pairs [ i ] . key ) ; } this . opcode ( 'popHash' ) ; } , // HELPERS opcode : function opcode ( name ) { this . opcodes . push ( { opcode : name , args : slice . call ( arguments , 1 ) , loc : this . sourceNode [ 0 ] . loc } ) ; } , addDepth : function addDepth ( depth ) { if ( ! depth ) { return ; } this . useDepths = true ; } , classifySexpr : function classifySexpr ( sexpr ) { var isSimple = _ast2 [ 'default' ] . helpers . simpleId ( sexpr . path ) ; var isBlockParam = isSimple && ! ! this . blockParamIndex ( sexpr . path . parts [ 0 ] ) ; // a mustache is an eligible helper if: // * its id is simple (a single part, not `this` or `..`) var isHelper = ! isBlockParam && _ast2 [ 'default' ] . helpers . helperExpression ( sexpr ) ; // if a mustache is an eligible helper but not a definite // helper, it is ambiguous, and will be resolved in a later // pass or at runtime. var isEligible = ! isBlockParam && ( isHelper || isSimple ) ; // if ambiguous, we can possibly resolve the ambiguity now // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc. if ( isEligible && ! isHelper ) { var _name2 = sexpr . path . parts [ 0 ] , options = this . options ; if ( options . knownHelpers [ _name2 ] ) { isHelper = true ; } else if ( options . knownHelpersOnly ) { isEligible = false ; } } if ( isHelper ) { return 'helper' ; } else if ( isEligible ) { return 'ambiguous' ; } else { return 'simple' ; } } , pushParams : function pushParams ( params ) { for ( var i = 0 , l = params . length ; i < l ; i ++ ) { this . pushParam ( params [ i ] ) ; } } , pushParam : function pushParam ( val ) { var value = val . value != null ? val . value : val . original || '' ; if ( this . stringParams ) { if ( value . replace ) { value = value . replace ( / ^(\\.?\\.\\/)* / g , '' ) . replace ( / \\/ / g , '.' ) ; } if ( val . depth ) { this . addDepth ( val . depth ) ; } this . opcode ( 'getContext' , val . depth || 0 ) ; this . opcode ( 'pushStringParam' , value , val . type ) ; if ( val . type === 'SubExpression' ) { // SubExpressions get evaluated and passed in // in string params mode. this . accept ( val ) ; } } else { if ( this . trackIds ) { var blockParamIndex = undefined ; if ( val . parts && ! _ast2 [ 'default' ] . helpers . scopedId ( val ) && ! val . depth ) { blockParamIndex = this . blockParamIndex ( val . parts [ 0 ] ) ; } if ( blockParamIndex ) { var blockParamChild = val . parts . slice ( 1 ) . join ( '.' ) ; this . opcode ( 'pushId' , 'BlockParam' , blockParamIndex , blockParamChild ) ; } else { value = val . original || value ; if ( value . replace ) { value = value . replace ( / ^this(?:\\.|$) / , '' ) . replace ( / ^\\.\\/ / , '' ) . replace ( / ^\\.$ / , '' ) ; } this . opcode ( 'pushId' , val . type , value ) ; } } this . accept ( val ) ; } } , setupFullMustacheParams : function setupFullMustacheParams ( sexpr , program , inverse , omitEmpty ) { var params = sexpr . params ; this . pushParams ( params ) ; this . opcode ( 'pushProgram' , program ) ; this . opcode ( 'pushProgram' , inverse ) ; if ( sexpr . hash ) { this . accept ( sexpr . hash ) ; } else { this . opcode ( 'emptyHash' , omitEmpty ) ; } return params ; } , blockParamIndex : function blockParamIndex ( name ) { for ( var depth = 0 , len = this . options . blockParams . length ; depth < len ; depth ++ ) { var blockParams = this . options . blockParams [ depth ] , param = blockParams && _utils . indexOf ( blockParams , name ) ; if ( blockParams && param >= 0 ) { return [ depth , param ] ; } } } } ; function precompile ( input , options , env ) { if ( input == null || typeof input !== 'string' && input . type !== 'Program' ) { throw new _exception2 [ 'default' ] ( 'You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input ) ; } options = options || { } ; if ( ! ( 'data' in options ) ) { options . data = true ; } if ( options . compat ) { options . useDepths = true ; } var ast = env . parse ( input , options ) , environment = new env . Compiler ( ) . compile ( ast , options ) ; return new env . JavaScriptCompiler ( ) . compile ( environment , options ) ; } function compile ( input , options , env ) { if ( options === undefined ) options = { } ; if ( input == null || typeof input !== 'string' && input . type !== 'Program' ) { throw new _exception2 [ 'default' ] ( 'You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input ) ; } if ( ! ( 'data' in options ) ) { options . data = true ; } if ( options . compat ) { options . useDepths = true ; } var compiled = undefined ; function compileInput ( ) { var ast = env . parse ( input , options ) , environment = new env . Compiler ( ) . compile ( ast , options ) , templateSpec = new env . JavaScriptCompiler ( ) . compile ( environment , options , undefined , true ) ; return env . template ( templateSpec ) ; } // Template is only compiled on first use and cached after that point. function ret ( context , execOptions ) { if ( ! compiled ) { compiled = compileInput ( ) ; } return compiled . call ( this , context , execOptions ) ; } ret . _setup = function ( setupOptions ) { if ( ! compiled ) { compiled = compileInput ( ) ; } return compiled . _setup ( setupOptions ) ; } ; ret . _child = function ( i , data , blockParams , depths ) { if ( ! compiled ) { compiled = compileInput ( ) ; } return compiled . _child ( i , data , blockParams , depths ) ; } ; return ret ; } function argEquals ( a , b ) { if ( a === b ) { return true ; } if ( _utils . isArray ( a ) && _utils . isArray ( b ) && a . length === b . length ) { for ( var i = 0 ; i < a . length ; i ++ ) { if ( ! argEquals ( a [ i ] , b [ i ] ) ) { return false ; } } return true ; } } function transformLiteralToPath ( sexpr ) { if ( ! sexpr . path . parts ) { var literal = sexpr . path ; // Casting to string here to make false and 0 literal values play nicely with the rest // of the system. sexpr . path = { type : 'PathExpression' , data : false , depth : 0 , parts : [ literal . original + '' ] , original : literal . original + '' , loc : literal . loc } ; } } /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "HELPERS [CODESPLIT] function opcode ( name ) { this . opcodes . push ( { opcode : name , args : slice . call ( arguments , 1 ) , loc : this . sourceNode [ 0 ] . loc } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Template is only compiled on first use and cached after that point . [CODESPLIT] function ret ( context , execOptions ) { if ( ! compiled ) { compiled = compileInput ( ) ; } return compiled . call ( this , context , execOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 28 [CODESPLIT] function ( module , exports , __webpack_require__ ) { 'use strict' ; var _interopRequireDefault = __webpack_require__ ( 1 ) [ 'default' ] ; exports . __esModule = true ; var _base = __webpack_require__ ( 4 ) ; var _exception = __webpack_require__ ( 6 ) ; var _exception2 = _interopRequireDefault ( _exception ) ; var _utils = __webpack_require__ ( 5 ) ; var _codeGen = __webpack_require__ ( 29 ) ; var _codeGen2 = _interopRequireDefault ( _codeGen ) ; function Literal ( value ) { this . value = value ; } function JavaScriptCompiler ( ) { } JavaScriptCompiler . prototype = { // PUBLIC API: You can override these methods in a subclass to provide // alternative compiled forms for name lookup and buffering semantics nameLookup : function nameLookup ( parent , name /* , type*/ ) { if ( JavaScriptCompiler . isValidJavaScriptVariableName ( name ) ) { return [ parent , '.' , name ] ; } else { return [ parent , '[' , JSON . stringify ( name ) , ']' ] ; } } , depthedLookup : function depthedLookup ( name ) { return [ this . aliasable ( 'container.lookup' ) , '(depths, \"' , name , '\")' ] ; } , compilerInfo : function compilerInfo ( ) { var revision = _base . COMPILER_REVISION , versions = _base . REVISION_CHANGES [ revision ] ; return [ revision , versions ] ; } , appendToBuffer : function appendToBuffer ( source , location , explicit ) { // Force a source as this simplifies the merge logic. if ( ! _utils . isArray ( source ) ) { source = [ source ] ; } source = this . source . wrap ( source , location ) ; if ( this . environment . isSimple ) { return [ 'return ' , source , ';' ] ; } else if ( explicit ) { // This is a case where the buffer operation occurs as a child of another // construct, generally braces. We have to explicitly output these buffer // operations to ensure that the emitted code goes in the correct location. return [ 'buffer += ' , source , ';' ] ; } else { source . appendToBuffer = true ; return source ; } } , initializeBuffer : function initializeBuffer ( ) { return this . quotedString ( '' ) ; } , // END PUBLIC API compile : function compile ( environment , options , context , asObject ) { this . environment = environment ; this . options = options ; this . stringParams = this . options . stringParams ; this . trackIds = this . options . trackIds ; this . precompile = ! asObject ; this . name = this . environment . name ; this . isChild = ! ! context ; this . context = context || { decorators : [ ] , programs : [ ] , environments : [ ] } ; this . preamble ( ) ; this . stackSlot = 0 ; this . stackVars = [ ] ; this . aliases = { } ; this . registers = { list : [ ] } ; this . hashes = [ ] ; this . compileStack = [ ] ; this . inlineStack = [ ] ; this . blockParams = [ ] ; this . compileChildren ( environment , options ) ; this . useDepths = this . useDepths || environment . useDepths || environment . useDecorators || this . options . compat ; this . useBlockParams = this . useBlockParams || environment . useBlockParams ; var opcodes = environment . opcodes , opcode = undefined , firstLoc = undefined , i = undefined , l = undefined ; for ( i = 0 , l = opcodes . length ; i < l ; i ++ ) { opcode = opcodes [ i ] ; this . source . currentLocation = opcode . loc ; firstLoc = firstLoc || opcode . loc ; this [ opcode . opcode ] . apply ( this , opcode . args ) ; } // Flush any trailing content that might be pending. this . source . currentLocation = firstLoc ; this . pushSource ( '' ) ; /* istanbul ignore next */ if ( this . stackSlot || this . inlineStack . length || this . compileStack . length ) { throw new _exception2 [ 'default' ] ( 'Compile completed with content left on stack' ) ; } if ( ! this . decorators . isEmpty ( ) ) { this . useDecorators = true ; this . decorators . prepend ( 'var decorators = container.decorators;\\n' ) ; this . decorators . push ( 'return fn;' ) ; if ( asObject ) { this . decorators = Function . apply ( this , [ 'fn' , 'props' , 'container' , 'depth0' , 'data' , 'blockParams' , 'depths' , this . decorators . merge ( ) ] ) ; } else { this . decorators . prepend ( 'function(fn, props, container, depth0, data, blockParams, depths) {\\n' ) ; this . decorators . push ( '}\\n' ) ; this . decorators = this . decorators . merge ( ) ; } } else { this . decorators = undefined ; } var fn = this . createFunctionContext ( asObject ) ; if ( ! this . isChild ) { var ret = { compiler : this . compilerInfo ( ) , main : fn } ; if ( this . decorators ) { ret . main_d = this . decorators ; // eslint-disable-line camelcase ret . useDecorators = true ; } var _context = this . context ; var programs = _context . programs ; var decorators = _context . decorators ; for ( i = 0 , l = programs . length ; i < l ; i ++ ) { if ( programs [ i ] ) { ret [ i ] = programs [ i ] ; if ( decorators [ i ] ) { ret [ i + '_d' ] = decorators [ i ] ; ret . useDecorators = true ; } } } if ( this . environment . usePartial ) { ret . usePartial = true ; } if ( this . options . data ) { ret . useData = true ; } if ( this . useDepths ) { ret . useDepths = true ; } if ( this . useBlockParams ) { ret . useBlockParams = true ; } if ( this . options . compat ) { ret . compat = true ; } if ( ! asObject ) { ret . compiler = JSON . stringify ( ret . compiler ) ; this . source . currentLocation = { start : { line : 1 , column : 0 } } ; ret = this . objectLiteral ( ret ) ; if ( options . srcName ) { ret = ret . toStringWithSourceMap ( { file : options . destName } ) ; ret . map = ret . map && ret . map . toString ( ) ; } else { ret = ret . toString ( ) ; } } else { ret . compilerOptions = this . options ; } return ret ; } else { return fn ; } } , preamble : function preamble ( ) { // track the last context pushed into place to allow skipping the // getContext opcode when it would be a noop this . lastContext = 0 ; this . source = new _codeGen2 [ 'default' ] ( this . options . srcName ) ; this . decorators = new _codeGen2 [ 'default' ] ( this . options . srcName ) ; } , createFunctionContext : function createFunctionContext ( asObject ) { var varDeclarations = '' ; var locals = this . stackVars . concat ( this . registers . list ) ; if ( locals . length > 0 ) { varDeclarations += ', ' + locals . join ( ', ' ) ; } // Generate minimizer alias mappings // // When using true SourceNodes, this will update all references to the given alias // as the source nodes are reused in situ. For the non-source node compilation mode, // aliases will not be used, but this case is already being run on the client and // we aren't concern about minimizing the template size. var aliasCount = 0 ; for ( var alias in this . aliases ) { // eslint-disable-line guard-for-in var node = this . aliases [ alias ] ; if ( this . aliases . hasOwnProperty ( alias ) && node . children && node . referenceCount > 1 ) { varDeclarations += ', alias' + ++ aliasCount + '=' + alias ; node . children [ 0 ] = 'alias' + aliasCount ; } } var params = [ 'container' , 'depth0' , 'helpers' , 'partials' , 'data' ] ; if ( this . useBlockParams || this . useDepths ) { params . push ( 'blockParams' ) ; } if ( this . useDepths ) { params . push ( 'depths' ) ; } // Perform a second pass over the output to merge content when possible var source = this . mergeSource ( varDeclarations ) ; if ( asObject ) { params . push ( source ) ; return Function . apply ( this , params ) ; } else { return this . source . wrap ( [ 'function(' , params . join ( ',' ) , ') {\\n  ' , source , '}' ] ) ; } } , mergeSource : function mergeSource ( varDeclarations ) { var isSimple = this . environment . isSimple , appendOnly = ! this . forceBuffer , appendFirst = undefined , sourceSeen = undefined , bufferStart = undefined , bufferEnd = undefined ; this . source . each ( function ( line ) { if ( line . appendToBuffer ) { if ( bufferStart ) { line . prepend ( '  + ' ) ; } else { bufferStart = line ; } bufferEnd = line ; } else { if ( bufferStart ) { if ( ! sourceSeen ) { appendFirst = true ; } else { bufferStart . prepend ( 'buffer += ' ) ; } bufferEnd . add ( ';' ) ; bufferStart = bufferEnd = undefined ; } sourceSeen = true ; if ( ! isSimple ) { appendOnly = false ; } } } ) ; if ( appendOnly ) { if ( bufferStart ) { bufferStart . prepend ( 'return ' ) ; bufferEnd . add ( ';' ) ; } else if ( ! sourceSeen ) { this . source . push ( 'return \"\";' ) ; } } else { varDeclarations += ', buffer = ' + ( appendFirst ? '' : this . initializeBuffer ( ) ) ; if ( bufferStart ) { bufferStart . prepend ( 'return buffer + ' ) ; bufferEnd . add ( ';' ) ; } else { this . source . push ( 'return buffer;' ) ; } } if ( varDeclarations ) { this . source . prepend ( 'var ' + varDeclarations . substring ( 2 ) + ( appendFirst ? '' : ';\\n' ) ) ; } return this . source . merge ( ) ; } , // [blockValue] // // On stack, before: hash, inverse, program, value // On stack, after: return value of blockHelperMissing // // The purpose of this opcode is to take a block of the form // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and // replace it on the stack with the result of properly // invoking blockHelperMissing. blockValue : function blockValue ( name ) { var blockHelperMissing = this . aliasable ( 'helpers.blockHelperMissing' ) , params = [ this . contextName ( 0 ) ] ; this . setupHelperArgs ( name , 0 , params ) ; var blockName = this . popStack ( ) ; params . splice ( 1 , 0 , blockName ) ; this . push ( this . source . functionCall ( blockHelperMissing , 'call' , params ) ) ; } , // [ambiguousBlockValue] // // On stack, before: hash, inverse, program, value // Compiler value, before: lastHelper=value of last found helper, if any // On stack, after, if no lastHelper: same as [blockValue] // On stack, after, if lastHelper: value ambiguousBlockValue : function ambiguousBlockValue ( ) { // We're being a bit cheeky and reusing the options value from the prior exec var blockHelperMissing = this . aliasable ( 'helpers.blockHelperMissing' ) , params = [ this . contextName ( 0 ) ] ; this . setupHelperArgs ( '' , 0 , params , true ) ; this . flushInline ( ) ; var current = this . topStack ( ) ; params . splice ( 1 , 0 , current ) ; this . pushSource ( [ 'if (!' , this . lastHelper , ') { ' , current , ' = ' , this . source . functionCall ( blockHelperMissing , 'call' , params ) , '}' ] ) ; } , // [appendContent] // // On stack, before: ... // On stack, after: ... // // Appends the string value of `content` to the current buffer appendContent : function appendContent ( content ) { if ( this . pendingContent ) { content = this . pendingContent + content ; } else { this . pendingLocation = this . source . currentLocation ; } this . pendingContent = content ; } , // [append] // // On stack, before: value, ... // On stack, after: ... // // Coerces `value` to a String and appends it to the current buffer. // // If `value` is truthy, or 0, it is coerced into a string and appended // Otherwise, the empty string is appended append : function append ( ) { if ( this . isInline ( ) ) { this . replaceStack ( function ( current ) { return [ ' != null ? ' , current , ' : \"\"' ] ; } ) ; this . pushSource ( this . appendToBuffer ( this . popStack ( ) ) ) ; } else { var local = this . popStack ( ) ; this . pushSource ( [ 'if (' , local , ' != null) { ' , this . appendToBuffer ( local , undefined , true ) , ' }' ] ) ; if ( this . environment . isSimple ) { this . pushSource ( [ 'else { ' , this . appendToBuffer ( \"''\" , undefined , true ) , ' }' ] ) ; } } } , // [appendEscaped] // // On stack, before: value, ... // On stack, after: ... // // Escape `value` and append it to the buffer appendEscaped : function appendEscaped ( ) { this . pushSource ( this . appendToBuffer ( [ this . aliasable ( 'container.escapeExpression' ) , '(' , this . popStack ( ) , ')' ] ) ) ; } , // [getContext] // // On stack, before: ... // On stack, after: ... // Compiler value, after: lastContext=depth // // Set the value of the `lastContext` compiler value to the depth getContext : function getContext ( depth ) { this . lastContext = depth ; } , // [pushContext] // // On stack, before: ... // On stack, after: currentContext, ... // // Pushes the value of the current context onto the stack. pushContext : function pushContext ( ) { this . pushStackLiteral ( this . contextName ( this . lastContext ) ) ; } , // [lookupOnContext] // // On stack, before: ... // On stack, after: currentContext[name], ... // // Looks up the value of `name` on the current context and pushes // it onto the stack. lookupOnContext : function lookupOnContext ( parts , falsy , strict , scoped ) { var i = 0 ; if ( ! scoped && this . options . compat && ! this . lastContext ) { // The depthed query is expected to handle the undefined logic for the root level that // is implemented below, so we evaluate that directly in compat mode this . push ( this . depthedLookup ( parts [ i ++ ] ) ) ; } else { this . pushContext ( ) ; } this . resolvePath ( 'context' , parts , i , falsy , strict ) ; } , // [lookupBlockParam] // // On stack, before: ... // On stack, after: blockParam[name], ... // // Looks up the value of `parts` on the given block param and pushes // it onto the stack. lookupBlockParam : function lookupBlockParam ( blockParamId , parts ) { this . useBlockParams = true ; this . push ( [ 'blockParams[' , blockParamId [ 0 ] , '][' , blockParamId [ 1 ] , ']' ] ) ; this . resolvePath ( 'context' , parts , 1 ) ; } , // [lookupData] // // On stack, before: ... // On stack, after: data, ... // // Push the data lookup operator lookupData : function lookupData ( depth , parts , strict ) { if ( ! depth ) { this . pushStackLiteral ( 'data' ) ; } else { this . pushStackLiteral ( 'container.data(data, ' + depth + ')' ) ; } this . resolvePath ( 'data' , parts , 0 , true , strict ) ; } , resolvePath : function resolvePath ( type , parts , i , falsy , strict ) { // istanbul ignore next var _this = this ; if ( this . options . strict || this . options . assumeObjects ) { this . push ( strictLookup ( this . options . strict && strict , this , parts , type ) ) ; return ; } var len = parts . length ; for ( ; i < len ; i ++ ) { /* eslint-disable no-loop-func */ this . replaceStack ( function ( current ) { var lookup = _this . nameLookup ( current , parts [ i ] , type ) ; // We want to ensure that zero and false are handled properly if the context (falsy flag) // needs to have the special handling for these values. if ( ! falsy ) { return [ ' != null ? ' , lookup , ' : ' , current ] ; } else { // Otherwise we can use generic falsy handling return [ ' && ' , lookup ] ; } } ) ; /* eslint-enable no-loop-func */ } } , // [resolvePossibleLambda] // // On stack, before: value, ... // On stack, after: resolved value, ... // // If the `value` is a lambda, replace it on the stack by // the return value of the lambda resolvePossibleLambda : function resolvePossibleLambda ( ) { this . push ( [ this . aliasable ( 'container.lambda' ) , '(' , this . popStack ( ) , ', ' , this . contextName ( 0 ) , ')' ] ) ; } , // [pushStringParam] // // On stack, before: ... // On stack, after: string, currentContext, ... // // This opcode is designed for use in string mode, which // provides the string value of a parameter along with its // depth rather than resolving it immediately. pushStringParam : function pushStringParam ( string , type ) { this . pushContext ( ) ; this . pushString ( type ) ; // If it's a subexpression, the string result // will be pushed after this opcode. if ( type !== 'SubExpression' ) { if ( typeof string === 'string' ) { this . pushString ( string ) ; } else { this . pushStackLiteral ( string ) ; } } } , emptyHash : function emptyHash ( omitEmpty ) { if ( this . trackIds ) { this . push ( '{}' ) ; // hashIds } if ( this . stringParams ) { this . push ( '{}' ) ; // hashContexts this . push ( '{}' ) ; // hashTypes } this . pushStackLiteral ( omitEmpty ? 'undefined' : '{}' ) ; } , pushHash : function pushHash ( ) { if ( this . hash ) { this . hashes . push ( this . hash ) ; } this . hash = { values : [ ] , types : [ ] , contexts : [ ] , ids : [ ] } ; } , popHash : function popHash ( ) { var hash = this . hash ; this . hash = this . hashes . pop ( ) ; if ( this . trackIds ) { this . push ( this . objectLiteral ( hash . ids ) ) ; } if ( this . stringParams ) { this . push ( this . objectLiteral ( hash . contexts ) ) ; this . push ( this . objectLiteral ( hash . types ) ) ; } this . push ( this . objectLiteral ( hash . values ) ) ; } , // [pushString] // // On stack, before: ... // On stack, after: quotedString(string), ... // // Push a quoted version of `string` onto the stack pushString : function pushString ( string ) { this . pushStackLiteral ( this . quotedString ( string ) ) ; } , // [pushLiteral] // // On stack, before: ... // On stack, after: value, ... // // Pushes a value onto the stack. This operation prevents // the compiler from creating a temporary variable to hold // it. pushLiteral : function pushLiteral ( value ) { this . pushStackLiteral ( value ) ; } , // [pushProgram] // // On stack, before: ... // On stack, after: program(guid), ... // // Push a program expression onto the stack. This takes // a compile-time guid and converts it into a runtime-accessible // expression. pushProgram : function pushProgram ( guid ) { if ( guid != null ) { this . pushStackLiteral ( this . programExpression ( guid ) ) ; } else { this . pushStackLiteral ( null ) ; } } , // [registerDecorator] // // On stack, before: hash, program, params..., ... // On stack, after: ... // // Pops off the decorator's parameters, invokes the decorator, // and inserts the decorator into the decorators list. registerDecorator : function registerDecorator ( paramSize , name ) { var foundDecorator = this . nameLookup ( 'decorators' , name , 'decorator' ) , options = this . setupHelperArgs ( name , paramSize ) ; this . decorators . push ( [ 'fn = ' , this . decorators . functionCall ( foundDecorator , '' , [ 'fn' , 'props' , 'container' , options ] ) , ' || fn;' ] ) ; } , // [invokeHelper] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of helper invocation // // Pops off the helper's parameters, invokes the helper, // and pushes the helper's return value onto the stack. // // If the helper is not found, `helperMissing` is called. invokeHelper : function invokeHelper ( paramSize , name , isSimple ) { var nonHelper = this . popStack ( ) , helper = this . setupHelper ( paramSize , name ) , simple = isSimple ? [ helper . name , ' || ' ] : '' ; var lookup = [ '(' ] . concat ( simple , nonHelper ) ; if ( ! this . options . strict ) { lookup . push ( ' || ' , this . aliasable ( 'helpers.helperMissing' ) ) ; } lookup . push ( ')' ) ; this . push ( this . source . functionCall ( lookup , 'call' , helper . callParams ) ) ; } , // [invokeKnownHelper] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of helper invocation // // This operation is used when the helper is known to exist, // so a `helperMissing` fallback is not required. invokeKnownHelper : function invokeKnownHelper ( paramSize , name ) { var helper = this . setupHelper ( paramSize , name ) ; this . push ( this . source . functionCall ( helper . name , 'call' , helper . callParams ) ) ; } , // [invokeAmbiguous] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of disambiguation // // This operation is used when an expression like `{{foo}}` // is provided, but we don't know at compile-time whether it // is a helper or a path. // // This operation emits more code than the other options, // and can be avoided by passing the `knownHelpers` and // `knownHelpersOnly` flags at compile-time. invokeAmbiguous : function invokeAmbiguous ( name , helperCall ) { this . useRegister ( 'helper' ) ; var nonHelper = this . popStack ( ) ; this . emptyHash ( ) ; var helper = this . setupHelper ( 0 , name , helperCall ) ; var helperName = this . lastHelper = this . nameLookup ( 'helpers' , name , 'helper' ) ; var lookup = [ '(' , '(helper = ' , helperName , ' || ' , nonHelper , ')' ] ; if ( ! this . options . strict ) { lookup [ 0 ] = '(helper = ' ; lookup . push ( ' != null ? helper : ' , this . aliasable ( 'helpers.helperMissing' ) ) ; } this . push ( [ '(' , lookup , helper . paramsInit ? [ '),(' , helper . paramsInit ] : [ ] , '),' , '(typeof helper === ' , this . aliasable ( '\"function\"' ) , ' ? ' , this . source . functionCall ( 'helper' , 'call' , helper . callParams ) , ' : helper))' ] ) ; } , // [invokePartial] // // On stack, before: context, ... // On stack after: result of partial invocation // // This operation pops off a context, invokes a partial with that context, // and pushes the result of the invocation back. invokePartial : function invokePartial ( isDynamic , name , indent ) { var params = [ ] , options = this . setupParams ( name , 1 , params ) ; if ( isDynamic ) { name = this . popStack ( ) ; delete options . name ; } if ( indent ) { options . indent = JSON . stringify ( indent ) ; } options . helpers = 'helpers' ; options . partials = 'partials' ; options . decorators = 'container.decorators' ; if ( ! isDynamic ) { params . unshift ( this . nameLookup ( 'partials' , name , 'partial' ) ) ; } else { params . unshift ( name ) ; } if ( this . options . compat ) { options . depths = 'depths' ; } options = this . objectLiteral ( options ) ; params . push ( options ) ; this . push ( this . source . functionCall ( 'container.invokePartial' , '' , params ) ) ; } , // [assignToHash] // // On stack, before: value, ..., hash, ... // On stack, after: ..., hash, ... // // Pops a value off the stack and assigns it to the current hash assignToHash : function assignToHash ( key ) { var value = this . popStack ( ) , context = undefined , type = undefined , id = undefined ; if ( this . trackIds ) { id = this . popStack ( ) ; } if ( this . stringParams ) { type = this . popStack ( ) ; context = this . popStack ( ) ; } var hash = this . hash ; if ( context ) { hash . contexts [ key ] = context ; } if ( type ) { hash . types [ key ] = type ; } if ( id ) { hash . ids [ key ] = id ; } hash . values [ key ] = value ; } , pushId : function pushId ( type , name , child ) { if ( type === 'BlockParam' ) { this . pushStackLiteral ( 'blockParams[' + name [ 0 ] + '].path[' + name [ 1 ] + ']' + ( child ? ' + ' + JSON . stringify ( '.' + child ) : '' ) ) ; } else if ( type === 'PathExpression' ) { this . pushString ( name ) ; } else if ( type === 'SubExpression' ) { this . pushStackLiteral ( 'true' ) ; } else { this . pushStackLiteral ( 'null' ) ; } } , // HELPERS compiler : JavaScriptCompiler , compileChildren : function compileChildren ( environment , options ) { var children = environment . children , child = undefined , compiler = undefined ; for ( var i = 0 , l = children . length ; i < l ; i ++ ) { child = children [ i ] ; compiler = new this . compiler ( ) ; // eslint-disable-line new-cap var index = this . matchExistingProgram ( child ) ; if ( index == null ) { this . context . programs . push ( '' ) ; // Placeholder to prevent name conflicts for nested children index = this . context . programs . length ; child . index = index ; child . name = 'program' + index ; this . context . programs [ index ] = compiler . compile ( child , options , this . context , ! this . precompile ) ; this . context . decorators [ index ] = compiler . decorators ; this . context . environments [ index ] = child ; this . useDepths = this . useDepths || compiler . useDepths ; this . useBlockParams = this . useBlockParams || compiler . useBlockParams ; } else { child . index = index ; child . name = 'program' + index ; this . useDepths = this . useDepths || child . useDepths ; this . useBlockParams = this . useBlockParams || child . useBlockParams ; } } } , matchExistingProgram : function matchExistingProgram ( child ) { for ( var i = 0 , len = this . context . environments . length ; i < len ; i ++ ) { var environment = this . context . environments [ i ] ; if ( environment && environment . equals ( child ) ) { return i ; } } } , programExpression : function programExpression ( guid ) { var child = this . environment . children [ guid ] , programParams = [ child . index , 'data' , child . blockParams ] ; if ( this . useBlockParams || this . useDepths ) { programParams . push ( 'blockParams' ) ; } if ( this . useDepths ) { programParams . push ( 'depths' ) ; } return 'container.program(' + programParams . join ( ', ' ) + ')' ; } , useRegister : function useRegister ( name ) { if ( ! this . registers [ name ] ) { this . registers [ name ] = true ; this . registers . list . push ( name ) ; } } , push : function push ( expr ) { if ( ! ( expr instanceof Literal ) ) { expr = this . source . wrap ( expr ) ; } this . inlineStack . push ( expr ) ; return expr ; } , pushStackLiteral : function pushStackLiteral ( item ) { this . push ( new Literal ( item ) ) ; } , pushSource : function pushSource ( source ) { if ( this . pendingContent ) { this . source . push ( this . appendToBuffer ( this . source . quotedString ( this . pendingContent ) , this . pendingLocation ) ) ; this . pendingContent = undefined ; } if ( source ) { this . source . push ( source ) ; } } , replaceStack : function replaceStack ( callback ) { var prefix = [ '(' ] , stack = undefined , createdStack = undefined , usedLiteral = undefined ; /* istanbul ignore next */ if ( ! this . isInline ( ) ) { throw new _exception2 [ 'default' ] ( 'replaceStack on non-inline' ) ; } // We want to merge the inline statement into the replacement statement via ',' var top = this . popStack ( true ) ; if ( top instanceof Literal ) { // Literals do not need to be inlined stack = [ top . value ] ; prefix = [ '(' , stack ] ; usedLiteral = true ; } else { // Get or create the current stack name for use by the inline createdStack = true ; var _name = this . incrStack ( ) ; prefix = [ '((' , this . push ( _name ) , ' = ' , top , ')' ] ; stack = this . topStack ( ) ; } var item = callback . call ( this , stack ) ; if ( ! usedLiteral ) { this . popStack ( ) ; } if ( createdStack ) { this . stackSlot -- ; } this . push ( prefix . concat ( item , ')' ) ) ; } , incrStack : function incrStack ( ) { this . stackSlot ++ ; if ( this . stackSlot > this . stackVars . length ) { this . stackVars . push ( 'stack' + this . stackSlot ) ; } return this . topStackName ( ) ; } , topStackName : function topStackName ( ) { return 'stack' + this . stackSlot ; } , flushInline : function flushInline ( ) { var inlineStack = this . inlineStack ; this . inlineStack = [ ] ; for ( var i = 0 , len = inlineStack . length ; i < len ; i ++ ) { var entry = inlineStack [ i ] ; /* istanbul ignore if */ if ( entry instanceof Literal ) { this . compileStack . push ( entry ) ; } else { var stack = this . incrStack ( ) ; this . pushSource ( [ stack , ' = ' , entry , ';' ] ) ; this . compileStack . push ( stack ) ; } } } , isInline : function isInline ( ) { return this . inlineStack . length ; } , popStack : function popStack ( wrapped ) { var inline = this . isInline ( ) , item = ( inline ? this . inlineStack : this . compileStack ) . pop ( ) ; if ( ! wrapped && item instanceof Literal ) { return item . value ; } else { if ( ! inline ) { /* istanbul ignore next */ if ( ! this . stackSlot ) { throw new _exception2 [ 'default' ] ( 'Invalid stack pop' ) ; } this . stackSlot -- ; } return item ; } } , topStack : function topStack ( ) { var stack = this . isInline ( ) ? this . inlineStack : this . compileStack , item = stack [ stack . length - 1 ] ; /* istanbul ignore if */ if ( item instanceof Literal ) { return item . value ; } else { return item ; } } , contextName : function contextName ( context ) { if ( this . useDepths && context ) { return 'depths[' + context + ']' ; } else { return 'depth' + context ; } } , quotedString : function quotedString ( str ) { return this . source . quotedString ( str ) ; } , objectLiteral : function objectLiteral ( obj ) { return this . source . objectLiteral ( obj ) ; } , aliasable : function aliasable ( name ) { var ret = this . aliases [ name ] ; if ( ret ) { ret . referenceCount ++ ; return ret ; } ret = this . aliases [ name ] = this . source . wrap ( name ) ; ret . aliasable = true ; ret . referenceCount = 1 ; return ret ; } , setupHelper : function setupHelper ( paramSize , name , blockHelper ) { var params = [ ] , paramsInit = this . setupHelperArgs ( name , paramSize , params , blockHelper ) ; var foundHelper = this . nameLookup ( 'helpers' , name , 'helper' ) , callContext = this . aliasable ( this . contextName ( 0 ) + ' != null ? ' + this . contextName ( 0 ) + ' : {}' ) ; return { params : params , paramsInit : paramsInit , name : foundHelper , callParams : [ callContext ] . concat ( params ) } ; } , setupParams : function setupParams ( helper , paramSize , params ) { var options = { } , contexts = [ ] , types = [ ] , ids = [ ] , objectArgs = ! params , param = undefined ; if ( objectArgs ) { params = [ ] ; } options . name = this . quotedString ( helper ) ; options . hash = this . popStack ( ) ; if ( this . trackIds ) { options . hashIds = this . popStack ( ) ; } if ( this . stringParams ) { options . hashTypes = this . popStack ( ) ; options . hashContexts = this . popStack ( ) ; } var inverse = this . popStack ( ) , program = this . popStack ( ) ; // Avoid setting fn and inverse if neither are set. This allows // helpers to do a check for `if (options.fn)` if ( program || inverse ) { options . fn = program || 'container.noop' ; options . inverse = inverse || 'container.noop' ; } // The parameters go on to the stack in order (making sure that they are evaluated in order) // so we need to pop them off the stack in reverse order var i = paramSize ; while ( i -- ) { param = this . popStack ( ) ; params [ i ] = param ; if ( this . trackIds ) { ids [ i ] = this . popStack ( ) ; } if ( this . stringParams ) { types [ i ] = this . popStack ( ) ; contexts [ i ] = this . popStack ( ) ; } } if ( objectArgs ) { options . args = this . source . generateArray ( params ) ; } if ( this . trackIds ) { options . ids = this . source . generateArray ( ids ) ; } if ( this . stringParams ) { options . types = this . source . generateArray ( types ) ; options . contexts = this . source . generateArray ( contexts ) ; } if ( this . options . data ) { options . data = 'data' ; } if ( this . useBlockParams ) { options . blockParams = 'blockParams' ; } return options ; } , setupHelperArgs : function setupHelperArgs ( helper , paramSize , params , useRegister ) { var options = this . setupParams ( helper , paramSize , params ) ; options = this . objectLiteral ( options ) ; if ( useRegister ) { this . useRegister ( 'options' ) ; params . push ( 'options' ) ; return [ 'options=' , options ] ; } else if ( params ) { params . push ( options ) ; return '' ; } else { return options ; } } } ; ( function ( ) { var reservedWords = ( 'break else new var' + ' case finally return void' + ' catch for switch while' + ' continue function this with' + ' default if throw' + ' delete in try' + ' do instanceof typeof' + ' abstract enum int short' + ' boolean export interface static' + ' byte extends long super' + ' char final native synchronized' + ' class float package throws' + ' const goto private transient' + ' debugger implements protected volatile' + ' double import public let yield await' + ' null true false' ) . split ( ' ' ) ; var compilerWords = JavaScriptCompiler . RESERVED_WORDS = { } ; for ( var i = 0 , l = reservedWords . length ; i < l ; i ++ ) { compilerWords [ reservedWords [ i ] ] = true ; } } ) ( ) ; JavaScriptCompiler . isValidJavaScriptVariableName = function ( name ) { return ! JavaScriptCompiler . RESERVED_WORDS [ name ] && / ^[a-zA-Z_$][0-9a-zA-Z_$]*$ / . test ( name ) ; } ; function strictLookup ( requireTerminal , compiler , parts , type ) { var stack = compiler . popStack ( ) , i = 0 , len = parts . length ; if ( requireTerminal ) { len -- ; } for ( ; i < len ; i ++ ) { stack = compiler . nameLookup ( stack , parts [ i ] , type ) ; } if ( requireTerminal ) { return [ compiler . aliasable ( 'container.strict' ) , '(' , stack , ', ' , compiler . quotedString ( parts [ i ] ) , ')' ] ; } else { return stack ; } } exports [ 'default' ] = JavaScriptCompiler ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PUBLIC API : You can override these methods in a subclass to provide alternative compiled forms for name lookup and buffering semantics [CODESPLIT] function nameLookup ( parent , name /* , type*/ ) { if ( JavaScriptCompiler . isValidJavaScriptVariableName ( name ) ) { return [ parent , '.' , name ] ; } else { return [ parent , '[' , JSON . stringify ( name ) , ']' ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ blockValue ] On stack before : hash inverse program value On stack after : return value of blockHelperMissing The purpose of this opcode is to take a block of the form {{ #this . foo }} ... {{ / this . foo }} resolve the value of foo and replace it on the stack with the result of properly invoking blockHelperMissing . [CODESPLIT] function blockValue ( name ) { var blockHelperMissing = this . aliasable ( 'helpers.blockHelperMissing' ) , params = [ this . contextName ( 0 ) ] ; this . setupHelperArgs ( name , 0 , params ) ; var blockName = this . popStack ( ) ; params . splice ( 1 , 0 , blockName ) ; this . push ( this . source . functionCall ( blockHelperMissing , 'call' , params ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ ambiguousBlockValue ] On stack before : hash inverse program value Compiler value before : lastHelper = value of last found helper if any On stack after if no lastHelper : same as [ blockValue ] On stack after if lastHelper : value [CODESPLIT] function ambiguousBlockValue ( ) { // We're being a bit cheeky and reusing the options value from the prior exec var blockHelperMissing = this . aliasable ( 'helpers.blockHelperMissing' ) , params = [ this . contextName ( 0 ) ] ; this . setupHelperArgs ( '' , 0 , params , true ) ; this . flushInline ( ) ; var current = this . topStack ( ) ; params . splice ( 1 , 0 , current ) ; this . pushSource ( [ 'if (!' , this . lastHelper , ') { ' , current , ' = ' , this . source . functionCall ( blockHelperMissing , 'call' , params ) , '}' ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ appendContent ] On stack before : ... On stack after : ... Appends the string value of content to the current buffer [CODESPLIT] function appendContent ( content ) { if ( this . pendingContent ) { content = this . pendingContent + content ; } else { this . pendingLocation = this . source . currentLocation ; } this . pendingContent = content ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ append ] On stack before : value ... On stack after : ... Coerces value to a String and appends it to the current buffer . If value is truthy or 0 it is coerced into a string and appended Otherwise the empty string is appended [CODESPLIT] function append ( ) { if ( this . isInline ( ) ) { this . replaceStack ( function ( current ) { return [ ' != null ? ' , current , ' : \"\"' ] ; } ) ; this . pushSource ( this . appendToBuffer ( this . popStack ( ) ) ) ; } else { var local = this . popStack ( ) ; this . pushSource ( [ 'if (' , local , ' != null) { ' , this . appendToBuffer ( local , undefined , true ) , ' }' ] ) ; if ( this . environment . isSimple ) { this . pushSource ( [ 'else { ' , this . appendToBuffer ( \"''\" , undefined , true ) , ' }' ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ lookupOnContext ] On stack before : ... On stack after : currentContext [ name ] ... Looks up the value of name on the current context and pushes it onto the stack . [CODESPLIT] function lookupOnContext ( parts , falsy , strict , scoped ) { var i = 0 ; if ( ! scoped && this . options . compat && ! this . lastContext ) { // The depthed query is expected to handle the undefined logic for the root level that // is implemented below, so we evaluate that directly in compat mode this . push ( this . depthedLookup ( parts [ i ++ ] ) ) ; } else { this . pushContext ( ) ; } this . resolvePath ( 'context' , parts , i , falsy , strict ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ lookupBlockParam ] On stack before : ... On stack after : blockParam [ name ] ... Looks up the value of parts on the given block param and pushes it onto the stack . [CODESPLIT] function lookupBlockParam ( blockParamId , parts ) { this . useBlockParams = true ; this . push ( [ 'blockParams[' , blockParamId [ 0 ] , '][' , blockParamId [ 1 ] , ']' ] ) ; this . resolvePath ( 'context' , parts , 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ pushStringParam ] On stack before : ... On stack after : string currentContext ... This opcode is designed for use in string mode which provides the string value of a parameter along with its depth rather than resolving it immediately . [CODESPLIT] function pushStringParam ( string , type ) { this . pushContext ( ) ; this . pushString ( type ) ; // If it's a subexpression, the string result // will be pushed after this opcode. if ( type !== 'SubExpression' ) { if ( typeof string === 'string' ) { this . pushString ( string ) ; } else { this . pushStackLiteral ( string ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ registerDecorator ] On stack before : hash program params ... ... On stack after : ... Pops off the decorator s parameters invokes the decorator and inserts the decorator into the decorators list . [CODESPLIT] function registerDecorator ( paramSize , name ) { var foundDecorator = this . nameLookup ( 'decorators' , name , 'decorator' ) , options = this . setupHelperArgs ( name , paramSize ) ; this . decorators . push ( [ 'fn = ' , this . decorators . functionCall ( foundDecorator , '' , [ 'fn' , 'props' , 'container' , options ] ) , ' || fn;' ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ invokeHelper ] On stack before : hash inverse program params ... ... On stack after : result of helper invocation Pops off the helper s parameters invokes the helper and pushes the helper s return value onto the stack . If the helper is not found helperMissing is called . [CODESPLIT] function invokeHelper ( paramSize , name , isSimple ) { var nonHelper = this . popStack ( ) , helper = this . setupHelper ( paramSize , name ) , simple = isSimple ? [ helper . name , ' || ' ] : '' ; var lookup = [ '(' ] . concat ( simple , nonHelper ) ; if ( ! this . options . strict ) { lookup . push ( ' || ' , this . aliasable ( 'helpers.helperMissing' ) ) ; } lookup . push ( ')' ) ; this . push ( this . source . functionCall ( lookup , 'call' , helper . callParams ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ invokeKnownHelper ] On stack before : hash inverse program params ... ... On stack after : result of helper invocation This operation is used when the helper is known to exist so a helperMissing fallback is not required . [CODESPLIT] function invokeKnownHelper ( paramSize , name ) { var helper = this . setupHelper ( paramSize , name ) ; this . push ( this . source . functionCall ( helper . name , 'call' , helper . callParams ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ assignToHash ] On stack before : value ... hash ... On stack after : ... hash ... Pops a value off the stack and assigns it to the current hash [CODESPLIT] function assignToHash ( key ) { var value = this . popStack ( ) , context = undefined , type = undefined , id = undefined ; if ( this . trackIds ) { id = this . popStack ( ) ; } if ( this . stringParams ) { type = this . popStack ( ) ; context = this . popStack ( ) ; } var hash = this . hash ; if ( context ) { hash . contexts [ key ] = context ; } if ( type ) { hash . types [ key ] = type ; } if ( id ) { hash . ids [ key ] = id ; } hash . values [ key ] = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 29 [CODESPLIT] function ( module , exports , __webpack_require__ ) { /* global define */ 'use strict' ; exports . __esModule = true ; var _utils = __webpack_require__ ( 5 ) ; var SourceNode = undefined ; try { /* istanbul ignore next */ if ( false ) { // We don't support this in AMD environments. For these environments, we asusme that // they are running on the browser and thus have no need for the source-map library. var SourceMap = require ( 'source-map' ) ; SourceNode = SourceMap . SourceNode ; } } catch ( err ) { } /* NOP */ /* istanbul ignore if: tested but not covered in istanbul due to dist build  */ if ( ! SourceNode ) { SourceNode = function ( line , column , srcFile , chunks ) { this . src = '' ; if ( chunks ) { this . add ( chunks ) ; } } ; /* istanbul ignore next */ SourceNode . prototype = { add : function add ( chunks ) { if ( _utils . isArray ( chunks ) ) { chunks = chunks . join ( '' ) ; } this . src += chunks ; } , prepend : function prepend ( chunks ) { if ( _utils . isArray ( chunks ) ) { chunks = chunks . join ( '' ) ; } this . src = chunks + this . src ; } , toStringWithSourceMap : function toStringWithSourceMap ( ) { return { code : this . toString ( ) } ; } , toString : function toString ( ) { return this . src ; } } ; } function castChunk ( chunk , codeGen , loc ) { if ( _utils . isArray ( chunk ) ) { var ret = [ ] ; for ( var i = 0 , len = chunk . length ; i < len ; i ++ ) { ret . push ( codeGen . wrap ( chunk [ i ] , loc ) ) ; } return ret ; } else if ( typeof chunk === 'boolean' || typeof chunk === 'number' ) { // Handle primitives that the SourceNode will throw up on return chunk + '' ; } return chunk ; } function CodeGen ( srcFile ) { this . srcFile = srcFile ; this . source = [ ] ; } CodeGen . prototype = { isEmpty : function isEmpty ( ) { return ! this . source . length ; } , prepend : function prepend ( source , loc ) { this . source . unshift ( this . wrap ( source , loc ) ) ; } , push : function push ( source , loc ) { this . source . push ( this . wrap ( source , loc ) ) ; } , merge : function merge ( ) { var source = this . empty ( ) ; this . each ( function ( line ) { source . add ( [ '  ' , line , '\\n' ] ) ; } ) ; return source ; } , each : function each ( iter ) { for ( var i = 0 , len = this . source . length ; i < len ; i ++ ) { iter ( this . source [ i ] ) ; } } , empty : function empty ( ) { var loc = this . currentLocation || { start : { } } ; return new SourceNode ( loc . start . line , loc . start . column , this . srcFile ) ; } , wrap : function wrap ( chunk ) { var loc = arguments . length <= 1 || arguments [ 1 ] === undefined ? this . currentLocation || { start : { } } : arguments [ 1 ] ; if ( chunk instanceof SourceNode ) { return chunk ; } chunk = castChunk ( chunk , this , loc ) ; return new SourceNode ( loc . start . line , loc . start . column , this . srcFile , chunk ) ; } , functionCall : function functionCall ( fn , type , params ) { params = this . generateList ( params ) ; return this . wrap ( [ fn , type ? '.' + type + '(' : '(' , params , ')' ] ) ; } , quotedString : function quotedString ( str ) { return '\"' + ( str + '' ) . replace ( / \\\\ / g , '\\\\\\\\' ) . replace ( / \" / g , '\\\\\"' ) . replace ( / \\n / g , '\\\\n' ) . replace ( / \\r / g , '\\\\r' ) . replace ( / \\u2028 / g , '\\\\u2028' ) // Per Ecma-262 7.3 + 7.8.4 . replace ( / \\u2029 / g , '\\\\u2029' ) + '\"' ; } , objectLiteral : function objectLiteral ( obj ) { var pairs = [ ] ; for ( var key in obj ) { if ( obj . hasOwnProperty ( key ) ) { var value = castChunk ( obj [ key ] , this ) ; if ( value !== 'undefined' ) { pairs . push ( [ this . quotedString ( key ) , ':' , value ] ) ; } } } var ret = this . generateList ( pairs ) ; ret . prepend ( '{' ) ; ret . add ( '}' ) ; return ret ; } , generateList : function generateList ( entries ) { var ret = this . empty ( ) ; for ( var i = 0 , len = entries . length ; i < len ; i ++ ) { if ( i ) { ret . add ( ',' ) ; } ret . add ( castChunk ( entries [ i ] , this ) ) ; } return ret ; } , generateArray : function generateArray ( entries ) { var ret = this . generateList ( entries ) ; ret . prepend ( '[' ) ; ret . add ( ']' ) ; return ret ; } } ; exports [ 'default' ] = CodeGen ; module . exports = exports [ 'default' ] ; /***/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The allocation of the changed nodes . [CODESPLIT] function reduceChildListMutation ( mutationContent , record ) { const isAdded = Boolean ( record . addedNodes . length ) ; const isNext = Boolean ( record . nextSibling ) ; const isPrev = Boolean ( record . previousSibling ) ; const isRemoved = Boolean ( record . removedNodes . length ) ; // innerHTML or replace if ( isAdded && ( isRemoved || ( ! isRemoved && ! isNext && ! isPrev ) ) ) { while ( mutationContent . firstChild ) { mutationContent . removeChild ( mutationContent . firstChild ) ; } forEach ( record . addedNodes , function ( node ) { mutationContent . appendChild ( node ) ; } ) ; // appendChild } else if ( isAdded && ! isRemoved && ! isNext && isPrev ) { forEach ( record . addedNodes , function ( node ) { mutationContent . appendChild ( node ) ; } ) ; // insertBefore } else if ( isAdded && ! isRemoved && isNext && ! isPrev ) { forEach ( record . addedNodes , function ( node ) { mutationContent . insertBefore ( node , mutationContent . firstChild ) ; } ) ; } return mutationContent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents a Kademlia node [CODESPLIT] function Node ( options ) { if ( ! ( this instanceof Node ) ) { return new Node ( options ) } events . EventEmitter . call ( this ) this . _setStorageAdapter ( options . storage ) this . _log = options . logger this . _rpc = options . transport this . _self = this . _rpc . _contact this . _validator = options . validator this . _router = options . router || new Router ( { logger : this . _log , transport : this . _rpc , validator : this . _validateKeyValuePair . bind ( this ) } ) this . _bindRouterEventHandlers ( ) this . _bindRPCMessageHandlers ( ) this . _startReplicationInterval ( ) this . _startExpirationInterval ( ) this . _log . info ( 'node created' , { nodeID : this . _self . nodeID } ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a promise from the queue that will resolve when there is a slot available [CODESPLIT] function ( ) { var deferred ; deferred = Q . defer ( ) ; if ( running . length < limit ) { running . push ( deferred ) ; deferred . resolve ( ) ; } else { queue . push ( deferred ) ; } return deferred . promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals the queue an item is done running [CODESPLIT] function ( ) { var next ; running . pop ( ) ; if ( queue . length > 0 && running . length < limit ) { switch ( type ) { case \"lifo\" : next = queue . pop ( ) ; break ; default : next = queue . shift ( ) ; } running . push ( next ) ; return next . resolve ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flushes the queue . Will reject any remaining promises [CODESPLIT] function ( ) { var promise ; while ( promise = queue . pop ( ) ) { promise . reject ( \"flush\" ) ; } while ( promise = running . pop ( ) ) { promise . reject ( \"flush\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads matching fields from a model instance into this form . [CODESPLIT] function ( record ) { var me = this ; me . _record = record ; if ( record && record . data ) { me . setValues ( record . data ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a Ajax - based submission of form values ( if { @link #standardSubmit } is false ) or otherwise executes a standard HTML Form submit action . [CODESPLIT] function ( options , e ) { options = options || { } ; var me = this , formValues = me . getValues ( me . getStandardSubmit ( ) || ! options . submitDisabled ) , form = me . element . dom || { } ; if ( this . getEnableSubmissionForm ( ) ) { form = this . createSubmissionForm ( form , formValues ) ; } options = Ext . apply ( { url : me . getUrl ( ) || form . action , submit : false , form : form , method : me . getMethod ( ) || form . method || 'post' , autoAbort : false , params : null , waitMsg : null , headers : null , success : null , failure : null } , options || { } ) ; return me . fireAction ( 'beforesubmit' , [ me , formValues , options , e ] , 'doBeforeSubmit' , null , null , 'after' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an Ajax or Ext . Direct call to load values for this form . [CODESPLIT] function ( options ) { options = options || { } ; var me = this , api = me . getApi ( ) , url = me . getUrl ( ) || options . url , waitMsg = options . waitMsg , successFn = function ( response , data ) { me . setValues ( data . data ) ; if ( Ext . isFunction ( options . success ) ) { options . success . call ( options . scope || me , me , response , data ) ; } me . fireEvent ( 'load' , me , response ) ; } , failureFn = function ( response , data ) { if ( Ext . isFunction ( options . failure ) ) { options . failure . call ( scope , me , response , data ) ; } me . fireEvent ( 'exception' , me , response ) ; } , load , method , args ; if ( options . waitMsg ) { if ( typeof waitMsg === 'string' ) { waitMsg = { xtype : 'loadmask' , message : waitMsg } ; } me . setMasked ( waitMsg ) ; } if ( api ) { load = api . load ; if ( typeof load === 'string' ) { load = Ext . direct . Manager . parseMethod ( load ) ; if ( load ) { api . load = load ; } } if ( load ) { method = load . directCfg . method ; args = method . getArgs ( me . getParams ( options . params ) , me . getParamOrder ( ) , me . getParamsAsHash ( ) ) ; args . push ( function ( data , response , success ) { me . setMasked ( false ) ; if ( success ) { successFn ( response , data ) ; } else { failureFn ( response , data ) ; } } , me ) ; return load . apply ( window , args ) ; } } else if ( url ) { return Ext . Ajax . request ( { url : url , timeout : ( options . timeout || this . getTimeout ( ) ) * 1000 , method : options . method || 'GET' , autoAbort : options . autoAbort , headers : Ext . apply ( { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } , options . headers || { } ) , callback : function ( callbackOptions , success , response ) { var responseText = response . responseText , statusResult = Ext . Ajax . parseStatus ( response . status , response ) ; me . setMasked ( false ) ; if ( success ) { if ( statusResult && responseText . length == 0 ) { success = true ; } else { response = Ext . decode ( responseText ) ; success = ! ! response . success ; } if ( success ) { successFn ( response , responseText ) ; } else { failureFn ( response , responseText ) ; } } else { failureFn ( response , responseText ) ; } } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the values of form fields in bulk . Example usage : [CODESPLIT] function ( values ) { var fields = this . getFields ( ) , me = this , name , field , value , ln , i , f ; values = values || { } ; for ( name in values ) { if ( values . hasOwnProperty ( name ) ) { field = fields [ name ] ; value = values [ name ] ; if ( field ) { // If there are multiple fields with the same name. Checkboxes, radio fields and maybe event just normal fields.. if ( Ext . isArray ( field ) ) { ln = field . length ; // Loop through each of the fields for ( i = 0 ; i < ln ; i ++ ) { f = field [ i ] ; if ( f . isRadio ) { // If it is a radio field just use setGroupValue which will handle all of the radio fields f . setGroupValue ( value ) ; break ; } else if ( f . isCheckbox ) { if ( Ext . isArray ( value ) ) { f . setChecked ( ( value . indexOf ( f . _value ) != - 1 ) ) ; } else { f . setChecked ( ( value == f . _value ) ) ; } } else { // If it is a bunch of fields with the same name, check if the value is also an array, so we can map it // to each field if ( Ext . isArray ( value ) ) { f . setValue ( value [ i ] ) ; } } } } else { if ( field . isRadio || field . isCheckbox ) { // If the field is a radio or a checkbox field . setChecked ( value ) ; } else { // If just a normal field field . setValue ( value ) ; } } if ( me . getTrackResetOnLoad ( ) ) { field . resetOriginalValue ( ) ; } } } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an object containing the value of each field in the form keyed to the field s name . For groups of checkbox fields with the same name it will be arrays of values . For example : [CODESPLIT] function ( enabled , all ) { var fields = this . getFields ( ) , values = { } , isArray = Ext . isArray , field , value , addValue , bucket , name , ln , i ; // Function which you give a field and a name, and it will add it into the values // object accordingly addValue = function ( field , name ) { if ( ! all && ( ! name || name === 'null' ) || field . isFile ) { return ; } if ( field . isCheckbox ) { value = field . getSubmitValue ( ) ; } else { value = field . getValue ( ) ; } if ( ! ( enabled && field . getDisabled ( ) ) ) { // RadioField is a special case where the value returned is the fields valUE // ONLY if it is checked if ( field . isRadio ) { if ( field . isChecked ( ) ) { values [ name ] = value ; } } else { // Check if the value already exists bucket = values [ name ] ; if ( ! Ext . isEmpty ( bucket ) ) { // if it does and it isn't an array, we need to make it into an array // so we can push more if ( ! isArray ( bucket ) ) { bucket = values [ name ] = [ bucket ] ; } // Check if it is an array if ( isArray ( value ) ) { // Concat it into the other values bucket = values [ name ] = bucket . concat ( value ) ; } else { // If it isn't an array, just pushed more values bucket . push ( value ) ; } } else { values [ name ] = value ; } } } } ; // Loop through each of the fields, and add the values for those fields. for ( name in fields ) { if ( fields . hasOwnProperty ( name ) ) { field = fields [ name ] ; if ( isArray ( field ) ) { ln = field . length ; for ( i = 0 ; i < ln ; i ++ ) { addValue ( field [ i ] , name ) ; } } else { addValue ( field , name ) ; } } } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all { [CODESPLIT] function ( byName ) { var fields = { } , itemName ; var getFieldsFrom = function ( item ) { if ( item . isField ) { itemName = item . getName ( ) ; if ( ( byName && itemName == byName ) || typeof byName == 'undefined' ) { if ( fields . hasOwnProperty ( itemName ) ) { if ( ! Ext . isArray ( fields [ itemName ] ) ) { fields [ itemName ] = [ fields [ itemName ] ] ; } fields [ itemName ] . push ( item ) ; } else { fields [ itemName ] = item ; } } } if ( item . isContainer ) { item . items . each ( getFieldsFrom ) ; } } ; this . getItems ( ) . each ( getFieldsFrom ) ; return ( byName ) ? ( fields [ byName ] || [ ] ) : fields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of fields in this formpanel . [CODESPLIT] function ( ) { var fields = [ ] ; var getFieldsFrom = function ( item ) { if ( item . isField ) { fields . push ( item ) ; } if ( item . isContainer ) { item . items . each ( getFieldsFrom ) ; } } ; this . items . each ( getFieldsFrom ) ; return fields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shows a generic / custom mask over a designated Element . @param { String / Object } cfg Either a string message or a configuration object supporting the following options : [CODESPLIT] function ( cfg , target ) { //<debug> Ext . Logger . warn ( 'showMask is now deprecated. Please use Ext.form.Panel#setMasked instead' ) ; //</debug> cfg = Ext . isObject ( cfg ) ? cfg . message : cfg ; if ( cfg ) { this . setMasked ( { xtype : 'loadmask' , message : cfg } ) ; } else { this . setMasked ( true ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the currently focused field [CODESPLIT] function ( ) { var fields = this . getFieldsArray ( ) , ln = fields . length , field , i ; for ( i = 0 ; i < ln ; i ++ ) { field = fields [ i ] ; if ( field . isFocused ) { return field ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A bucket is a column of the routing table . It is an array - like object that holds { [CODESPLIT] function Bucket ( index , routingTable ) { if ( ! ( this instanceof Bucket ) ) { return new Bucket ( ) } assert ( _ . isNumber ( index ) && index >= 0 && index <= constants . B ) this . index = index this . contacts = [ ] this . _cache = { } this . _routingTable = routingTable }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy static assets from theme to dist [CODESPLIT] function staticMove ( source : string , dest : string , assets : Array < string > ) : Promise { assets . forEach ( folder => { fs . copy ( path . join ( source , folder ) , path . join ( dest , folder ) ) ; } ) ; return Promise . resolve ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile scss assets [CODESPLIT] function scss ( source : string , dest : string ) : Promise { return new Promise ( ( resolve , reject ) => { sass . render ( { file : source , outFile : dest , outputStyle : 'compressed' , } , ( err , result ) => { if ( err ) reject ( err ) ; fs . ensureFile ( dest ) . then ( fs . writeFile ( dest , result . css ) ) . then ( resolve ) . catch ( reject ) ; } , ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "< / debug > [CODESPLIT] function ( axis , scrollerPosition ) { if ( ! this . isAxisEnabled ( axis ) ) { return this ; } var scroller = this . getScroller ( ) , scrollerMaxPosition = scroller . getMaxPosition ( ) [ axis ] , scrollerContainerSize = scroller . getContainerSize ( ) [ axis ] , value ; if ( scrollerMaxPosition === 0 ) { value = scrollerPosition / scrollerContainerSize ; if ( scrollerPosition >= 0 ) { value += 1 ; } } else { if ( scrollerPosition > scrollerMaxPosition ) { value = 1 + ( ( scrollerPosition - scrollerMaxPosition ) / scrollerContainerSize ) ; } else if ( scrollerPosition < 0 ) { value = scrollerPosition / scrollerContainerSize ; } else { value = scrollerPosition / scrollerMaxPosition ; } } this . getIndicators ( ) [ axis ] . setValue ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new instance of { [CODESPLIT] function ( e ) { var changedTouches = e . changedTouches , touch = ( changedTouches && changedTouches . length > 0 ) ? changedTouches [ 0 ] : e ; return this . fromTouch ( touch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Whether the given point is not away from this point within the given threshold amount . [CODESPLIT] function ( point , threshold ) { if ( typeof threshold == 'number' ) { threshold = { x : threshold } ; threshold . y = threshold . x ; } var x = point . x , y = point . y , thresholdX = threshold . x , thresholdY = threshold . y ; return ( this . x <= x + thresholdX && this . x >= x - thresholdX && this . y <= y + thresholdY && this . y >= y - thresholdY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare this point with another point when the x and y values of both points are rounded . For example : [ 100 . 3 199 . 8 ] will equals to [ 100 200 ] . [CODESPLIT] function ( point ) { if ( typeof point != 'object' ) { point = { x : 0 , y : 0 } ; } return ( Math . round ( this . x ) === Math . round ( point . x ) && Math . round ( this . y ) === Math . round ( point . y ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run a single SSH command and returns the result . When fullfilled the promise result is an object with the following properties : [CODESPLIT] function sshExecSingleCommand ( cnxParams , cmd , fnOutput ) { var result = { \"command\" : cmd , \"success\" : true , \"error\" : null , \"value\" : null } ; return Q . promise ( function ( resolve , reject ) { var sshClient = new SSHClient ( ) ; sshClient . on ( 'ready' , function ( ) { // sshClient Ready var stdout = \"\" ; var stderr = \"\" ; sshClient . exec ( cmd , function ( err , stream ) { if ( err ) { throw err ; } stream . on ( 'close' , function ( code , signal ) { sshClient . end ( ) ; if ( code !== 0 ) { result . success = false ; result . error = { \"stderr\" : stderr , \"code\" : code } ; reject ( result ) ; } else if ( fnOutput && typeof fnOutput === 'function' ) { result . value = fnOutput ( stdout ) ; resolve ( result ) ; } else { result . value = stdout ; resolve ( result ) ; } } ) . on ( 'data' , function ( data ) { stdout += data ; } ) . stderr . on ( 'data' , function ( data ) { stderr += data ; } ) ; } ) ; } ) . on ( 'error' , function ( error ) { // sshClient Error result . success = false ; result . error = error ; reject ( result ) ; } ) . connect ( cnxParams ) ; // sshClient Connect } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a list of commands in parallel and returns a Promise for all results . This function is a wrapper around * Q . allSettled * API . [CODESPLIT] function sshCommandParallel ( connection , commands , fnOutput ) { var commandList = commands . map ( function ( command ) { return sshExecSingleCommand ( connection , command , fnOutput ) ; } ) ; return Q . allSettled ( commandList ) . then ( function ( results ) { return results . map ( function ( result ) { if ( result . state === \"rejected\" ) { return result . reason ; } else { return result . value ; } } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sequentially execute a list of Promised based SSH command and returns a Promise whose value is resvoled as an array . This array contains objects that holds the SSH command success or error . [CODESPLIT] function sshCommandSequence ( connection , commands , fnOutput ) { var allResults = [ ] ; var successHandler = function ( nextPromise ) { return function ( result ) { if ( result !== true ) { // the first result must be ignored allResults . push ( result ) ; } return nextPromise ( ) ; } ; } ; var errorHandler = function ( nextPromise ) { return function ( error ) { allResults . push ( error ) ; return nextPromise ( ) ; } ; } ; // start the sequential fullfilment of the Promise chain // The first result (true) will not be inserted in the result array, it is here // just to start the chain. var result = Q ( true ) ; commands . map ( function ( command ) { return function ( ) { return sshExecSingleCommand ( connection , command , fnOutput ) ; } ; } ) . forEach ( function ( f ) { result = result . then ( successHandler ( f ) , errorHandler ( f ) ) ; } ) ; // As the last result is not handled in the forEach loop, we must handle it now return result . then ( function ( finalResult ) { allResults . push ( finalResult ) ; return allResults ; } , function ( error ) { allResults . push ( error ) ; return allResults ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - replacement helpers [CODESPLIT] function replaceRefs ( parsed , options ) { var topLevel = topLevelDeclsAndRefs ( parsed ) , refsToReplace = topLevel . refs . filter ( ref => shouldRefBeCaptured ( ref , topLevel , options ) ) , locallyIgnored = [ ] ; const replaced = ReplaceVisitor . run ( parsed , ( node , path ) => { // cs 2016/06/27, 1a4661 // ensure keys of shorthand properties are not renamed while capturing if ( node . type === \"Property\" && refsToReplace . includes ( node . key ) && node . shorthand ) return prop ( id ( node . key . name ) , node . value ) ; // don't replace var refs in expressions such as \"export { x }\" or \"export var x;\" // We make sure that those var references are defined in insertDeclarationsForExports() if ( node . type === \"ExportNamedDeclaration\" ) { var { declaration , specifiers } = node ; if ( declaration ) { if ( declaration . id ) locallyIgnored . push ( declaration . id ) else if ( declaration . declarations ) locallyIgnored . push ( ... declaration . declarations . map ( ( { id } ) => id ) ) } specifiers && specifiers . forEach ( ( { local } ) => locallyIgnored . push ( local ) ) ; return node ; } // declaration wrapper function for assignments // \"a = 3\" => \"a = _define('a', 'assignment', 3, _rec)\" if ( node . type === \"AssignmentExpression\" && refsToReplace . includes ( node . left ) && options . declarationWrapper ) return { ... node , right : declarationWrapperCall ( options . declarationWrapper , null , literal ( node . left . name ) , literal ( \"assignment\" ) , node . right , options . captureObj , options ) } ; return node } ) ; return ReplaceVisitor . run ( replaced , ( node , path , parent ) => refsToReplace . includes ( node ) && ! locallyIgnored . includes ( node ) ? member ( options . captureObj , node ) : node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - naming - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - [CODESPLIT] function generateUniqueName ( declaredNames , hint ) { var unique = hint , n = 1 ; while ( declaredNames . indexOf ( unique ) > - 1 ) { if ( n > 1000 ) throw new Error ( \"Endless loop searching for unique variable \" + unique ) ; unique = unique . replace ( / _[0-9]+$|$ / , \"_\" + ( ++ n ) ) ; } return unique ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - exclude / include helpers - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - [CODESPLIT] function additionalIgnoredDecls ( parsed , options ) { var topLevel = topLevelDeclsAndRefs ( parsed ) , ignoreDecls = [ ] ; for ( var i = 0 ; i < topLevel . scope . varDecls . length ; i ++ ) { var decl = topLevel . scope . varDecls [ i ] , path = Path ( topLevel . scope . varDeclPaths [ i ] ) , parent = path . slice ( 0 , - 1 ) . get ( parsed ) ; if ( parent . type === \"ForStatement\" || parent . type === \"ForInStatement\" || parent . type === \"ForOfStatement\" || parent . type === \"ExportNamedDeclaration\" ) ignoreDecls . push ( ... decl . declarations ) } return topLevel . scope . catches . map ( ea => ea . name ) . concat ( ignoreDecls . map ( ea => ea . id . name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - capturing specific code - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - [CODESPLIT] function replaceClassDecls ( parsed , options ) { if ( options . classToFunction ) return classToFunctionTransform ( parsed , options . classToFunction ) ; var topLevel = topLevelDeclsAndRefs ( parsed ) ; if ( ! topLevel . classDecls . length ) return parsed ; for ( var i = parsed . body . length - 1 ; i >= 0 ; i -- ) { var stmt = parsed . body [ i ] ; if ( stmt . id && topLevel . classDecls . includes ( stmt ) ) parsed . body . splice ( i + 1 , 0 , assignExpr ( options . captureObj , stmt . id , stmt . id , false ) ) ; } return parsed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - code generation helpers - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - [CODESPLIT] function varDeclOrAssignment ( parsed , declarator , kind ) { var topLevel = topLevelDeclsAndRefs ( parsed ) , name = declarator . id . name return topLevel . declaredNames . indexOf ( name ) > - 1 ? // only create a new declaration if necessary exprStmt ( assign ( declarator . id , declarator . init ) ) : { declarations : [ declarator ] , kind : kind || \"var\" , type : \"VariableDeclaration\" } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Storage model for DHT items which is serialized to JSON before being passed to the storage adapter [CODESPLIT] function Item ( key , value , publisher , timestamp ) { if ( ! ( this instanceof Item ) ) { return new Item ( key , value , publisher , timestamp ) } assert ( typeof key === 'string' , 'Invalid key supplied' ) assert ( utils . isValidKey ( publisher ) , 'Invalid publisher nodeID supplied' ) if ( timestamp ) { assert ( typeof timestamp === 'number' , 'Invalid timestamp supplied' ) assert ( Date . now ( ) >= timestamp , 'Timestamp cannot be in the future' ) } this . key = key this . value = value this . publisher = publisher this . timestamp = timestamp || Date . now ( ) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "login [CODESPLIT] function ( ) { function onLoginResponse ( res ) { if ( res . statusCode === 302 && res . headers [ 'location' ] . indexOf ( 'login.do' ) === - 1 ) { console . log ( 'login success' ) ; } else { throw new Error ( 'Login error' ) ; } } request . post ( process . env . ONEAPM_LOGIN_URL ) . form ( { encode : true , username : process . env . ONEAPM_USERNAME , strong : true , password : base64 ( process . env . ONEAPM_PASSWORD ) , } ) . on ( 'response' , onLoginResponse ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a handle function for a given top [CODESPLIT] function on ( top ) { top = typeof top === 'string' ? document . querySelector ( top ) : top ; var h = handle . bind ( this , top ) ; h . once = once . bind ( this , top ) ; return h ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind element event type to fn . [CODESPLIT] function handle ( top , element , type , fn , capture ) { if ( ! element || ! ( typeof element === 'string' || typeof element . length === 'number' || typeof element . addEventListener === 'function' ) ) { throw new TypeError ( 'Cannot bind event ' + inspect ( type ) + ' to ' + inspect ( element ) ) ; } if ( typeof type !== 'string' ) throw new TypeError ( 'Event type must be a string, e.g. \"click\", not ' + inspect ( type ) ) ; if ( typeof fn !== 'function' ) throw new TypeError ( '`fn` (the function to call when the event is triggered) must be a function, not ' + inspect ( fn ) ) ; if ( capture !== undefined && capture !== false && capture !== true ) { throw new TypeError ( '`capture` must be `undefined` (defaults to `false`), `false` or `true`, not ' + inspect ( capture ) ) ; } if ( typeof element === 'string' ) { return handleElement ( top , type , function ( body , e ) { var target = findMatch ( body , e . target , element ) ; e . delegateTarget = target ; if ( target ) fn ( target , e ) ; } , capture ) ; } else if ( typeof element . addEventListener !== 'function' && typeof element . length === 'number' ) { return handleElements ( element , type , fn , capture ) ; } else { return handleElement ( element , type , fn , capture ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind elements event type to fn . [CODESPLIT] function handleElements ( elements , type , fn , capture ) { if ( ! elements || typeof elements . length !== 'number' ) throw new TypeError ( 'Cannot bind event ' + inspect ( type ) + ' to ' + inspect ( elements ) ) ; if ( typeof type !== 'string' ) throw new TypeError ( 'Event type must be a string, e.g. \"click\", not ' + inspect ( type ) ) ; if ( typeof fn !== 'function' ) throw new TypeError ( '`fn` (the function to call when the event is triggered) must be a function, not ' + inspect ( fn ) ) ; if ( capture !== undefined && capture !== false && capture !== true ) { throw new TypeError ( '`capture` must be `undefined` (defaults to `false`), `false` or `true`, not ' + inspect ( capture ) ) ; } var handles = [ ] ; for ( var i = 0 ; i < elements . length ; i ++ ) { handles . push ( handleElement ( elements [ i ] , type , fn , capture ) ) ; } return function dispose ( ) { for ( var i = 0 ; i < handles . length ; i ++ ) { handles [ i ] ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind element event type to fn . [CODESPLIT] function handleElement ( element , type , fn , capture ) { if ( ! element || typeof element . addEventListener !== 'function' ) throw new TypeError ( 'Cannot bind event ' + inspect ( type ) + ' to ' + inspect ( element ) ) ; if ( typeof type !== 'string' ) throw new TypeError ( 'Event type must be a string, e.g. \"click\", not ' + inspect ( type ) ) ; if ( typeof fn !== 'function' ) throw new TypeError ( '`fn` (the function to call when the event is triggered) must be a function, not ' + inspect ( fn ) ) ; if ( capture !== undefined && capture !== false && capture !== true ) { throw new TypeError ( '`capture` must be `undefined` (defaults to `false`), `false` or `true`, not ' + inspect ( capture ) ) ; } function onEvent ( e ) { e . delegateTarget = element ; return fn ( element , e ) ; } element . addEventListener ( type , onEvent , capture || false ) ; return element . removeEventListener . bind ( element , type , onEvent , capture || false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look for an element that is a child of top and a parent of bottom ( or bottom ) that matches selector . [CODESPLIT] function findMatch ( top , bottom , selector ) { while ( bottom != top && bottom ) { if ( matches ( bottom , selector ) ) return bottom ; bottom = bottom . parentElement ; } if ( bottom && matches ( bottom , selector ) ) return bottom ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recadrage et redimensionnement d une image ( en SVG et canvas ) [CODESPLIT] function CropAndResize ( arg , opt ) { /**\n         * dimensions initiales du rectangle de recadrage (si keepRatio == true, height sera écrasé par la valeur proportionnelle)\n         */ this . boxInit = new Box ( ) ; /**\n         * Objet Editable\n         */ this . editor = new Editor ( arg ) ; /**\n         * Masque pour ombrer ce qui n'est pas sélectionné\n         */ this . mask = new JSYG ( '<rect>' ) [ 0 ] ; /**\n         * Cadre de sélection\n         */ this . selection = new JSYG ( '<rect>' ) [ 0 ] ; /**\n         * Element pattern\n         */ this . pattern = new JSYG ( '<pattern>' ) [ 0 ] ; if ( arg ) this . setNode ( arg ) ; if ( opt ) this . enable ( opt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exporte la sélection sous forme d objet Canvas [CODESPLIT] function ( width , height ) { var box = this . selection . getBBox ( ) ; return JSYG ( this . node ) . toCanvas ( ) . then ( function ( canvas ) { var maxWidth = canvas . getAttribute ( \"width\" ) , maxHeight = canvas . getAttribute ( \"height\" ) , x = Math . max ( 0 , box . x ) , y = Math . max ( 0 , box . y ) , boxWidth = Math . min ( maxWidth , box . width ) , boxHeight = Math . min ( maxHeight , box . height ) ; canvas = new Canvas ( canvas ) ; canvas = canvas . crop ( x , y , boxWidth , boxHeight ) ; if ( width != null || height != null ) canvas = canvas . resize ( width , height ) ; return canvas [ 0 ] ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Active le recadrage [CODESPLIT] function ( opt ) { this . disable ( ) ; if ( opt ) this . set ( opt ) ; var jNode = new JSYG ( this . node ) , dim = jNode . getDim ( ) , color = jNode . fill ( ) , svg = jNode . offsetParent ( ) , id = 'idpattern' + JSYG . rand ( 0 , 5000 ) , g , rect , selection ; if ( ! color || color == 'transparent' || color == 'none' ) color = 'white' ; if ( dim . width < this . boxInit . width ) this . boxInit . width = dim . width ; if ( dim . height < this . boxInit . height ) this . boxInit . height = dim . height ; rect = new JSYG ( '<rect>' ) . fill ( color ) ; g = new JSYG ( '<g>' ) . append ( rect ) ; new JSYG ( this . pattern ) . attr ( { id : id , patternUnits : 'userSpaceOnUse' } ) . append ( g ) . appendTo ( svg ) ; new JSYG ( this . mask ) . css ( 'fill-opacity' , 0.5 ) . appendTo ( svg ) ; if ( this . keepRatio ) this . boxInit . height = dim . height * this . boxInit . width / dim . width ; selection = new JSYG ( this . selection ) . attr ( this . boxInit ) . attr ( 'fill' , \"url(#\" + id + \")\" ) . appendTo ( svg ) ; this . editor . target ( selection ) ; this . editor . displayShadow = false ; new JSYG ( this . editor . pathBox ) . css ( 'fill-opacity' , 0 ) ; this . editor . ctrlsDrag . enable ( { bounds : 0 } ) ; this . editor . ctrlsResize . enable ( { keepRatio : this . keepRatio , bounds : 0 } ) ; this . editor . show ( ) ; this . enabled = true ; this . update ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Désactive le recadrage [CODESPLIT] function ( ) { this . editor . hide ( ) ; new JSYG ( this . pattern ) . remove ( ) ; new JSYG ( this . mask ) . remove ( ) ; new JSYG ( this . selection ) . remove ( ) ; this . enabled = false ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ TODO : at this moment we support only postinstall scripts from installed components only from component in current dir ... / should be fixed in future ... [CODESPLIT] function postinstall ( ) { var json = Readers . getBowerJSON ( ) ; if ( ! json . scripts || ! json . scripts . postinstall ) return ; ///nothing to be done ... Node . executeCommand ( json . scripts . postinstall ) . done ( Node . info . bind ( null , 'Postinstall done' ) , Node . info . bind ( null , 'Postinstall failed' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a pie in the pies / folder with the default files . [CODESPLIT] function ( pie ) { var current = process . cwd ( ) ; // First, check if there is a pies/ folder var files = fs . readdirSync ( current ) ; if ( ! ~ files . indexOf ( 'pies' ) ) { // If it doesn't exist, we're doing something wrong console . error ( \"\\nThe pies/ folder doesn't exist.\" ) ; console . error ( \"Are you sure you're at the root of your folder?\\n\" ) ; process . exit ( - 1 ) ; } console . log ( '\\nCreating folder pies/' + pie + '...' ) ; // First, create the directory wrench . mkdirSyncRecursive ( path . join ( current , 'pies' , pie ) ) ; console . log ( '\\nCopying the files in pies/' + pie + '...' ) ; // Then, copy the files into it wrench . copyDirSyncRecursive ( path . join ( __dirname , 'default' , 'pie' ) , path . join ( current , 'pies' , pie ) ) ; // Now, get the pies.json and add the new pie to it var piesPath = path . join ( current , 'pies.json' ) ; // First, get the datas var pies = JSON . parse ( fs . readFileSync ( piesPath ) ) ; // We need to check if the pie has a \"/\", it'd mean // that the path property is different than the name. var pieName ; if ( ~ pie . indexOf ( '/' ) ) { pieName = pie . split ( '/' ) . reverse ( ) [ 0 ] ; } else { pieName = pie ; } // Add the new property to it pies [ pieName ] = { path : pie } ; // And write the object back to the file fs . writeFileSync ( piesPath , JSON . stringify ( pies , null , 4 ) ) ; console . log ( '\\nPie \"' + pie + '\" created.\\n' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decorator which validates an options hash and delegates to func . If the options are not an object a TypeError is thrown . If the options hash is missing any of the required properties a RangeError is thrown . [CODESPLIT] function reqo ( func , requiredKeys ) { var optionsIndex = arguments [ 2 ] === undefined ? 0 : arguments [ 2 ] ; var context = arguments [ 3 ] === undefined ? undefined : arguments [ 3 ] ; return function ( ) { for ( var _len = arguments . length , args = Array ( _len ) , _key = 0 ; _key < _len ; _key ++ ) { args [ _key ] = arguments [ _key ] ; } var options = args [ optionsIndex ] ; if ( ! ( 0 , _lodash . isPlainObject ) ( options ) ) { throw new TypeError ( 'options must be a plain object literal' ) ; } // Check that all of the properties represented in requiredKeys are present // as properties in the options hash. Does so by taking an intersection // of the options keys and the required keys, and then checking the // intersection is equivalent to the requirements. var optionsKeys = ( 0 , _lodash . keys ) ( options ) ; var intersectionOfKeys = ( 0 , _lodash . intersection ) ( requiredKeys , optionsKeys ) ; var hasAllRequiredKeys = ( 0 , _lodash . isEqual ) ( intersectionOfKeys , requiredKeys ) ; // If any required keys are missing in options hash. if ( ! hasAllRequiredKeys ) { var missingOptions = ( 0 , _lodash . difference ) ( requiredKeys , intersectionOfKeys ) ; throw new RangeError ( 'Options must contain ' + missingOptions . toString ( ) ) ; } // Call the decorated function in the right context with its' arguments. var boundFunc = func . bind ( context ) ; return boundFunc . apply ( undefined , args ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strategy constructor . [CODESPLIT] function Strategy ( options , verify ) { options = options || { } ; if ( options . statusnet === undefined ) { throw new Error ( \"A StatusNet instance is required (e.g. identi.ca)\" ) ; } this . prefix = \"https://\" + options . statusnet + \"/api\" ; options . requestTokenURL = options . requestTokenURL || this . prefix + '/oauth/request_token' ; options . accessTokenURL = options . accessTokenURL || this . prefix + '/oauth/access_token' ; options . userAuthorizationURL = options . userAuthorizationURL || this . prefix + '/oauth/authorize' ; options . sessionKey = options . sessionKey || 'oauth:' + options . statusnet ; OAuthStrategy . call ( this , options , verify ) ; this . name = options . statusnet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new array with the same content as the input minus the specified values . [CODESPLIT] function without ( toRemove ) { return function ( prev , curr ) { if ( ! Array . isArray ( prev ) ) { prev = ! testValue ( prev , toRemove ) ? [ prev ] : [ ] } if ( ! testValue ( curr , toRemove ) ) prev . push ( curr ) return prev } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the dhtmlXToolbarObject inside its container . [CODESPLIT] function initDhtmlxToolbar ( container ) { var impl = null ; if ( Util . isNode ( container ) ) { impl = new dhtmlXToolbarObject ( container , SKIN ) ; } else if ( container . type === OBJECT_TYPE . LAYOUT_CELL || container . type === OBJECT_TYPE . ACCORDION_CELL || container . type === OBJECT_TYPE . LAYOUT || container . type === OBJECT_TYPE . WINDOW || container . type === OBJECT_TYPE . TAB ) { impl = container . impl . attachToolbar ( ) ; impl . setSkin ( SKIN ) ; } else { throw new Error ( 'initDhtmlxToolbar: container is not valid.' ) ; } return impl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets the data on the model [CODESPLIT] function ( data , track ) { if ( track !== false ) data = $track ( data , track ) ; this . data = data ; this . _dep . changed ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "an array of models in the current stack with the root as the first [CODESPLIT] function ( ) { var models = [ this ] , model = this ; while ( model . parent ) { models . unshift ( model = model . parent ) ; } return models }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets the model in the stack at the index negative values start at root [CODESPLIT] function ( index ) { if ( ! _ . isNumber ( index ) || isNaN ( index ) ) index = 0 ; if ( index < 0 ) return this . getAllModels ( ) [ ~ index ] ; var model = this ; while ( index && model ) { model = model . parent ; index -- ; } return model ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the first model which passes the function [CODESPLIT] function ( fn ) { var index = 0 , model = this ; while ( model != null ) { if ( fn . call ( this , model , index ++ ) ) return model ; model = model . parent ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the value at path but only looks in the data on this model [CODESPLIT] function ( path ) { if ( typeof path === \"string\" ) path = parse ( path , { startRule : \"path\" } ) ; if ( ! _ . isObject ( path ) ) throw new Error ( \"Expecting string or object for path.\" ) ; var self = this ; this . _dep . depend ( ) ; return _ . reduce ( path . parts , function ( target , part ) { target = self . _get ( target , part . key ) ; _ . each ( part . children , function ( k ) { if ( _ . isObject ( k ) ) k = self . get ( k ) ; target = self . _get ( target , k ) ; } ) ; return target ; } , this . data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "retrieves value with path query [CODESPLIT] function ( paths ) { var self = this ; if ( typeof paths === \"string\" ) paths = parse ( paths , { startRule : \"pathQuery\" } ) ; if ( ! _ . isArray ( paths ) ) paths = paths != null ? [ paths ] : [ ] ; if ( ! paths . length ) { var model = this . findModel ( function ( m ) { return ! _ . isUndefined ( m . data ) ; } ) ; if ( model == null ) return ; var val = model . data ; if ( _ . isFunction ( val ) ) val = val . call ( this , null ) ; return val ; } return _ . reduce ( paths , function ( result , path , index ) { var model = self , scope = true , val ; if ( path . type === \"root\" ) { model = self . getRootModel ( ) ; } else if ( path . type === \"parent\" ) { model = self . getModelAtOffset ( path . distance ) ; scope = false ; } else if ( path . type === \"all\" ) { scope = false ; } if ( model == null ) return ; while ( _ . isUndefined ( val ) && model != null ) { val = model . getLocal ( path ) ; model = model . parent ; if ( scope ) break ; } if ( _ . isFunction ( val ) ) { val = val . call ( self , index === 0 ? null : result ) ; } return val ; } , void 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * lastKey = the next directory to query in lexical order [CODESPLIT] function deepQuery ( root , currentDir , lastKey , cb ) { if ( ! lastKey ) { // initial query return void query ( root , currentDir , ( err , files , dirs ) => { if ( err ) return void cb ( err ) ; const lastKey = dirs . length > 0 ? buildLastKeyRight ( currentDir , path . join ( currentDir , dirs [ 0 ] . Key ) ) : null ; cb ( null , files , [ ] , lastKey ) ; } ) ; } // resume query via lastKey const keyInfo = getLastKeyInfo ( lastKey ) ; const lastDir = keyInfo . leftToRight === false ? path . basename ( keyInfo . lastDir ) : null ; const ignoreFiles = ! keyInfo . leftToRight ; // ignore files in nextDir if going backwards //console.log(`querying ${keyInfo.nextDir}, leftToRight:${keyInfo.leftToRight}, lastDir:${lastDir}, ignoreFiles:${ignoreFiles}...`) query ( root , keyInfo . nextDir , { lastDir , ignoreFiles } , ( err , files , dirs ) => { if ( err ) return void cb ( err ) ; // we're done, bail if ( dirs . length === 0 ) { // no directories to continue down, go back cb ( null , files , [ ] , buildLastKeyLeft ( keyInfo . nextDir ) ) ; } else { // contains directories, so continue searching cb ( null , files , [ ] , buildLastKeyRight ( keyInfo . nextDir , dirs [ 0 ] . Key ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate random token [CODESPLIT] function ( done ) { crypto . randomBytes ( 20 , function ( err , buffer ) { var token = buffer . toString ( 'hex' ) ; done ( err , token ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup user by username [CODESPLIT] function ( token , done ) { if ( req . body . username ) { User . findOne ( { username : req . body . username } , '-salt -password' , function ( err , user ) { if ( ! user ) { return res . status ( 400 ) . send ( { message : 'No account with that username has been found' } ) ; } else if ( user . provider !== 'local' ) { return res . status ( 400 ) . send ( { message : 'It seems like you signed up using your ' + user . provider + ' account' } ) ; } else { user . resetPasswordToken = token ; user . resetPasswordExpires = Date . now ( ) + 3600000 ; // 1 hour user . save ( function ( err ) { done ( err , token , user ) ; } ) ; } } ) ; } else { return res . status ( 400 ) . send ( { message : 'Username field must not be blank' } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If valid email send reset email using service [CODESPLIT] function ( emailHTML , user , done ) { var smtpTransport = nodemailer . createTransport ( config . mailer . options ) ; var mailOptions = { to : user . email , from : config . mailer . from , subject : 'Your password has been changed' , html : emailHTML } ; smtpTransport . sendMail ( mailOptions , function ( err ) { done ( err , 'done' ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts array of issue objects by last updated date . [CODESPLIT] function sortIssues ( issues ) { var sorted ; // Issues might be pre-arranged by super/sub tasks. if ( Object . keys ( issues ) . indexOf ( 'supers' ) > - 1 ) { // Network format issue sort issues . supers = _ . sortBy ( issues . supers , function ( issue ) { return new Date ( issue . updated_at ) ; } ) . reverse ( ) ; issues . singletons = _ . sortBy ( issues . singletons , function ( issue ) { return new Date ( issue . updated_at ) ; } ) . reverse ( ) ; sorted = issues ; } else { sorted = _ . sortBy ( issues , function ( issue ) { return new Date ( issue . updated_at ) ; } ) . reverse ( ) ; } return sorted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes duplicate collaborators . [CODESPLIT] function deduplicateCollaborators ( collaborators ) { var foundLogins = [ ] ; return _ . filter ( collaborators , function ( collaborator ) { var duplicate = false , login = collaborator . login ; if ( foundLogins . indexOf ( login ) > - 1 ) { duplicate = true ; } else { foundLogins . push ( login ) ; } return ! duplicate ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Using regex finds subtasks within a super issue s body string and returns them in an array of issue numbers . [CODESPLIT] function extractSuperIssueSubTaskNumbers ( superIssue ) { var matches = superIssue . body . match ( markdownTasksRegex ) , subTaskIds = [ ] ; _ . each ( matches , function ( line ) { var match = line . match ( subtaskRegex ) ; if ( match ) { subTaskIds . push ( parseInt ( match [ 3 ] ) ) ; } } ) ; return subTaskIds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes an array of issue objects and presents them differently depending on format . The only valid option now is network which groups super issue subtasks into a subtasks array on the super issue object . [CODESPLIT] function formatIssues ( format , issues ) { var formattedIssues , partition , superIssues , singletonIssues , removedSubtasks = [ ] ; if ( format == 'network' ) { formattedIssues = { supers : [ ] , singletons : [ ] , all : issues } ; partition = _ . partition ( issues , function ( issue ) { return _ . find ( issue . labels , function ( label ) { return label . name == 'super' ; } ) ; } ) ; superIssues = partition . shift ( ) ; singletonIssues = partition . shift ( ) ; _ . each ( superIssues , function ( superIssue ) { var subTaskNumbers = extractSuperIssueSubTaskNumbers ( superIssue ) ; superIssue . subtasks = _ . filter ( singletonIssues , function ( issue ) { var isSubtask = _ . contains ( subTaskNumbers , issue . number ) ; if ( isSubtask ) { removedSubtasks . push ( issue . number ) ; } return isSubtask ; } ) ; } ) ; formattedIssues . supers = superIssues ; _ . each ( singletonIssues , function ( issue ) { if ( ! _ . contains ( removedSubtasks , issue . number ) ) { formattedIssues . singletons . push ( issue ) ; } } ) ; } else { formattedIssues = issues ; } return formattedIssues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a list of issues and pull requests populate the additional properties that exist within any issues into the PR objects so they contain as much info as possible . [CODESPLIT] function mergeIssuesAndPrs ( issues , prs ) { _ . each ( issues , function ( issue ) { var targetPr , targetPrIndex = _ . findIndex ( prs , function ( pr ) { return pr && pr . number == issue . number ; } ) ; if ( targetPrIndex > - 1 ) { targetPr = prs [ targetPrIndex ] ; prs [ targetPrIndex ] = _ . merge ( targetPr , issue ) ; } } ) ; return prs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper class around the GitHub API client providing some authentication convenience and additional utility functions for executing operations across the issue trackers of several repositories at once . [CODESPLIT] function Sprinter ( username , password , repoSlugs , cache ) { if ( ! username ) { throw new Error ( 'Missing username.' ) ; } if ( ! password ) { throw new Error ( 'Missing password.' ) ; } if ( ! repoSlugs ) { throw new Error ( 'Missing repositories.' ) ; } this . username = username ; this . password = password ; // Verify required configuration elements. this . repos = convertSlugsToObjects ( repoSlugs ) ; this . gh = new GitHubApi ( { version : '3.0.0' , timeout : 5000 } ) ; this . gh . authenticate ( { type : 'basic' , username : this . username , password : this . password } ) ; this . _CACHE = { } ; this . setCacheDuration ( cache ) ; this . _setupCaching ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This exists so we can populate an errors object from the async calls . Otherwise if there is an error passed to the async callback the async module will stop executing remaining functions . [CODESPLIT] function getFetchByStateCallback ( callback ) { return function ( err , data ) { if ( err ) { asyncErrors . push ( err ) ; } callback ( null , data ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return a cached list of availables adapter unless forceRefresh is true [CODESPLIT] function listAvailables ( forceRefresh ) { forceRefresh && ( adaptersCache = [ ] ) ; if ( adaptersCache . length ) { return adaptersCache ; } adaptersCache = fs . readdirSync ( __dirname ) . filter ( function ( fileOrDirName ) { return isDir ( __dirname + '/' + fileOrDirName ) ; } ) ; return adaptersCache ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read a config for given adapter at path [CODESPLIT] function readConfig ( adapterName , path ) { var adapter = getAdapterInstance ( adapterName ) ; return adapter . configLoader ( normalizeAdapterConfigPath ( adapter , path ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write a config for given adapter in given path [CODESPLIT] function writeConfig ( adapterName , path , config ) { var adapter = getAdapterInstance ( adapterName ) ; return adapter . configWriter ( normalizeAdapterConfigPath ( adapter , path ) , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle non - i18n files [CODESPLIT] function handleFiles ( files ) { files . forEach ( function ( f ) { f . src . filter ( srcExists ) . map ( function ( filepath ) { var pathInfo = getPathInfo ( filepath , f . dest ) , context = getContext ( f . context , pathInfo ) ; renderFile ( pathInfo . outfile , filepath , context ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle i18n files [CODESPLIT] function handleI18nFiles ( files ) { options . locales . forEach ( function ( locale ) { grunt . registerTask ( 'swigtemplatesSubtask-' + locale , function ( ) { var done = this . async ( ) ; var translatorFactory = options . translateFunction ( locale ) ; Q . when ( translatorFactory , function ( translator ) { doTranslations ( files , locale , translator ) } ) . done ( done ) ; } ) ; grunt . task . run ( 'swigtemplatesSubtask-' + locale ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do translations [CODESPLIT] function doTranslations ( files , locale , translator ) { files . forEach ( function ( f ) { f . src . filter ( srcExists ) . map ( function ( filepath ) { var pathInfo = getPathInfo ( filepath , f . dest ) , context = getContext ( f . context , pathInfo ) ; if ( locale !== options . defaultLocale ) { pathInfo . outfile = path . join ( f . dest , locale , pathInfo . outfilePath , pathInfo . outfileName ) ; } context . locale = locale ; options . locals [ options . translateFunctionName ] = function ( ) { var args = Array . prototype . slice . call ( arguments ) ; return translator ( args ) ; } ; swig . setDefaults ( { locals : options . locals } ) ; renderFile ( pathInfo . outfile , filepath , context ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render file [CODESPLIT] function renderFile ( outfile , filepath , context ) { grunt . file . write ( outfile , swig . renderFile ( filepath , context ) ) ; grunt . log . ok ( 'File \"' + outfile + '\" created.' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get path info for src / dest [CODESPLIT] function getPathInfo ( filepath , dest ) { var outfileName = path . basename ( filepath , '.swig' ) , dirName = path . dirname ( filepath ) , outfilePath = path . normalize ( path . relative ( options . templatesDir , dirName ) ) , outfile = path . join ( dest , outfilePath , outfileName ) ; return { outfileName : outfileName , dirName : dirName , outfilePath : outfilePath , outfile : outfile } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get swig context [CODESPLIT] function getContext ( context , pathInfo ) { var globalContext , templateContext ; try { globalContext = grunt . file . readJSON ( path . join ( options . templatesDir , \"global.json\" ) ) ; } catch ( err ) { globalContext = { } ; } try { templateContext = grunt . file . readJSON ( path . join ( pathInfo . dirName , pathInfo . outfileName ) + \".json\" ) ; } catch ( err ) { templateContext = { } ; } return _ . extend ( { } , globalContext , templateContext , options . defaultContext , context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LRU ( Least Recently Used ) [CODESPLIT] function Lru ( options ) { if ( options === undefined ) { options = { } } this . size = 0 ; this . maxSize = options . maxSize ; this . delCallback = options . delCallback ; this . hashEnabled = options . hashEnabled === undefined ? true : options . hashEnabled ; // Add to head this . head = null ; // Remove from tail this . tail = null ; this . hash = { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render pages with handle bar template [CODESPLIT] function render ( url ) { return async page => { try { const template = ` ${ page . template || 'schedule' } ` ; // Load template and compile const filePath = path . join ( process . cwd ( ) , config . theme || 'theme' , config . template || 'templates' , template , ) ; const output = Handlebars . compile ( await fs . readFile ( filePath , 'utf-8' ) ) ( page ) ; await fs . ensureDir ( outputDir ) ; // if home page skip else create page dir const dir = url !== 'index' ? path . join ( outputDir , url ) : outputDir ; await fs . ensureDir ( dir ) ; await fs . writeFile ( path . join ( dir , 'index.html' ) , output , 'utf8' ) ; } catch ( err ) { throw err ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a menu based on the file names in the pages dir index . [ md|json ] is called Home [CODESPLIT] async function generateMenu ( ) { try { const files = await fs . readdir ( source ) ; const filter = files . filter ( file => file . substring ( 0 , file . lastIndexOf ( '.' ) ) !== 'index' ) ; const menu = filter . map ( file => ( { title : file . substring ( 0 , file . lastIndexOf ( '.' ) ) , url : file . substring ( 0 , file . lastIndexOf ( '.' ) ) , } ) ) ; menu . unshift ( { title : 'Home' , url : '' } ) ; return menu ; } catch ( err ) { throw err ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether a function has a name . [CODESPLIT] function isNamedFunction ( node ) { if ( node . id ) return true ; const { parent } = node ; const { type } = parent ; const namedFunction = type === 'MethodDefinition' || type === 'Property' && ( parent . kind === 'get' || parent . kind === 'set' || parent . method ) ; return namedFunction ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the config for a given function . [CODESPLIT] function getConfigForFunction ( node ) { if ( isNamedFunction ( node ) ) return 'never' ; if ( node . type === 'ArrowFunctionExpression' ) { // Always ignore non-async functions and arrow functions without parens, e.g. // `async foo => bar`. if ( ! node . async || ! astUtils . isOpeningParenToken ( sourceCode . getFirstToken ( node , { skip : 1 } ) ) ) return 'ignore' ; } return 'always' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the parens of a function node . [CODESPLIT] function checkFunction ( node ) { const functionConfig = getConfigForFunction ( node ) ; if ( functionConfig === 'ignore' ) return ; const rightToken = sourceCode . getFirstToken ( node , astUtils . isOpeningParenToken ) ; const leftToken = sourceCode . getTokenBefore ( rightToken ) ; const text = sourceCode . text . slice ( leftToken . range [ 1 ] , rightToken . range [ 0 ] ) . replace ( / \\/\\*[^]*?\\*\\/ / g , '' ) ; if ( astUtils . LINEBREAK_MATCHER . test ( text ) ) return ; const hasSpacing = / \\s / . test ( text ) ; if ( hasSpacing && functionConfig === 'never' ) { const report = { node , loc : leftToken . loc . end , message : 'Unexpected space before function parentheses.' , fix : fixer => fixer . removeRange ( [ leftToken . range [ 1 ] , rightToken . range [ 0 ] ] ) , } ; context . report ( report ) ; } else if ( ! hasSpacing && functionConfig === 'always' ) { const report = { node , loc : leftToken . loc . end , message : 'Missing space before function parentheses.' , fix : fixer => fixer . insertTextAfter ( leftToken , ' ' ) , } ; context . report ( report ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new TapRepeater . [CODESPLIT] function ( config ) { var me = this ; //<debug warn> for ( var configName in config ) { if ( me . self . prototype . config && ! ( configName in me . self . prototype . config ) ) { me [ configName ] = config [ configName ] ; Ext . Logger . warn ( 'Applied config as instance property: \"' + configName + '\"' , me ) ; } } //</debug> me . initConfig ( config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "callback ( isok err ) [CODESPLIT] function checkStructMember ( structname , obj , callback , root ) { var membername = obj . name . name ; if ( ! isVarString ( membername ) ) { callback ( false , structname + '.' + membername + ': The first letter should be lowercase.' ) ; return false ; } if ( ! base . isType ( obj . type , root ) ) { callback ( false , structname + '.' + membername + ': ' + obj . type + ' not defined.' ) ; return false ; } if ( obj . type == 'time' ) { if ( obj . hasOwnProperty ( 'val' ) ) { if ( typeof ( obj . val ) == 'object' ) { if ( obj . val . type == 'NULL' ) { return true ; } else if ( obj . val . type == 'time' && obj . val . val == 'NOW' ) { return true ; } } callback ( false , structname + '.' + membername + ': default is not NULL or NOW.' ) ; return false ; } } else if ( obj . type == 'int' ) { if ( obj . hasOwnProperty ( 'val' ) ) { if ( typeof ( obj . val ) == 'object' ) { if ( obj . val . type == 'int' && obj . val . val == 'AUTOINC' ) { if ( obj . type2 != 'primary' ) { callback ( false , structname + '.' + membername + ': AUTOINC is primary.' ) ; return false ; } } } } } if ( obj . type2 == 'expand' ) { if ( obj . hasOwnProperty ( 'expand' ) ) { if ( ! base . isEnum ( obj . expand , root ) ) { callback ( false , structname + '.' + membername + ': expand need enum!.' ) ; return false ; } } else { var cobj = base . getGlobalObj ( obj . type , root ) ; if ( cobj == undefined ) { callback ( false , structname + '.' + membername + ': expand fail!.' ) ; return false ; } var structobj = base . getGlobalObj ( structname , root ) ; for ( var i = 0 ; i < cobj . val . length ; ++ i ) { if ( base . hasMemberEx ( cobj . val [ i ] . name . name , obj . type , structobj , root ) ) { callback ( false , structname + '.' + membername + '.' + cobj . val [ i ] . name . name + ': expand err(duplication of name).' ) ; return false ; } } } } if ( obj . type2 == 'repeated' ) { if ( obj . hasOwnProperty ( 'memberkey' ) ) { if ( ! ( base . isStruct ( obj . type , root ) || base . isStatic ( obj . type , root ) ) ) { callback ( false , structname + '.' + membername + ': repeated object must be struct.' ) ; return false ; } if ( ! base . hasMember2 ( obj . memberkey , base . getGlobalObj ( obj . type , root ) , root ) ) { callback ( false , structname + '.' + membername + ': repeated key(' + obj . memberkey + ') not defined in ' + obj . type + '.' ) ; return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "callback ( isok err ) [CODESPLIT] function checkStruct ( obj , callback , root ) { if ( obj . type == 'struct' || obj . type == 'static' || obj . type == 'message' ) { if ( ! isTypeString ( obj . name ) ) { callback ( false , 'struct ' + obj . name + ': The first letter should be capitalized.' ) ; return false ; } for ( var i = 0 ; i < obj . val . length ; ++ i ) { if ( base . countMember ( obj . val [ i ] . name . name , obj , root ) > 1 ) { callback ( false , 'struct ' + obj . name + '.' + obj . val [ i ] . name . name + ': duplication of name.' ) ; return false ; } if ( ! checkStructMember ( obj . name , obj . val [ i ] , callback , root ) ) { return false ; } if ( obj . type == 'message' ) { if ( obj . val [ i ] . name . name . indexOf ( '_' ) == 0 ) { callback ( false , 'message ' + obj . name + '.' + obj . val [ i ] . name . name + \": can't begin with an underscore(_).\" ) ; return false ; } } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "callback ( isok err ) [CODESPLIT] function checkEnumMember ( enumname , enumarr , obj , callback ) { if ( ! isEnumString ( obj . name ) ) { callback ( false , enumname + '.' + obj . name + ': All letters should be capitalized.' ) ; return false ; } if ( obj . type != 'int' ) { callback ( false , enumname + '.' + obj . name + ': This member is not int.' ) ; return false ; } if ( obj . name . indexOf ( enumname + '_' ) != 0 ) { callback ( false , enumname + '.' + obj . name + ': This member is begin ' + enumname + '_.' ) ; return false ; } if ( enumarr . indexOf ( obj . val ) >= 0 ) { callback ( false , enumname + '.' + obj . name + ': This member\\'s val is used.' ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "callback ( isok err ) [CODESPLIT] function checkEnum ( obj , callback ) { if ( obj . type == 'enum' ) { if ( ! isEnumString ( obj . name ) ) { callback ( false , 'enum ' + obj . name + ': All letters should be capitalized.' ) ; return false ; } var enumarr = [ ] ; for ( var i = 0 ; i < obj . val . length ; ++ i ) { if ( ! checkEnumMember ( obj . name , enumarr , obj . val [ i ] , callback ) ) { return false ; } enumarr . push ( obj . val [ i ] . val ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "callback ( isok err ) [CODESPLIT] function checkType ( obj , callback , root ) { if ( obj . type == 'type' ) { if ( ! isTypeString ( obj . name ) ) { callback ( false , 'global type ' + obj . name + ': The first letter should be capitalized.' ) ; return false ; } if ( ! base . isType ( obj . name , root ) ) { callback ( false , 'global type ' + obj . name + ': ' + obj . name + ' not defined.' ) ; return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "callback ( isok err ) [CODESPLIT] function checkGrammar ( obj , callback ) { let hasver = false ; if ( Array . isArray ( obj ) ) { for ( var i = 0 ; i < obj . length ; ++ i ) { var nums = base . countGlobalObj ( obj [ i ] . name , obj ) ; if ( nums > 1 ) { callback ( false , obj [ i ] . name + ': duplication of name' ) ; return false ; } if ( obj [ i ] . name == 'VER' ) { hasver = true ; } if ( obj [ i ] . type == 'struct' || obj [ i ] . type == 'static' || obj [ i ] . type == 'message' ) { checkStruct ( obj [ i ] , callback , obj ) ; } else if ( obj [ i ] . type == 'enum' ) { checkEnum ( obj [ i ] , callback ) ; } else if ( obj [ i ] . type == 'type' ) { checkType ( obj [ i ] , callback , obj ) ; } } if ( ! hasver ) { callback ( false , 'no VER!' ) ; return false ; } return true ; } callback ( false , 'empty file!' ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind to user supplied event map where key is event name [CODESPLIT] function bindEventMap ( eventMap , eventEmitter ) { var eventNames = Object . keys ( eventMap ) ; eventNames . map ( function ( eventName ) { eventEmitter . on ( eventName , eventMap [ eventName ] ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cancels any pending timeout and queues a new one . [CODESPLIT] function ( delay , newFn , newScope , newArgs ) { var me = this ; //cancel any existing queued functions me . cancel ( ) ; //set all the new configurations if ( Ext . isNumber ( delay ) ) { me . setDelay ( delay ) ; } if ( Ext . isFunction ( newFn ) ) { me . setFn ( newFn ) ; } if ( newScope ) { me . setScope ( newScope ) ; } if ( newScope ) { me . setArgs ( newArgs ) ; } //create the callback method for this delayed task var call = function ( ) { me . getFn ( ) . apply ( me . getScope ( ) , me . getArgs ( ) || [ ] ) ; me . cancel ( ) ; } ; me . setInterval ( setInterval ( call , me . getDelay ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns an Ext . data . Request object based on the options passed by the { [CODESPLIT] function ( operation ) { var me = this , params = Ext . applyIf ( operation . getParams ( ) || { } , me . getExtraParams ( ) || { } ) , request ; //copy any sorters, filters etc into the params so they can be sent over the wire params = Ext . applyIf ( params , me . getParams ( operation ) ) ; request = Ext . create ( 'Ext.data.Request' , { params : params , action : operation . getAction ( ) , records : operation . getRecords ( ) , url : operation . getUrl ( ) , operation : operation , proxy : me } ) ; request . setUrl ( me . buildUrl ( request ) ) ; operation . setRequest ( request ) ; return request ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method handles the processing of the response and is usually overridden by subclasses to do additional processing . [CODESPLIT] function ( success , operation , request , response , callback , scope ) { var me = this , action = operation . getAction ( ) , reader , resultSet ; if ( success === true ) { reader = me . getReader ( ) ; try { resultSet = reader . process ( me . getResponseResult ( response ) ) ; } catch ( e ) { operation . setException ( e . message ) ; me . fireEvent ( 'exception' , me , response , operation ) ; return ; } // This could happen if the model was configured using metaData if ( ! operation . getModel ( ) ) { operation . setModel ( this . getModel ( ) ) ; } if ( operation . process ( action , resultSet , request , response ) === false ) { me . setException ( operation , response ) ; me . fireEvent ( 'exception' , me , response , operation ) ; } } else { me . setException ( operation , response ) ; /**\n             * @event exception\n             * Fires when the server returns an exception\n             * @param {Ext.data.proxy.Proxy} this\n             * @param {Object} response The response from the AJAX request\n             * @param {Ext.data.Operation} operation The operation that triggered request\n             */ me . fireEvent ( 'exception' , this , response , operation ) ; } //this callback is the one that was passed to the 'read' or 'write' function above if ( typeof callback == 'function' ) { callback . call ( scope || me , operation ) ; } me . afterRequest ( request , success ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up an exception on the operation [CODESPLIT] function ( operation , response ) { if ( Ext . isObject ( response ) ) { operation . setException ( { status : response . status , statusText : response . statusText } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the array of { [CODESPLIT] function ( sorters ) { var min = [ ] , length = sorters . length , i = 0 ; for ( ; i < length ; i ++ ) { min [ i ] = { property : sorters [ i ] . getProperty ( ) , direction : sorters [ i ] . getDirection ( ) } ; } return this . applyEncoding ( min ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the array of { [CODESPLIT] function ( filters ) { var min = [ ] , length = filters . length , i = 0 ; for ( ; i < length ; i ++ ) { min [ i ] = { property : filters [ i ] . getProperty ( ) , value : filters [ i ] . getValue ( ) } ; } return this . applyEncoding ( min ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a url based on a given Ext . data . Request object . By default ServerProxy s buildUrl will add the cache - buster param to the end of the url . Subclasses may need to perform additional modifications to the url . [CODESPLIT] function ( request ) { var me = this , url = me . getUrl ( request ) ; //<debug> if ( ! url ) { Ext . Logger . error ( \"You are using a ServerProxy but have not supplied it with a url.\" ) ; } //</debug> if ( me . getNoCache ( ) ) { url = Ext . urlAppend ( url , Ext . String . format ( \"{0}={1}\" , me . getCacheString ( ) , Ext . Date . now ( ) ) ) ; } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断是否有TAB页 [CODESPLIT] function hasTAB ( excelobj , tabname ) { for ( let ii = 0 ; ii < excelobj . length ; ++ ii ) { if ( excelobj [ ii ] . name == tabname ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "src1 是老版本，src2 是新版本 [CODESPLIT] function mergeExcel ( src1 , src2 ) { if ( src1 == undefined ) { return src2 ; } if ( src1 [ 0 ] . name != src2 [ 0 ] . name ) { return src2 ; } if ( src1 [ 0 ] . data . length <= 2 ) { return src2 ; } let dest = [ ] ; dest . push ( { name : src2 [ 0 ] . name , data : [ ] } ) ; for ( let ii = 0 ; ii < src1 [ 0 ] . data . length ; ++ ii ) { dest [ 0 ] . data . push ( [ ] ) ; } for ( let ii = 0 ; ii < src2 [ 0 ] . data [ 1 ] . length ; ++ ii ) { let sf = findField ( src1 [ 0 ] . data , src2 [ 0 ] . data [ 1 ] [ ii ] ) ; if ( sf != - 1 ) { let cn = src1 [ 0 ] . data . length - 2 ; dest [ 0 ] . data [ 0 ] . push ( src2 [ 0 ] . data [ 0 ] [ ii ] ) ; dest [ 0 ] . data [ 1 ] . push ( src2 [ 0 ] . data [ 1 ] [ ii ] ) ; for ( let jj = 0 ; jj < cn ; ++ jj ) { dest [ 0 ] . data [ jj + 2 ] . push ( src1 [ 0 ] . data [ jj + 2 ] [ sf ] ) ; } } else { let cn = src1 [ 0 ] . data . length - 2 ; dest [ 0 ] . data [ 0 ] . push ( src2 [ 0 ] . data [ 0 ] [ ii ] ) ; dest [ 0 ] . data [ 1 ] . push ( src2 [ 0 ] . data [ 1 ] [ ii ] ) ; for ( let jj = 0 ; jj < cn ; ++ jj ) { dest [ 0 ] . data [ jj + 2 ] . push ( '' ) ; } } } for ( let ii = 1 ; ii < src2 . length ; ++ ii ) { dest . push ( src2 [ ii ] ) ; } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the date format in the field . [CODESPLIT] function ( newDateFormat , oldDateFormat ) { var value = this . getValue ( ) ; if ( newDateFormat != oldDateFormat && Ext . isDate ( value ) ) { this . getComponent ( ) . setValue ( Ext . Date . format ( value , newDateFormat || Ext . util . Format . defaultDateFormat ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value of the field formatted using the specified format . If it is not specified it will default to { [CODESPLIT] function ( format ) { var value = this . getValue ( ) ; return ( Ext . isDate ( value ) ) ? Ext . Date . format ( value , format || this . getDateFormat ( ) || Ext . util . Format . defaultDateFormat ) : value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the picker changes its value . [CODESPLIT] function ( picker , value ) { var me = this , oldValue = me . getValue ( ) ; me . setValue ( value ) ; me . fireEvent ( 'select' , me , value ) ; me . onChange ( me , value , oldValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Destroys the picker when it is hidden if { [CODESPLIT] function ( ) { var me = this , picker = me . getPicker ( ) ; if ( me . getDestroyPickerOnHide ( ) && picker ) { picker . destroy ( ) ; me . _picker = me . getInitialConfig ( ) . picker || true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints out debugging to console if ghosttrain . get ( debug ) is true [CODESPLIT] function debug ( gt ) { var args = arrayify ( arguments ) ; args . splice ( 0 , 1 ) ; // Pop first `gt` argument if ( gt . get ( 'debug' ) ) console . log . apply ( console , [ 'GhostTrain debug: ' ] . concat ( args ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "findRoute takes a verb and a url and returns a matching GhostTrain . Route or null if no matches . url can be a string that gets parsed or an already parsed ( . / lib / url#parse ) URL object . [CODESPLIT] function findRoute ( ghosttrain , verb , url ) { // Extract path from the object or string var path = url . pathname ? url . pathname : parseURL ( url ) ; var routes = ghosttrain . routes [ verb . toLowerCase ( ) ] ; if ( ! routes ) return null ; for ( var i = 0 ; i < routes . length ; i ++ ) if ( routes [ i ] . match ( path ) ) return routes [ i ] ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clones an object properties onto a new object [CODESPLIT] function clone ( obj ) { var newObj = { } ; // Return a new obj if no `obj` passed in if ( ! obj || typeof obj !== 'object' || Array . isArray ( obj ) ) return newObj ; for ( var prop in obj ) newObj [ prop ] = obj [ prop ] ; return newObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turns a url string or a parsed url object ( . / lib / url#parse ) into a string of the URL with host / port / protocol info stripped [CODESPLIT] function requestURL ( url ) { var parsedURL = url . pathname ? url : parseURL ( url , true ) ; return parsedURL . pathname + ( parsedURL . search || '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a function that acts as app . VERB ( path route ) ; helper function used in . / lib / ghosttrain . js . [CODESPLIT] function addRoute ( verb ) { return function ( path , fn ) { // Support all HTTP verbs if ( ! this . routes [ verb ] ) this . routes [ verb ] = [ ] ; this . routes [ verb ] . push ( new Route ( verb , path , fn , { sensitive : this . settings [ 'case sensitive routing' ] , strict : this . settings [ 'strict routing' ] } ) ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "From Express : Normalize the given path string returning a regular expression . [CODESPLIT] function pathRegexp ( path , keys , sensitive , strict ) { if ( Object . prototype . toString . call ( path ) == '[object RegExp]' ) return path ; if ( Array . isArray ( path ) ) path = '(' + path . join ( '|' ) + ')' ; path = path . concat ( strict ? '' : '/?' ) . replace ( / \\/\\( / g , '(?:/' ) . replace ( / (\\/)?(\\.)?:(\\w+)(?:(\\(.*?\\)))?(\\?)?(\\*)? / g , function ( _ , slash , format , key , capture , optional , star ) { keys . push ( { name : key , optional : ! ! optional } ) ; slash = slash || '' ; return '' + ( optional ? '' : slash ) + '(?:' + ( optional ? slash : '' ) + ( format || '' ) + ( capture || ( format && '([^/.]+?)' || '([^/]+?)' ) ) + ')' + ( optional || '' ) + ( star ? '(/*)?' : '' ) ; } ) . replace ( / ([\\/.]) / g , '\\\\$1' ) . replace ( / \\* / g , '(.*)' ) ; return new RegExp ( '^' + path + '$' , sensitive ? '' : 'i' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ImpulseBin constructor . [CODESPLIT] function ImpulseBin ( ) { this . settings = { adapter : 'commander' , quietOption : 'quiet' , requiredOptionTmpl : '--%s is required' , verboseOption : 'verbose' , verboseLogName : '[verbose]' , stdoutLogName : '[stdout]' , stderrLogName : '[stderr]' } ; this . console = require ( 'long-con' ) . create ( ) ; // Assigned in run(): this . adapter = null ; this . options = null ; this . provider = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new Component . [CODESPLIT] function ( config ) { var me = this , currentConfig = me . config , id ; me . onInitializedListeners = [ ] ; me . initialConfig = config ; if ( config !== undefined && 'id' in config ) { id = config . id ; } else if ( 'id' in currentConfig ) { id = currentConfig . id ; } else { id = me . getId ( ) ; } me . id = id ; me . setId ( id ) ; Ext . ComponentManager . register ( me ) ; me . initElement ( ) ; me . initConfig ( me . initialConfig ) ; me . refreshSizeState = me . doRefreshSizeState ; me . refreshFloating = me . doRefreshFloating ; if ( me . refreshSizeStateOnInitialized ) { me . refreshSizeState ( ) ; } if ( me . refreshFloatingOnInitialized ) { me . refreshFloating ( ) ; } me . initialize ( ) ; me . triggerInitialized ( ) ; /**\n         * Force the component to take up 100% width and height available, by adding it to {@link Ext.Viewport}.\n         * @cfg {Boolean} fullscreen\n         */ if ( me . config . fullscreen ) { me . fireEvent ( 'fullscreen' , me ) ; } me . fireEvent ( 'initialize' , me ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CSS class ( or classes ) to this Component s rendered element . [CODESPLIT] function ( cls , prefix , suffix ) { var oldCls = this . getCls ( ) , newCls = ( oldCls ) ? oldCls . slice ( ) : [ ] , ln , i , cachedCls ; prefix = prefix || '' ; suffix = suffix || '' ; if ( typeof cls == \"string\" ) { cls = [ cls ] ; } ln = cls . length ; //check if there is currently nothing in the array and we don't need to add a prefix or a suffix. //if true, we can just set the newCls value to the cls property, because that is what the value will be //if false, we need to loop through each and add them to the newCls array if ( ! newCls . length && prefix === '' && suffix === '' ) { newCls = cls ; } else { for ( i = 0 ; i < ln ; i ++ ) { cachedCls = prefix + cls [ i ] + suffix ; if ( newCls . indexOf ( cachedCls ) == - 1 ) { newCls . push ( cachedCls ) ; } } } this . setCls ( newCls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the given CSS class ( es ) from this Component s rendered element . [CODESPLIT] function ( cls , prefix , suffix ) { var oldCls = this . getCls ( ) , newCls = ( oldCls ) ? oldCls . slice ( ) : [ ] , ln , i ; prefix = prefix || '' ; suffix = suffix || '' ; if ( typeof cls == \"string\" ) { newCls = Ext . Array . remove ( newCls , prefix + cls + suffix ) ; } else { ln = cls . length ; for ( i = 0 ; i < ln ; i ++ ) { newCls = Ext . Array . remove ( newCls , prefix + cls [ i ] + suffix ) ; } } this . setCls ( newCls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces specified classes with the newly specified classes . It uses the { [CODESPLIT] function ( oldCls , newCls , prefix , suffix ) { // We could have just called {@link #removeCls} and {@link #addCls}, but that would mean {@link #updateCls} // would get called twice, which would have performance implications because it will update the dom. var cls = this . getCls ( ) , array = ( cls ) ? cls . slice ( ) : [ ] , ln , i , cachedCls ; prefix = prefix || '' ; suffix = suffix || '' ; //remove all oldCls if ( typeof oldCls == \"string\" ) { array = Ext . Array . remove ( array , prefix + oldCls + suffix ) ; } else if ( oldCls ) { ln = oldCls . length ; for ( i = 0 ; i < ln ; i ++ ) { array = Ext . Array . remove ( array , prefix + oldCls [ i ] + suffix ) ; } } //add all newCls if ( typeof newCls == \"string\" ) { array . push ( prefix + newCls + suffix ) ; } else if ( newCls ) { ln = newCls . length ; //check if there is currently nothing in the array and we don't need to add a prefix or a suffix. //if true, we can just set the array value to the newCls property, because that is what the value will be //if false, we need to loop through each and add them to the array if ( ! array . length && prefix === '' && suffix === '' ) { array = newCls ; } else { for ( i = 0 ; i < ln ; i ++ ) { cachedCls = prefix + newCls [ i ] + suffix ; if ( array . indexOf ( cachedCls ) == - 1 ) { array . push ( cachedCls ) ; } } } } this . setCls ( array ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add or removes a class based on if the class is already added to the Component . [CODESPLIT] function ( className , /* private */ force ) { var oldCls = this . getCls ( ) , newCls = ( oldCls ) ? oldCls . slice ( ) : [ ] ; if ( force || newCls . indexOf ( className ) == - 1 ) { newCls . push ( className ) ; } else { Ext . Array . remove ( newCls , className ) ; } this . setCls ( newCls ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the { [CODESPLIT] function ( newHtmlCls , oldHtmlCls ) { var innerHtmlElement = this . innerHtmlElement , innerElement = this . innerElement ; if ( this . getStyleHtmlContent ( ) && oldHtmlCls ) { if ( innerHtmlElement ) { innerHtmlElement . replaceCls ( oldHtmlCls , newHtmlCls ) ; } else { innerElement . replaceCls ( oldHtmlCls , newHtmlCls ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hides this Component optionally using an animation . [CODESPLIT] function ( animation ) { this . setCurrentAlignmentInfo ( null ) ; /*\n        if(this.activeAnimation) {\n            this.activeAnimation.on({\n                animationend: function(){\n                    this.hide(animation);\n                },\n                scope: this,\n                single: true\n            });\n            return this;\n        }\n       */ if ( ! this . getHidden ( ) ) { if ( animation === undefined || ( animation && animation . isComponent ) ) { animation = this . getHideAnimation ( ) ; } if ( animation ) { if ( animation === true ) { animation = 'fadeOut' ; } this . onBefore ( { hiddenchange : 'animateFn' , scope : this , single : true , args : [ animation ] } ) ; } this . setHidden ( true ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shows this component optionally using an animation . [CODESPLIT] function ( animation ) { if ( this . activeAnimation ) { this . activeAnimation . on ( { animationend : function ( ) { this . show ( animation ) ; } , scope : this , single : true } ) ; return this ; } var hidden = this . getHidden ( ) ; if ( hidden || hidden === null ) { if ( animation === true ) { animation = 'fadeIn' ; } else if ( animation === undefined || ( animation && animation . isComponent ) ) { animation = this . getShowAnimation ( ) ; } if ( animation ) { this . beforeShowAnimation ( ) ; this . onBefore ( { hiddenchange : 'animateFn' , scope : this , single : true , args : [ animation ] } ) ; } this . setHidden ( false ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the size of the Component . [CODESPLIT] function ( width , height ) { if ( width != undefined ) { this . setWidth ( width ) ; } if ( height != undefined ) { this . setHeight ( height ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shows this component by another component . If you specify no alignment it will automatically position this component relative to the reference component . [CODESPLIT] function ( component , alignment ) { var me = this , viewport = Ext . Viewport , parent = me . getParent ( ) ; me . setVisibility ( false ) ; if ( parent !== viewport ) { viewport . add ( me ) ; } me . show ( ) ; me . on ( { hide : 'onShowByErased' , destroy : 'onShowByErased' , single : true , scope : me } ) ; viewport . on ( 'resize' , 'alignTo' , me , { args : [ component , alignment ] } ) ; me . alignTo ( component , alignment ) ; me . setVisibility ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares information on aligning this to component using alignment . Also checks to see if this is already aligned to component according to alignment . [CODESPLIT] function ( component , alignment ) { var alignToElement = component . isComponent ? component . renderElement : component , alignToBox = alignToElement . getPageBox ( ) , element = this . renderElement , box = element . getPageBox ( ) , stats = { alignToBox : alignToBox , alignment : alignment , top : alignToBox . top , left : alignToBox . left , alignToWidth : alignToBox . width , alignToHeight : alignToBox . height , width : box . width , height : box . height } , currentAlignmentInfo = this . getCurrentAlignmentInfo ( ) , isAligned = true ; if ( ! Ext . isEmpty ( currentAlignmentInfo ) ) { Ext . Object . each ( stats , function ( key , value ) { if ( ! Ext . isObject ( value ) && currentAlignmentInfo [ key ] != value ) { isAligned = false ; return false ; } return true ; } ) ; } else { isAligned = false ; } return { isAligned : isAligned , stats : stats } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the current Alignment information called by alignTo [CODESPLIT] function ( alignmentInfo ) { this . $currentAlignmentInfo = Ext . isEmpty ( alignmentInfo ) ? null : Ext . merge ( { } , alignmentInfo . stats ? alignmentInfo . stats : alignmentInfo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walks up the ownerCt axis looking for an ancestor Container which matches the passed simple selector . [CODESPLIT] function ( selector ) { var result = this . parent ; if ( selector ) { for ( ; result ; result = result . parent ) { if ( Ext . ComponentQuery . is ( result , selector ) ) { return result ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Destroys this Component . If it is currently added to a Container it will first be removed from that Container . All Ext . Element references are also deleted and the Component is de - registered from Ext . ComponentManager [CODESPLIT] function ( ) { this . destroy = Ext . emptyFn ; var parent = this . getParent ( ) , referenceList = this . referenceList , i , ln , reference ; this . isDestroying = true ; Ext . destroy ( this . getTranslatable ( ) , this . getPlugins ( ) ) ; // Remove this component itself from the container if it's currently contained if ( parent ) { parent . remove ( this , false ) ; } // Destroy all element references for ( i = 0 , ln = referenceList . length ; i < ln ; i ++ ) { reference = referenceList [ i ] ; this [ reference ] . destroy ( ) ; delete this [ reference ] ; } Ext . destroy ( this . innerHtmlElement ) ; this . setRecord ( null ) ; this . callSuper ( ) ; Ext . ComponentManager . unregister ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove [CODESPLIT] function ( from , to ) { var me = this , items = me . getViewItems ( ) , i = to - from , item ; for ( ; i >= 0 ; i -- ) { item = items [ from + i ] ; Ext . get ( item ) . destroy ( ) ; } if ( me . getViewItems ( ) . length == 0 ) { this . dataview . showEmptyText ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add [CODESPLIT] function ( records ) { var me = this , dataview = me . dataview , store = dataview . getStore ( ) , ln = records . length , i , record ; if ( ln ) { dataview . hideEmptyText ( ) ; } for ( i = 0 ; i < ln ; i ++ ) { records [ i ] . _tmpIndex = store . indexOf ( records [ i ] ) ; } Ext . Array . sort ( records , function ( record1 , record2 ) { return record1 . _tmpIndex > record2 . _tmpIndex ? 1 : - 1 ; } ) ; for ( i = 0 ; i < ln ; i ++ ) { record = records [ i ] ; me . addListItem ( record . _tmpIndex , record ) ; delete record . _tmpIndex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when an list item has been tapped . [CODESPLIT] function ( list , index , target , record , e ) { var me = this , store = list . getStore ( ) , node = store . getAt ( index ) ; me . fireEvent ( 'itemtap' , this , list , index , target , record , e ) ; if ( node . isLeaf ( ) ) { me . fireEvent ( 'leafitemtap' , this , list , index , target , record , e ) ; me . goToLeaf ( node ) ; } else { this . goToNode ( node ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the backButton has been tapped . [CODESPLIT] function ( ) { var me = this , node = me . getLastNode ( ) , detailCard = me . getDetailCard ( ) , detailCardActive = detailCard && me . getActiveItem ( ) == detailCard , lastActiveList = me . getLastActiveList ( ) ; this . fireAction ( 'back' , [ this , node , lastActiveList , detailCardActive ] , 'doBack' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to handle going to a specific node within this nested list . Node must be part of the internal { [CODESPLIT] function ( node ) { if ( ! node ) { return ; } var me = this , activeItem = me . getActiveItem ( ) , detailCard = me . getDetailCard ( ) , detailCardActive = detailCard && me . getActiveItem ( ) == detailCard , reverse = me . goToNodeReverseAnimation ( node ) , firstList = me . firstList , secondList = me . secondList , layout = me . getLayout ( ) , animation = ( layout ) ? layout . getAnimation ( ) : null , list ; //if the node is a leaf, throw an error if ( node . isLeaf ( ) ) { throw new Error ( 'goToNode: passed a node which is a leaf.' ) ; } //if we are currently at the passed node, do nothing. if ( node == me . getLastNode ( ) && ! detailCardActive ) { return ; } if ( detailCardActive ) { if ( animation ) { animation . setReverse ( true ) ; } list = me . getLastActiveList ( ) ; list . getStore ( ) . setNode ( node ) ; node . expand ( ) ; me . setActiveItem ( list ) ; } else { if ( animation ) { animation . setReverse ( reverse ) ; } if ( firstList && secondList ) { //firstList and secondList have both been created activeItem = me . getActiveItem ( ) ; me . setLastActiveList ( activeItem ) ; list = ( activeItem == firstList ) ? secondList : firstList ; list . getStore ( ) . setNode ( node ) ; node . expand ( ) ; me . setActiveItem ( list ) ; if ( this . getClearSelectionOnListChange ( ) ) { list . deselectAll ( ) ; } } else if ( firstList ) { //only firstList has been created me . setLastActiveList ( me . getActiveItem ( ) ) ; me . setActiveItem ( me . getList ( node ) ) ; me . secondList = me . getActiveItem ( ) ; } else { //no lists have been created me . setActiveItem ( me . getList ( node ) ) ; me . firstList = me . getActiveItem ( ) ; } } me . fireEvent ( 'listchange' , this , me . getActiveItem ( ) ) ; me . setLastNode ( node ) ; me . syncToolbar ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The leaf you want to navigate to . You should pass a node instance . [CODESPLIT] function ( node ) { if ( ! node . isLeaf ( ) ) { throw new Error ( 'goToLeaf: passed a node which is not a leaf.' ) ; } var me = this , card = me . getDetailCard ( node ) , container = me . getDetailContainer ( ) , sharedContainer = container == this , layout = me . getLayout ( ) , animation = ( layout ) ? layout . getAnimation ( ) : false ; if ( card ) { if ( container . getItems ( ) . indexOf ( card ) === - 1 ) { container . add ( card ) ; } if ( sharedContainer ) { if ( me . getActiveItem ( ) instanceof Ext . dataview . List ) { me . setLastActiveList ( me . getActiveItem ( ) ) ; } me . setLastNode ( node ) ; } if ( animation ) { animation . setReverse ( false ) ; } container . setActiveItem ( card ) ; me . syncToolbar ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "bring all function declarations and exports containing them to top of the program [CODESPLIT] function hoistFunctions ( program ) { var functions = [ ] ; var body = [ ] ; for ( let line of program . body ) { if ( line . type === 'ExportDefaultDeclaration' ) { if ( line . declaration . type === 'FunctionDeclaration' ) { functions . push ( line ) ; } else { body . push ( line ) ; } continue ; } if ( line . type === 'ExportNamedDeclaration' ) { if ( ! ! line . declaration && line . declaration . type === 'FunctionDeclaration' ) { functions . push ( line ) ; } else { body . push ( line ) ; } continue ; } if ( line . type === 'FunctionDeclaration' ) { functions . push ( line ) ; } else { body . push ( line ) ; } } return makeProgram ( [ ... functions , ... body ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get ast from loaded id ( if applicable ) [CODESPLIT] function getAST ( load ) { if ( load . ast ) { return load . ast ; } else { if ( load . source ) { const opts = Object . assign ( { sourceFile : load . sourceFile } , parseOpts ) ; return acorn . parse ( load . source , opts ) ; } else { throw new Error ( 'Cannot get AST!' ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The police website provides dates in czech human readable form like 7 . ledna 2015 ( ledna == january ) . Let s transform them to D . M . YYYY format . [CODESPLIT] function ( date ) { return date . replace ( 'ledna' , '1.' ) . replace ( 'února',   2.')  . replace ( 'března',   3.')  . replace ( 'dubna' , '4.' ) . replace ( 'května',   5.')  . replace ( 'června',   6.')  . replace ( 'července',   7.')  . replace ( 'srpna' , '8.' ) . replace ( 'září', ' 9 ')  . replace ( 'října',  ' 0.')  . replace ( 'listopadu' , '11.' ) . replace ( 'prosince' , '12.' ) . replace ( / \\s / g , '' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse vehicle ID from the search results table [CODESPLIT] function parseVehicleID ( $ , item ) { let fields = $ ( item ) . find ( 'td' ) ; let id = $ ( fields [ 1 ] ) . find ( 'a' ) . attr ( 'href' ) . replace ( 'Detail.aspx?id=' , '' ) ; return id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add current timestamp and results count to the output object [CODESPLIT] function formatDetails ( details ) { let result = { results : details , count : details . length , time : new Date ( ) . toISOString ( ) } ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read all possible information about desired vehicle . Loads vehicle details page [CODESPLIT] function getByID ( id ) { var url = ` ${ APP_BASE_URL } ${ id } ` ; return request ( url ) . then ( function ( body ) { let $ = cheerio . load ( body ) ; let info = { url : url , id : id } ; $ ( 'table#searchTableResults tr' ) . each ( ( i , item ) => { let span = $ ( item ) . find ( 'span' ) ; let key = $ ( span ) . attr ( 'id' ) . replace ( 'ctl00_Application_lbl' , '' ) . toLowerCase ( ) ; let value = $ ( span ) . text ( ) . trim ( ) ; info [ translations [ key ] || key ] = value ; } ) ; info . stolendate = getStandardizedDateStr ( info . stolendate ) ; return info ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The main and only method of the client search . It takes searchQuery either VIN or registration number . Returns object in the following form : { results : [ ... ] count : 1 time : 2016 - 03 - 03T07 : 10 : 55 . 213Z } [CODESPLIT] function ( searchQuery ) { return request ( constructSearchUrl ( searchQuery ) ) . then ( function ( body ) { let $ = cheerio . load ( body ) ; let rows = $ ( 'table#celacr tr' ) ; let promises = rows . filter ( idx => idx >= 1 ) // skip header row (index=0) . map ( ( idx , el ) => parseVehicleID ( $ , el ) ) . get ( ) // convert cheerio object to plain array . map ( getByID ) ; return Promise . all ( promises ) ; } ) . then ( formatDetails ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the current user is able to make payments . [CODESPLIT] function ( config ) { if ( ! config . callback ) { Ext . Logger . error ( 'You must specify a `callback` for `#canMakePayments` to work.' ) ; return false ; } Ext . device . Communicator . send ( { command : 'Purchase#canMakePayments' , callbacks : { callback : function ( flag ) { config . callback . call ( config . scope || this , flag ) ; } } , scope : config . scope || this } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Ext . data . Store } instance of all products available to purchase . [CODESPLIT] function ( config ) { if ( ! config . success ) { Ext . Logger . error ( 'You must specify a `success` callback for `#getProducts` to work.' ) ; return false ; } if ( ! config . failure ) { Ext . Logger . error ( 'You must specify a `failure` callback for `#getProducts` to work.' ) ; return false ; } Ext . device . Communicator . send ( { command : 'Purchase#getProducts' , productInfos : JSON . stringify ( config . productInfos ) , callbacks : { success : function ( products ) { var store = Ext . create ( 'Ext.data.Store' , { model : 'Ext.device.Purchases.Product' , data : products } ) ; config . success . call ( config . scope || this , store ) ; } , failure : config . failure } , scope : config . scope || this } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Ext . data . Store } instance of all purchases the current user has been charged . [CODESPLIT] function ( config ) { if ( ! config . callback ) { Ext . Logger . error ( 'You must specify a `callback` for `#getPurchases` to work.' ) ; return false ; } Ext . device . Communicator . send ( { command : 'Purchase#getPurchases' , callbacks : { callback : function ( purchases ) { var ln = purchases . length , i ; for ( i = 0 ; i < ln ; i ++ ) { purchases [ i ] . state = 'charged' ; } var store = Ext . create ( 'Ext.data.Store' , { model : 'Ext.device.purchases.Purchase' , data : purchases } ) ; config . callback . call ( config . scope || this , store ) ; } } , scope : config . scope || this } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will attempt to purchase this product . [CODESPLIT] function ( config ) { if ( ! config . success ) { Ext . Logger . error ( 'You must specify a `success` callback for `#purchase` to work.' ) ; return false ; } if ( ! config . failure ) { Ext . Logger . error ( 'You must specify a `failure` callback for `#purchase` to work.' ) ; return false ; } Ext . device . Communicator . send ( { command : 'Purchase#purchase' , identifier : this . get ( 'productIdentifier' ) , callbacks : { success : config . success , failure : config . failure } , scope : config . scope || this } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to mark this purchase as complete [CODESPLIT] function ( config ) { var me = this ; if ( ! config . success ) { Ext . Logger . error ( 'You must specify a `success` callback for `#complete` to work.' ) ; return false ; } if ( ! config . failure ) { Ext . Logger . error ( 'You must specify a `failure` callback for `#complete` to work.' ) ; return false ; } if ( this . get ( 'state' ) != 'charged' ) { config . failure . call ( config . scope || this , 'purchase is not charged' ) ; } Ext . device . Communicator . send ( { command : 'Purchase#complete' , identifier : me . get ( 'transactionIdentifier' ) , callbacks : { success : function ( ) { me . set ( 'state' , 'completed' ) ; config . success . call ( config . scope || this ) ; } , failure : function ( ) { me . set ( 'state' , 'charged' ) ; config . failure . call ( config . scope || this ) ; } } , scope : config . scope || this } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data from the configured { [CODESPLIT] function ( operation , callback , scope ) { var me = this , reader = me . getReader ( ) ; if ( operation . process ( 'read' , reader . process ( me . getData ( ) ) ) === false ) { this . fireEvent ( 'exception' , this , null , operation ) ; } Ext . callback ( callback , scope || me , [ operation ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PDF // FUNCTION : pdf ( x mu sigma ) Evaluates the probability density function ( PDF ) for a Normal distribution with mean mu and standard deviation sigma at a value x . [CODESPLIT] function pdf ( x , mu , sigma ) { if ( sigma === 0 ) { return x === mu ? Number . POSITIVE_INFINITY : 0 ; } var s2 = pow ( sigma , 2 ) , A = 1 / ( sqrt ( 2 * s2 * PI ) ) , B = - 1 / ( 2 * s2 ) ; return A * exp ( B * pow ( x - mu , 2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 自动require所有的enum [CODESPLIT] function requireAllEnum ( dir ) { if ( ! fs . existsSync ( dir ) ) { return ; } log . verbose ( ` ` ) ; var files = fs . readdirSync ( dir ) . filter ( ( file ) => ( ( file . startsWith ( \"E\" ) && file . endsWith ( \".js\" ) ) ) ) ; for ( var file of files ) { var fileName = file . substring ( 0 , file . lastIndexOf ( \".js\" ) ) ; global [ fileName ] = require ( path . resolve ( dir , file ) ) ; log . verbose ( ` ${ file } ` ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 自动require interceptors [CODESPLIT] function requireAllInterceptor ( dir ) { if ( ! fs . existsSync ( dir ) ) { return ; } log . verbose ( ` ` ) ; global [ 'BaseInterceptorHandler' ] = require ( path . resolve ( dir , 'BaseInterceptorHandler' ) ) ; log . verbose ( ` ` ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simple fast parsing of OpenSSH RSA and DSA keys to programmatically access key type length and and multiple key formats [CODESPLIT] function ( key ) { this . key = key ; this . keyType = key . split ( \" \" ) [ 0 ] ; this . rawkey = key . split ( \" \" ) [ 1 ] ; try { this . keyComment = key . split ( \" \" ) [ 2 ] ; } catch ( err ) { this . keyComment = null ; } this . byteArray = this . _stringToBytes ( atob ( this . rawkey ) ) ; this . slicedArray = [ ] ; this . wordLength = 4 ; this . _load ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether to execute a function as a constructor or a normal function with the provided arguments [CODESPLIT] function ( sourceFunc , boundFunc , context , callingContext , args ) { if ( ! ( callingContext instanceof boundFunc ) ) return sourceFunc . apply ( context , args ) ; Ctor . prototype = sourceFunc . prototype ; var self = new Ctor ; Ctor . prototype = null ; var result = sourceFunc . apply ( self , args ) ; if ( _ . isObject ( result ) ) return result ; return self ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires the check or uncheck event when the checked value of this component changes . [CODESPLIT] function ( e ) { var me = this , oldChecked = me . _checked , newChecked = me . getChecked ( ) ; // only fire the event when the value changes if ( oldChecked != newChecked ) { if ( newChecked ) { me . fireEvent ( 'check' , me , e ) ; } else { me . fireEvent ( 'uncheck' , me , e ) ; } me . fireEvent ( 'change' , me , newChecked , oldChecked ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of values from the checkboxes in the group that are checked . [CODESPLIT] function ( ) { var values = [ ] ; this . getSameGroupFields ( ) . forEach ( function ( field ) { if ( field . getChecked ( ) ) { values . push ( field . getValue ( ) ) ; } } ) ; return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the status of all matched checkboxes in the same group to checked . [CODESPLIT] function ( values ) { this . getSameGroupFields ( ) . forEach ( function ( field ) { field . setChecked ( ( values . indexOf ( field . getValue ( ) ) !== - 1 ) ) ; } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "apply to the selection model to maintain visual UI cues [CODESPLIT] function ( e ) { var me = this ; if ( e . target != me . element . dom ) { return ; } if ( me . getDeselectOnContainerClick ( ) && me . getStore ( ) ) { me . deselectAll ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "invoked by the selection model to maintain visual UI cues [CODESPLIT] function ( record , suppressEvent ) { var me = this ; if ( suppressEvent ) { me . doItemSelect ( me , record ) ; } else { me . fireAction ( 'select' , [ me , record ] , 'doItemSelect' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "invoked by the selection model to maintain visual UI cues [CODESPLIT] function ( record , suppressEvent ) { var me = this ; if ( me . container && ! me . isDestroyed ) { if ( suppressEvent ) { me . doItemDeselect ( me , record ) ; } else { me . fireAction ( 'deselect' , [ me , record , suppressEvent ] , 'doItemDeselect' ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refreshes the view by reloading the data from the store and re - rendering the template . [CODESPLIT] function ( ) { var me = this , container = me . container ; if ( ! me . getStore ( ) ) { if ( ! me . hasLoadedStore && ! me . getDeferEmptyText ( ) ) { me . showEmptyText ( ) ; } return ; } if ( container ) { me . fireAction ( 'refresh' , [ me ] , 'doRefresh' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strategy constructor . [CODESPLIT] function Strategy ( options , verify ) { options = options || { } ; options . clientID = options . clientID || { } ; options . clientSecret = options . clientSecret || { } ; options . grant_type = \"password\" ; options . skipUserProfile = true ; options . authorizationURL = options . authorizationURL || 'https://winkapi.quirky.com/oauth2/token' ; options . tokenURL = options . tokenURL || 'https://winkapi.quirky.com/oauth2/token' ; OAuth2Strategy . call ( this , options , verify ) ; this . name = 'wink' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method to process a params string in a snippet invocation and corretly parse out the various parameters in it . [CODESPLIT] function processParams ( paramsString ) { var individualParams = paramsString . split ( \"&\" ) , resultObject = { } ; individualParams . forEach ( function ( item ) { var itemParts = item . split ( \"=\" ) , paramName = itemParts [ 0 ] , paramValue = decodeURIComponent ( itemParts [ 1 ] || \"\" ) ; var paramObject = { } ; paramObject [ paramName ] = paramValue ; $ . extend ( resultObject , paramObject ) ; } ) ; return resultObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Array of contact objects . [CODESPLIT] function ( config ) { if ( ! this . _store ) { this . _store = [ { first : 'Robert' , last : 'Dougan' , emails : { work : 'rob@sencha.com' } } , { first : 'Jamie' , last : 'Avins' , emails : { work : 'jamie@sencha.com' } } ] ; } config . success . call ( config . scope || this , this . _store ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns localized user readable label for a contact field ( i . e . Mobile Home ) ** This method is for Sencha Native Packager only ** [CODESPLIT] function ( config ) { config . callback . call ( config . scope || this , config . label . toUpperCase ( ) , config . label ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new collection [CODESPLIT] function Collection ( options ) { if ( ! ( this instanceof Collection ) ) { return new Collection ( options ) ; } options = options || { } ; if ( options instanceof Array ) { this . modelType = undefined ; this . items = options ; } else { this . modelType = options . modelType ; this . items = options . items || [ ] ; if ( ! ( this . items instanceof Array ) ) { throw new CollectionException ( 'Items must be an array' ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the first item matching filter [CODESPLIT] function find ( filter ) { var item ; var i ; var ilen ; var keys ; var key ; var k ; var klen ; var found ; if ( filter instanceof Function ) { for ( i = 0 , ilen = this . items . length ; i < ilen ; ++ i ) { item = this . items [ i ] ; if ( filter ( item , i ) ) { return item ; } } } else if ( filter !== null && filter !== undefined ) { if ( typeof filter === 'object' ) { keys = Object . keys ( filter ) ; klen = keys . length ; for ( i = 0 , ilen = this . items . length ; i < ilen ; ++ i ) { item = this . items [ i ] ; found = true ; for ( k = 0 ; k < klen && found ; ++ k ) { key = keys [ k ] ; if ( filter [ key ] !== item [ key ] ) { found = false ; } } if ( found ) { return item ; } } } else if ( this . modelType ) { keys = Object . keys ( this . modelType . attributes ) ; klen = keys . length ; for ( i = 0 , ilen = this . items . length ; i < ilen ; ++ i ) { item = this . items [ i ] ; found = false ; for ( k = 0 ; k < klen && ! found ; ++ k ) { key = keys [ k ] ; if ( filter === item [ key ] ) { found = true ; } } if ( found ) { return item ; } } } else { for ( i = 0 , ilen = this . items . length ; i < ilen ; ++ i ) { item = this . items [ i ] ; found = false ; keys = Object . keys ( item ) ; for ( k = 0 , klen = keys . length ; k < klen && ! found ; ++ k ) { key = keys [ k ] ; if ( filter === item [ key ] ) { found = true ; } } if ( found ) { return item ; } } } } return undefined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new task . [CODESPLIT] function ( context , grunt ) { this . context = context ; this . grunt = grunt ; // Merge task-specific and/or target-specific options with these defaults. this . options = context . options ( defaultOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
