idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
7,500
def encode ( self , encoding = None ) : try : fc = self . func . value except AttributeError : # application-specific function code fc = self . func mhash = bytes ( [ fc , len ( self . digest ) ] ) + self . digest if encoding : mhash = CodecReg . get_encoder ( encoding ) ( mhash ) return mhash
r Encode into a multihash - encoded digest .
81
12
7,501
def verify ( self , data ) : digest = _do_digest ( data , self . func ) return digest [ : len ( self . digest ) ] == self . digest
r Does the given data hash to the digest in this Multihash ?
37
15
7,502
def truncate ( self , length ) : if length > len ( self . digest ) : raise ValueError ( "cannot enlarge the original digest by %d bytes" % ( length - len ( self . digest ) ) ) return self . __class__ ( self . func , self . digest [ : length ] )
Return a new Multihash with a shorter digest length .
66
12
7,503
def set ( self , key : URIRef , value : Union [ Literal , BNode , URIRef , str , int ] , lang : Optional [ str ] = None ) : if not isinstance ( value , Literal ) and lang is not None : value = Literal ( value , lang = lang ) elif not isinstance ( value , ( BNode , URIRef ) ) : value , _type = term . _castPythonToLitera...
Set the VALUE for KEY predicate in the Metadata Graph
150
12
7,504
def add ( self , key , value , lang = None ) : if not isinstance ( value , Literal ) and lang is not None : value = Literal ( value , lang = lang ) elif not isinstance ( value , ( BNode , URIRef ) ) : value , _type = term . _castPythonToLiteral ( value ) if _type is None : value = Literal ( value ) else : value = Liter...
Add a triple to the graph related to this node
124
10
7,505
def get ( self , key , lang = None ) : if lang is not None : for o in self . graph . objects ( self . asNode ( ) , key ) : if o . language == lang : yield o else : for o in self . graph . objects ( self . asNode ( ) , key ) : yield o
Returns triple related to this node . Can filter on lang
69
11
7,506
def get_single ( self , key , lang = None ) : if not isinstance ( key , URIRef ) : key = URIRef ( key ) if lang is not None : default = None for o in self . graph . objects ( self . asNode ( ) , key ) : default = o if o . language == lang : return o return default else : for o in self . graph . objects ( self . asNode ...
Returns a single triple related to this node .
99
9
7,507
def remove ( self , predicate = None , obj = None ) : self . graph . remove ( ( self . asNode ( ) , predicate , obj ) )
Remove triple matching the predicate or the object
33
8
7,508
def unlink ( self , subj = None , predicate = None ) : self . graph . remove ( ( subj , predicate , self . asNode ( ) ) )
Remove triple where Metadata is the object
36
8
7,509
def getOr ( subject , predicate , * args , * * kwargs ) : if ( subject , predicate , None ) in get_graph ( ) : return Metadata ( node = get_graph ( ) . objects ( subject , predicate ) . __next__ ( ) ) return Metadata ( * args , * * kwargs )
Retrieve a metadata node or generate a new one
71
10
7,510
def forwards_func ( apps , schema_editor ) : print ( "\n" ) create_count = 0 BackupRun = apps . get_model ( "backup_app" , "BackupRun" ) # historical version of BackupRun backup_runs = BackupRun . objects . all ( ) for backup_run in backup_runs : # Use the origin BackupRun model to get access to write_config() temp = O...
manage migrate backup_app 0004_BackupRun_ini_file_20160203_1415
184
22
7,511
def reverse_func ( apps , schema_editor ) : print ( "\n" ) remove_count = 0 BackupRun = apps . get_model ( "backup_app" , "BackupRun" ) backup_runs = BackupRun . objects . all ( ) for backup_run in backup_runs : # Use the origin BackupRun model to get access to get_config_path() temp = OriginBackupRun ( name = backup_r...
manage migrate backup_app 0003_auto_20160127_2002
194
16
7,512
def speziale_grun ( v , v0 , gamma0 , q0 , q1 ) : if isuncertainties ( [ v , v0 , gamma0 , q0 , q1 ] ) : gamma = gamma0 * unp . exp ( q0 / q1 * ( ( v / v0 ) ** q1 - 1. ) ) else : gamma = gamma0 * np . exp ( q0 / q1 * ( ( v / v0 ) ** q1 - 1. ) ) return gamma
calculate Gruneisen parameter for the Speziale equation
111
14
7,513
def speziale_debyetemp ( v , v0 , gamma0 , q0 , q1 , theta0 ) : if isuncertainties ( [ v , v0 , gamma0 , q0 , q1 , theta0 ] ) : f_vu = np . vectorize ( uct . wrap ( integrate_gamma ) , excluded = [ 1 , 2 , 3 , 4 , 5 , 6 ] ) integ = f_vu ( v , v0 , gamma0 , q0 , q1 , theta0 ) theta = unp . exp ( unp . log ( theta0 ) - i...
calculate Debye temperature for the Speziale equation
212
13
7,514
def integrate_gamma ( v , v0 , gamma0 , q0 , q1 , theta0 ) : def f_integrand ( v ) : gamma = gamma0 * np . exp ( q0 / q1 * ( ( v / v0 ) ** q1 - 1. ) ) return gamma / v theta_term = quad ( f_integrand , v0 , v ) [ 0 ] return theta_term
internal function to calculate Debye temperature
93
7
7,515
def speziale_pth ( v , temp , v0 , gamma0 , q0 , q1 , theta0 , n , z , t_ref = 300. , three_r = 3. * constants . R ) : v_mol = vol_uc2mol ( v , z ) gamma = speziale_grun ( v , v0 , gamma0 , q0 , q1 ) theta = speziale_debyetemp ( v , v0 , gamma0 , q0 , q1 , theta0 ) xx = theta / temp debye = debye_E ( xx ) if t_ref == 0...
calculate thermal pressure for the Speziale equation
233
12
7,516
def text ( self ) -> str : return self . export ( output = Mimetypes . PLAINTEXT , exclude = self . default_exclude )
String representation of the text
32
5
7,517
def set_creator ( self , value : Union [ Literal , Identifier , str ] , lang : str = None ) : self . metadata . add ( key = DC . creator , value = value , lang = lang )
Set the DC Creator literal value
47
6
7,518
def set_title ( self , value : Union [ Literal , Identifier , str ] , lang : str = None ) : return self . metadata . add ( key = DC . title , value = value , lang = lang )
Set the DC Title literal value
48
6
7,519
def get_description ( self , lang : str = None ) -> Literal : return self . metadata . get_single ( key = DC . description , lang = lang )
Get the description of the object
36
6
7,520
def set_description ( self , value : Union [ Literal , Identifier , str ] , lang : str = None ) : return self . metadata . add ( key = DC . description , value = value , lang = lang )
Set the DC Description literal value
48
6
7,521
def set_subject ( self , value : Union [ Literal , Identifier , str ] , lang : str = None ) : return self . metadata . add ( key = DC . subject , value = value , lang = lang )
Set the DC Subject literal value
48
6
7,522
def childIds ( self ) -> BaseReferenceSet : if self . _childIds is None : self . _childIds = self . getReffs ( ) return self . _childIds
Identifiers of children
44
4
7,523
def firstId ( self ) -> BaseReference : if self . childIds is not None : if len ( self . childIds ) > 0 : return self . childIds [ 0 ] return None else : raise NotImplementedError
First child s id of current TextualNode
51
9
7,524
def lastId ( self ) -> BaseReference : if self . childIds is not None : if len ( self . childIds ) > 0 : return self . childIds [ - 1 ] return None else : raise NotImplementedError
Last child s id of current TextualNode
52
9
7,525
def compile_vocab ( docs , limit = 1e6 , verbose = 0 , tokenizer = Tokenizer ( stem = None , lower = None , strip = None ) ) : tokenizer = make_tokenizer ( tokenizer ) d = Dictionary ( ) try : limit = min ( limit , docs . count ( ) ) docs = docs . iterator ( ) except ( AttributeError , TypeError ) : pass for i , doc in...
Get the set of words used anywhere in a sequence of documents and assign an integer id
272
17
7,526
def gen_file_lines ( path , mode = 'rUb' , strip_eol = True , ascii = True , eol = '\n' ) : if isinstance ( path , str ) : path = open ( path , mode ) with path : # TODO: read one char at a time looking for the eol char and yielding the interveening chars for line in path : if ascii : line = str ( line ) if strip_eol :...
Generate a sequence of documents from the lines in a file
117
12
7,527
def inventory ( self , inventory_name ) : def decorator ( f ) : self . add ( func = f , inventory_name = inventory_name ) return f return decorator
Decorator to register filters for given inventory . For a function abc it has the same effect
38
20
7,528
def dispatch ( self , collection , * * kwargs ) : for inventory , method in self . methods [ : : - 1 ] : if method ( collection , * * kwargs ) is True : collection . parent = self . collection . children [ inventory ] return raise UndispatchedTextError ( "CapitainsCtsText not dispatched %s" % collection . id )
Dispatch a collection using internal filters
81
6
7,529
def generate_tokens ( doc , regex = CRE_TOKEN , strip = True , nonwords = False ) : if isinstance ( regex , basestring ) : regex = re . compile ( regex ) for w in regex . finditer ( doc ) : if w : w = w . group ( ) if strip : w = w . strip ( r'-_*`()}{' + r"'" ) if w and ( nonwords or not re . match ( r'^' + RE_NONWORD...
r Return a sequence of words or tokens using a re . match iteratively through the str
122
18
7,530
def financial_float ( s , scale_factor = 1 , typ = float , ignore = FINANCIAL_WHITESPACE , percent_str = PERCENT_SYMBOLS , replace = FINANCIAL_MAPPING , normalize_case = str . lower ) : percent_scale_factor = 1 if isinstance ( s , basestring ) : s = normalize_case ( s ) . strip ( ) for i in ignore : s = s . replace ( n...
Strip dollar signs and commas from financial numerical string
221
11
7,531
def is_invalid_date ( d ) : if not isinstance ( d , DATE_TYPES ) : return False if d . year < 1970 or d . year >= 2100 : return True
Return boolean to indicate whether date is invalid None if valid False if not a date
43
16
7,532
def vocab_freq ( docs , limit = 1e6 , verbose = 1 , tokenizer = generate_tokens ) : total = Counter ( ) try : limit = min ( limit , docs . count ( ) ) docs = docs . iterator ( ) except : pass for i , doc in enumerate ( docs ) : try : doc = doc . values ( ) except AttributeError : if not isinstance ( doc , basestring ) ...
Get the set of words used anywhere in a sequence of documents and count occurrences
228
15
7,533
def make_filename ( s , allow_whitespace = False , allow_underscore = False , allow_hyphen = False , limit = 255 , lower = False ) : s = stringify ( s ) s = CRE_BAD_FILENAME . sub ( '' , s ) if not allow_whitespace : s = CRE_WHITESPACE . sub ( '' , s ) if lower : s = str . lower ( s ) if not allow_hyphen : s = s . repl...
r Make sure the provided string is a valid filename and optionally remove whitespace
157
15
7,534
def stem ( self , s ) : if self . _stemmer is None : return passthrough ( s ) try : # try the local attribute `stemmer`, a StemmerI instance first # if you use the self.stem method from an unpickled object it may not work return getattr ( getattr ( self , '_stemmer' , None ) , 'stem' , None ) ( s ) except ( AttributeEr...
This should make the Stemmer picklable and unpicklable by not using bound methods
130
20
7,535
def assoc ( self , index , value ) : newvec = ImmutableVector ( ) newvec . tree = self . tree . assoc ( index , value ) if index >= self . _length : newvec . _length = index + 1 else : newvec . _length = self . _length return newvec
Return a new vector with value associated at index . The implicit parameter is not modified .
67
17
7,536
def concat ( self , tailvec ) : newvec = ImmutableVector ( ) vallist = [ ( i + self . _length , tailvec [ i ] ) for i in range ( 0 , tailvec . _length ) ] newvec . tree = self . tree . multi_assoc ( vallist ) newvec . _length = self . _length + tailvec . _length return newvec
Returns the result of concatenating tailvec to the implicit parameter
88
13
7,537
def pop ( self ) : if self . _length == 0 : raise IndexError ( ) newvec = ImmutableVector ( ) newvec . tree = self . tree . remove ( self . _length - 1 ) newvec . _length = self . _length - 1 return newvec
Return a new ImmutableVector with the last item removed .
60
12
7,538
def read ( self , identifier , path ) : with open ( path ) as f : o = self . classes [ "text" ] ( urn = identifier , resource = self . xmlparse ( f ) ) return o
Retrieve and parse a text given an identifier
46
9
7,539
def _parse_textgroup ( self , cts_file ) : with io . open ( cts_file ) as __xml__ : return self . classes [ "textgroup" ] . parse ( resource = __xml__ ) , cts_file
Parses a textgroup from a cts file
54
11
7,540
def _parse_work ( self , cts_file , textgroup ) : with io . open ( cts_file ) as __xml__ : work , texts = self . classes [ "work" ] . parse ( resource = __xml__ , parent = textgroup , _with_children = True ) return work , texts , os . path . dirname ( cts_file )
Parses a work from a cts file
82
10
7,541
def _parse_text ( self , text , directory ) : text_id , text_metadata = text . id , text text_metadata . path = "{directory}/{textgroup}.{work}.{version}.xml" . format ( directory = directory , textgroup = text_metadata . urn . textgroup , work = text_metadata . urn . work , version = text_metadata . urn . version ) if...
Complete the TextMetadata object with its citation scheme by parsing the original text
398
15
7,542
def _dispatch ( self , textgroup , directory ) : if textgroup . id in self . dispatcher . collection : self . dispatcher . collection [ textgroup . id ] . update ( textgroup ) else : self . dispatcher . dispatch ( textgroup , path = directory ) for work_urn , work in textgroup . works . items ( ) : if work_urn in self ...
Run the dispatcher over a textgroup .
107
8
7,543
def parse ( self , resource ) : textgroups = [ ] texts = [ ] invalids = [ ] for folder in resource : cts_files = glob ( "{base_folder}/data/*/__cts__.xml" . format ( base_folder = folder ) ) for cts_file in cts_files : textgroup , cts_file = self . _parse_textgroup ( cts_file ) textgroups . append ( ( textgroup , cts_f...
Parse a list of directories and reads it into a collection
333
12
7,544
def velocities_to_moduli ( rho , v_phi , v_s ) : return v_phi * v_phi * rho , v_s * v_s * rho
convert velocities to moduli mainly to support Burnman operations
44
14
7,545
def moduli_to_velocities ( rho , K_s , G ) : return np . sqrt ( K_s / rho ) , np . sqrt ( G / rho )
convert moduli to velocities mainly to support Burnman operations
44
14
7,546
def jamieson_pst ( v , v0 , c0 , s , gamma0 , q , theta0 , n , z , mass , c_v , three_r = 3. * constants . R , t_ref = 300. ) : rho = mass / vol_uc2mol ( v , z ) * 1.e-6 rho0 = mass / vol_uc2mol ( v0 , z ) * 1.e-6 p_h = hugoniot_p ( rho , rho0 , c0 , s ) p_th_h = jamieson_pth ( v , v0 , c0 , s , gamma0 , q , theta0 , n...
calculate static pressure at 300 K from Hugoniot data using the constq formulation
197
18
7,547
def jamieson_pth ( v , v0 , c0 , s , gamma0 , q , theta0 , n , z , mass , c_v , three_r = 3. * constants . R , t_ref = 300. ) : rho = mass / vol_uc2mol ( v , z ) * 1.e-6 rho0 = mass / vol_uc2mol ( v0 , z ) * 1.e-6 temp = hugoniot_t ( rho , rho0 , c0 , s , gamma0 , q , theta0 , n , mass , three_r = three_r , t_ref = t_r...
calculate thermal pressure from Hugoniot data using the constq formulation
205
15
7,548
def hugoniot_p_nlin ( rho , rho0 , a , b , c ) : eta = 1. - ( rho0 / rho ) Up = np . zeros_like ( eta ) if isuncertainties ( [ rho , rho0 , a , b , c ] ) : Up [ eta != 0. ] = ( ( b * eta - 1. ) + unp . sqrt ( np . power ( ( 1. - b * eta ) , 2. ) - 4. * np . power ( eta , 2. ) * a * c ) ) / ( - 2. * eta * c ) else : Up ...
calculate pressure along a Hugoniot throug nonlinear equations presented in Jameison 1982
244
21
7,549
def generate_address_label ( self ) : if self . organisation_name : self . address_label . append ( self . organisation_name ) if self . department_name : self . address_label . append ( self . department_name ) if self . po_box_number : self . address_label . append ( 'PO Box ' + self . po_box_number ) elements = [ se...
Construct a list for address label .
243
7
7,550
def _is_exception_rule ( self , element ) : if element [ 0 ] . isdigit ( ) and element [ - 1 ] . isdigit ( ) : return True if len ( element ) > 1 and element [ 0 ] . isdigit ( ) and element [ - 2 ] . isdigit ( ) and element [ - 1 ] . isalpha ( ) : return True if len ( element ) == 1 and element . isalpha ( ) : return T...
Check for exception rule .
99
5
7,551
def _append_to_label ( self , element ) : if len ( self . address_label ) > 0 and self . _is_exception_rule ( self . address_label [ - 1 ] ) : self . address_label [ - 1 ] += ( ' ' + element ) else : self . address_label . append ( element )
Append address element to the label .
74
8
7,552
def load_template_source ( template_name , template_dirs = None ) : template_zipfiles = getattr ( settings , "TEMPLATE_ZIP_FILES" , [ ] ) # Try each ZIP file in TEMPLATE_ZIP_FILES. for fname in template_zipfiles : try : z = zipfile . ZipFile ( fname ) source = z . read ( template_name ) except ( IOError , KeyError ) : ...
Template loader that loads templates from a ZIP file .
170
10
7,553
def sanitize_capabilities ( caps ) : platform = caps [ "platform" ] upper_platform = platform . upper ( ) if upper_platform . startswith ( "WINDOWS 8" ) : caps [ "platform" ] = "WIN8" elif upper_platform . startswith ( "OS X " ) : caps [ "platform" ] = "MAC" elif upper_platform == "WINDOWS 10" : del caps [ "platform" ]...
Sanitize the capabilities we pass to Selenic so that they can be consumed by Browserstack .
224
20
7,554
def my_func ( version ) : # noqa: D202 class MyClass ( object ) : """Enclosed class.""" if version == 2 : import docs . support . python2_module as pm else : import docs . support . python3_module as pm def __init__ ( self , value ) : self . _value = value def _get_value ( self ) : return self . _value value = property...
Enclosing function .
109
5
7,555
def get_subscriptions ( self , publication_id = None , owner_id = None , since_when = None , limit_to = 200 , max_calls = None , start_record = 0 , verbose = False ) : query = "SELECT Objects() FROM Subscription" # collect all where parameters into a list of # (key, operator, value) tuples where_params = [ ] if owner_i...
Fetches all subscriptions from Membersuite of a particular publication_id if set .
305
18
7,556
def get_prep_value ( self , value ) : if isinstance ( value , JSON . JsonDict ) : return json . dumps ( value , cls = JSON . Encoder ) if isinstance ( value , JSON . JsonList ) : return value . json_string if isinstance ( value , JSON . JsonString ) : return json . dumps ( value ) return value
The psycopg adaptor returns Python objects but we also have to handle conversion ourselves
82
17
7,557
def registry ( attr , base = type ) : class Registry ( base ) : def __init__ ( cls , name , bases , attrs ) : super ( Registry , cls ) . __init__ ( name , bases , attrs ) if not hasattr ( cls , '__registry__' ) : cls . __registry__ = { } key = getattr ( cls , attr ) if key is not NotImplemented : assert key not in cls ...
Generates a meta class to index sub classes by their keys .
173
13
7,558
def debug_generate ( self , debug_generator , * gen_args , * * gen_kwargs ) : if self . isEnabledFor ( logging . DEBUG ) : message = debug_generator ( * gen_args , * * gen_kwargs ) # Allow for content filtering to skip logging if message is not None : return self . debug ( message )
Used for efficient debug logging where the actual message isn t evaluated unless it will actually be accepted by the logger .
77
22
7,559
def verify_token ( token , public_key_or_address , signing_algorithm = "ES256K" ) : decoded_token = decode_token ( token ) decoded_token_payload = decoded_token [ "payload" ] if "subject" not in decoded_token_payload : raise ValueError ( "Token doesn't have a subject" ) if "publicKey" not in decoded_token_payload [ "su...
A function for validating an individual token .
568
9
7,560
def verify_token_record ( token_record , public_key_or_address , signing_algorithm = "ES256K" ) : if "token" not in token_record : raise ValueError ( "Token record must have a token inside it" ) token = token_record [ "token" ] decoded_token = verify_token ( token , public_key_or_address , signing_algorithm = signing_a...
A function for validating an individual token record and extracting the decoded token .
188
16
7,561
def get_profile_from_tokens ( token_records , public_key_or_address , hierarchical_keys = False ) : if hierarchical_keys : raise NotImplementedError ( "Hierarchical key support not implemented" ) profile = { } for token_record in token_records : # print token_record try : decoded_token = verify_token_record ( token_rec...
A function for extracting a profile from a list of tokens .
165
12
7,562
def resolve_zone_file_to_profile ( zone_file , address_or_public_key ) : if is_profile_in_legacy_format ( zone_file ) : return zone_file try : token_file_url = get_token_file_url_from_zone_file ( zone_file ) except Exception as e : raise Exception ( "Token file URL could not be extracted from zone file" ) try : r = req...
Resolves a zone file to a profile and checks to makes sure the tokens are signed with a key that corresponds to the address or public key provided .
212
30
7,563
def __dog_started ( self ) : if self . __task is not None : raise RuntimeError ( 'Unable to start task. In order to start a new task - at first stop it' ) self . __task = self . record ( ) . task ( ) if isinstance ( self . __task , WScheduleTask ) is False : task_class = self . __task . __class__ . __qualname__ raise R...
Prepare watchdog for scheduled task starting
113
7
7,564
def __thread_started ( self ) : if self . __task is None : raise RuntimeError ( 'Unable to start thread without "start" method call' ) self . __task . start ( ) self . __task . start_event ( ) . wait ( self . __scheduled_task_startup_timeout__ )
Start a scheduled task
71
4
7,565
def _polling_iteration ( self ) : if self . __task is None : self . ready_event ( ) . set ( ) elif self . __task . check_events ( ) is True : self . ready_event ( ) . set ( ) self . registry ( ) . task_finished ( self )
Poll for scheduled task stop events
68
6
7,566
def thread_stopped ( self ) : if self . __task is not None : if self . __task . stop_event ( ) . is_set ( ) is False : self . __task . stop ( ) self . __task = None
Stop scheduled task beacuse of watchdog stop
52
9
7,567
def stop_running_tasks ( self ) : for task in self . __running_registry : task . stop ( ) self . __running_registry . clear ( )
Terminate all the running tasks
38
6
7,568
def add_source ( self , task_source ) : next_start = task_source . next_start ( ) self . __sources [ task_source ] = next_start self . __update ( task_source )
Add new tasks source
48
4
7,569
def __update_all ( self ) : self . __next_start = None self . __next_sources = [ ] for source in self . __sources : self . __update ( source )
Recheck next start of records from all the sources
43
11
7,570
def __update ( self , task_source ) : next_start = task_source . next_start ( ) if next_start is not None : if next_start . tzinfo is None or next_start . tzinfo != timezone . utc : raise ValueError ( 'Invalid timezone information' ) if self . __next_start is None or next_start < self . __next_start : self . __next_sta...
Recheck next start of tasks from the given one only
139
12
7,571
def check ( self ) : if self . __next_start is not None : utc_now = utc_datetime ( ) if utc_now >= self . __next_start : result = [ ] for task_source in self . __next_sources : records = task_source . has_records ( ) if records is not None : result . extend ( records ) self . __update_all ( ) if len ( result ) > 0 : re...
Check if there are records that are ready to start and return them if there are any
104
17
7,572
def thread_started ( self ) : self . __running_record_registry . start ( ) self . __running_record_registry . start_event ( ) . wait ( ) WPollingThreadTask . thread_started ( self )
Start required registries and start this scheduler
52
9
7,573
def dir_contains ( dirname , path , exists = True ) : if exists : dirname = osp . abspath ( dirname ) path = osp . abspath ( path ) if six . PY2 or six . PY34 : return osp . exists ( path ) and osp . samefile ( osp . commonprefix ( [ dirname , path ] ) , dirname ) else : return osp . samefile ( osp . commonpath ( [ dir...
Check if a file of directory is contained in another .
129
11
7,574
def get_next_name ( old , fmt = '%i' ) : nums = re . findall ( '\d+' , old ) if not nums : raise ValueError ( "Could not get the next name because the old name " "has no numbers in it" ) num0 = nums [ - 1 ] num1 = str ( int ( num0 ) + 1 ) return old [ : : - 1 ] . replace ( num0 [ : : - 1 ] , num1 [ : : - 1 ] , 1 ) [ : ...
Return the next name that numerically follows old
121
9
7,575
def go_through_dict ( key , d , setdefault = None ) : patt = re . compile ( r'(?<!\\)\.' ) sub_d = d splitted = patt . split ( key ) n = len ( splitted ) for i , k in enumerate ( splitted ) : if i < n - 1 : if setdefault is not None : sub_d = sub_d . setdefault ( k , setdefault ( ) ) else : sub_d = sub_d [ k ] else : r...
Split up the key by . and get the value from the base dictionary d
120
15
7,576
def sha1_hmac ( secret , document ) : signature = hmac . new ( secret , document , hashlib . sha1 ) . digest ( ) . encode ( "base64" ) [ : - 1 ] return signature
Calculate the Base 64 encoding of the HMAC for the given document .
50
16
7,577
def filter_query_string ( query ) : return '&' . join ( [ q for q in query . split ( '&' ) if not ( q . startswith ( '_k=' ) or q . startswith ( '_e=' ) or q . startswith ( '_s' ) ) ] )
Return a version of the query string with the _e _k and _s values removed .
71
19
7,578
def fost_hmac_url_signature ( key , secret , host , path , query_string , expires ) : if query_string : document = '%s%s?%s\n%s' % ( host , path , query_string , expires ) else : document = '%s%s\n%s' % ( host , path , expires ) signature = sha1_hmac ( secret , document ) return signature
Return a signature that corresponds to the signed URL .
95
10
7,579
def fost_hmac_request_signature ( secret , method , path , timestamp , headers = { } , body = '' ) : signed_headers , header_values = 'X-FOST-Headers' , [ ] for header , value in headers . items ( ) : signed_headers += ' ' + header header_values . append ( value ) return fost_hmac_request_signature_with_headers ( secre...
Calculate the signature for the given secret and arguments .
111
12
7,580
def fost_hmac_request_signature_with_headers ( secret , method , path , timestamp , headers , body ) : document = "%s %s\n%s\n%s\n%s" % ( method , path , timestamp , '\n' . join ( headers ) , body ) signature = sha1_hmac ( secret , document ) logging . info ( "Calculated signature %s for document\n%s" , signature , doc...
Calculate the signature for the given secret and other arguments .
106
13
7,581
def get_order ( membersuite_id , client = None ) : if not membersuite_id : return None client = client or get_new_client ( request_session = True ) if not client . session_id : client . request_session ( ) object_query = "SELECT Object() FROM ORDER WHERE ID = '{}'" . format ( membersuite_id ) result = client . execute_...
Get an Order by ID .
188
6
7,582
def export_private_key ( self , password = None ) : if self . __private_key is None : raise ValueError ( 'Unable to call this method. Private key must be set' ) if password is not None : if isinstance ( password , str ) is True : password = password . encode ( ) return self . __private_key . private_bytes ( encoding = ...
Export a private key in PEM - format
167
9
7,583
def export_public_key ( self ) : if self . __public_key is None : raise ValueError ( 'Unable to call this method. Public key must be set' ) return self . __public_key . public_bytes ( encoding = serialization . Encoding . PEM , format = serialization . PublicFormat . SubjectPublicKeyInfo )
Export a public key in PEM - format
75
9
7,584
def import_private_key ( self , pem_text , password = None ) : if isinstance ( pem_text , str ) is True : pem_text = pem_text . encode ( ) if password is not None and isinstance ( password , str ) is True : password = password . encode ( ) self . __set_private_key ( serialization . load_pem_private_key ( pem_text , pas...
Import a private key from data in PEM - format
109
11
7,585
def decrypt ( self , data , oaep_hash_fn_name = None , mgf1_hash_fn_name = None ) : if self . __private_key is None : raise ValueError ( 'Unable to call this method. Private key must be set' ) if oaep_hash_fn_name is None : oaep_hash_fn_name = self . __class__ . __default_oaep_hash_function_name__ if mgf1_hash_fn_name ...
Decrypt a data that used PKCS1 OAEP protocol
251
13
7,586
def validate ( self , value , model = None , context = None ) : length = len ( str ( value ) ) params = dict ( min = self . min , max = self . max ) # too short? if self . min and self . max is None : if length < self . min : return Error ( self . too_short , params ) # too long? if self . max and self . min is None : ...
Validate Perform value validation against validation settings and return simple result object
153
13
7,587
def qteSaveMacroData ( self , data , widgetObj : QtGui . QWidget = None ) : # Check type of input arguments. if not hasattr ( widgetObj , '_qteAdmin' ) and ( widgetObj is not None ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise Qtmacs...
Associate arbitrary data with widgetObj .
161
8
7,588
def qteMacroData ( self , widgetObj : QtGui . QWidget = None ) : # Check type of input arguments. if not hasattr ( widgetObj , '_qteAdmin' ) and ( widgetObj is not None ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ...
Retrieve widgetObj specific data previously saved with qteSaveMacroData .
230
16
7,589
def qteSetAppletSignature ( self , appletSignatures : ( str , tuple , list ) ) : # Convert the argument to a tuple if it is not already a tuple # or list. if not isinstance ( appletSignatures , ( tuple , list ) ) : appletSignatures = appletSignatures , # Ensure that all arguments in the tuple/list are strings. for idx ...
Specify the applet signatures with which this macro is compatible .
176
13
7,590
def qteSetWidgetSignature ( self , widgetSignatures : ( str , tuple , list ) ) : # Convert the argument to a tuple if it is not already a tuple # or list. if not isinstance ( widgetSignatures , ( tuple , list ) ) : widgetSignatures = widgetSignatures , # Ensure that all arguments in the tuple/list are strings. for idx ...
Specify the widget signatures with which this macro is compatible .
166
12
7,591
def qtePrepareToRun ( self ) : # Report the execution attempt. msgObj = QtmacsMessage ( ( self . qteMacroName ( ) , self . qteWidget ) , None ) msgObj . setSignalName ( 'qtesigMacroStart' ) self . qteMain . qtesigMacroStart . emit ( msgObj ) # Try to run the macro and radio the success via the # ``qtesigMacroFinished``...
This method is called by Qtmacs to prepare the macro for execution .
372
15
7,592
def all_valid ( formsets ) : valid = True for formset in formsets : if not formset . is_valid ( ) : valid = False return valid
Returns true if every formset in formsets is valid .
35
12
7,593
def forms_valid ( self , inlines ) : for formset in inlines : formset . save ( ) return HttpResponseRedirect ( self . get_success_url ( ) )
If the form and formsets are valid save the associated models .
41
13
7,594
def post ( self , request , * args , * * kwargs ) : self . object = self . get_object ( ) self . get_context_data ( ) inlines = self . construct_inlines ( ) if all_valid ( inlines ) : return self . forms_valid ( inlines ) return self . forms_invalid ( inlines )
Handles POST requests instantiating a form and formset instances with the passed POST variables and then checked for validity .
78
23
7,595
def get_success_url ( self ) : if self . success_url : # Forcing possible reverse_lazy evaluation url = force_text ( self . success_url ) else : raise ImproperlyConfigured ( "No URL to redirect to. Provide a success_url." ) return url
Returns the supplied success URL .
63
6
7,596
def displayStatusMessage ( self , msgObj ) : # Ensure the message ends with a newline character. msg = msgObj . data if not msg . endswith ( '\n' ) : msg = msg + '\n' # Display the message in the status field. self . qteLabel . setText ( msg )
Display the last status message and partially completed key sequences .
70
11
7,597
def qteUpdateLogSlot ( self ) : # Fetch all log records that have arrived since the last # fetch() call and update the record counter. log = self . logHandler . fetch ( start = self . qteLogCnt ) self . qteLogCnt += len ( log ) # Return immediately if no log message is available (this case # should be impossible). if n...
Fetch and display the next batch of log messages .
420
11
7,598
def qteMoveToEndOfBuffer ( self ) : tc = self . qteText . textCursor ( ) tc . movePosition ( QtGui . QTextCursor . End ) self . qteText . setTextCursor ( tc )
Move cursor to the end of the buffer to facilitate auto scrolling .
54
13
7,599
def sign_token_records ( profile_components , parent_private_key , signing_algorithm = "ES256K" ) : if signing_algorithm != "ES256K" : raise ValueError ( "Signing algorithm not supported" ) token_records = [ ] for profile_component in profile_components : private_key = ECPrivateKey ( parent_private_key ) public_key = p...
Function for iterating through a list of profile components and signing separate individual profile tokens .
197
17