idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
37,400
def has_add_permission ( self , request ) : perm_string = '%s.add_%s' % ( self . model . _meta . app_label , self . model . _meta . object_name . lower ( ) ) return request . user . has_perm ( perm_string )
Returns True if the requesting user is allowed to add an object False otherwise .
37,401
def has_update_permission ( self , request , obj ) : perm_string = '%s.change_%s' % ( self . model . _meta . app_label , self . model . _meta . object_name . lower ( ) ) return request . user . has_perm ( perm_string )
Returns True if the requesting user is allowed to update the given object False otherwise .
37,402
def serialize ( self , obj , fields ) : data = { } remaining_fields = [ ] for field in fields : if callable ( field ) : data [ field . __name__ ] = field ( obj ) elif hasattr ( self , field ) and callable ( getattr ( self , field ) ) : data [ field ] = getattr ( self , field ) ( obj ) elif hasattr ( obj , field ) : att...
Serializes a single model instance to a Python dict based on the specified list of fields .
37,403
def json_dumps ( self , data , ** options ) : params = { 'sort_keys' : True , 'indent' : 2 } params . update ( options ) if json . __version__ . split ( '.' ) >= [ '2' , '1' , '3' ] : params . update ( { 'use_decimal' : False } ) return json . dumps ( data , cls = DjangoJSONEncoder , ** params )
Wrapper around json . dumps that uses a special JSON encoder .
37,404
def dir ( cls , label , children ) : return FSEntry ( label = label , children = children , type = u"Directory" , use = None )
Return FSEntry directory object .
37,405
def from_fptr ( cls , label , type_ , fptr ) : return FSEntry ( label = label , type = type_ , path = fptr . path , use = fptr . use , file_uuid = fptr . file_uuid , derived_from = fptr . derived_from , checksum = fptr . checksum , checksumtype = fptr . checksumtype , )
Return FSEntry object .
37,406
def file_id ( self ) : if self . type . lower ( ) == "directory" : return None if self . file_uuid is None : raise exceptions . MetsError ( "No FILEID: File %s does not have file_uuid set" % self . path ) if self . is_aip : return os . path . splitext ( os . path . basename ( self . path ) ) [ 0 ] return utils . FILE_I...
Returns the fptr
37,407
def add_child ( self , child ) : if self . type . lower ( ) != "directory" : raise ValueError ( "Only directory objects can have children" ) if child is self : raise ValueError ( "Cannot be a child of itself!" ) if child not in self . _children : self . _children . append ( child ) child . parent = self return child
Add a child FSEntry to this FSEntry .
37,408
def remove_child ( self , child ) : try : self . _children . remove ( child ) except ValueError : pass else : child . parent = None
Remove a child from this FSEntry
37,409
def serialize_filesec ( self ) : if ( self . type . lower ( ) not in ( "item" , "archival information package" ) or self . use is None ) : return None el = etree . Element ( utils . lxmlns ( "mets" ) + "file" , ID = self . file_id ( ) ) if self . group_id ( ) : el . attrib [ "GROUPID" ] = self . group_id ( ) if self . ...
Return the file Element for this file appropriate for use in a fileSec .
37,410
def is_empty_dir ( self ) : if self . mets_div_type == "Directory" : children = self . _children if children : if all ( child . is_empty_dir for child in children ) : return True else : return False else : return True else : return False
Returns True if this fs item is a directory with no children or a directory with only other empty directories as children .
37,411
def serialize_structmap ( self , recurse = True , normative = False ) : if not self . label : return None if self . is_empty_dir and not normative : return None el = etree . Element ( utils . lxmlns ( "mets" ) + "div" , TYPE = self . mets_div_type ) el . attrib [ "LABEL" ] = self . label if ( not normative ) and self ....
Return the div Element for this file appropriate for use in a structMap .
37,412
def check_secret ( self , secret ) : try : return hmac . compare_digest ( secret , self . secret ) except AttributeError : return secret == self . secret
Checks if the secret string used in the authentication attempt matches the known secret string . Some mechanisms will override this method to control how this comparison is made .
37,413
def secure ( cls ) : builtin_mechs = cls . _get_builtin_mechanisms ( ) secure_mechs = [ mech for _ , mech in builtin_mechs . items ( ) if not mech . insecure and mech . priority is not None ] return SASLAuth ( secure_mechs )
Uses only authentication mechanisms that are secure for use in non - encrypted sessions .
37,414
def read ( cls , source ) : if hasattr ( source , "read" ) : return cls . fromfile ( source ) if os . path . exists ( source ) : return cls . fromfile ( source ) if isinstance ( source , six . string_types ) : source = source . encode ( "utf8" ) return cls . fromstring ( source )
Read source into a METSDocument instance . This is an instance constructor . The source may be a path to a METS file a file - like object or a string of XML .
37,415
def _collect_all_files ( self , files = None ) : if files is None : files = self . _root_elements collected = set ( ) for entry in files : collected . add ( entry ) collected . update ( self . _collect_all_files ( entry . children ) ) return collected
Collect all FSEntrys into a set including all descendants .
37,416
def get_file ( self , ** kwargs ) : for entry in self . all_files ( ) : if all ( value == getattr ( entry , key ) for key , value in kwargs . items ( ) ) : return entry return None
Return the FSEntry that matches parameters .
37,417
def append_file ( self , fs_entry ) : if fs_entry in self . _root_elements : return self . _root_elements . append ( fs_entry ) self . _all_files = None
Adds an FSEntry object to this METS document s tree . Any of the represented object s children will also be added to the document .
37,418
def remove_entry ( self , fs_entry ) : try : self . _root_elements . remove ( fs_entry ) except ValueError : pass if fs_entry . parent : fs_entry . parent . remove_child ( fs_entry ) self . _all_files = None
Removes an FSEntry object from this METS document .
37,419
def _document_root ( self , fully_qualified = True ) : nsmap = { "xsi" : utils . NAMESPACES [ "xsi" ] , "xlink" : utils . NAMESPACES [ "xlink" ] } if fully_qualified : nsmap [ "mets" ] = utils . NAMESPACES [ "mets" ] else : nsmap [ None ] = utils . NAMESPACES [ "mets" ] attrib = { "{}schemaLocation" . format ( utils . ...
Return the mets Element for the document root .
37,420
def _mets_header ( self , now ) : header_tag = etree . QName ( utils . NAMESPACES [ u"mets" ] , u"metsHdr" ) header_attrs = { } if self . createdate is None : header_attrs [ u"CREATEDATE" ] = now else : header_attrs [ u"CREATEDATE" ] = self . createdate header_attrs [ u"LASTMODDATE" ] = now header_element = etree . Ele...
Return the metsHdr Element .
37,421
def _collect_mdsec_elements ( files ) : dmdsecs = [ ] amdsecs = [ ] for f in files : for d in f . dmdsecs : dmdsecs . append ( d ) for a in f . amdsecs : amdsecs . append ( a ) dmdsecs . sort ( key = lambda x : x . id_string ) amdsecs . sort ( key = lambda x : x . id_string ) return dmdsecs + amdsecs
Return all dmdSec and amdSec classes associated with the files .
37,422
def _structmap ( self ) : structmap = etree . Element ( utils . lxmlns ( "mets" ) + "structMap" , TYPE = "physical" , ID = "structMap_1" , LABEL = "Archivematica default" , ) for item in self . _root_elements : child = item . serialize_structmap ( recurse = True ) if child is not None : structmap . append ( child ) ret...
Returns structMap element for all files .
37,423
def _filesec ( self , files = None ) : if files is None : files = self . all_files ( ) filesec = etree . Element ( utils . lxmlns ( "mets" ) + "fileSec" ) filegrps = { } for file_ in files : if file_ . type . lower ( ) not in ( "item" , AIP_ENTRY_TYPE ) : continue filegrp = filegrps . get ( file_ . use ) if filegrp is ...
Returns fileSec Element containing all files grouped by use .
37,424
def serialize ( self , fully_qualified = True ) : now = datetime . utcnow ( ) . replace ( microsecond = 0 ) . isoformat ( "T" ) files = self . all_files ( ) mdsecs = self . _collect_mdsec_elements ( files ) root = self . _document_root ( fully_qualified = fully_qualified ) root . append ( self . _mets_header ( now = no...
Returns this document serialized to an xml Element .
37,425
def tostring ( self , fully_qualified = True , pretty_print = True , encoding = "UTF-8" ) : root = self . serialize ( fully_qualified = fully_qualified ) kwargs = { "pretty_print" : pretty_print , "encoding" : encoding } if encoding != "unicode" : kwargs [ "xml_declaration" ] = True return etree . tostring ( root , ** ...
Serialize and return a string of this METS document .
37,426
def write ( self , filepath , fully_qualified = True , pretty_print = False , encoding = "UTF-8" ) : root = self . serialize ( fully_qualified = fully_qualified ) tree = root . getroottree ( ) kwargs = { "pretty_print" : pretty_print , "encoding" : encoding } if encoding != "unicode" : kwargs [ "xml_declaration" ] = Tr...
Serialize and write this METS document to filepath .
37,427
def _get_el_to_normative ( parent_elem , normative_parent_elem ) : el_to_normative = OrderedDict ( ) if normative_parent_elem is None : for el in parent_elem : el_to_normative [ el ] = None else : for norm_el in normative_parent_elem : matches = [ el for el in parent_elem if el . get ( "TYPE" ) == norm_el . get ( "TYPE...
Return ordered dict el_to_normative which maps children of parent_elem to their normative counterparts in the children of normative_parent_elem or to None if there is no normative parent . If there is a normative div element with no non - normative counterpart that element is treated as a key with value None . This all...
37,428
def fromfile ( cls , path ) : parser = etree . XMLParser ( remove_blank_text = True ) return cls . fromtree ( etree . parse ( path , parser = parser ) )
Creates a METS by parsing a file .
37,429
def fromstring ( cls , string ) : parser = etree . XMLParser ( remove_blank_text = True ) root = etree . fromstring ( string , parser ) tree = root . getroottree ( ) return cls . fromtree ( tree )
Create a METS by parsing a string .
37,430
def fromtree ( cls , tree ) : mets = cls ( ) mets . tree = tree mets . _parse_tree ( tree ) return mets
Create a METS from an ElementTree or Element .
37,431
def schematron_validate ( mets_doc , schematron = AM_SCT_PATH ) : if isinstance ( schematron , six . string_types ) : schematron = get_schematron ( schematron ) is_valid = schematron . validate ( mets_doc ) report = schematron . validation_report return is_valid , report
Validate a METS file using a schematron schema . Return a boolean indicating validity and a report as an lxml . ElementTree instance .
37,432
def sct_report_string ( report ) : ret = [ ] namespaces = { "svrl" : "http://purl.oclc.org/dsdl/svrl" } for index , failed_assert_el in enumerate ( report . findall ( "svrl:failed-assert" , namespaces = namespaces ) ) : ret . append ( "{}. {}" . format ( index + 1 , failed_assert_el . find ( "svrl:text" , namespaces = ...
Return a human - readable string representation of the error report returned by lxml s schematron validator .
37,433
def xsd_error_log_string ( xsd_error_log ) : ret = [ ] for error in xsd_error_log : ret . append ( "ERROR ON LINE {}: {}" . format ( error . line , error . message . encode ( "utf-8" ) ) ) return "\n" . join ( ret )
Return a human - readable string representation of the error log returned by lxml s XMLSchema validator .
37,434
def get_view_url ( self ) : url = reverse ( "django_popup_view_field:get_popup_view" , args = ( self . view_class_name , ) ) return "{url}?{cd}" . format ( url = url , cd = self . callback_data )
Return url for ajax to view for render dialog content
37,435
def send ( self , data , sample_rate = 1 ) : if self . prefix : data = dict ( ( "." . join ( ( self . prefix , stat ) ) , value ) for stat , value in data . items ( ) ) if sample_rate < 1 : if random . random ( ) > sample_rate : return sampled_data = dict ( ( stat , "%s|@%s" % ( value , sample_rate ) ) for stat , value...
Squirt the metrics over UDP
37,436
def restart ( self , * args , ** kw ) : self . stop ( ) self . start ( * args , ** kw )
Restart the daemon .
37,437
def get_auth_providers ( self , netloc ) : url = "https://%s/info/system?null" % ( netloc ) response = requests . get ( url , verify = self . verify ) if not response . ok or not hasattr ( response , "json" ) : error_message = '%s Unexpected Error: %s for uri: %s\nText: %r' % ( response . status_code , response . reaso...
BIG - IQ specific query for auth providers
37,438
def get_new_token ( self , netloc ) : login_body = { 'username' : self . username , 'password' : self . password , } if self . auth_provider : if self . auth_provider == 'local' : login_body [ 'loginProviderName' ] = 'local' elif self . auth_provider == 'tmos' : login_body [ 'loginProviderName' ] = 'tmos' elif self . a...
Get a new token from BIG - IP and store it internally .
37,439
def decorate_HTTP_verb_method ( method ) : @ functools . wraps ( method ) def wrapper ( self , RIC_base_uri , ** kwargs ) : partition = kwargs . pop ( 'partition' , '' ) sub_path = kwargs . pop ( 'subPath' , '' ) suffix = kwargs . pop ( 'suffix' , '' ) identifier , kwargs = _unique_resource_identifier_from_kwargs ( ** ...
Prepare and Post - Process HTTP VERB method for BigIP - RESTServer request .
37,440
def _unique_resource_identifier_from_kwargs ( ** kwargs ) : name = kwargs . pop ( 'name' , '' ) uuid = kwargs . pop ( 'uuid' , '' ) id = kwargs . pop ( 'id' , '' ) if uuid : return uuid , kwargs elif id : return id , kwargs else : return name , kwargs
Chooses an identifier given different choices
37,441
def delete ( self , uri , ** kwargs ) : args1 = get_request_args ( kwargs ) args2 = get_send_args ( kwargs ) req = requests . Request ( 'DELETE' , uri , ** args1 ) prepared = self . session . prepare_request ( req ) if self . debug : self . _debug_output . append ( debug_prepared_request ( prepared ) ) return self . se...
Sends a HTTP DELETE command to the BIGIP REST Server .
37,442
def append_user_agent ( self , user_agent ) : old_ua = self . session . headers . get ( 'User-Agent' , '' ) ua = old_ua + ' ' + user_agent self . session . headers [ 'User-Agent' ] = ua . strip ( )
Append text to the User - Agent header for the request .
37,443
def validate_public_key ( value ) : is_valid = False exc = None for load in ( load_pem_public_key , load_ssh_public_key ) : if not is_valid : try : load ( value . encode ( 'utf-8' ) , default_backend ( ) ) is_valid = True except Exception as e : exc = e if not is_valid : raise ValidationError ( 'Public key is invalid: ...
Check that the given value is a valid RSA Public key in either PEM or OpenSSH format . If it is invalid raises django . core . exceptions . ValidationError .
37,444
def _register_formats ( cls ) : for fmt in cls . OUTPUT_FORMATS : clean_fmt = fmt . replace ( '+' , '_' ) setattr ( cls , clean_fmt , property ( ( lambda x , fmt = fmt : cls . _output ( x , fmt ) ) , ( lambda x , y , fmt = fmt : cls . _input ( x , y , fmt ) ) ) )
Adds format properties .
37,445
def sign ( username , private_key , generate_nonce = None , iat = None , algorithm = DEFAULT_ALGORITHM ) : iat = iat if iat else time . time ( ) if not generate_nonce : generate_nonce = lambda username , iat : random . random ( ) token_data = { 'username' : username , 'time' : iat , 'nonce' : generate_nonce ( username ...
Create a signed JWT using the given username and RSA private key .
37,446
def get_claimed_username ( token ) : unverified_data = jwt . decode ( token , options = { 'verify_signature' : False } ) if 'username' not in unverified_data : return None return unverified_data [ 'username' ]
Given a JWT get the username that it is claiming to be without verifying that the signature is valid .
37,447
def verify ( token , public_key , validate_nonce = None , algorithms = [ DEFAULT_ALGORITHM ] ) : try : token_data = jwt . decode ( token , public_key , algorithms = algorithms ) except jwt . InvalidTokenError : logger . debug ( 'JWT failed verification' ) return False claimed_username = token_data . get ( 'username' ) ...
Verify the validity of the given JWT using the given public key .
37,448
def log_used_nonce ( self , username , iat , nonce ) : key = self . create_nonce_key ( username , iat ) used = cache . get ( key , [ ] ) used . append ( nonce ) cache . set ( key , set ( used ) , token . TIMESTAMP_TOLERANCE * 2 )
Log a nonce as being used and therefore henceforth invalid .
37,449
def validate_nonce ( self , username , iat , nonce ) : key = self . create_nonce_key ( username , iat ) used = cache . get ( key , [ ] ) return nonce not in used
Confirm that the given nonce hasn t already been used .
37,450
def process_request ( self , request ) : if 'HTTP_AUTHORIZATION' not in request . META : return try : method , claim = request . META [ 'HTTP_AUTHORIZATION' ] . split ( ' ' , 1 ) except ValueError : return if method . upper ( ) != AUTH_METHOD : return username = token . get_claimed_username ( claim ) if not username : ...
Process a Django request and authenticate users .
37,451
def load_private_key ( key_file , key_password = None ) : key_file = os . path . expanduser ( key_file ) key_file = os . path . abspath ( key_file ) if not key_password : with open ( key_file , 'r' ) as key : return key . read ( ) with open ( key_file , 'rb' ) as key : key_bytes = key . read ( ) return decrypt_key ( ke...
Load a private key from disk .
37,452
def decrypt_key ( key , password ) : private = serialization . load_pem_private_key ( key , password = password , backend = default_backend ( ) ) return private . private_bytes ( Encoding . PEM , PrivateFormat . PKCS8 , NoEncryption ( ) )
Decrypt an encrypted private key .
37,453
def create_auth_header ( username , key = None , key_file = "~/.ssh/id_rsa" , key_password = None ) : if not key : key = load_private_key ( key_file , key_password ) claim = token . sign ( username , key ) return "%s %s" % ( AUTH_METHOD , claim . decode ( ENCODING ) )
Create an HTTP Authorization header using a private key file .
37,454
def _config_logs ( lvl = None , name = None ) : FORMAT = '%(message)s' for h in list ( logging . root . handlers ) : logging . root . removeHandler ( h ) global _log_level if lvl : _log_level = lvl logging . basicConfig ( level = _log_level , format = FORMAT , stream = sys . stdout ) _log = logging . getLogger ( __name...
Set up or change logging configuration .
37,455
def mk_set_headers ( self , data , columns ) : columns = tuple ( columns ) lens = [ ] for key in columns : value_len = max ( len ( str ( each . get ( key , '' ) ) ) for each in data ) lens . append ( max ( value_len , len ( self . _get_name ( key ) ) ) ) fmt = self . mk_fmt ( * lens ) return fmt
figure out sizes and create header fmt
37,456
def _get_name ( self , key ) : if key in self . display_names : return self . display_names [ key ] return key . capitalize ( )
get display name for a key or mangle for display
37,457
def display_set ( self , typ , data , columns ) : self . display_section ( "%s (%d)" % ( self . _get_name ( typ ) , len ( data ) ) ) headers = tuple ( map ( self . _get_name , columns ) ) fmt = self . mk_set_headers ( data , columns ) self . display_headers ( fmt , headers ) for each in data : row = tuple ( self . _get...
display a list of dicts
37,458
def _print ( self , * args ) : string = u" " . join ( args ) + '\n' self . fobj . write ( string )
internal print to self . fobj
37,459
def display ( self , typ , data ) : if hasattr ( self , 'print_' + typ ) : getattr ( self , 'print_' + typ ) ( data ) elif not data : self . _print ( "%s: %s" % ( typ , data ) ) elif isinstance ( data , collections . Mapping ) : self . _print ( "\n" , typ ) for k , v in data . items ( ) : self . print ( k , v ) elif is...
display section of typ with data
37,460
def _handler ( func ) : "Decorate a command handler" def _wrapped ( * a , ** k ) : r = func ( * a , ** k ) if r is None : r = 0 return r return staticmethod ( _wrapped )
Decorate a command handler
37,461
def add_subcommands ( parser , commands ) : "Add commands to a parser" subps = parser . add_subparsers ( ) for cmd , cls in commands : subp = subps . add_parser ( cmd , help = cls . __doc__ ) add_args = getattr ( cls , 'add_arguments' , None ) if add_args : add_args ( subp ) handler = getattr ( cls , 'handle' , None ) ...
Add commands to a parser
37,462
def update ( self , res , pk , depth = 1 , since = None ) : fetch = lambda : self . _fetcher . fetch_latest ( res , pk , 1 , since = since ) self . _update ( res , fetch , depth )
Try to sync an object to the local database in case of failure where a referenced object is not found attempt to fetch said object from the REST api
37,463
def get_task ( self , key ) : res , pk = key jobs , lock = self . _jobs with lock : return jobs [ res ] . get ( pk )
Get a scheduled task or none
37,464
def set_job ( self , key , func , args ) : res , pk = key jobs , lock = self . _jobs task = _tasks . UpdateTask ( func ( * args ) , key ) with lock : job = jobs [ res ] . get ( pk ) had = bool ( job ) if not job : job = task jobs [ res ] [ pk ] = job else : task . cancel ( ) self . _log . debug ( 'Scheduling: %s-%s (%s...
Get a scheduled task or set if none exists .
37,465
def pending_tasks ( self , res ) : "Synchronized access to tasks" jobs , lock = self . _jobs with lock : return jobs [ res ] . copy ( )
Synchronized access to tasks
37,466
def fetch_and_index ( self , fetch_func ) : "Fetch data with func, return dict indexed by ID" data , e = fetch_func ( ) if e : raise e yield { row [ 'id' ] : row for row in data }
Fetch data with func return dict indexed by ID
37,467
def initialize_object ( B , res , row ) : B = get_backend ( ) field_groups = FieldGroups ( B . get_concrete ( res ) ) try : obj = B . get_object ( B . get_concrete ( res ) , row [ 'id' ] ) except B . object_missing_error ( B . get_concrete ( res ) ) : tbl = B . get_concrete ( res ) obj = tbl ( ) for fname , field in fi...
Do a shallow initialization of an object
37,468
def read_config ( conf_dir = DEFAULT_CONFIG_DIR ) : "Find and read config file for a directory, return None if not found." conf_path = os . path . expanduser ( conf_dir ) if not os . path . exists ( conf_path ) : if conf_dir != DEFAULT_CONFIG_DIR : raise IOError ( "Config directory not found at %s" % ( conf_path , ) ) ...
Find and read config file for a directory return None if not found .
37,469
def detect_old ( data ) : "Check for a config file with old schema" if not data : return False ok , errors , warnings = _schema . validate ( _OLD_SCHEMA , data ) return ok and not ( errors or warnings )
Check for a config file with old schema
37,470
def convert_old ( data ) : "Convert config data with old schema to new schema" ret = default_config ( ) ret [ 'sync' ] . update ( data . get ( 'peeringdb' , { } ) ) ret [ 'orm' ] [ 'database' ] . update ( data . get ( 'database' , { } ) ) return ret
Convert config data with old schema to new schema
37,471
def write_config ( data , conf_dir = DEFAULT_CONFIG_DIR , codec = "yaml" , backup_existing = False ) : if not codec : codec = 'yaml' codec = munge . get_codec ( codec ) ( ) conf_dir = os . path . expanduser ( conf_dir ) if not os . path . exists ( conf_dir ) : os . mkdir ( conf_dir ) outpath = os . path . join ( conf_d...
Write config values to a file .
37,472
def prompt_config ( sch , defaults = None , path = None ) : out = { } for name , attr in sch . attributes ( ) : fullpath = name if path : fullpath = '{}.{}' . format ( path , name ) if defaults is None : defaults = { } default = defaults . get ( name ) if isinstance ( attr , _schema . Schema ) : value = prompt_config (...
Utility function to recursively prompt for config values
37,473
def fetch ( self , R , pk , depth = 1 ) : "Request object from API" d , e = self . _fetcher . fetch ( R , pk , depth ) if e : raise e return d
Request object from API
37,474
def fetch_all ( self , R , depth = 1 , ** kwargs ) : "Request multiple objects from API" d , e = self . _fetcher . fetch_all ( R , depth , kwargs ) if e : raise e return d
Request multiple objects from API
37,475
def all ( self , res ) : "Get resources using a filter condition" B = get_backend ( ) return B . get_objects ( B . get_concrete ( res ) )
Get resources using a filter condition
37,476
def run_task ( func ) : def _wrapped ( * a , ** k ) : gen = func ( * a , ** k ) return _consume_task ( gen ) return _wrapped
Decorator to collect and return generator results returning a list if there are multiple results
37,477
def get ( self , typ , id , ** kwargs ) : return self . _load ( self . _request ( typ , id = id , params = kwargs ) )
Load type by id
37,478
def wrap_generator ( func ) : async def _wrapped ( * a , ** k ) : r , ret = None , [ ] gen = func ( * a , ** k ) while True : try : item = gen . send ( r ) except StopIteration : break if inspect . isawaitable ( item ) : r = await item else : r = item ret . append ( r ) if len ( ret ) == 1 : return ret . pop ( ) return...
Decorator to convert a generator function to an async function which collects and returns generator results returning a list if there are multiple results
37,479
def run_task ( func ) : def _wrapped ( * a , ** k ) : loop = asyncio . get_event_loop ( ) return loop . run_until_complete ( func ( * a , ** k ) ) return _wrapped
Decorator to wrap an async function in an event loop . Use for main sync interface methods .
37,480
def prompt ( msg , default = None ) : "Prompt for input" if default is not None : msg = '{} ({})' . format ( msg , repr ( default ) ) msg = '{}: ' . format ( msg ) try : s = input ( msg ) except KeyboardInterrupt : exit ( 1 ) except EOFError : s = '' if not s : s = default return s
Prompt for input
37,481
def limit_mem ( limit = ( 4 * 1024 ** 3 ) ) : "Set soft memory limit" rsrc = resource . RLIMIT_DATA soft , hard = resource . getrlimit ( rsrc ) resource . setrlimit ( rsrc , ( limit , hard ) ) softnew , _ = resource . getrlimit ( rsrc ) assert softnew == limit _log = logging . getLogger ( __name__ ) _log . debug ( 'Set...
Set soft memory limit
37,482
def render_module ( inits , calls , inputs , outputs , dst_dir , pytorch_dict , pytorch_module_name ) : inits = [ i for i in inits if len ( i ) > 0 ] output = pytorch_model_template . format ( ** { 'module_name' : pytorch_module_name , 'module_name_lower' : pytorch_module_name . lower ( ) , 'inits' : '\n' . join ( init...
Render model .
37,483
def getAllFtpConnections ( self ) : outputMsg = "Current ftp connections:\n" counter = 1 for k in self . ftpList : outputMsg += str ( counter ) + ". " + k + " " outputMsg += str ( self . ftpList [ k ] ) + "\n" counter += 1 if self . printOutput : logger . info ( outputMsg ) return self . ftpList
Returns a dictionary containing active ftp connections .
37,484
def setup_logging ( verbose = 0 , colors = False , name = None ) : root_logger = logging . getLogger ( name ) root_logger . setLevel ( logging . DEBUG if verbose > 0 else logging . INFO ) formatter = ColorFormatter ( verbose > 0 , colors ) if colors : colorclass . Windows . enable ( ) handler_stdout = logging . StreamH...
Configure console logging . Info and below go to stdout others go to stderr .
37,485
def format ( self , record ) : formatted = super ( ColorFormatter , self ) . format ( record ) if self . verbose or not record . name . startswith ( self . SPECIAL_SCOPE ) : return formatted formatted = '=> ' + formatted if not self . colors : return formatted if record . levelno >= logging . ERROR : formatted = str ( ...
Apply little arrow and colors to the record .
37,486
def get_root ( directory ) : command = [ 'git' , 'rev-parse' , '--show-toplevel' ] try : output = run_command ( directory , command , env_var = False ) except CalledProcessError as exc : raise GitError ( 'Failed to find local git repository root in {}.' . format ( repr ( directory ) ) , exc . output ) if IS_WINDOWS : o...
Get root directory of the local git repo from any subdirectory within it .
37,487
def filter_and_date ( local_root , conf_rel_paths , commits ) : dates_paths = dict ( ) for commit in commits : if commit in dates_paths : continue command = [ 'git' , 'ls-tree' , '--name-only' , '-r' , commit ] + conf_rel_paths try : output = run_command ( local_root , command ) except CalledProcessError as exc : raise...
Get commit Unix timestamps and first matching conf . py path . Exclude commits with no conf . py file .
37,488
def fetch_commits ( local_root , remotes ) : command = [ 'git' , 'fetch' , 'origin' ] run_command ( local_root , command ) for sha , name , kind in remotes : try : run_command ( local_root , [ 'git' , 'reflog' , sha ] ) except CalledProcessError : run_command ( local_root , command + [ 'refs/{0}/{1}' . format ( kind , ...
Fetch from origin .
37,489
def export ( local_root , commit , target ) : log = logging . getLogger ( __name__ ) target = os . path . realpath ( target ) mtimes = list ( ) def extract ( stdout ) : queued_links = list ( ) try : with tarfile . open ( fileobj = stdout , mode = 'r|' ) as tar : for info in tar : log . debug ( 'name: %s; mode: %d; size...
Export git commit to directory . Extracts all files at the commit to the target directory .
37,490
def clone ( local_root , new_root , remote , branch , rel_dest , exclude ) : log = logging . getLogger ( __name__ ) output = run_command ( local_root , [ 'git' , 'remote' , '-v' ] ) remotes = dict ( ) for match in RE_ALL_REMOTES . findall ( output ) : remotes . setdefault ( match [ 0 ] , [ None , None ] ) if match [ 2 ...
Clone local_root origin into a new directory and check out a specific branch . Optionally run git rm .
37,491
def commit_and_push ( local_root , remote , versions ) : log = logging . getLogger ( __name__ ) current_branch = run_command ( local_root , [ 'git' , 'rev-parse' , '--abbrev-ref' , 'HEAD' ] ) . strip ( ) run_command ( local_root , [ 'git' , 'add' , '.' ] ) try : run_command ( local_root , [ 'git' , 'diff' , 'HEAD' , '-...
Commit changed new and deleted files in the repo and attempt to push the branch to the remote repository .
37,492
def multi_sort ( remotes , sort ) : exploded_alpha = list ( ) exploded_semver = list ( ) if 'alpha' in sort : alpha_max_len = max ( len ( r [ 'name' ] ) for r in remotes ) for name in ( r [ 'name' ] for r in remotes ) : exploded_alpha . append ( [ ord ( i ) for i in name ] + [ 0 ] * ( alpha_max_len - len ( name ) ) ) i...
Sort remotes in place . Allows sorting by multiple conditions .
37,493
def read_local_conf ( local_conf ) : log = logging . getLogger ( __name__ ) log . info ( 'Reading config from %s...' , local_conf ) try : config = read_config ( os . path . dirname ( local_conf ) , '<local>' ) except HandledError : log . warning ( 'Unable to read file, continuing with only CLI args.' ) return dict ( ) ...
Search for conf . py in any rel_source directory in CWD and if found read it and return .
37,494
def gather_git_info ( root , conf_rel_paths , whitelist_branches , whitelist_tags ) : log = logging . getLogger ( __name__ ) log . info ( 'Getting list of all remote branches/tags...' ) try : remotes = list_remote ( root ) except GitError as exc : log . error ( exc . message ) log . error ( exc . output ) raise Handled...
Gather info about the remote git repository . Get list of refs .
37,495
def pre_build ( local_root , versions ) : log = logging . getLogger ( __name__ ) exported_root = TempDir ( True ) . name for sha in { r [ 'sha' ] for r in versions . remotes } : target = os . path . join ( exported_root , sha ) log . debug ( 'Exporting %s to temporary directory.' , sha ) export ( local_root , sha , tar...
Build docs for all versions to determine root directory and master_doc names .
37,496
def build_all ( exported_root , destination , versions ) : log = logging . getLogger ( __name__ ) while True : remote = versions [ Config . from_context ( ) . root_ref ] log . info ( 'Building root: %s' , remote [ 'name' ] ) source = os . path . dirname ( os . path . join ( exported_root , remote [ 'sha' ] , remote [ '...
Build all versions .
37,497
def _build ( argv , config , versions , current_name , is_root ) : application . Config = ConfigInject if config . show_banner : EventHandlers . BANNER_GREATEST_TAG = config . banner_greatest_tag EventHandlers . BANNER_MAIN_VERSION = config . banner_main_ref EventHandlers . BANNER_RECENT_TAG = config . banner_recent_ta...
Build Sphinx docs via multiprocessing for isolation .
37,498
def _read_config ( argv , config , current_name , queue ) : EventHandlers . ABORT_AFTER_READ = queue _build ( argv , config , Versions ( list ( ) ) , current_name , False )
Read the Sphinx config via multiprocessing for isolation .
37,499
def read_config ( source , current_name ) : log = logging . getLogger ( __name__ ) queue = multiprocessing . Queue ( ) config = Config . from_context ( ) with TempDir ( ) as temp_dir : argv = ( 'sphinx-build' , source , temp_dir ) log . debug ( 'Running sphinx-build for config values with args: %s' , str ( argv ) ) chi...
Read the Sphinx config for one version .