idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
225,200
def arbiter ( * * params ) : arbiter = get_actor ( ) if arbiter is None : # Create the arbiter return set_actor ( _spawn_actor ( 'arbiter' , None , * * params ) ) elif arbiter . is_arbiter ( ) : return arbiter
Obtain the arbiter .
67
6
225,201
def manage_actor ( self , monitor , actor , stop = False ) : if not monitor . is_running ( ) : stop = True if not actor . is_alive ( ) : if not actor . should_be_alive ( ) and not stop : return 1 actor . join ( ) self . _remove_monitored_actor ( monitor , actor ) return 0 timeout = None started_stopping = bool ( actor . stopping_start ) # if started_stopping is True, set stop to True stop = stop or started_stopping if not stop and actor . notified : gap = time ( ) - actor . notified stop = timeout = gap > actor . cfg . timeout if stop : # we are stopping the actor dt = actor . should_terminate ( ) if not actor . mailbox or dt : if not actor . mailbox : monitor . logger . warning ( 'kill %s - no mailbox.' , actor ) else : monitor . logger . warning ( 'kill %s - could not stop ' 'after %.2f seconds.' , actor , dt ) actor . kill ( ) self . _remove_monitored_actor ( monitor , actor ) return 0 elif not started_stopping : if timeout : monitor . logger . warning ( 'Stopping %s. Timeout %.2f' , actor , timeout ) else : monitor . logger . info ( 'Stopping %s.' , actor ) actor . stop ( ) return 1
If an actor failed to notify itself to the arbiter for more than the timeout stop the actor .
308
20
225,202
def spawn_actors ( self , monitor ) : to_spawn = monitor . cfg . workers - len ( self . managed_actors ) if monitor . cfg . workers and to_spawn > 0 : for _ in range ( to_spawn ) : monitor . spawn ( )
Spawn new actors if needed .
60
6
225,203
def stop_actors ( self , monitor ) : if monitor . cfg . workers : num_to_kill = len ( self . managed_actors ) - monitor . cfg . workers for i in range ( num_to_kill , 0 , - 1 ) : w , kage = 0 , sys . maxsize for worker in self . managed_actors . values ( ) : age = worker . impl . age if age < kage : w , kage = worker , age self . manage_actor ( monitor , w , True )
Maintain the number of workers by spawning or killing as required
116
12
225,204
def add_monitor ( self , actor , monitor_name , * * params ) : if monitor_name in self . registered : raise KeyError ( 'Monitor "%s" already available' % monitor_name ) params . update ( actor . actorparams ( ) ) params [ 'name' ] = monitor_name params [ 'kind' ] = 'monitor' return actor . spawn ( * * params )
Add a new monitor .
84
5
225,205
def publish_event ( self , channel , event , message ) : assert self . protocol is not None , "Protocol required" msg = { 'event' : event , 'channel' : channel } if message : msg [ 'data' ] = message return self . publish ( channel , msg )
Publish a new event message to a channel .
62
10
225,206
def spawn ( self , actor , aid = None , * * params ) : aid = aid or create_aid ( ) future = actor . send ( 'arbiter' , 'spawn' , aid = aid , * * params ) return actor_proxy_future ( aid , future )
Spawn a new actor from actor .
60
7
225,207
def run_actor ( self , actor ) : set_actor ( actor ) if not actor . mailbox . address : address = ( '127.0.0.1' , 0 ) actor . _loop . create_task ( actor . mailbox . start_serving ( address = address ) ) actor . _loop . run_forever ( )
Start running the actor .
72
5
225,208
def setup_event_loop ( self , actor ) : actor . logger = self . cfg . configured_logger ( 'pulsar.%s' % actor . name ) try : loop = asyncio . get_event_loop ( ) except RuntimeError : if self . cfg and self . cfg . concurrency == 'thread' : loop = asyncio . new_event_loop ( ) asyncio . set_event_loop ( loop ) else : raise if not hasattr ( loop , 'logger' ) : loop . logger = actor . logger actor . mailbox = self . create_mailbox ( actor , loop ) return loop
Set up the event loop for actor .
138
8
225,209
def hand_shake ( self , actor , run = True ) : try : assert actor . state == ACTOR_STATES . STARTING if actor . cfg . debug : actor . logger . debug ( 'starting handshake' ) actor . event ( 'start' ) . fire ( ) if run : self . _switch_to_run ( actor ) except Exception as exc : actor . stop ( exc )
Perform the hand shake for actor
85
7
225,210
def create_mailbox ( self , actor , loop ) : client = MailboxClient ( actor . monitor . address , actor , loop ) loop . call_soon_threadsafe ( self . hand_shake , actor ) return client
Create the mailbox for actor .
48
6
225,211
def stop ( self , actor , exc = None , exit_code = None ) : if actor . state <= ACTOR_STATES . RUN : # The actor has not started the stopping process. Starts it now. actor . state = ACTOR_STATES . STOPPING actor . event ( 'start' ) . clear ( ) if exc : if not exit_code : exit_code = getattr ( exc , 'exit_code' , 1 ) if exit_code == 1 : exc_info = sys . exc_info ( ) if exc_info [ 0 ] is not None : actor . logger . critical ( 'Stopping' , exc_info = exc_info ) else : actor . logger . critical ( 'Stopping: %s' , exc ) elif exit_code == 2 : actor . logger . error ( str ( exc ) ) elif exit_code : actor . stream . writeln ( str ( exc ) ) else : if not exit_code : exit_code = getattr ( actor . _loop , 'exit_code' , 0 ) # # Fire stopping event actor . exit_code = exit_code actor . stopping_waiters = [ ] actor . event ( 'stopping' ) . fire ( ) if actor . stopping_waiters and actor . _loop . is_running ( ) : actor . logger . info ( 'asynchronous stopping' ) # make sure to return the future (used by arbiter for waiting) return actor . _loop . create_task ( self . _async_stopping ( actor ) ) else : if actor . logger : actor . logger . info ( 'stopping' ) self . _stop_actor ( actor ) elif actor . stopped ( ) : return self . _stop_actor ( actor , True )
Gracefully stop the actor .
378
7
225,212
def authenticated ( self , environ , username = None , password = None , * * params ) : if username != self . username : return False o = self . options qop = o . get ( 'qop' ) method = environ [ 'REQUEST_METHOD' ] uri = environ . get ( 'PATH_INFO' , '' ) ha1 = self . ha1 ( o [ 'realm' ] , password ) ha2 = self . ha2 ( qop , method , uri ) if qop is None : response = hexmd5 ( ":" . join ( ( ha1 , self . nonce , ha2 ) ) ) elif qop == 'auth' or qop == 'auth-int' : response = hexmd5 ( ":" . join ( ( ha1 , o [ 'nonce' ] , o [ 'nc' ] , o [ 'cnonce' ] , qop , ha2 ) ) ) else : raise ValueError ( "qop value are wrong" ) return o [ 'response' ] == response
Called by the server to check if client is authenticated .
228
12
225,213
async def register ( self , channel , event , callback ) : channel = self . channel ( channel ) event = channel . register ( event , callback ) await channel . connect ( event . name ) return channel
Register a callback to channel_name and event .
43
10
225,214
async def unregister ( self , channel , event , callback ) : channel = self . channel ( channel , create = False ) if channel : channel . unregister ( event , callback ) if not channel : await channel . disconnect ( ) self . channels . pop ( channel . name ) return channel
Safely unregister a callback from the list of event callbacks for channel_name .
61
18
225,215
async def connect ( self , next_time = None ) : if self . status in can_connect : loop = self . _loop if loop . is_running ( ) : self . status = StatusType . connecting await self . _connect ( next_time )
Connect with store
56
3
225,216
def register ( self , event , callback ) : pattern = self . channels . event_pattern ( event ) entry = self . callbacks . get ( pattern ) if not entry : entry = event_callbacks ( event , pattern , re . compile ( pattern ) , [ ] ) self . callbacks [ entry . pattern ] = entry if callback not in entry . callbacks : entry . callbacks . append ( callback ) return entry
Register a callback for event
89
5
225,217
def add_errback ( future , callback , loop = None ) : def _error_back ( fut ) : if fut . _exception : callback ( fut . exception ( ) ) elif fut . cancelled ( ) : callback ( CancelledError ( ) ) future = ensure_future ( future , loop = None ) future . add_done_callback ( _error_back ) return future
Add a callback to a future executed only if an exception or cancellation has occurred .
82
16
225,218
def timeit ( self , method , times , * args , * * kwargs ) : bench = Bench ( times , loop = self . _loop ) return bench ( getattr ( self , method ) , * args , * * kwargs )
Useful utility for benchmarking an asynchronous method .
53
10
225,219
async def read ( self , n = None ) : if self . _streamed : return b'' buffer = [ ] async for body in self : buffer . append ( body ) return b'' . join ( buffer )
Read all content
46
3
225,220
def notify ( request , info ) : t = time ( ) actor = request . actor remote_actor = request . caller if isinstance ( remote_actor , ActorProxyMonitor ) : remote_actor . mailbox = request . connection info [ 'last_notified' ] = t remote_actor . info = info callback = remote_actor . callback # if a callback is still available, this is the first # time we got notified if callback : remote_actor . callback = None callback . set_result ( remote_actor ) if actor . cfg . debug : actor . logger . debug ( 'Got first notification from %s' , remote_actor ) elif actor . cfg . debug : actor . logger . debug ( 'Got notification from %s' , remote_actor ) else : actor . logger . warning ( 'notify got a bad actor' ) return t
The actor notify itself with a dictionary of information .
182
10
225,221
def write ( self , data ) : if self . closed : raise ConnectionResetError ( 'Transport closed - cannot write on %s' % self ) else : t = self . transport if self . _paused or self . _buffer : self . _buffer . appendleft ( data ) self . _buffer_size += len ( data ) self . _write_from_buffer ( ) if self . _buffer_size > 2 * self . _b_limit : if self . _waiter and not self . _waiter . cancelled ( ) : self . logger . warning ( '%s buffer size is %d: limit is %d ' , self . _buffer_size , self . _b_limit ) else : t . pause_reading ( ) self . _waiter = self . _loop . create_future ( ) else : t . write ( data ) self . changed ( ) return self . _waiter
Write data into the wire .
197
6
225,222
def pipeline ( self , consumer ) : if self . _pipeline is None : self . _pipeline = ResponsePipeline ( self ) self . event ( 'connection_lost' ) . bind ( self . _close_pipeline ) self . _pipeline . put ( consumer )
Add a consumer to the pipeline
65
6
225,223
def encode ( self , message , final = True , masking_key = None , opcode = None , rsv1 = 0 , rsv2 = 0 , rsv3 = 0 ) : fin = 1 if final else 0 opcode , masking_key , data = self . _info ( message , opcode , masking_key ) return self . _encode ( data , opcode , masking_key , fin , rsv1 , rsv2 , rsv3 )
Encode a message for writing into the wire .
105
10
225,224
def multi_encode ( self , message , masking_key = None , opcode = None , rsv1 = 0 , rsv2 = 0 , rsv3 = 0 , max_payload = 0 ) : max_payload = max ( 2 , max_payload or self . _max_payload ) opcode , masking_key , data = self . _info ( message , opcode , masking_key ) # while data : if len ( data ) >= max_payload : chunk , data , fin = ( data [ : max_payload ] , data [ max_payload : ] , 0 ) else : chunk , data , fin = data , b'' , 1 yield self . _encode ( chunk , opcode , masking_key , fin , rsv1 , rsv2 , rsv3 )
Encode a message into several frames depending on size .
182
11
225,225
def sort ( self , key , start = None , num = None , by = None , get = None , desc = False , alpha = False , store = None , groups = False ) : if ( ( start is not None and num is None ) or ( num is not None and start is None ) ) : raise CommandError ( "``start`` and ``num`` must both be specified" ) pieces = [ key ] if by is not None : pieces . append ( 'BY' ) pieces . append ( by ) if start is not None and num is not None : pieces . append ( 'LIMIT' ) pieces . append ( start ) pieces . append ( num ) if get is not None : # If get is a string assume we want to get a single value. # Otherwise assume it's an interable and we want to get multiple # values. We can't just iterate blindly because strings are # iterable. if isinstance ( get , str ) : pieces . append ( 'GET' ) pieces . append ( get ) else : for g in get : pieces . append ( 'GET' ) pieces . append ( g ) if desc : pieces . append ( 'DESC' ) if alpha : pieces . append ( 'ALPHA' ) if store is not None : pieces . append ( 'STORE' ) pieces . append ( store ) if groups : if not get or isinstance ( get , str ) or len ( get ) < 2 : raise CommandError ( 'when using "groups" the "get" argument ' 'must be specified and contain at least ' 'two keys' ) options = { 'groups' : len ( get ) if groups else None } return self . execute_command ( 'SORT' , * pieces , * * options )
Sort and return the list set or sorted set at key .
370
12
225,226
def commit ( self , raise_on_error = True ) : cmds = list ( chain ( [ ( ( 'multi' , ) , { } ) ] , self . command_stack , [ ( ( 'exec' , ) , { } ) ] ) ) self . reset ( ) return self . store . execute_pipeline ( cmds , raise_on_error )
Send commands to redis .
81
6
225,227
def copy_globals ( self , cfg ) : for name , setting in cfg . settings . items ( ) : csetting = self . settings . get ( name ) if ( setting . is_global and csetting is not None and not csetting . modified ) : csetting . set ( setting . get ( ) )
Copy global settings from cfg to this config .
70
10
225,228
def parse_command_line ( self , argv = None ) : if self . config : parser = argparse . ArgumentParser ( add_help = False ) self . settings [ 'config' ] . add_argument ( parser ) opts , _ = parser . parse_known_args ( argv ) if opts . config is not None : self . set ( 'config' , opts . config ) self . params . update ( self . import_from_module ( ) ) parser = self . parser ( ) opts = parser . parse_args ( argv ) for k , v in opts . __dict__ . items ( ) : if v is None : continue self . set ( k . lower ( ) , v )
Parse the command line
156
5
225,229
def num2eng ( num ) : num = str ( int ( num ) ) # Convert to string, throw if bad number if ( len ( num ) / 3 >= len ( _PRONOUNCE ) ) : # Sanity check return num elif num == '0' : # Zero is a special case return 'zero' pron = [ ] # Result accumulator first = True for pr , bits in zip ( _PRONOUNCE , grouper ( 3 , reversed ( num ) , '' ) ) : num = '' . join ( reversed ( bits ) ) n = int ( num ) bits = [ ] if n > 99 : # Got hundred bits . append ( '%s hundred' % _SMALL [ num [ 0 ] ] ) num = num [ 1 : ] n = int ( num ) num = str ( n ) if ( n > 20 ) and ( n != ( n // 10 * 10 ) ) : bits . append ( '%s %s' % ( _SMALL [ num [ 0 ] + '0' ] , _SMALL [ num [ 1 ] ] ) ) elif n : bits . append ( _SMALL [ num ] ) if len ( bits ) == 2 and first : first = False p = ' and ' . join ( bits ) else : p = ' ' . join ( bits ) if p and pr : p = '%s %s' % ( p , pr ) pron . append ( p ) return ', ' . join ( reversed ( pron ) )
English representation of a number up to a trillion .
316
10
225,230
def get_params ( self , * args , * * kwargs ) : kwargs . update ( self . _data ) if args and kwargs : raise ValueError ( 'Cannot mix positional and named parameters' ) if args : return list ( args ) else : return kwargs
Create an array or positional or named parameters Mixing positional and named parameters in one call is not possible .
63
21
225,231
def send ( self , command , sender , target , args , kwargs ) : command = get_command ( command ) data = { 'command' : command . __name__ , 'id' : create_aid ( ) , 'sender' : actor_identity ( sender ) , 'target' : actor_identity ( target ) , 'args' : args if args is not None else ( ) , 'kwargs' : kwargs if kwargs is not None else { } } waiter = self . _loop . create_future ( ) ack = None if command . ack : ack = create_aid ( ) data [ 'ack' ] = ack self . pending_responses [ ack ] = waiter try : self . write ( data ) except Exception as exc : waiter . set_exception ( exc ) if ack : self . pending_responses . pop ( ack , None ) else : if not ack : waiter . set_result ( None ) return waiter
Used by the server to send messages to the client . Returns a future .
215
15
225,232
def read ( self ) : if not self . fname : return try : with open ( self . fname , "r" ) as f : wpid = int ( f . read ( ) or 0 ) if wpid <= 0 : return return wpid except IOError : return
Validate pidfile and make it stale if needed
59
10
225,233
def acquire ( self , timeout = None ) : green = getcurrent ( ) parent = green . parent if parent is None : raise MustBeInChildGreenlet ( 'GreenLock.acquire in main greenlet' ) if self . _local . locked : future = create_future ( self . _loop ) self . _queue . append ( future ) parent . switch ( future ) self . _local . locked = green return self . locked ( )
Acquires the lock if in the unlocked state otherwise switch back to the parent coroutine .
94
19
225,234
def cookies ( self ) : cookies = SimpleCookie ( ) cookie = self . environ . get ( 'HTTP_COOKIE' ) if cookie : cookies . load ( cookie ) return cookies
Container of request cookies
41
4
225,235
def data_and_files ( self , data = True , files = True , stream = None ) : if self . method in ENCODE_URL_METHODS : value = { } , None else : value = self . cache . get ( 'data_and_files' ) if not value : return self . _data_and_files ( data , files , stream ) elif data and files : return value elif data : return value [ 0 ] elif files : return value [ 1 ] else : return None
Retrieve body data .
110
5
225,236
def get_host ( self , use_x_forwarded = True ) : # We try three options, in order of decreasing preference. if use_x_forwarded and ( 'HTTP_X_FORWARDED_HOST' in self . environ ) : host = self . environ [ 'HTTP_X_FORWARDED_HOST' ] port = self . environ . get ( 'HTTP_X_FORWARDED_PORT' ) if port and port != ( '443' if self . is_secure else '80' ) : host = '%s:%s' % ( host , port ) return host elif 'HTTP_HOST' in self . environ : host = self . environ [ 'HTTP_HOST' ] else : # Reconstruct the host using the algorithm from PEP 333. host = self . environ [ 'SERVER_NAME' ] server_port = str ( self . environ [ 'SERVER_PORT' ] ) if server_port != ( '443' if self . is_secure else '80' ) : host = '%s:%s' % ( host , server_port ) return host
Returns the HTTP host using the environment or request headers .
252
11
225,237
def get_client_address ( self , use_x_forwarded = True ) : xfor = self . environ . get ( 'HTTP_X_FORWARDED_FOR' ) if use_x_forwarded and xfor : return xfor . split ( ',' ) [ - 1 ] . strip ( ) else : return self . environ [ 'REMOTE_ADDR' ]
Obtain the client IP address
85
6
225,238
def full_path ( self , * args , * * query ) : path = None if args : if len ( args ) > 1 : raise TypeError ( "full_url() takes exactly 1 argument " "(%s given)" % len ( args ) ) path = args [ 0 ] if not path : path = self . path elif not path . startswith ( '/' ) : path = remove_double_slash ( '%s/%s' % ( self . path , path ) ) return iri_to_uri ( path , query )
Return a full path
119
4
225,239
def absolute_uri ( self , location = None , scheme = None , * * query ) : if not is_absolute_uri ( location ) : if location or location is None : location = self . full_path ( location , * * query ) if not scheme : scheme = self . is_secure and 'https' or 'http' base = '%s://%s' % ( scheme , self . get_host ( ) ) return '%s%s' % ( base , location ) elif not scheme : return iri_to_uri ( location ) else : raise ValueError ( 'Absolute location with scheme not valid' )
Builds an absolute URI from location and variables available in this request .
136
14
225,240
def set_response_content_type ( self , response_content_types = None ) : request_content_types = self . content_types if request_content_types : ct = request_content_types . best_match ( response_content_types ) if ct and '*' in ct : ct = None if not ct and response_content_types : raise HttpException ( status = 415 , msg = request_content_types ) self . response . content_type = ct
Evaluate the content type for the response to a client request .
110
14
225,241
def checkarity ( func , args , kwargs , discount = 0 ) : spec = inspect . getargspec ( func ) self = getattr ( func , '__self__' , None ) if self and spec . args : discount += 1 args = list ( args ) defaults = list ( spec . defaults or ( ) ) len_defaults = len ( defaults ) len_args = len ( spec . args ) - discount len_args_input = len ( args ) minlen = len_args - len_defaults totlen = len_args_input + len ( kwargs ) maxlen = len_args if spec . varargs or spec . keywords : maxlen = None if not minlen : return if not spec . defaults and maxlen : start = '"{0}" takes' . format ( func . __name__ ) else : if maxlen and totlen > maxlen : start = '"{0}" takes at most' . format ( func . __name__ ) else : start = '"{0}" takes at least' . format ( func . __name__ ) if totlen < minlen : return '{0} {1} parameters. {2} given.' . format ( start , minlen , totlen ) elif maxlen and totlen > maxlen : return '{0} {1} parameters. {2} given.' . format ( start , maxlen , totlen ) # Length of parameter OK, check names if len_args_input < len_args : le = minlen - len_args_input for arg in spec . args [ discount : ] : if args : args . pop ( 0 ) else : if le > 0 : if defaults : defaults . pop ( 0 ) elif arg not in kwargs : return ( '"{0}" has missing "{1}" parameter.' . format ( func . __name__ , arg ) ) kwargs . pop ( arg , None ) le -= 1 if kwargs and maxlen : s = '' if len ( kwargs ) > 1 : s = 's' p = ', ' . join ( '"{0}"' . format ( p ) for p in kwargs ) return ( '"{0}" does not accept {1} parameter{2}.' . format ( func . __name__ , p , s ) ) elif len_args_input > len_args + len_defaults : n = len_args + len_defaults start = '"{0}" takes' . format ( func . __name__ ) return ( '{0} {1} positional parameters. {2} given.' . format ( start , n , len_args_input ) )
Check if arguments respect a given function arity and return an error message if the check did not pass otherwise it returns None .
575
25
225,242
def sphinx_extension ( app , exception ) : if not app . builder . name in ( "html" , "dirhtml" ) : return if not app . config . sphinx_to_github : if app . config . sphinx_to_github_verbose : print ( "Sphinx-to-github: Disabled, doing nothing." ) return if exception : if app . config . sphinx_to_github_verbose : print ( "Sphinx-to-github: Exception raised in main build, doing nothing." ) return dir_helper = DirHelper ( os . path . isdir , os . listdir , os . walk , shutil . rmtree ) file_helper = FileSystemHelper ( open , os . path . join , shutil . move , os . path . exists ) operations_factory = OperationsFactory ( ) handler_factory = HandlerFactory ( ) layout_factory = LayoutFactory ( operations_factory , handler_factory , file_helper , dir_helper , app . config . sphinx_to_github_verbose , sys . stdout , force = True ) layout = layout_factory . create_layout ( app . outdir ) layout . process ( )
Wrapped up as a Sphinx Extension
272
8
225,243
def setup ( app ) : app . add_config_value ( "sphinx_to_github" , True , '' ) app . add_config_value ( "sphinx_to_github_verbose" , True , '' ) app . connect ( "build-finished" , sphinx_extension )
Setup function for Sphinx Extension
70
6
225,244
def url ( self , * * urlargs ) : if self . defaults : d = self . defaults . copy ( ) d . update ( urlargs ) urlargs = d url = '/' . join ( self . _url_generator ( urlargs ) ) if not url : return '/' else : url = '/' + url return url if self . is_leaf else url + '/'
Build a url from urlargs key - value parameters
87
11
225,245
def split ( self ) : rule = self . rule if not self . is_leaf : rule = rule [ : - 1 ] if not rule : return Route ( '/' ) , None bits = ( '/' + rule ) . split ( '/' ) last = Route ( bits [ - 1 ] if self . is_leaf else bits [ - 1 ] + '/' ) if len ( bits ) > 1 : return Route ( '/' . join ( bits [ : - 1 ] ) + '/' ) , last else : return last , None
Return a two element tuple containing the parent route and the last url bit as route . If this route is the root route it returns the root route and None .
113
32
225,246
def was_modified_since ( header = None , mtime = 0 , size = 0 ) : header_mtime = modified_since ( header , size ) if header_mtime and header_mtime <= mtime : return False return True
Check if an item was modified since the user last downloaded it
52
12
225,247
def file_response ( request , filepath , block = None , status_code = None , content_type = None , encoding = None , cache_control = None ) : file_wrapper = request . get ( 'wsgi.file_wrapper' ) if os . path . isfile ( filepath ) : response = request . response info = os . stat ( filepath ) size = info [ stat . ST_SIZE ] modified = info [ stat . ST_MTIME ] header = request . get ( 'HTTP_IF_MODIFIED_SINCE' ) if not was_modified_since ( header , modified , size ) : response . status_code = 304 else : if not content_type : content_type , encoding = mimetypes . guess_type ( filepath ) file = open ( filepath , 'rb' ) response . headers [ 'content-length' ] = str ( size ) response . content = file_wrapper ( file , block ) response . content_type = content_type response . encoding = encoding if status_code : response . status_code = status_code else : response . headers [ "Last-Modified" ] = http_date ( modified ) if cache_control : etag = digest ( 'modified: %d - size: %d' % ( modified , size ) ) cache_control ( response . headers , etag = etag ) return response raise Http404
Utility for serving a local file
301
7
225,248
def has_parent ( self , router ) : parent = self while parent and parent is not router : parent = parent . _parent return parent is not None
Check if router is self or a parent or self
32
10
225,249
def count_bytes ( array ) : # this algorithm can be rewritten as # for i in array: # count += sum(b=='1' for b in bin(i)[2:]) # but this version is almost 2 times faster count = 0 for i in array : i = i - ( ( i >> 1 ) & 0x55555555 ) i = ( i & 0x33333333 ) + ( ( i >> 2 ) & 0x33333333 ) count += ( ( ( i + ( i >> 4 ) ) & 0x0F0F0F0F ) * 0x01010101 ) >> 24 return count
Count the number of bits in a byte array .
136
10
225,250
def write ( self , message , opcode = None , encode = True , * * kw ) : if encode : message = self . parser . encode ( message , opcode = opcode , * * kw ) result = self . connection . write ( message ) if opcode == 0x8 : self . connection . close ( ) return result
Write a new message into the wire .
73
8
225,251
def ping ( self , message = None ) : return self . write ( self . parser . ping ( message ) , encode = False )
Write a ping frame .
28
5
225,252
def pong ( self , message = None ) : return self . write ( self . parser . pong ( message ) , encode = False )
Write a pong frame .
30
6
225,253
def write_close ( self , code = None ) : return self . write ( self . parser . close ( code ) , opcode = 0x8 , encode = False )
Write a close frame with code .
37
7
225,254
def escape ( html , force = False ) : if hasattr ( html , '__html__' ) and not force : return html if html in NOTHING : return '' else : return to_string ( html ) . replace ( '&' , '&amp;' ) . replace ( '<' , '&lt;' ) . replace ( '>' , '&gt;' ) . replace ( "'" , '&#39;' ) . replace ( '"' , '&quot;' )
Returns the given HTML with ampersands quotes and angle brackets encoded .
111
14
225,255
def capfirst ( x ) : x = to_string ( x ) . strip ( ) if x : return x [ 0 ] . upper ( ) + x [ 1 : ] . lower ( ) else : return x
Capitalise the first letter of x .
45
8
225,256
def nicename ( name ) : name = to_string ( name ) return capfirst ( ' ' . join ( name . replace ( '-' , ' ' ) . replace ( '_' , ' ' ) . split ( ) ) )
Make name a more user friendly string .
50
8
225,257
def set ( self , key , value ) : task = Task . current_task ( ) try : context = task . _context except AttributeError : task . _context = context = { } context [ key ] = value
Set a value in the task context
47
7
225,258
def stack_pop ( self , key ) : task = Task . current_task ( ) try : context = task . _context_stack except AttributeError : raise KeyError ( 'pop from empty stack' ) from None value = context [ key ] stack_value = value . pop ( ) if not value : context . pop ( key ) return stack_value
Remove a value in a task context stack
76
8
225,259
def module_attribute ( dotpath , default = None , safe = False ) : if dotpath : bits = str ( dotpath ) . split ( ':' ) try : if len ( bits ) == 2 : attr = bits [ 1 ] module_name = bits [ 0 ] else : bits = bits [ 0 ] . split ( '.' ) if len ( bits ) > 1 : attr = bits [ - 1 ] module_name = '.' . join ( bits [ : - 1 ] ) else : raise ValueError ( 'Could not find attribute in %s' % dotpath ) module = import_module ( module_name ) return getattr ( module , attr ) except Exception : if not safe : raise return default else : if not safe : raise ImportError return default
Load an attribute from a module .
164
7
225,260
def start ( self , exit = True ) : if self . state == ACTOR_STATES . INITIAL : self . _concurrency . before_start ( self ) self . _concurrency . add_events ( self ) try : self . cfg . when_ready ( self ) except Exception : # pragma nocover self . logger . exception ( 'Unhandled exception in when_ready hook' ) self . _started = self . _loop . time ( ) self . _exit = exit self . state = ACTOR_STATES . STARTING self . _run ( )
Called after forking to start the actor s life .
125
12
225,261
def send ( self , target , action , * args , * * kwargs ) : target = self . monitor if target == 'monitor' else target mailbox = self . mailbox if isinstance ( target , ActorProxyMonitor ) : mailbox = target . mailbox else : actor = self . get_actor ( target ) if isinstance ( actor , Actor ) : # this occur when sending a message from arbiter to monitors or # vice-versa. return command_in_context ( action , self , actor , args , kwargs ) elif isinstance ( actor , ActorProxyMonitor ) : mailbox = actor . mailbox if hasattr ( mailbox , 'send' ) : # if not mailbox.closed: return mailbox . send ( action , self , target , args , kwargs ) else : raise CommandError ( 'Cannot execute "%s" in %s. Unknown actor %s.' % ( action , self , target ) )
Send a message to target to perform action with given positional args and key - valued kwargs . Returns a coroutine or a Future .
195
28
225,262
def stream ( self , request , counter = 0 ) : if self . _children : for child in self . _children : if isinstance ( child , String ) : yield from child . stream ( request , counter + 1 ) else : yield child
Returns an iterable over strings .
51
7
225,263
def to_bytes ( self , request = None ) : data = bytearray ( ) for chunk in self . stream ( request ) : if isinstance ( chunk , str ) : chunk = chunk . encode ( self . charset ) data . extend ( chunk ) return bytes ( data )
Called to transform the collection of streams into the content string . This method can be overwritten by derived classes .
61
23
225,264
def attr ( self , * args ) : attr = self . _attr if not args : return attr or { } result , adding = self . _attrdata ( 'attr' , * args ) if adding : for key , value in result . items ( ) : if DATARE . match ( key ) : self . data ( key [ 5 : ] , value ) else : if attr is None : self . _extra [ 'attr' ] = attr = { } attr [ key ] = value result = self return result
Add the specific attribute to the attribute dictionary with key name and value value and return self .
116
18
225,265
def addClass ( self , cn ) : if cn : if isinstance ( cn , ( tuple , list , set , frozenset ) ) : add = self . addClass for c in cn : add ( c ) else : classes = self . _classes if classes is None : self . _extra [ 'classes' ] = classes = set ( ) add = classes . add for cn in cn . split ( ) : add ( slugify ( cn ) ) return self
Add the specific class names to the class set and return self .
105
13
225,266
def flatatt ( self , * * attr ) : cs = '' attr = self . _attr classes = self . _classes data = self . _data css = self . _css attr = attr . copy ( ) if attr else { } if classes : cs = ' ' . join ( classes ) attr [ 'class' ] = cs if css : attr [ 'style' ] = ' ' . join ( ( '%s:%s;' % ( k , v ) for k , v in css . items ( ) ) ) if data : for k , v in data . items ( ) : attr [ 'data-%s' % k ] = dump_data_value ( v ) if attr : return '' . join ( attr_iter ( attr ) ) else : return ''
Return a string with attributes to add to the tag
179
10
225,267
def css ( self , mapping = None ) : css = self . _css if mapping is None : return css elif isinstance ( mapping , Mapping ) : if css is None : self . _extra [ 'css' ] = css = { } css . update ( mapping ) return self else : return css . get ( mapping ) if css else None
Update the css dictionary if mapping is a dictionary otherwise return the css value at mapping .
82
19
225,268
def absolute_path ( self , path , minify = True ) : if minify : ending = '.%s' % self . mediatype if not path . endswith ( ending ) : if self . minified : path = '%s.min' % path path = '%s%s' % ( path , ending ) # if self . is_relative ( path ) and self . media_path : return '%s%s' % ( self . media_path , path ) elif self . asset_protocol and path . startswith ( '//' ) : return '%s%s' % ( self . asset_protocol , path ) else : return path
Return a suitable absolute url for path .
148
8
225,269
def insert ( self , index , child , rel = None , type = None , media = None , condition = None , * * kwargs ) : if child : srel = 'stylesheet' stype = 'text/css' minify = rel in ( None , srel ) and type in ( None , stype ) path = self . absolute_path ( child , minify = minify ) if path . endswith ( '.css' ) : rel = rel or srel type = type or stype value = Html ( 'link' , href = path , rel = rel , * * kwargs ) if type : value . attr ( 'type' , type ) if media not in ( None , 'all' ) : value . attr ( 'media' , media ) if condition : value = Html ( None , '<!--[if %s]>\n' % condition , value , '<![endif]-->\n' ) value = value . to_string ( ) if value not in self . children : if index is None : self . children . append ( value ) else : self . children . insert ( index , value )
Append a link to this container .
250
8
225,270
def insert ( self , index , child , * * kwargs ) : if child : script = self . script ( child , * * kwargs ) if script not in self . children : if index is None : self . children . append ( script ) else : self . children . insert ( index , script )
add a new script to the container .
66
8
225,271
def get_meta ( self , name , meta_key = None ) : meta_key = meta_key or 'name' for child in self . meta . _children : if isinstance ( child , Html ) and child . attr ( meta_key ) == name : return child . attr ( 'content' )
Get the content attribute of a meta tag name .
69
10
225,272
def replace_meta ( self , name , content = None , meta_key = None ) : children = self . meta . _children if not content : # small optimazation children = tuple ( children ) meta_key = meta_key or 'name' for child in children : if child . attr ( meta_key ) == name : if content : child . attr ( 'content' , content ) else : self . meta . _children . remove ( child ) return if content : self . add_meta ( * * { meta_key : name , 'content' : content } )
Replace the content attribute of meta tag name
125
9
225,273
def randompaths ( request , num_paths = 1 , size = 250 , mu = 0 , sigma = 1 ) : r = [ ] for p in range ( num_paths ) : v = 0 path = [ v ] r . append ( path ) for t in range ( size ) : v += normalvariate ( mu , sigma ) path . append ( v ) return r
Lists of random walks .
84
6
225,274
def setup ( self , environ ) : json_handler = Root ( ) . putSubHandler ( 'calc' , Calculator ( ) ) middleware = wsgi . Router ( '/' , post = json_handler , accept_content_types = JSON_CONTENT_TYPES ) response = [ wsgi . GZipMiddleware ( 200 ) ] return wsgi . WsgiHandler ( middleware = [ wsgi . wait_for_body_middleware , middleware ] , response_middleware = response )
Called once to setup the list of wsgi middleware .
116
14
225,275
def AsyncResponseMiddleware ( environ , resp ) : future = create_future ( ) future . _loop . call_soon ( future . set_result , resp ) return future
This is just for testing the asynchronous response middleware
39
10
225,276
def encode ( self , message ) : if not isinstance ( message , dict ) : message = { 'message' : message } message [ 'time' ] = time . time ( ) return json . dumps ( message )
Encode a message when publishing .
46
7
225,277
def on_message ( self , websocket , msg ) : if msg : lines = [ ] for li in msg . split ( '\n' ) : li = li . strip ( ) if li : lines . append ( li ) msg = ' ' . join ( lines ) if msg : return self . pubsub . publish ( self . channel , msg )
When a new message arrives it publishes to all listening clients .
75
12
225,278
async def rpc_message ( self , request , message ) : await self . pubsub . publish ( self . channel , message ) return 'OK'
Publish a message via JSON - RPC
33
8
225,279
def setup ( self , environ ) : request = wsgi_request ( environ ) cfg = request . cache . cfg loop = request . cache . _loop self . store = create_store ( cfg . data_store , loop = loop ) pubsub = self . store . pubsub ( protocol = Protocol ( ) ) channel = '%s_webchat' % self . name ensure_future ( pubsub . subscribe ( channel ) , loop = loop ) return WsgiHandler ( [ Router ( '/' , get = self . home_page ) , WebSocket ( '/message' , Chat ( pubsub , channel ) ) , Router ( '/rpc' , post = Rpc ( pubsub , channel ) , response_content_types = JSON_CONTENT_TYPES ) ] , [ AsyncResponseMiddleware , GZipMiddleware ( min_length = 20 ) ] )
Called once only to setup the WSGI application handler .
193
12
225,280
def _get_headers ( self , environ ) : headers = self . headers method = environ [ 'REQUEST_METHOD' ] if has_empty_content ( self . status_code , method ) and method != HEAD : headers . pop ( 'content-type' , None ) headers . pop ( 'content-length' , None ) self . _content = ( ) else : if not self . is_streamed ( ) : cl = reduce ( count_len , self . _content , 0 ) headers [ 'content-length' ] = str ( cl ) ct = headers . get ( 'content-type' ) # content type encoding available if self . encoding : ct = ct or 'text/plain' if ';' not in ct : ct = '%s; charset=%s' % ( ct , self . encoding ) if ct : headers [ 'content-type' ] = ct if method == HEAD : self . _content = ( ) # Cookies if ( self . status_code < 400 and self . _can_store_cookies and self . _cookies ) : for c in self . cookies . values ( ) : headers . add ( 'set-cookie' , c . OutputString ( ) ) return headers . items ( )
The list of headers for this response
276
7
225,281
def rpc_method ( func , doc = None , format = 'json' , request_handler = None ) : def _ ( self , * args , * * kwargs ) : request = args [ 0 ] if request_handler : kwargs = request_handler ( request , format , kwargs ) try : return func ( * args , * * kwargs ) except TypeError : msg = checkarity ( func , args , kwargs ) if msg : raise InvalidParams ( 'Invalid Parameters. %s' % msg ) else : raise _ . __doc__ = doc or func . __doc__ _ . __name__ = func . __name__ _ . FromApi = True return _
A decorator which exposes a function func as an rpc function .
152
14
225,282
def clean_path_middleware ( environ , start_response = None ) : path = environ [ 'PATH_INFO' ] if path and '//' in path : url = re . sub ( "/+" , '/' , path ) if not url . startswith ( '/' ) : url = '/%s' % url qs = environ [ 'QUERY_STRING' ] if qs : url = '%s?%s' % ( url , qs ) raise HttpRedirect ( url )
Clean url from double slashes and redirect if needed .
115
11
225,283
def authorization_middleware ( environ , start_response = None ) : key = 'http.authorization' c = environ . get ( key ) if c is None : code = 'HTTP_AUTHORIZATION' if code in environ : environ [ key ] = parse_authorization_header ( environ [ code ] )
Parse the HTTP_AUTHORIZATION key in the environ .
74
16
225,284
async def wait_for_body_middleware ( environ , start_response = None ) : if environ . get ( 'wsgi.async' ) : try : chunk = await environ [ 'wsgi.input' ] . read ( ) except TypeError : chunk = b'' environ [ 'wsgi.input' ] = BytesIO ( chunk ) environ . pop ( 'wsgi.async' )
Use this middleware to wait for the full body .
94
11
225,285
def middleware_in_executor ( middleware ) : @ wraps ( middleware ) def _ ( environ , start_response ) : loop = get_event_loop ( ) return loop . run_in_executor ( None , middleware , environ , start_response ) return _
Use this middleware to run a synchronous middleware in the event loop executor .
63
18
225,286
async def release_forks ( self , philosopher ) : forks = self . forks self . forks = [ ] self . started_waiting = 0 for fork in forks : philosopher . logger . debug ( 'Putting down fork %s' , fork ) await philosopher . send ( 'monitor' , 'putdown_fork' , fork ) await sleep ( self . cfg . waiting_period )
The philosopher has just eaten and is ready to release both forks .
83
13
225,287
def hello ( environ , start_response ) : if environ [ 'REQUEST_METHOD' ] == 'GET' : data = b'Hello World!\n' status = '200 OK' response_headers = [ ( 'Content-type' , 'text/plain' ) , ( 'Content-Length' , str ( len ( data ) ) ) ] start_response ( status , response_headers ) return iter ( [ data ] ) else : raise MethodNotAllowed
The WSGI_ application handler which returns an iterable over the Hello World! message .
102
18
225,288
async def parse_headers ( fp , _class = HTTPMessage ) : headers = [ ] while True : line = await fp . readline ( ) headers . append ( line ) if len ( headers ) > _MAXHEADERS : raise HttpException ( "got more than %d headers" % _MAXHEADERS ) if line in ( b'\r\n' , b'\n' , b'' ) : break hstring = b'' . join ( headers ) . decode ( 'iso-8859-1' ) return email . parser . Parser ( _class = _class ) . parsestr ( hstring )
Parses only RFC2822 headers from a file pointer . email Parser wants to see strings rather than bytes . But a TextIOWrapper around self . rfile would buffer too many bytes from the stream bytes which we later need to read as bytes . So we read the correct bytes here as bytes for email Parser to parse .
139
70
225,289
def _waiting_expect ( self ) : if self . _expect_sent is None : if self . environ . get ( 'HTTP_EXPECT' , '' ) . lower ( ) == '100-continue' : return True self . _expect_sent = '' return False
True when the client is waiting for 100 Continue .
63
10
225,290
def base64 ( self , charset = None ) : return b64encode ( self . bytes ( ) ) . decode ( charset or self . charset )
Data encoded as base 64
35
5
225,291
def feed_data ( self , data ) : if data : self . _bytes . append ( data ) if self . parser . stream : self . parser . stream ( self ) else : self . parser . buffer . extend ( data )
Feed new data into the MultiPart parser or the data stream
49
12
225,292
def server ( name = 'proxy-server' , headers_middleware = None , server_software = None , * * kwargs ) : if headers_middleware is None : headers_middleware = [ x_forwarded_for ] wsgi_proxy = ProxyServerWsgiHandler ( headers_middleware ) kwargs [ 'server_software' ] = server_software or SERVER_SOFTWARE return wsgi . WSGIServer ( wsgi_proxy , name = name , * * kwargs )
Function to Create a WSGI Proxy Server .
115
9
225,293
async def request ( self ) : request_headers = self . request_headers ( ) environ = self . environ method = environ [ 'REQUEST_METHOD' ] data = None if method in ENCODE_BODY_METHODS : data = DataIterator ( self ) http = self . wsgi . http_client try : await http . request ( method , environ [ 'RAW_URI' ] , data = data , headers = request_headers , version = environ [ 'SERVER_PROTOCOL' ] , pre_request = self . pre_request ) except Exception as exc : self . error ( exc )
Perform the Http request to the upstream server
138
10
225,294
def pre_request ( self , response , exc = None ) : if response . request . method == 'CONNECT' : self . start_response ( '200 Connection established' , [ ( 'content-length' , '0' ) ] ) # send empty byte so that headers are sent self . future . set_result ( [ b'' ] ) # proxy - server connection upstream = response . connection # client - proxy connection dostream = self . connection # Upgrade downstream connection dostream . upgrade ( partial ( StreamTunnel . create , upstream ) ) # # upstream upgrade upstream . upgrade ( partial ( StreamTunnel . create , dostream ) ) response . fire_event ( 'post_request' ) # abort the event raise AbortEvent else : response . event ( 'data_processed' ) . bind ( self . data_processed ) response . event ( 'post_request' ) . bind ( self . post_request )
Start the tunnel .
202
4
225,295
def connection_lost ( self , exc = None ) : if self . _loop . get_debug ( ) : self . producer . logger . debug ( 'connection lost %s' , self ) self . event ( 'connection_lost' ) . fire ( exc = exc )
Fires the connection_lost event .
58
8
225,296
def start ( self , request = None ) : self . connection . processed += 1 self . producer . requests_processed += 1 self . event ( 'post_request' ) . bind ( self . finished_reading ) self . request = request or self . create_request ( ) try : self . fire_event ( 'pre_request' ) except AbortEvent : if self . _loop . get_debug ( ) : self . producer . logger . debug ( 'Abort request %s' , request ) else : self . start_request ( )
Starts processing the request for this protocol consumer .
117
10
225,297
def process_global ( name , val = None , setval = False ) : p = current_process ( ) if not hasattr ( p , '_pulsar_globals' ) : p . _pulsar_globals = { 'lock' : Lock ( ) } if setval : p . _pulsar_globals [ name ] = val else : return p . _pulsar_globals . get ( name )
Access and set global variables for the current process .
100
10
225,298
def get_environ_proxies ( ) : proxy_keys = [ 'all' , 'http' , 'https' , 'ftp' , 'socks' , 'ws' , 'wss' , 'no' ] def get_proxy ( k ) : return os . environ . get ( k ) or os . environ . get ( k . upper ( ) ) proxies = [ ( key , get_proxy ( key + '_proxy' ) ) for key in proxy_keys ] return dict ( [ ( key , val ) for ( key , val ) in proxies if val ] )
Return a dict of environment proxies . From requests_ .
130
11
225,299
def has_vary_header ( response , header_query ) : if not response . has_header ( 'Vary' ) : return False vary_headers = cc_delim_re . split ( response [ 'Vary' ] ) existing_headers = set ( [ header . lower ( ) for header in vary_headers ] ) return header_query . lower ( ) in existing_headers
Checks to see if the response has a given header name in its Vary header .
84
18