idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
37,200 | def registered_capabilities ( self ) : return dict ( [ ( CAPABILITIES [ c . id ] , c ) for c in self . capabilities if c . id in CAPABILITIES ] ) | Return dictionary of non - YANG capabilities . |
37,201 | def listsdelete ( x , xs ) : i = xs . index ( x ) return xs [ : i ] + xs [ ( i + 1 ) : ] | Return a new list with x removed from xs |
37,202 | def unique_prefixes ( context ) : res = { } for m in context . modules . values ( ) : if m . keyword == "submodule" : continue prf = new = m . i_prefix suff = 0 while new in res . values ( ) : suff += 1 new = "%s%x" % ( prf , suff ) res [ m ] = new return res | Return a dictionary with unique prefixes for modules in context . |
37,203 | def preprocess_files ( self , prefix ) : if prefix is None : return files = ( "bin/yang2dsdl" , "man/man1/yang2dsdl.1" , "pyang/plugins/jsonxsl.py" ) regex = re . compile ( "^(.*)/usr/local(.*)$" ) for f in files : inf = open ( f ) cnt = inf . readlines ( ) inf . close ( ) ouf = open ( f , "w" ) for line in cnt : mo = ... | Change the installation prefix where necessary . |
37,204 | def add_module ( self , ref , text , format = None , expect_modulename = None , expect_revision = None , expect_failure_error = True ) : if format == None : format = util . guess_format ( text ) if format == 'yin' : p = yin_parser . YinParser ( ) else : p = yang_parser . YangParser ( ) module = p . parse ( self , ref ,... | Parse a module text and add the module data to the context |
37,205 | def del_module ( self , module ) : rev = util . get_latest_revision ( module ) del self . modules [ ( module . arg , rev ) ] | Remove a module from the context |
37,206 | def get_module ( self , modulename , revision = None ) : if revision is None and modulename in self . revs : ( revision , _handle ) = self . _get_latest_rev ( self . revs [ modulename ] ) if revision is not None : if ( modulename , revision ) in self . modules : return self . modules [ ( modulename , revision ) ] else ... | Return the module if it exists in the context |
37,207 | def init ( plugindirs = [ ] ) : from . translators import yang , yin , dsdl yang . pyang_plugin_init ( ) yin . pyang_plugin_init ( ) dsdl . pyang_plugin_init ( ) for ep in pkg_resources . iter_entry_points ( group = 'pyang.plugin' ) : plugin_init = ep . load ( ) plugin_init ( ) basedir = os . path . split ( sys . modul... | Initialize the plugin framework |
37,208 | def split_qname ( qname ) : res = qname . split ( YinParser . ns_sep ) if len ( res ) == 1 : return None , res [ 0 ] else : return res | Split qname into namespace URI and local name |
37,209 | def check_attr ( self , pos , attrs ) : for at in attrs : ( ns , local_name ) = self . split_qname ( at ) if ns is None : error . err_add ( self . ctx . errors , pos , 'UNEXPECTED_ATTRIBUTE' , local_name ) elif ns == yin_namespace : error . err_add ( self . ctx . errors , pos , 'UNEXPECTED_ATTRIBUTE' , "{" + at ) | Check for unknown attributes . |
37,210 | def search_definition ( self , module , keyword , arg ) : r = module . search_one ( keyword , arg ) if r is not None : return r for i in module . search ( 'include' ) : modulename = i . arg m = self . ctx . search_module ( i . pos , modulename ) if m is not None : r = m . search_one ( keyword , arg ) if r is not None :... | Search for a defintion with keyword name Search the module and its submodules . |
37,211 | def emit_path_arg ( keywordstr , arg , fd , indent , max_line_len , line_len , eol ) : quote = '"' arg = escape_str ( arg ) if not ( need_new_line ( max_line_len , line_len , arg ) ) : fd . write ( " " + quote + arg + quote ) return False num_chars = max_line_len - line_len if num_chars <= 0 : fd . write ( " " + quote ... | Heuristically pretty print a path argument |
37,212 | def emit_arg ( keywordstr , stmt , fd , indent , indentstep , max_line_len , line_len ) : arg = escape_str ( stmt . arg ) lines = arg . splitlines ( True ) if len ( lines ) <= 1 : if len ( arg ) > 0 and arg [ - 1 ] == '\n' : arg = arg [ : - 1 ] + r'\n' if ( stmt . keyword in _force_newline_arg or need_new_line ( max_li... | Heuristically pretty print the argument string with double quotes |
37,213 | def process_children ( self , node , elem , module , path , omit = [ ] ) : for ch in node . i_children : if ch not in omit and ( ch . i_config or self . doctype == "data" ) : self . node_handler . get ( ch . keyword , self . ignore ) ( ch , elem , module , path ) | Proceed with all children of node . |
37,214 | def container ( self , node , elem , module , path ) : nel , newm , path = self . sample_element ( node , elem , module , path ) if path is None : return if self . annots : pres = node . search_one ( "presence" ) if pres is not None : nel . append ( etree . Comment ( " presence: %s " % pres . arg ) ) self . process_chi... | Create a sample container element and proceed with its children . |
37,215 | def leaf ( self , node , elem , module , path ) : if node . i_default is None : nel , newm , path = self . sample_element ( node , elem , module , path ) if path is None : return if self . annots : nel . append ( etree . Comment ( " type: %s " % node . search_one ( "type" ) . arg ) ) elif self . defaults : nel , newm ,... | Create a sample leaf element . |
37,216 | def anyxml ( self , node , elem , module , path ) : nel , newm , path = self . sample_element ( node , elem , module , path ) if path is None : return if self . annots : nel . append ( etree . Comment ( " anyxml " ) ) | Create a sample anyxml element . |
37,217 | def list ( self , node , elem , module , path ) : nel , newm , path = self . sample_element ( node , elem , module , path ) if path is None : return for kn in node . i_key : self . node_handler . get ( kn . keyword , self . ignore ) ( kn , nel , newm , path ) self . process_children ( node , nel , newm , path , node . ... | Create sample entries of a list . |
37,218 | def leaf_list ( self , node , elem , module , path ) : nel , newm , path = self . sample_element ( node , elem , module , path ) if path is None : return minel = node . search_one ( "min-elements" ) self . add_copies ( node , elem , nel , minel ) self . list_comment ( node , nel , minel ) | Create sample entries of a leaf - list . |
37,219 | def sample_element ( self , node , parent , module , path ) : if path is None : return parent , module , None elif path == [ ] : pass else : if node . arg == path [ 0 ] : path = path [ 1 : ] else : return parent , module , None res = etree . SubElement ( parent , node . arg ) mm = node . main_module ( ) if mm != module... | Create element under parent . |
37,220 | def add_copies ( self , node , parent , elem , minel ) : rep = 0 if minel is None else int ( minel . arg ) - 1 for i in range ( rep ) : parent . append ( copy . deepcopy ( elem ) ) | Add appropriate number of elem copies to parent . |
37,221 | def list_comment ( self , node , elem , minel ) : lo = "0" if minel is None else minel . arg maxel = node . search_one ( "max-elements" ) hi = "" if maxel is None else maxel . arg elem . insert ( 0 , etree . Comment ( " # entries: %s..%s " % ( lo , hi ) ) ) if node . keyword == 'list' : elem . insert ( 0 , etree . Comm... | Add list annotation to elem . |
37,222 | def slugify ( value , separator = '-' , max_length = 0 , word_boundary = False , entities = True , decimal = True , hexadecimal = True ) : value = normalize ( 'NFKD' , to_string ( value , 'utf-8' , 'ignore' ) ) if unidecode : value = unidecode ( value ) if entities : value = CHAR_ENTITY_REXP . sub ( lambda m : chr ( na... | Normalizes string removes non - alpha characters and converts spaces to separator character |
37,223 | def smart_truncate ( value , max_length = 0 , word_boundaries = False , separator = ' ' ) : value = value . strip ( separator ) if not max_length : return value if len ( value ) < max_length : return value if not word_boundaries : return value [ : max_length ] . strip ( separator ) if separator not in value : return va... | Truncate a string |
37,224 | def get ( self ) : if self . _current : return self . _resume ( self . _current , False ) else : return self . _get ( None ) | Called by the protocol consumer |
37,225 | def pack_pipeline ( self , commands ) : return b'' . join ( starmap ( lambda * args : b'' . join ( self . _pack_command ( args ) ) , ( a for a , _ in commands ) ) ) | Packs pipeline commands into bytes . |
37,226 | def pypi_release ( self ) : meta = self . distribution . metadata pypi = ServerProxy ( self . pypi_index_url ) releases = pypi . package_releases ( meta . name ) if releases : return next ( iter ( sorted ( releases , reverse = True ) ) ) | Get the latest pypi release |
37,227 | def is_mainthread ( thread = None ) : thread = thread if thread is not None else current_thread ( ) return isinstance ( thread , threading . _MainThread ) | Check if thread is the main thread . |
37,228 | def process_data ( name = None ) : ct = current_process ( ) if not hasattr ( ct , '_pulsar_local' ) : ct . _pulsar_local = { } loc = ct . _pulsar_local return loc . get ( name ) if name else loc | Fetch the current process local data dictionary . |
37,229 | def thread_data ( name , value = NOTHING , ct = None ) : ct = ct or current_thread ( ) if is_mainthread ( ct ) : loc = process_data ( ) elif not hasattr ( ct , '_pulsar_local' ) : ct . _pulsar_local = loc = { } else : loc = ct . _pulsar_local if value is not NOTHING : if name in loc : if loc [ name ] is not value : rai... | Set or retrieve an attribute name from thread ct . |
37,230 | def parse_address ( netloc , default_port = 8000 ) : if isinstance ( netloc , tuple ) : if len ( netloc ) != 2 : raise ValueError ( 'Invalid address %s' % str ( netloc ) ) return netloc netloc = native_str ( netloc ) auth = None if '@' in netloc : auth , netloc = netloc . split ( '@' ) if netloc . startswith ( "unix:" ... | Parse an internet address netloc and return a tuple with host and port . |
37,231 | def is_socket_closed ( sock ) : if not sock : return True try : if not poll : if not select : return False try : return bool ( select ( [ sock ] , [ ] , [ ] , 0.0 ) [ 0 ] ) except socket . error : return True p = poll ( ) p . register ( sock , POLLIN ) for ( fno , ev ) in p . poll ( 0.0 ) : if fno == sock . fileno ( ) ... | Check if socket sock is closed . |
37,232 | def close_socket ( sock ) : if sock : try : sock . shutdown ( socket . SHUT_RDWR ) except Exception : pass try : sock . close ( ) except Exception : pass | Shutdown and close the socket . |
37,233 | async def rpc_server_info ( self , request ) : info = await send ( 'arbiter' , 'info' ) info = self . extra_server_info ( request , info ) try : info = await info except TypeError : pass return info | Return a dictionary of information regarding the server and workers . |
37,234 | def bind ( self , callback ) : handlers = self . _handlers if self . _self is None : raise RuntimeError ( '%s already fired, cannot add callbacks' % self ) if handlers is None : handlers = [ ] self . _handlers = handlers handlers . append ( callback ) | Bind a callback to this event . |
37,235 | def unbind ( self , callback ) : handlers = self . _handlers if handlers : filtered_callbacks = [ f for f in handlers if f != callback ] removed_count = len ( handlers ) - len ( filtered_callbacks ) if removed_count : self . _handlers = filtered_callbacks return removed_count return 0 | Remove a callback from the list |
37,236 | def fire ( self , exc = None , data = None ) : o = self . _self if o is not None : handlers = self . _handlers if self . _onetime : self . _handlers = None self . _self = None if handlers : if exc is not None : for hnd in handlers : hnd ( o , exc = exc ) elif data is not None : for hnd in handlers : hnd ( o , data = da... | Fire the event |
37,237 | def fire_event ( self , name , exc = None , data = None ) : if self . _events and name in self . _events : self . _events [ name ] . fire ( exc = exc , data = data ) | Fire event at name if it is registered |
37,238 | def bind_events ( self , events ) : evs = self . _events if evs and events : for event in evs . values ( ) : if event . name in events : event . bind ( events [ event . name ] ) | Register all known events found in events key - valued parameters . |
37,239 | def _get_args_for_reloading ( ) : rv = [ sys . executable ] py_script = sys . argv [ 0 ] if os . name == 'nt' and not os . path . exists ( py_script ) and os . path . exists ( py_script + '.exe' ) : py_script += '.exe' rv . append ( py_script ) rv . extend ( sys . argv [ 1 : ] ) return rv | Returns the executable . This contains a workaround for windows if the executable is incorrectly reported to not have the . exe extension which can cause bugs on reloading . |
37,240 | def restart_with_reloader ( self ) : while True : LOGGER . info ( 'Restarting with %s reloader' % self . name ) args = _get_args_for_reloading ( ) new_environ = os . environ . copy ( ) new_environ [ PULSAR_RUN_MAIN ] = 'true' exit_code = subprocess . call ( args , env = new_environ , close_fds = False ) if exit_code !=... | Spawn a new Python interpreter with the same arguments as this one |
37,241 | def kill ( self , sig ) : if self . is_alive ( ) and self . _loop : self . _loop . call_soon_threadsafe ( self . _loop . stop ) | Invoke the stop on the event loop method . |
37,242 | def encode ( self , method , uri ) : if not self . username or not self . password : return o = self . options qop = o . get ( 'qop' ) realm = o . get ( 'realm' ) nonce = o . get ( 'nonce' ) entdig = None p_parsed = urlparse ( uri ) path = p_parsed . path if p_parsed . query : path += '?' + p_parsed . query ha1 = self ... | Called by the client to encode Authentication header . |
37,243 | def handle_wsgi_error ( environ , exc ) : if isinstance ( exc , tuple ) : exc_info = exc exc = exc [ 1 ] else : exc_info = True request = wsgi_request ( environ ) request . cache . handle_wsgi_error = True old_response = request . cache . pop ( 'response' , None ) response = request . response if old_response : respons... | The default error handler while serving a WSGI request . |
37,244 | def render_error ( request , exc ) : cfg = request . get ( 'pulsar.cfg' ) debug = cfg . debug if cfg else False response = request . response if not response . content_type : content_type = request . get ( 'default.content_type' ) response . content_type = request . content_types . best_match ( as_tuple ( content_type ... | Default renderer for errors . |
37,245 | def render_error_debug ( request , exception , is_html ) : error = Html ( 'div' , cn = 'well well-lg' ) if is_html else [ ] for trace in format_traceback ( exception ) : counter = 0 for line in trace . split ( '\n' ) : if line . startswith ( ' ' ) : counter += 1 line = line [ 2 : ] if line : if is_html : line = Html (... | Render the exception traceback |
37,246 | def arbiter ( ** params ) : arbiter = get_actor ( ) if arbiter is None : return set_actor ( _spawn_actor ( 'arbiter' , None , ** params ) ) elif arbiter . is_arbiter ( ) : return arbiter | Obtain the arbiter . |
37,247 | 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 ... | If an actor failed to notify itself to the arbiter for more than the timeout stop the actor . |
37,248 | 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 . |
37,249 | 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 ,... | Maintain the number of workers by spawning or killing as required |
37,250 | 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 . |
37,251 | 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 . |
37,252 | 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 . |
37,253 | 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 . |
37,254 | 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 : rai... | Set up the event loop for actor . |
37,255 | 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 |
37,256 | 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 . |
37,257 | def stop ( self , actor , exc = None , exit_code = None ) : if actor . state <= ACTOR_STATES . RUN : 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 ]... | Gracefully stop the actor . |
37,258 | 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 ( ... | Called by the server to check if client is authenticated . |
37,259 | 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 . |
37,260 | 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 . |
37,261 | 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 |
37,262 | 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 ... | Register a callback for event |
37,263 | 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 . |
37,264 | 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 . |
37,265 | 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 |
37,266 | 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 callback : remote_actor . ... | The actor notify itself with a dictionary of information . |
37,267 | 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... | Write data into the wire . |
37,268 | 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 |
37,269 | 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 . |
37,270 | 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 , d... | Encode a message into several frames depending on size . |
37,271 | 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 ... | Sort and return the list set or sorted set at key . |
37,272 | 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 . |
37,273 | 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 . |
37,274 | 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 ( ... | Parse the command line |
37,275 | def num2eng ( num ) : num = str ( int ( num ) ) if ( len ( num ) / 3 >= len ( _PRONOUNCE ) ) : return num elif num == '0' : return 'zero' pron = [ ] first = True for pr , bits in zip ( _PRONOUNCE , grouper ( 3 , reversed ( num ) , '' ) ) : num = '' . join ( reversed ( bits ) ) n = int ( num ) bits = [ ] if n > 99 : bit... | English representation of a number up to a trillion . |
37,276 | 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 . |
37,277 | 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 no... | Used by the server to send messages to the client . Returns a future . |
37,278 | 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 |
37,279 | 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 .... | Acquires the lock if in the unlocked state otherwise switch back to the parent coroutine . |
37,280 | def cookies ( self ) : cookies = SimpleCookie ( ) cookie = self . environ . get ( 'HTTP_COOKIE' ) if cookie : cookies . load ( cookie ) return cookies | Container of request cookies |
37,281 | 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... | Retrieve body data . |
37,282 | def get_host ( self , use_x_forwarded = True ) : 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 )... | Returns the HTTP host using the environment or request headers . |
37,283 | 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 |
37,284 | 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 , p... | Return a full path |
37,285 | 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 ... | Builds an absolute URI from location and variables available in this request . |
37,286 | 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 , ... | Evaluate the content type for the response to a client request . |
37,287 | 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_... | Check if arguments respect a given function arity and return an error message if the check did not pass otherwise it returns None . |
37,288 | def sphinx_extension ( app , exception ) : "Wrapped up as a Sphinx Extension" 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 ... | Wrapped up as a Sphinx Extension |
37,289 | def setup ( app ) : "Setup function for Sphinx Extension" 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 |
37,290 | 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 |
37,291 | 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 ... | 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 . |
37,292 | 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 |
37,293 | 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... | Utility for serving a local file |
37,294 | 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 |
37,295 | def count_bytes ( array ) : 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 . |
37,296 | 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 . |
37,297 | def ping ( self , message = None ) : return self . write ( self . parser . ping ( message ) , encode = False ) | Write a ping frame . |
37,298 | def pong ( self , message = None ) : return self . write ( self . parser . pong ( message ) , encode = False ) | Write a pong frame . |
37,299 | def write_close ( self , code = None ) : return self . write ( self . parser . close ( code ) , opcode = 0x8 , encode = False ) | Write a close frame with code . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.