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 ] }


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 } ; }


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 }


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 ) }


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 ) }


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 ) }


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 ) }


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 ) } }


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 ) }


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 ) }


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 }


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 ) } }


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 ) }


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 ) + "()" ) }


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 ) } }


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 }


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 } }


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 } ` ) ) ; }


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 ) ; } } ] ) ) ; } ) ; } ; }


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 ) ; }


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' ) + ']' ; } ) ; }


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 "" ; } }


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 } ] } ] ; }


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 ; } , { } ) ; }


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 ; }


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 ) ; }


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 } ; }


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 ( ) ; }


Input: / * [CODESPLIT] function encodeGroupProtocol ( protocol ) { this . Int16BE ( protocol . name . length ) . string ( protocol . name ) . string ( _encodeProtocolData ( protocol ) ) ; }


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 ; }


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 ( ) ) ; }


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 ; }


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 ) ; }


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 ) ; } ; }


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 ] ; } } ; }


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.' ) ) ; } ) ; }


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' ) ) ; }


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 ; }


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 ) ; } }


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 ) ; } } ) ; } }


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 ) ; }


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 ` ) ; }


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 ` ) ; }


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 ) ; }


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 ; } , { } ) ; }


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" ) ; }


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 ( ) ; }


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 ( ) ; } ) ; } ) ; } } ; }


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 , } ; }


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 ) } }


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 ) } }


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 ) ) } ) }


Input: Copy file from template directory . [CODESPLIT] function copyTemplate ( from , to ) { write ( to , fs . readFileSync ( path . join ( TEMPLATE_DIR , from ) , 'utf-8' ) ) }


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 ) ) } ) }


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 ( ) }


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 ( ) }


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 ) } ) }


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 ( ) }


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 } }


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 ) } } ) } } ) }


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 ) }


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 } }


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 ( ) }


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 ) }


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 } ; }


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 ; }


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 ) } }


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 ; }


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 ) ; }


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 ) ; } ) ; }


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 , } ) ) ; }


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 ] } ` , } ) ; } } } } } }


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 ( ) ; } } ) ; } ) ; }


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 ) ; }


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 } ` ; }


Input: Copyright 2017 - present Callstack . All rights reserved . [CODESPLIT] function cleanPathMiddleware ( req , res , next ) { req . cleanPath = req . path . replace ( / \/$ / , '' ) ; next ( ) ; }


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 ; }


Input:
Devtools middleware compatible with default React Native implementation [CODESPLIT] function devToolsMiddleware ( debuggerProxy ) { return ( req , res , next ) => { switch ( req . cleanPath ) { /**
       * Request for the debugger frontend
       */ 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 ; } /**
       * Request for the debugger worker
       */ 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 ; } /**
       * Request for (maybe) launching devtools
       */ case '/launch-js-devtools' : { if ( ! debuggerProxy . isDebuggerConnected ( ) ) { launchBrowser ( ` ${ req . socket . localPort } ` ) ; } res . end ( 'OK' ) ; break ; } default : next ( ) ; } } ; }


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 ; }


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 ; } }


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 ( ) ; } } } , } , } ; }


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 ; }


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" ; }


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 ) ) ; } } } }


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 } ; }


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 ; }


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 ; }


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 ) ; }


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 ) ) ; }


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.
	 *
	 * Unlike orthogonal patterns, the "null" pattern (one without crossing edges)
	 * must be filtered, and the ends of both the "null" and L patterns are not
	 * known: L and U patterns have different endings, and the adjacent pattern is
	 * unknown. Therefore, a blend of both possibilites is computed.
	 */ switch ( pattern ) { case 0 : { /*         .-´
			 *       .-´
			 *     .-´
			 *   .-´
			 *   ´
			 */ // 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 : { /*         .-´
			 *       .-´
			 *     .-´
			 *   .-´
			 *   |
			 *   |
			 */ 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 : { /*         .----
			 *       .-´
			 *     .-´
			 *   .-´
			 *   ´
			 */ 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 : { /*
			 *         .----
			 *       .-´
			 *     .-´
			 *   .-´
			 *   |
			 *   |
			 */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , result ) ; break ; } case 4 : { /*         .-´
			 *       .-´
			 *     .-´
			 * ----´
			 */ 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 : { /*         .-´
			 *       .-´
			 *     .-´
			 * --.-´
			 *   |
			 *   |
			 */ 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 : { /*         .----
			 *       .-´
			 *     .-´
			 * ----´
			 */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 1.0 + d , 0.0 + d ) , left , offset , result ) ; break ; } case 7 : { /*         .----
			 *       .-´
			 *     .-´
			 * --.-´
			 *   |
			 *   |
			 */ 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 : { /*         |
			 *         |
			 *       .-´
			 *     .-´
			 *   .-´
			 *   ´
			 */ 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 : { /*         |
			 *         |
			 *       .-´
			 *     .-´
			 *   .-´
			 *   |
			 *   |
			 */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 0.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , result ) ; break ; } case 10 : { /*         |
			 *         .----
			 *       .-´
			 *     .-´
			 *   .-´
			 *   ´
			 */ 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 : { /*         |
			 *         .----
			 *       .-´
			 *     .-´
			 *   .-´
			 *   |
			 *   |
			 */ 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 : { /*         |
			 *         |
			 *       .-´
			 *     .-´
			 * ----´
			 */ calculateDiagonalArea ( pattern , p1 . set ( 1.0 , 1.0 ) , p2 . set ( 1.0 + d , 1.0 + d ) , left , offset , result ) ; break ; } case 13 : { /*         |
			 *         |
			 *       .-´
			 *     .-´
			 * --.-´
			 *   |
			 *   |
			 */ 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 : { /*         |
			 *         .----
			 *       .-´
			 *     .-´
			 * ----´
			 */ 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 : { /*         |
			 *         .----
			 *       .-´
			 *     .-´
			 * --.-´
			 *   |
			 *   |
			 */ 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 ; }