idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
11,300
def append_data ( self , data_buffer ) : if len ( data_buffer ) % ( self . sample_width * self . channels ) != 0 : raise ValueError ( "length of data_buffer must be a multiple of (sample_width * channels)" ) self . _buffer += data_buffer self . _left += len ( data_buffer )
Append data to this audio stream
11,301
def user_post_save ( sender , ** kwargs ) : if kwargs . get ( "raw" , False ) : return False user , created = kwargs [ "instance" ] , kwargs [ "created" ] disabled = getattr ( user , "_disable_account_creation" , not settings . ACCOUNT_CREATE_ON_SAVE ) if created and not disabled : Account . create ( user = user )
After User . save is called we check to see if it was a created user . If so we check if the User object wants account creation . If all passes we create an Account object .
11,302
def check_password_expired ( user ) : if not settings . ACCOUNT_PASSWORD_USE_HISTORY : return False if hasattr ( user , "password_expiry" ) : expiry = user . password_expiry . expiry else : expiry = settings . ACCOUNT_PASSWORD_EXPIRY if expiry == 0 : return False try : latest = user . password_history . latest ( "times...
Return True if password is expired and system is using password expiration False otherwise .
11,303
def login_required ( func = None , redirect_field_name = REDIRECT_FIELD_NAME , login_url = None ) : def decorator ( view_func ) : @ functools . wraps ( view_func , assigned = available_attrs ( view_func ) ) def _wrapped_view ( request , * args , ** kwargs ) : if is_authenticated ( request . user ) : return view_func ( ...
Decorator for views that checks that the user is logged in redirecting to the log in page if necessary .
11,304
def add_next ( self , url , context ) : if all ( [ key in context for key in [ "redirect_field_name" , "redirect_field_value" ] ] ) : if context [ "redirect_field_value" ] : url += "?" + urlencode ( { context [ "redirect_field_name" ] : context [ "redirect_field_value" ] , } ) return url
With both redirect_field_name and redirect_field_value available in the context add on a querystring to handle next redirecting .
11,305
def _verify ( self , request , return_payload = False , verify = True , raise_missing = False , request_args = None , request_kwargs = None , * args , ** kwargs ) : if "permakey" in request . headers : permakey = request . headers . get ( "permakey" ) payload = self . _decode ( permakey , verify = verify ) if return_pa...
If there is a permakey then we will verify the token by checking the database . Otherwise just do the normal verification .
11,306
def get ( self , item ) : if item in self : item = getattr ( self , item ) return item ( )
Helper method to avoid calling getattr
11,307
def extract_presets ( app_config ) : return { x . lower ( ) [ 10 : ] : app_config . get ( x ) for x in filter ( lambda x : x . startswith ( "SANIC_JWT" ) , app_config ) }
Pull the application s configurations for Sanic JWT
11,308
def initialize ( * args , ** kwargs ) : if len ( args ) > 1 : kwargs . update ( { "authenticate" : args [ 1 ] } ) return Initialize ( args [ 0 ] , ** kwargs )
Functional approach to initializing Sanic JWT . This was the original method but was replaced by the Initialize class . It is recommended to use the class because it is more flexible . There is no current plan to remove this method but it may be depracated in the future .
11,309
def __check_deprecated ( self ) : if "SANIC_JWT_HANDLER_PAYLOAD_SCOPES" in self . app . config : raise exceptions . InvalidConfiguration ( "SANIC_JWT_HANDLER_PAYLOAD_SCOPES has been deprecated. " "Instead, pass your handler method (not an import path) as " "initialize(add_scopes_to_payload=my_scope_extender)" ) if "SAN...
Checks for deprecated configuration keys
11,310
def __add_endpoints ( self ) : for mapping in endpoint_mappings : if all ( map ( self . config . get , mapping . keys ) ) : self . __add_single_endpoint ( mapping . cls , mapping . endpoint , mapping . is_protected ) self . bp . exception ( exceptions . SanicJWTException ) ( self . responses . exception_response ) if n...
Initialize the Sanic JWT Blueprint and add to the instance initialized
11,311
def __add_class_views ( self ) : config = self . config if "class_views" in self . kwargs : class_views = self . kwargs . pop ( "class_views" ) for route , view in class_views : if issubclass ( view , endpoints . BaseEndpoint ) and isinstance ( route , str ) : self . bp . add_route ( view . as_view ( self . responses ,...
Include any custom class views on the Sanic JWT Blueprint
11,312
async def _get_user_id ( self , user , * , asdict = False ) : uid = self . config . user_id ( ) if isinstance ( user , dict ) : user_id = user . get ( uid ) elif hasattr ( user , "to_dict" ) : _to_dict = await utils . call ( user . to_dict ) user_id = _to_dict . get ( uid ) else : raise exceptions . InvalidRetrieveUser...
Get a user_id from a user object . If asdict is True will return it as a dict with config . user_id as key . The asdict keyword defaults to False .
11,313
def _check_authentication ( self , request , request_args , request_kwargs ) : try : is_valid , status , reasons = self . _verify ( request , request_args = request_args , request_kwargs = request_kwargs , ) except Exception as e : logger . debug ( e . args ) if self . config . debug ( ) : raise e args = e . args if is...
Checks a request object to determine if that request contains a valid and authenticated JWT .
11,314
def _decode ( self , token , verify = True ) : secret = self . _get_secret ( ) algorithm = self . _get_algorithm ( ) kwargs = { } for claim in self . claims : if claim != "exp" : setting = "claim_{}" . format ( claim . lower ( ) ) if setting in self . config : value = self . config . get ( setting ) kwargs . update ( {...
Take a JWT and return a decoded payload . Optionally will verify the claims on the token .
11,315
async def _get_payload ( self , user ) : payload = await utils . call ( self . build_payload , user ) if ( not isinstance ( payload , dict ) or self . config . user_id ( ) not in payload ) : raise exceptions . InvalidPayload payload = await utils . call ( self . add_claims , payload , user ) extend_payload_args = inspe...
Given a user object create a payload and extend it as configured .
11,316
def _get_token_from_cookies ( self , request , refresh_token ) : if refresh_token : cookie_token_name_key = "cookie_refresh_token_name" else : cookie_token_name_key = "cookie_access_token_name" cookie_token_name = getattr ( self . config , cookie_token_name_key ) return request . cookies . get ( cookie_token_name ( ) ,...
Extract the token if present inside the request cookies .
11,317
def _get_token_from_headers ( self , request , refresh_token ) : header = request . headers . get ( self . config . authorization_header ( ) , None ) if header is None : return None else : header_prefix_key = "authorization_header_prefix" header_prefix = getattr ( self . config , header_prefix_key ) if header_prefix ( ...
Extract the token if present inside the headers of a request .
11,318
def _get_token_from_query_string ( self , request , refresh_token ) : if refresh_token : query_string_token_name_key = "query_string_refresh_token_name" else : query_string_token_name_key = "query_string_access_token_name" query_string_token_name = getattr ( self . config , query_string_token_name_key ) return request ...
Extract the token if present from the request args .
11,319
def _get_token ( self , request , refresh_token = False ) : if self . config . cookie_set ( ) : token = self . _get_token_from_cookies ( request , refresh_token ) if token : return token else : if self . config . cookie_strict ( ) : raise exceptions . MissingAuthorizationCookie ( ) if self . config . query_string_set (...
Extract a token from a request object .
11,320
def _verify ( self , request , return_payload = False , verify = True , raise_missing = False , request_args = None , request_kwargs = None , * args , ** kwargs ) : try : token = self . _get_token ( request ) is_valid = True reason = None except ( exceptions . MissingAuthorizationCookie , exceptions . MissingAuthorizat...
Verify that a request object is authenticated .
11,321
def extract_payload ( self , request , verify = True , * args , ** kwargs ) : payload = self . _verify ( request , return_payload = True , verify = verify , * args , ** kwargs ) return payload
Extract a payload from a request object .
11,322
def extract_scopes ( self , request ) : payload = self . extract_payload ( request ) if not payload : return None scopes_attribute = self . config . scopes_name ( ) return payload . get ( scopes_attribute , None )
Extract scopes from a request object .
11,323
def extract_user_id ( self , request ) : payload = self . extract_payload ( request ) user_id_attribute = self . config . user_id ( ) return payload . get ( user_id_attribute , None )
Extract a user id from a request object .
11,324
async def generate_access_token ( self , user ) : payload = await self . _get_payload ( user ) secret = self . _get_secret ( True ) algorithm = self . _get_algorithm ( ) return jwt . encode ( payload , secret , algorithm = algorithm ) . decode ( "utf-8" )
Generate an access token for a given user .
11,325
async def generate_refresh_token ( self , request , user ) : refresh_token = await utils . call ( self . config . generate_refresh_token ( ) ) user_id = await self . _get_user_id ( user ) await utils . call ( self . store_refresh_token , user_id = user_id , refresh_token = refresh_token , request = request , ) return r...
Generate a refresh token for a given user .
11,326
def tsplit ( df , shape ) : if isinstance ( df , ( pd . DataFrame , pd . Series ) ) : return df . iloc [ 0 : shape ] , df . iloc [ shape : ] else : return df [ 0 : shape ] , df [ shape : ]
Split array into two parts .
11,327
def concat ( x , y , axis = 0 ) : if all ( [ isinstance ( df , ( pd . DataFrame , pd . Series ) ) for df in [ x , y ] ] ) : return pd . concat ( [ x , y ] , axis = axis ) else : if axis == 0 : return np . concatenate ( [ x , y ] ) else : return np . column_stack ( [ x , y ] )
Concatenate a sequence of pandas or numpy objects into one entity .
11,328
def reshape_1d ( df ) : shape = df . shape if len ( shape ) == 1 : return df . reshape ( shape [ 0 ] , 1 ) else : return df
If parameter is 1D row vector then convert it into 2D matrix .
11,329
def idx ( df , index ) : if isinstance ( df , ( pd . DataFrame , pd . Series ) ) : return df . iloc [ index ] else : return df [ index , : ]
Universal indexing for numpy and pandas objects .
11,330
def xgb_progressbar ( rounds = 1000 ) : pbar = tqdm ( total = rounds ) def callback ( _ , ) : pbar . update ( 1 ) return callback
Progressbar for xgboost using tqdm library .
11,331
def add ( self , model ) : if isinstance ( model , ( Regressor , Classifier ) ) : self . models . append ( model ) else : raise ValueError ( 'Unrecognized estimator.' )
Adds a single model .
11,332
def stack ( self , k = 5 , stratify = False , shuffle = True , seed = 100 , full_test = True , add_diff = False ) : result_train = [ ] result_test = [ ] y = None for model in self . models : result = model . stack ( k = k , stratify = stratify , shuffle = shuffle , seed = seed , full_test = full_test ) train_df = pd . ...
Stacks sequence of models .
11,333
def blend ( self , proportion = 0.2 , stratify = False , seed = 100 , indices = None , add_diff = False ) : result_train = [ ] result_test = [ ] y = None for model in self . models : result = model . blend ( proportion = proportion , stratify = stratify , seed = seed , indices = indices ) train_df = pd . DataFrame ( re...
Blends sequence of models .
11,334
def find_weights ( self , scorer , test_size = 0.2 , method = 'SLSQP' ) : p = Optimizer ( self . models , test_size = test_size , scorer = scorer ) return p . minimize ( method )
Finds optimal weights for weighted average of models .
11,335
def weight ( self , weights ) : return self . apply ( lambda x : np . average ( x , axis = 0 , weights = weights ) )
Applies weighted mean to models .
11,336
def onehot_features ( train , test , features , full = False , sparse = False , dummy_na = True ) : features = [ f for f in features if f in train . columns ] for column in features : if full : categories = pd . concat ( [ train [ column ] , test [ column ] ] ) . dropna ( ) . unique ( ) else : categories = train [ colu...
Encode categorical features using a one - hot scheme .
11,337
def factorize ( train , test , features , na_value = - 9999 , full = False , sort = True ) : for column in features : if full : vs = pd . concat ( [ train [ column ] , test [ column ] ] ) labels , indexer = pd . factorize ( vs , sort = sort ) else : labels , indexer = pd . factorize ( train [ column ] , sort = sort ) t...
Factorize categorical features .
11,338
def woe ( df , feature_name , target_name ) : def group_woe ( group ) : event = float ( group . sum ( ) ) non_event = group . shape [ 0 ] - event rel_event = event / event_total rel_non_event = non_event / non_event_total return np . log ( rel_non_event / rel_event ) * 100 if df [ target_name ] . nunique ( ) > 2 : rais...
Calculate weight of evidence .
11,339
def kfold ( self , k = 5 , stratify = False , shuffle = True , seed = 33 ) : if stratify : kf = StratifiedKFold ( n_splits = k , random_state = seed , shuffle = shuffle ) else : kf = KFold ( n_splits = k , random_state = seed , shuffle = shuffle ) for train_index , test_index in kf . split ( self . X_train , self . y_t...
K - Folds cross validation iterator .
11,340
def hash ( self ) : if self . _hash is None : m = hashlib . new ( 'md5' ) if self . _preprocessor is None : m . update ( numpy_buffer ( self . _X_train ) ) m . update ( numpy_buffer ( self . _y_train ) ) if self . _X_test is not None : m . update ( numpy_buffer ( self . _X_test ) ) if self . _y_test is not None : m . u...
Return md5 hash for current dataset .
11,341
def merge ( self , ds , inplace = False , axis = 1 ) : if not isinstance ( ds , Dataset ) : raise ValueError ( 'Expected `Dataset`, got %s.' % ds ) X_train = concat ( ds . X_train , self . X_train , axis = axis ) y_train = concat ( ds . y_train , self . y_train , axis = axis ) if ds . X_test is not None : X_test = conc...
Merge two datasets .
11,342
def to_csc ( self ) : self . _X_train = csc_matrix ( self . _X_train ) self . _X_test = csc_matrix ( self . _X_test )
Convert Dataset to scipy s Compressed Sparse Column matrix .
11,343
def to_csr ( self ) : self . _X_train = csr_matrix ( self . _X_train ) self . _X_test = csr_matrix ( self . _X_test )
Convert Dataset to scipy s Compressed Sparse Row matrix .
11,344
def to_dense ( self ) : if hasattr ( self . _X_train , 'todense' ) : self . _X_train = self . _X_train . todense ( ) self . _X_test = self . _X_test . todense ( )
Convert sparse Dataset to dense matrix .
11,345
def _dhash ( self , params ) : m = hashlib . new ( 'md5' ) m . update ( self . hash . encode ( 'utf-8' ) ) for key in sorted ( params . keys ( ) ) : h_string = ( '%s-%s' % ( key , params [ key ] ) ) . encode ( 'utf-8' ) m . update ( h_string ) return m . hexdigest ( )
Generate hash of the dictionary object .
11,346
def validate ( self , scorer = None , k = 1 , test_size = 0.1 , stratify = False , shuffle = True , seed = 100 , indices = None ) : if self . use_cache : pdict = { 'k' : k , 'stratify' : stratify , 'shuffle' : shuffle , 'seed' : seed , 'test_size' : test_size } if indices is not None : pdict [ 'train_index' ] = np_hash...
Evaluate score by cross - validation .
11,347
def stack ( self , k = 5 , stratify = False , shuffle = True , seed = 100 , full_test = True ) : train = None test = [ ] if self . use_cache : pdict = { 'k' : k , 'stratify' : stratify , 'shuffle' : shuffle , 'seed' : seed , 'full_test' : full_test } dhash = self . _dhash ( pdict ) c = Cache ( dhash , prefix = 's' ) if...
Stack a single model . You should rarely be using this method . Use ModelsPipeline . stack instead .
11,348
def blend ( self , proportion = 0.2 , stratify = False , seed = 100 , indices = None ) : if self . use_cache : pdict = { 'proportion' : proportion , 'stratify' : stratify , 'seed' : seed , 'indices' : indices } if indices is not None : pdict [ 'train_index' ] = np_hash ( indices [ 0 ] ) pdict [ 'test_index' ] = np_hash...
Blend a single model . You should rarely be using this method . Use ModelsPipeline . blend instead .
11,349
def numpy_buffer ( ndarray ) : if isinstance ( ndarray , ( pd . Series , pd . DataFrame ) ) : ndarray = ndarray . values if ndarray . flags . c_contiguous : obj_c_contiguous = ndarray elif ndarray . flags . f_contiguous : obj_c_contiguous = ndarray . T else : obj_c_contiguous = ndarray . flatten ( ) obj_c_contiguous = ...
Creates a buffer from c_contiguous numpy ndarray .
11,350
def store ( self , key , data ) : if not os . path . exists ( self . _hash_dir ) : os . makedirs ( self . _hash_dir ) if isinstance ( data , pd . DataFrame ) : columns = data . columns . tolist ( ) np . save ( os . path . join ( self . _hash_dir , key ) , data . values ) json . dump ( columns , open ( os . path . join ...
Takes an array and stores it in the cache .
11,351
def retrieve ( self , key ) : column_file = os . path . join ( self . _hash_dir , '%s.json' % key ) cache_file = os . path . join ( self . _hash_dir , '%s.npy' % key ) if os . path . exists ( cache_file ) : data = np . load ( cache_file ) if os . path . exists ( column_file ) : with open ( column_file , 'r' ) as json_f...
Retrieves a cached array if possible .
11,352
def from_coords ( cls , x , y ) : x_bytes = int ( math . ceil ( math . log ( x , 2 ) / 8.0 ) ) y_bytes = int ( math . ceil ( math . log ( y , 2 ) / 8.0 ) ) num_bytes = max ( x_bytes , y_bytes ) byte_string = b'\x04' byte_string += int_to_bytes ( x , width = num_bytes ) byte_string += int_to_bytes ( y , width = num_byte...
Creates an ECPoint object from the X and Y integer coordinates of the point
11,353
def to_coords ( self ) : data = self . native first_byte = data [ 0 : 1 ] if first_byte == b'\x04' : remaining = data [ 1 : ] field_len = len ( remaining ) // 2 x = int_from_bytes ( remaining [ 0 : field_len ] ) y = int_from_bytes ( remaining [ field_len : ] ) return ( x , y ) if first_byte not in set ( [ b'\x02' , b'\...
Returns the X and Y coordinates for this EC point as native Python integers
11,354
def unwrap ( self ) : if self . algorithm == 'rsa' : return self [ 'private_key' ] . parsed if self . algorithm == 'dsa' : params = self [ 'private_key_algorithm' ] [ 'parameters' ] return DSAPrivateKey ( { 'version' : 0 , 'p' : params [ 'p' ] , 'q' : params [ 'q' ] , 'g' : params [ 'g' ] , 'public_key' : self . public...
Unwraps the private key into an RSAPrivateKey DSAPrivateKey or ECPrivateKey object
11,355
def fingerprint ( self ) : if self . _fingerprint is None : params = self [ 'private_key_algorithm' ] [ 'parameters' ] key = self [ 'private_key' ] . parsed if self . algorithm == 'rsa' : to_hash = '%d:%d' % ( key [ 'modulus' ] . native , key [ 'public_exponent' ] . native , ) elif self . algorithm == 'dsa' : public_ke...
Creates a fingerprint that can be compared with a public key to see if the two form a pair .
11,356
def run ( ci = False ) : xml_report_path = os . path . join ( package_root , 'coverage.xml' ) if os . path . exists ( xml_report_path ) : os . unlink ( xml_report_path ) cov = coverage . Coverage ( include = '%s/*.py' % package_name ) cov . start ( ) from . tests import run as run_tests result = run_tests ( ) print ( )...
Runs the tests while measuring coverage
11,357
def _git_command ( params , cwd ) : proc = subprocess . Popen ( [ 'git' ] + params , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , cwd = cwd ) stdout , stderr = proc . communicate ( ) code = proc . wait ( ) if code != 0 : e = OSError ( 'git exit code was non-zero' ) e . stdout = stdout raise e return stdo...
Executes a git command returning the output
11,358
def _parse_env_var_file ( data ) : output = { } for line in data . splitlines ( ) : line = line . strip ( ) if not line or '=' not in line : continue parts = line . split ( '=' ) if len ( parts ) != 2 : continue name = parts [ 0 ] value = parts [ 1 ] if len ( value ) > 1 : if value [ 0 ] == '"' and value [ - 1 ] == '"'...
Parses a basic VAR = value data file contents into a dict
11,359
def _platform_name ( ) : if sys . platform == 'darwin' : version = _plat . mac_ver ( ) [ 0 ] _plat_ver_info = tuple ( map ( int , version . split ( '.' ) ) ) if _plat_ver_info < ( 10 , 12 ) : name = 'OS X' else : name = 'macOS' return '%s %s' % ( name , version ) elif sys . platform == 'win32' : _win_ver = sys . getwin...
Returns information about the current operating system and version
11,360
def _list_files ( root ) : dir_patterns , file_patterns = _gitignore ( root ) paths = [ ] prefix = os . path . abspath ( root ) + os . sep for base , dirs , files in os . walk ( root ) : for d in dirs : for dir_pattern in dir_patterns : if fnmatch ( d , dir_pattern ) : dirs . remove ( d ) break for f in files : skip = ...
Lists all of the files in a directory taking into account any . gitignore file that is present
11,361
def _execute ( params , cwd ) : proc = subprocess . Popen ( params , stdout = subprocess . PIPE , stderr = subprocess . PIPE , cwd = cwd ) stdout , stderr = proc . communicate ( ) code = proc . wait ( ) if code != 0 : e = OSError ( 'subprocess exit code for %r was %d: %s' % ( params , code , stderr ) ) e . stdout = std...
Executes a subprocess
11,362
def run ( ) : deps_dir = os . path . join ( build_root , 'modularcrypto-deps' ) if os . path . exists ( deps_dir ) : shutil . rmtree ( deps_dir , ignore_errors = True ) os . mkdir ( deps_dir ) try : print ( "Staging ci dependencies" ) _stage_requirements ( deps_dir , os . path . join ( package_root , 'requires' , 'ci' ...
Installs required development dependencies . Uses git to checkout other modularcrypto repos for more accurate coverage data .
11,363
def _download ( url , dest ) : print ( 'Downloading %s' % url ) filename = os . path . basename ( url ) dest_path = os . path . join ( dest , filename ) if sys . platform == 'win32' : powershell_exe = os . path . join ( 'system32\\WindowsPowerShell\\v1.0\\powershell.exe' ) code = "[System.Net.ServicePointManager]::Secu...
Downloads a URL to a directory
11,364
def _archive_single_dir ( archive ) : common_root = None for info in _list_archive_members ( archive ) : fn = _info_name ( info ) if fn in set ( [ '.' , '/' ] ) : continue sep = None if '/' in fn : sep = '/' elif '\\' in fn : sep = '\\' if sep is None : root_dir = fn else : root_dir , _ = fn . split ( sep , 1 ) if comm...
Check if all members of the archive are in a single top - level directory
11,365
def _info_name ( info ) : if isinstance ( info , zipfile . ZipInfo ) : return info . filename . replace ( '\\' , '/' ) return info . name . replace ( '\\' , '/' )
Returns a normalized file path for an archive info object
11,366
def _extract_info ( archive , info ) : if isinstance ( archive , zipfile . ZipFile ) : fn = info . filename is_dir = fn . endswith ( '/' ) or fn . endswith ( '\\' ) out = archive . read ( info ) if is_dir and out == b'' : return None return out info_file = archive . extractfile ( info ) if info_file : return info_file ...
Extracts the contents of an archive info object
11,367
def _extract_package ( deps_dir , pkg_path ) : if pkg_path . endswith ( '.exe' ) : try : zf = None zf = zipfile . ZipFile ( pkg_path , 'r' ) for zi in zf . infolist ( ) : if not zi . filename . startswith ( 'PLATLIB' ) : continue data = _extract_info ( zf , zi ) if data is not None : dst_path = os . path . join ( deps_...
Extract a . whl . zip . tar . gz or . tar . bz2 into a package path to use when running CI tasks
11,368
def _parse_requires ( path ) : python_version = '.' . join ( map ( str_cls , sys . version_info [ 0 : 2 ] ) ) sys_platform = sys . platform packages = [ ] with open ( path , 'rb' ) as f : contents = f . read ( ) . decode ( 'utf-8' ) for line in re . split ( r'\r?\n' , contents ) : line = line . strip ( ) if not len ( l...
Does basic parsing of pip requirements files to allow for using something other than Python to do actual TLS requests
11,369
def unarmor ( pem_bytes , multiple = False ) : generator = _unarmor ( pem_bytes ) if not multiple : return next ( generator ) return generator
Convert a PEM - encoded byte string into a DER - encoded byte string
11,370
def preferred_ordinal ( cls , attr_name ) : attr_name = cls . map ( attr_name ) if attr_name in cls . preferred_order : ordinal = cls . preferred_order . index ( attr_name ) else : ordinal = len ( cls . preferred_order ) return ( ordinal , attr_name )
Returns an ordering value for a particular attribute key .
11,371
def prepped_value ( self ) : if self . _prepped is None : self . _prepped = self . _ldap_string_prep ( self [ 'value' ] . native ) return self . _prepped
Returns the value after being processed by the internationalized string preparation as specified by RFC 5280
11,372
def _get_values ( self , rdn ) : output = { } [ output . update ( [ ( ntv [ 'type' ] . native , ntv . prepped_value ) ] ) for ntv in rdn ] return output
Returns a dict of prepped values contained in an RDN
11,373
def build ( cls , name_dict , use_printable = False ) : rdns = [ ] if not use_printable : encoding_name = 'utf8_string' encoding_class = UTF8String else : encoding_name = 'printable_string' encoding_class = PrintableString name_dict = OrderedDict ( sorted ( name_dict . items ( ) , key = lambda item : NameType . preferr...
Creates a Name object from a dict of unicode string keys and values . The keys should be from NameType . _map or a dotted - integer OID unicode string .
11,374
def _recursive_humanize ( self , value ) : if isinstance ( value , list ) : return ', ' . join ( reversed ( [ self . _recursive_humanize ( sub_value ) for sub_value in value ] ) ) return value . native
Recursively serializes data compiled from the RDNSequence
11,375
def crl_distribution_points ( self ) : if self . _crl_distribution_points is None : self . _crl_distribution_points = self . _get_http_crl_distribution_points ( self . crl_distribution_points_value ) return self . _crl_distribution_points
Returns complete CRL URLs - does not include delta CRLs
11,376
def delta_crl_distribution_points ( self ) : if self . _delta_crl_distribution_points is None : self . _delta_crl_distribution_points = self . _get_http_crl_distribution_points ( self . freshest_crl_value ) return self . _delta_crl_distribution_points
Returns delta CRL URLs - does not include complete CRLs
11,377
def _get_http_crl_distribution_points ( self , crl_distribution_points ) : output = [ ] if crl_distribution_points is None : return [ ] for distribution_point in crl_distribution_points : distribution_point_name = distribution_point [ 'distribution_point' ] if distribution_point_name is VOID : continue if distribution_...
Fetches the DistributionPoint object for non - relative HTTP CRLs referenced by the certificate
11,378
def _is_wildcard_match ( self , domain_labels , valid_domain_labels ) : first_domain_label = domain_labels [ 0 ] other_domain_labels = domain_labels [ 1 : ] wildcard_label = valid_domain_labels [ 0 ] other_valid_domain_labels = valid_domain_labels [ 1 : ] if other_domain_labels != other_valid_domain_labels : return Fal...
Determines if the labels in a domain are a match for labels from a wildcard valid domain name
11,379
def run ( ) : print ( 'Running flake8 %s' % flake8 . __version__ ) flake8_style = get_style_guide ( config_file = os . path . join ( package_root , 'tox.ini' ) ) paths = [ ] for _dir in [ package_name , 'dev' , 'tests' ] : for root , _ , filenames in os . walk ( _dir ) : for filename in filenames : if not filename . en...
Runs flake8 lint
11,380
def run ( ) : print ( 'Python ' + sys . version . replace ( '\n' , '' ) ) try : oscrypto_tests_module_info = imp . find_module ( 'tests' , [ os . path . join ( build_root , 'oscrypto' ) ] ) oscrypto_tests = imp . load_module ( 'oscrypto.tests' , * oscrypto_tests_module_info ) oscrypto = oscrypto_tests . local_oscrypto ...
Runs the linter and tests
11,381
def replace ( self , year = None , month = None , day = None ) : if year is None : year = self . year if month is None : month = self . month if day is None : day = self . day if year > 0 : cls = date else : cls = extended_date return cls ( year , month , day )
Returns a new datetime . date or asn1crypto . util . extended_date object with the specified components replaced
11,382
def replace ( self , year = None , month = None , day = None , hour = None , minute = None , second = None , microsecond = None , tzinfo = None ) : if year is None : year = self . year if month is None : month = self . month if day is None : day = self . day if hour is None : hour = self . hour if minute is None : minu...
Returns a new datetime . datetime or asn1crypto . util . extended_datetime object with the specified components replaced
11,383
def delta_crl_distribution_points ( self ) : if self . _delta_crl_distribution_points is None : self . _delta_crl_distribution_points = [ ] if self . freshest_crl_value is not None : for distribution_point in self . freshest_crl_value : distribution_point_name = distribution_point [ 'distribution_point' ] if distributi...
Returns delta CRL URLs - only applies to complete CRLs
11,384
def _set_extensions ( self ) : self . _critical_extensions = set ( ) for extension in self [ 'single_extensions' ] : name = extension [ 'extn_id' ] . native attribute_name = '_%s_value' % name if hasattr ( self , attribute_name ) : setattr ( self , attribute_name , extension [ 'extn_value' ] . parsed ) if extension [ '...
Sets common named extensions to private attributes and creates a list of critical extensions
11,385
def _basic_debug ( prefix , self ) : print ( '%s%s Object #%s' % ( prefix , type_name ( self ) , id ( self ) ) ) if self . _header : print ( '%s Header: 0x%s' % ( prefix , binascii . hexlify ( self . _header or b'' ) . decode ( 'utf-8' ) ) ) has_header = self . method is not None and self . class_ is not None and self...
Prints out basic information about an Asn1Value object . Extracted for reuse among different classes that customize the debug information .
11,386
def _tag_type_to_explicit_implicit ( params ) : if 'tag_type' in params : if params [ 'tag_type' ] == 'explicit' : params [ 'explicit' ] = ( params . get ( 'class' , 2 ) , params [ 'tag' ] ) elif params [ 'tag_type' ] == 'implicit' : params [ 'implicit' ] = ( params . get ( 'class' , 2 ) , params [ 'tag' ] ) del params...
Converts old - style tag_type and tag params to explicit and implicit
11,387
def _build_id_tuple ( params , spec ) : if spec is None : return ( None , None ) required_class = spec . class_ required_tag = spec . tag _tag_type_to_explicit_implicit ( params ) if 'explicit' in params : if isinstance ( params [ 'explicit' ] , tuple ) : required_class , required_tag = params [ 'explicit' ] else : req...
Builds a 2 - element tuple used to identify fields by grabbing the class_ and tag from an Asn1Value class and the params dict being passed to it
11,388
def _parse_build ( encoded_data , pointer = 0 , spec = None , spec_params = None , strict = False ) : encoded_len = len ( encoded_data ) info , new_pointer = _parse ( encoded_data , encoded_len , pointer ) if strict and new_pointer != pointer + encoded_len : extra_bytes = pointer + encoded_len - new_pointer raise Value...
Parses a byte string generically or using a spec with optional params
11,389
def _new_instance ( self ) : new_obj = self . __class__ ( ) new_obj . class_ = self . class_ new_obj . tag = self . tag new_obj . implicit = self . implicit new_obj . explicit = self . explicit return new_obj
Constructs a new copy of the current object preserving any tagging
11,390
def retag ( self , tagging , tag = None ) : if not isinstance ( tagging , dict ) : tagging = { tagging : tag } new_obj = self . __class__ ( explicit = tagging . get ( 'explicit' ) , implicit = tagging . get ( 'implicit' ) ) new_obj . _copy ( self , copy . deepcopy ) return new_obj
Copies the object applying a new tagging to it
11,391
def untag ( self ) : new_obj = self . __class__ ( ) new_obj . _copy ( self , copy . deepcopy ) return new_obj
Copies the object removing any special tagging from it
11,392
def _as_chunk ( self ) : if self . _chunks_offset == 0 : return self . contents return self . contents [ self . _chunks_offset : ]
A method to return a chunk of data that can be combined for constructed method values
11,393
def _copy ( self , other , copy_func ) : super ( Constructable , self ) . _copy ( other , copy_func ) self . method = other . method self . _indefinite = other . _indefinite
Copies the contents of another Constructable object to itself
11,394
def _copy ( self , other , copy_func ) : super ( Any , self ) . _copy ( other , copy_func ) self . _parsed = copy_func ( other . _parsed )
Copies the contents of another Any object to itself
11,395
def _setup ( self ) : cls = self . __class__ cls . _id_map = { } cls . _name_map = { } for index , info in enumerate ( cls . _alternatives ) : if len ( info ) < 3 : info = info + ( { } , ) cls . _alternatives [ index ] = info id_ = _build_id_tuple ( info [ 2 ] , info [ 1 ] ) cls . _id_map [ id_ ] = index cls . _name_ma...
Generates _id_map from _alternatives to allow validating contents
11,396
def parse ( self ) : if self . _parsed is not None : return self . _parsed try : _ , spec , params = self . _alternatives [ self . _choice ] self . _parsed , _ = _parse_build ( self . _contents , spec = spec , spec_params = params ) except ( ValueError , TypeError ) as e : args = e . args [ 1 : ] e . args = ( e . args ...
Parses the detected alternative
11,397
def _copy ( self , other , copy_func ) : super ( Choice , self ) . _copy ( other , copy_func ) self . _choice = other . _choice self . _name = other . _name self . _parsed = copy_func ( other . _parsed )
Copies the contents of another Choice object to itself
11,398
def _copy ( self , other , copy_func ) : super ( AbstractString , self ) . _copy ( other , copy_func ) self . _unicode = other . _unicode
Copies the contents of another AbstractString object to itself
11,399
def _copy ( self , other , copy_func ) : super ( OctetBitString , self ) . _copy ( other , copy_func ) self . _bytes = other . _bytes
Copies the contents of another OctetBitString object to itself