idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
235,200
def create_ticket ( self , Queue = None , files = [ ] , ** kwargs ) : post_data = 'id: ticket/new\nQueue: {}\n' . format ( Queue or self . default_queue , ) for key in kwargs : if key [ : 4 ] == 'Text' : post_data += "{}: {}\n" . format ( key , re . sub ( r'\n' , r'\n ' , kwargs [ key ] ) ) elif key [ : 3 ] == 'CF...
Create new ticket and set given parameters .
235,201
def edit_ticket ( self , ticket_id , ** kwargs ) : post_data = '' for key , value in iteritems ( kwargs ) : if isinstance ( value , ( list , tuple ) ) : value = ", " . join ( value ) if key [ : 3 ] != 'CF_' : post_data += "{}: {}\n" . format ( key , value ) else : post_data += "CF.{{{}}}: {}\n" . format ( key [ 3 : ] ,...
Edit ticket values .
235,202
def get_history ( self , ticket_id , transaction_id = None ) : if transaction_id is None : msgs = self . __request ( 'ticket/{}/history?format=l' . format ( str ( ticket_id ) , ) ) else : msgs = self . __request ( 'ticket/{}/history/id/{}' . format ( str ( ticket_id ) , str ( transaction_id ) ) ) lines = msgs . split (...
Get set of history items .
235,203
def get_short_history ( self , ticket_id ) : msg = self . __request ( 'ticket/{}/history' . format ( str ( ticket_id ) , ) ) items = [ ] lines = msg . split ( '\n' ) multiline_buffer = "" in_multiline = False if self . __get_status_code ( lines [ 0 ] ) == 200 : if ( len ( lines ) > 2 ) and self . RE_PATTERNS [ 'does_no...
Get set of short history items
235,204
def reply ( self , ticket_id , text = '' , cc = '' , bcc = '' , content_type = 'text/plain' , files = [ ] ) : return self . __correspond ( ticket_id , text , 'correspond' , cc , bcc , content_type , files )
Sends email message to the contacts in Requestors field of given ticket with subject as is set in Subject field .
235,205
def get_attachments ( self , ticket_id ) : msg = self . __request ( 'ticket/{}/attachments' . format ( str ( ticket_id ) , ) ) lines = msg . split ( '\n' ) if ( len ( lines ) > 2 ) and self . RE_PATTERNS [ 'does_not_exist_pattern' ] . match ( lines [ 2 ] ) : return None attachment_infos = [ ] if ( self . __get_status_c...
Get attachment list for a given ticket
235,206
def get_attachments_ids ( self , ticket_id ) : attachments = self . get_attachments ( ticket_id ) return [ int ( at [ 0 ] ) for at in attachments ] if attachments else attachments
Get IDs of attachments for given ticket .
235,207
def get_attachment ( self , ticket_id , attachment_id ) : msg = self . __request ( 'ticket/{}/attachments/{}' . format ( str ( ticket_id ) , str ( attachment_id ) ) , text_response = False ) msg = msg . split ( b'\n' ) if ( len ( msg ) > 2 ) and ( self . RE_PATTERNS [ 'invalid_attachment_pattern_bytes' ] . match ( msg ...
Get attachment .
235,208
def get_attachment_content ( self , ticket_id , attachment_id ) : msg = self . __request ( 'ticket/{}/attachments/{}/content' . format ( str ( ticket_id ) , str ( attachment_id ) ) , text_response = False ) lines = msg . split ( b'\n' , 3 ) if ( len ( lines ) == 4 ) and ( self . RE_PATTERNS [ 'invalid_attachment_patter...
Get content of attachment without headers .
235,209
def get_user ( self , user_id ) : msg = self . __request ( 'user/{}' . format ( str ( user_id ) , ) ) status_code = self . __get_status_code ( msg ) if ( status_code == 200 ) : pairs = { } lines = msg . split ( '\n' ) if ( len ( lines ) > 2 ) and self . RE_PATTERNS [ 'does_not_exist_pattern' ] . match ( lines [ 2 ] ) :...
Get user details .
235,210
def get_links ( self , ticket_id ) : msg = self . __request ( 'ticket/{}/links/show' . format ( str ( ticket_id ) , ) ) status_code = self . __get_status_code ( msg ) if ( status_code == 200 ) : pairs = { } msg = msg . split ( '\n' ) if ( len ( msg ) > 2 ) and self . RE_PATTERNS [ 'does_not_exist_pattern' ] . match ( m...
Gets the ticket links for a single ticket .
235,211
def edit_ticket_links ( self , ticket_id , ** kwargs ) : post_data = '' for key in kwargs : post_data += "{}: {}\n" . format ( key , str ( kwargs [ key ] ) ) msg = self . __request ( 'ticket/{}/links' . format ( str ( ticket_id ) , ) , post_data = { 'content' : post_data } ) state = msg . split ( '\n' ) [ 2 ] return se...
Edit ticket links .
235,212
def split_header ( line ) : match = re . match ( r'^(CF\.\{.*?}): (.*)$' , line ) if match : return ( match . group ( 1 ) , match . group ( 2 ) ) return line . split ( ': ' , 1 )
Split a header line into field name and field value .
235,213
def PrivateKeyFromWIF ( wif ) : if wif is None or len ( wif ) is not 52 : raise ValueError ( 'Please provide a wif with a length of 52 bytes (LEN: {0:d})' . format ( len ( wif ) ) ) data = base58 . b58decode ( wif ) length = len ( data ) if length is not 38 or data [ 0 ] is not 0x80 or data [ 33 ] is not 0x01 : raise V...
Get the private key from a WIF key
235,214
def PrivateKeyFromNEP2 ( nep2_key , passphrase ) : if not nep2_key or len ( nep2_key ) != 58 : raise ValueError ( 'Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})' . format ( len ( nep2_key ) ) ) ADDRESS_HASH_SIZE = 4 ADDRESS_HASH_OFFSET = len ( NEP_FLAG ) + len ( NEP_HEADER ) try : decoded_key = base5...
Gets the private key from a NEP - 2 encrypted private key
235,215
def GetAddress ( self ) : script = b'21' + self . PublicKey . encode_point ( True ) + b'ac' script_hash = Crypto . ToScriptHash ( script ) address = Crypto . ToAddress ( script_hash ) return address
Returns the public NEO address for this KeyPair
235,216
def Export ( self ) : data = bytearray ( 38 ) data [ 0 ] = 0x80 data [ 1 : 33 ] = self . PrivateKey [ 0 : 32 ] data [ 33 ] = 0x01 checksum = Crypto . Default ( ) . Hash256 ( data [ 0 : 34 ] ) data [ 34 : 38 ] = checksum [ 0 : 4 ] b58 = base58 . b58encode ( bytes ( data ) ) return b58 . decode ( "utf-8" )
Export this KeyPair s private key in WIF format .
235,217
def ExportNEP2 ( self , passphrase ) : if len ( passphrase ) < 2 : raise ValueError ( "Passphrase must have a minimum of 2 characters" ) address_hash_tmp = hashlib . sha256 ( self . GetAddress ( ) . encode ( "utf-8" ) ) . digest ( ) address_hash_tmp2 = hashlib . sha256 ( address_hash_tmp ) . digest ( ) address_hash = a...
Export the encrypted private key in NEP - 2 format .
235,218
def ReadByte ( self , do_ord = True ) : try : if do_ord : return ord ( self . stream . read ( 1 ) ) return self . stream . read ( 1 ) except Exception as e : logger . error ( "ord expected character but got none" ) return 0
Read a single byte .
235,219
def SafeReadBytes ( self , length ) : data = self . ReadBytes ( length ) if len ( data ) < length : raise ValueError ( "Not enough data available" ) else : return data
Read exactly length number of bytes from the stream .
235,220
def ToScriptHash ( data , unhex = True ) : if len ( data ) > 1 and unhex : data = binascii . unhexlify ( data ) return UInt160 ( data = binascii . unhexlify ( bytes ( Crypto . Hash160 ( data ) , encoding = 'utf-8' ) ) )
Get a script hash of the data .
235,221
def Sign ( message , private_key ) : hash = hashlib . sha256 ( binascii . unhexlify ( message ) ) . hexdigest ( ) v , r , s = bitcoin . ecdsa_raw_sign ( hash , private_key ) rb = bytearray ( r . to_bytes ( 32 , 'big' ) ) sb = bytearray ( s . to_bytes ( 32 , 'big' ) ) sig = rb + sb return sig
Sign the message with the given private key .
235,222
def sqrt ( self , val , flag ) : if val . iszero ( ) : return val sw = self . p % 8 if sw == 3 or sw == 7 : res = val ** ( ( self . p + 1 ) / 4 ) elif sw == 5 : x = val ** ( ( self . p + 1 ) / 4 ) if x == 1 : res = val ** ( ( self . p + 3 ) / 8 ) else : res = ( 4 * val ) ** ( ( self . p - 5 ) / 8 ) * 2 * val else : rai...
calculate the square root modulus p
235,223
def value ( self , x ) : return x if isinstance ( x , FiniteField . Value ) and x . field == self else FiniteField . Value ( self , x )
converts an integer or FinitField . Value to a value of this FiniteField .
235,224
def integer ( self , x ) : if type ( x ) is str : hex = binascii . unhexlify ( x ) return int . from_bytes ( hex , 'big' ) return x . value if isinstance ( x , FiniteField . Value ) else x
returns a plain integer
235,225
def add ( self , p , q ) : if p . iszero ( ) : return q if q . iszero ( ) : return p lft = 0 if p == q : if p . y == 0 : return self . zero ( ) lft = ( 3 * p . x ** 2 + self . a ) / ( 2 * p . y ) elif p . x == q . x : return self . zero ( ) else : lft = ( p . y - q . y ) / ( p . x - q . x ) x = lft ** 2 - ( p . x + q ....
perform elliptic curve addition
235,226
def point ( self , x , y ) : return EllipticCurve . ECPoint ( self , self . field . value ( x ) , self . field . value ( y ) )
construct a point from 2 values
235,227
def isoncurve ( self , p ) : return p . iszero ( ) or p . y ** 2 == p . x ** 3 + self . a * p . x + self . b
verifies if a point is on the curve
235,228
def secp256r1 ( ) : GFp = FiniteField ( int ( "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF" , 16 ) ) ec = EllipticCurve ( GFp , 115792089210356248762697446949407573530086143415290314195533631308867097853948 , 41058363725152142129326129780047268409114441015993725554835256314039467401291 ) return ECD...
create the secp256r1 curve
235,229
def decode_secp256r1 ( str , unhex = True , check_on_curve = True ) : GFp = FiniteField ( int ( "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF" , 16 ) ) ec = EllipticCurve ( GFp , 115792089210356248762697446949407573530086143415290314195533631308867097853948 , 4105836372515214212932612978004726840911...
decode a public key on the secp256r1 curve
235,230
def secp256k1 ( ) : GFp = FiniteField ( 2 ** 256 - 2 ** 32 - 977 ) ec = EllipticCurve ( GFp , 0 , 7 ) return ECDSA ( ec , ec . point ( 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798 , 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8 ) , 2 ** 256 - 4324203865656596568524208663949681...
create the secp256k1 curve
235,231
def isValidPublicAddress ( address : str ) -> bool : valid = False if len ( address ) == 34 and address [ 0 ] == 'A' : try : base58 . b58decode_check ( address . encode ( ) ) valid = True except ValueError : valid = False return valid
Check if address is a valid NEO address
235,232
def __Build ( leaves ) : if len ( leaves ) < 1 : raise Exception ( 'Leaves must have length' ) if len ( leaves ) == 1 : return leaves [ 0 ] num_parents = int ( ( len ( leaves ) + 1 ) / 2 ) parents = [ MerkleTreeNode ( ) for i in range ( 0 , num_parents ) ] for i in range ( 0 , num_parents ) : node = parents [ i ] node ...
Build the merkle tree .
235,233
def ComputeRoot ( hashes ) : if not len ( hashes ) : raise Exception ( 'Hashes must have length' ) if len ( hashes ) == 1 : return hashes [ 0 ] tree = MerkleTree ( hashes ) return tree . Root . Hash
Compute the root hash .
235,234
def ToHashArray ( self ) : hashes = set ( ) MerkleTree . __DepthFirstSearch ( self . Root , hashes ) return list ( hashes )
Turn the tree into a list of hashes .
235,235
def Trim ( self , flags ) : logger . info ( "Trimming!" ) flags = bytearray ( flags ) length = 1 << self . Depth - 1 while len ( flags ) < length : flags . append ( 0 ) MerkleTree . _TrimNode ( self . Root , 0 , self . Depth , flags )
Trim the nodes from the tree keeping only the root hash .
235,236
def _TrimNode ( node , index , depth , flags ) : if depth == 1 or node . LeftChild is None : return if depth == 2 : if not flags [ index * 2 ] and not flags [ index * 2 + 1 ] : node . LeftChild = None node . RightChild = None else : MerkleTree . _TrimNode ( node . LeftChild , index * 2 , depth - 1 , flags ) MerkleTree ...
Internal helper method to trim a node .
235,237
def double_sha256 ( ba ) : d1 = hashlib . sha256 ( ba ) d2 = hashlib . sha256 ( ) d1 . hexdigest ( ) d2 . update ( d1 . digest ( ) ) return d2 . hexdigest ( )
Perform two SHA256 operations on the input .
235,238
def scripthash_to_address ( scripthash ) : sb = bytearray ( [ ADDRESS_VERSION ] ) + scripthash c256 = bin_dbl_sha256 ( sb ) [ 0 : 4 ] outb = sb + bytearray ( c256 ) return base58 . b58encode ( bytes ( outb ) ) . decode ( "utf-8" )
Convert a script hash to a public address .
235,239
def base256_encode ( n , minwidth = 0 ) : if n > 0 : arr = [ ] while n : n , rem = divmod ( n , 256 ) arr . append ( rem ) b = bytearray ( reversed ( arr ) ) elif n == 0 : b = bytearray ( b'\x00' ) else : raise ValueError ( "Negative numbers not supported" ) if minwidth > 0 and len ( b ) < minwidth : padding = ( minwid...
Encode the input with base256 .
235,240
def xor_bytes ( a , b ) : assert isinstance ( a , bytes ) assert isinstance ( b , bytes ) assert len ( a ) == len ( b ) res = bytearray ( ) for i in range ( len ( a ) ) : res . append ( a [ i ] ^ b [ i ] ) return bytes ( res )
XOR on two bytes objects
235,241
def WriteBytes ( self , value , unhex = True ) : if unhex : try : value = binascii . unhexlify ( value ) except binascii . Error : pass return self . stream . write ( value )
Write a bytes type to the stream .
235,242
def WriteUInt160 ( self , value ) : if type ( value ) is UInt160 : value . Serialize ( self ) else : raise Exception ( "value must be UInt160 instance " )
Write a UInt160 type to the stream .
235,243
def WriteUInt256 ( self , value ) : if type ( value ) is UInt256 : value . Serialize ( self ) else : raise Exception ( "Cannot write value that is not UInt256" )
Write a UInt256 type to the stream .
235,244
def Write2000256List ( self , arr ) : for item in arr : ba = bytearray ( binascii . unhexlify ( item ) ) ba . reverse ( ) self . WriteBytes ( ba )
Write an array of 64 byte items to the stream .
235,245
def get_user_id ( self , user ) : user_field = getattr ( settings , 'SAML_IDP_DJANGO_USERNAME_FIELD' , None ) or getattr ( user , 'USERNAME_FIELD' , 'username' ) return str ( getattr ( user , user_field ) )
Get identifier for a user . Take the one defined in settings . SAML_IDP_DJANGO_USERNAME_FIELD first if not set use the USERNAME_FIELD property which is set on the user Model . This defaults to the user . username field .
235,246
def create_identity ( self , user , sp_mapping , ** extra_config ) : return { out_attr : getattr ( user , user_attr ) for user_attr , out_attr in sp_mapping . items ( ) if hasattr ( user , user_attr ) }
Generate an identity dictionary of the user based on the given mapping of desired user attributes by the SP
235,247
def sso_entry ( request ) : if request . method == 'POST' : passed_data = request . POST binding = BINDING_HTTP_POST else : passed_data = request . GET binding = BINDING_HTTP_REDIRECT request . session [ 'Binding' ] = binding try : request . session [ 'SAMLRequest' ] = passed_data [ 'SAMLRequest' ] except ( KeyError , ...
Entrypoint view for SSO . Gathers the parameters from the HTTP request stores them in the session and redirects the requester to the login_process view .
235,248
def metadata ( request ) : conf = IdPConfig ( ) conf . load ( copy . deepcopy ( settings . SAML_IDP_CONFIG ) ) metadata = entity_descriptor ( conf ) return HttpResponse ( content = text_type ( metadata ) . encode ( 'utf-8' ) , content_type = "text/xml; charset=utf8" )
Returns an XML with the SAML 2 . 0 metadata for this Idp . The metadata is constructed on - the - fly based on the config dict in the django settings .
235,249
def dispatch ( self , request , * args , ** kwargs ) : conf = IdPConfig ( ) try : conf . load ( copy . deepcopy ( settings . SAML_IDP_CONFIG ) ) self . IDP = Server ( config = conf ) except Exception as e : return self . handle_error ( request , exception = e ) return super ( IdPHandlerViewMixin , self ) . dispatch ( r...
Construct IDP server with config from settings dict
235,250
def get_processor ( self , entity_id , sp_config ) : processor_string = sp_config . get ( 'processor' , None ) if processor_string : try : return import_string ( processor_string ) ( entity_id ) except Exception as e : logger . error ( "Failed to instantiate processor: {} - {}" . format ( processor_string , e ) , exc_i...
Instantiate user - specified processor or default to an all - access base processor . Raises an exception if the configured processor class can not be found or initialized .
235,251
def get ( self , include_backups = False ) : leases = [ ] with open ( self . filename ) if not self . gzip else gzip . open ( self . filename ) as lease_file : lease_data = lease_file . read ( ) if self . gzip : lease_data = lease_data . decode ( 'utf-8' ) for match in self . regex_leaseblock . finditer ( lease_data ) ...
Parse the lease file and return a list of Lease instances .
235,252
def get_current ( self ) : all_leases = self . get ( ) leases = { } for lease in all_leases : if lease . valid and lease . active : if type ( lease ) is Lease : leases [ lease . ethernet ] = lease elif type ( lease ) is Lease6 : leases [ '%s-%s' % ( lease . type , lease . host_identifier_string ) ] = lease return lease...
Parse the lease file and return a dict of active and valid Lease instances . The key for this dict is the ethernet address of the lease .
235,253
def create_layout ( lexer = None , reserve_space_for_menu = 8 , get_prompt_tokens = None , get_bottom_toolbar_tokens = None , extra_input_processors = None , multiline = False , wrap_lines = True ) : input_processors = [ ConditionalProcessor ( HighlightSearchProcessor ( preview_search = True ) , HasFocus ( SEARCH_BUFFE...
Creates a custom Layout for the Crash input REPL
235,254
def _parse_statements ( lines ) : lines = ( l . strip ( ) for l in lines if l ) lines = ( l for l in lines if l and not l . startswith ( '--' ) ) parts = [ ] for line in lines : parts . append ( line . rstrip ( ';' ) ) if line . endswith ( ';' ) : yield '\n' . join ( parts ) parts [ : ] = [ ] if parts : yield '\n' . jo...
Return a generator of statements
235,255
def _show_tables ( self , * args ) : v = self . connection . lowest_server_version schema_name = "table_schema" if v >= TABLE_SCHEMA_MIN_VERSION else "schema_name" table_filter = " AND table_type = 'BASE TABLE'" if v >= TABLE_TYPE_MIN_VERSION else "" self . _exec ( "SELECT format('%s.%s', {schema}, table_name) AS name ...
print the existing tables within the doc schema
235,256
def execute ( self ) : if not self . cmd . is_conn_available ( ) : return if self . cmd . connection . lowest_server_version >= SYSINFO_MIN_VERSION : success , rows = self . _sys_info ( ) self . cmd . exit_code = self . cmd . exit_code or int ( not success ) if success : for result in rows : self . cmd . pprint ( resul...
print system and cluster info
235,257
def bwc_bool_transform_from ( cls , x ) : if x . lower ( ) == 'true' : return True elif x . lower ( ) == 'false' : return False return bool ( int ( x ) )
Read boolean values from old config files correctly and interpret True and False as correct booleans .
235,258
def _transform_field ( field ) : if isinstance ( field , bool ) : return TRUE if field else FALSE elif isinstance ( field , ( list , dict ) ) : return json . dumps ( field , sort_keys = True , ensure_ascii = False ) else : return field
transform field for displaying
235,259
def script ( ) : parser = argparse . ArgumentParser ( description = "Print all textual tags of one or more audio files." ) parser . add_argument ( "-b" , "--batch" , help = "disable user interaction" , action = "store_true" ) parser . add_argument ( "file" , nargs = "+" , help = "file(s) to print tags of" ) args = pars...
Run the command - line script .
235,260
def sw_reset ( self ) : self . write8 ( _STATUS_BASE , _STATUS_SWRST , 0xFF ) time . sleep ( .500 ) chip_id = self . read8 ( _STATUS_BASE , _STATUS_HW_ID ) if chip_id != _HW_ID_CODE : raise RuntimeError ( "Seesaw hardware ID returned (0x{:x}) is not " "correct! Expected 0x{:x}. Please check your wiring." . format ( chi...
Trigger a software reset of the SeeSaw chip
235,261
def _get_default_cache_file_path ( self ) : default_list_path = os . path . join ( self . _get_default_cache_dir ( ) , self . _CACHE_FILE_NAME ) if not os . access ( default_list_path , os . F_OK ) : raise CacheFileError ( "Default cache file does not exist " "'{}'!" . format ( default_list_path ) ) return default_list...
Returns default cache file path
235,262
def _get_writable_cache_dir ( self ) : dir_path_data = self . _get_default_cache_dir ( ) if os . access ( dir_path_data , os . W_OK ) : self . _default_cache_file = True return dir_path_data dir_path_user = user_cache_dir ( self . _URLEXTRACT_NAME ) if not os . path . exists ( dir_path_user ) : os . makedirs ( dir_path...
Get writable cache directory with fallback to user s cache directory and global temp directory
235,263
def _get_cache_file_path ( self , cache_dir = None ) : if cache_dir is None : cache_dir = self . _get_writable_cache_dir ( ) else : if not os . access ( cache_dir , os . W_OK ) : raise CacheFileError ( "None of cache directories is writable." ) return os . path . join ( cache_dir , self . _CACHE_FILE_NAME )
Get path for cache file
235,264
def _load_cached_tlds ( self ) : if not os . access ( self . _tld_list_path , os . R_OK ) : self . _logger . error ( "Cached file is not readable for current " "user. ({})" . format ( self . _tld_list_path ) ) raise CacheFileError ( "Cached file is not readable for current user." ) set_of_tlds = set ( ) with open ( sel...
Loads TLDs from cached file to set .
235,265
def _get_last_cachefile_modification ( self ) : try : mtime = os . path . getmtime ( self . _tld_list_path ) except OSError : return None return datetime . fromtimestamp ( mtime )
Get last modification of cache file with TLDs .
235,266
def _get_after_tld_chars ( self ) : after_tld_chars = set ( string . whitespace ) after_tld_chars |= { '/' , '\"' , '\'' , '<' , '>' , '?' , ':' , '.' , ',' } _ , right_enclosure = zip ( * self . _enclosure ) after_tld_chars |= set ( right_enclosure ) return after_tld_chars
Initialize after tld characters
235,267
def update_when_older ( self , days ) : last_cache = self . _get_last_cachefile_modification ( ) if last_cache is None : return self . update ( ) time_to_update = last_cache + timedelta ( days = days ) if datetime . now ( ) >= time_to_update : return self . update ( ) return True
Update TLD list cache file if the list is older than number of days given in parameter days or if does not exist .
235,268
def set_stop_chars ( self , stop_chars ) : warnings . warn ( "Method set_stop_chars is deprecated, " "use `set_stop_chars_left` or " "`set_stop_chars_right` instead" , DeprecationWarning ) self . _stop_chars = set ( stop_chars ) self . _stop_chars_left = self . _stop_chars self . _stop_chars_right = self . _stop_chars
Set stop characters used when determining end of URL .
235,269
def set_stop_chars_left ( self , stop_chars ) : if not isinstance ( stop_chars , set ) : raise TypeError ( "stop_chars should be type set " "but {} was given" . format ( type ( stop_chars ) ) ) self . _stop_chars_left = stop_chars self . _stop_chars = self . _stop_chars_left | self . _stop_chars_right
Set stop characters for text on left from TLD . Stop characters are used when determining end of URL .
235,270
def add_enclosure ( self , left_char , right_char ) : assert len ( left_char ) == 1 , "Parameter left_char must be character not string" assert len ( right_char ) == 1 , "Parameter right_char must be character not string" self . _enclosure . add ( ( left_char , right_char ) ) self . _after_tld_chars = self . _get_after...
Add new enclosure pair of characters . That and should be removed when their presence is detected at beginning and end of found URL
235,271
def remove_enclosure ( self , left_char , right_char ) : assert len ( left_char ) == 1 , "Parameter left_char must be character not string" assert len ( right_char ) == 1 , "Parameter right_char must be character not string" rm_enclosure = ( left_char , right_char ) if rm_enclosure in self . _enclosure : self . _enclos...
Remove enclosure pair from set of enclosures .
235,272
def _complete_url ( self , text , tld_pos , tld ) : left_ok = True right_ok = True max_len = len ( text ) - 1 end_pos = tld_pos start_pos = tld_pos while left_ok or right_ok : if left_ok : if start_pos <= 0 : left_ok = False else : if text [ start_pos - 1 ] not in self . _stop_chars_left : start_pos -= 1 else : left_ok...
Expand string in both sides to match whole URL .
235,273
def _validate_tld_match ( self , text , matched_tld , tld_pos ) : if tld_pos > len ( text ) : return False right_tld_pos = tld_pos + len ( matched_tld ) if len ( text ) > right_tld_pos : if text [ right_tld_pos ] in self . _after_tld_chars : if tld_pos > 0 and text [ tld_pos - 1 ] not in self . _stop_chars_left : retur...
Validate TLD match - tells if at found position is really TLD .
235,274
def _split_markdown ( text_url , tld_pos ) : left_bracket_pos = text_url . find ( '[' ) if left_bracket_pos > tld_pos - 3 : return text_url right_bracket_pos = text_url . find ( ')' ) if right_bracket_pos < tld_pos : return text_url middle_pos = text_url . rfind ( "](" ) if middle_pos > tld_pos : return text_url [ left...
Split markdown URL . There is an issue wen Markdown URL is found . Parsing of the URL does not stop on right place so wrongly found URL has to be split .
235,275
def gen_urls ( self , text ) : tld_pos = 0 matched_tlds = self . _tlds_re . findall ( text ) for tld in matched_tlds : tmp_text = text [ tld_pos : ] offset = tld_pos tld_pos = tmp_text . find ( tld ) validated = self . _validate_tld_match ( text , tld , offset + tld_pos ) if tld_pos != - 1 and validated : tmp_url = sel...
Creates generator over found URLs in given text .
235,276
def find_urls ( self , text , only_unique = False ) : urls = self . gen_urls ( text ) urls = OrderedDict . fromkeys ( urls ) if only_unique else urls return list ( urls )
Find all URLs in given text .
235,277
def possibly_award ( self , ** state ) : assert "user" in state if self . async : from . tasks import AsyncBadgeAward state = self . freeze ( ** state ) AsyncBadgeAward . delay ( self , state ) return self . actually_possibly_award ( ** state )
Will see if the user should be awarded a badge . If this badge is asynchronous it just queues up the badge awarding .
235,278
def actually_possibly_award ( self , ** state ) : user = state [ "user" ] force_timestamp = state . pop ( "force_timestamp" , None ) awarded = self . award ( ** state ) if awarded is None : return if awarded . level is None : assert len ( self . levels ) == 1 awarded . level = 1 awarded = awarded . level - 1 assert awa...
Does the actual work of possibly awarding a badge .
235,279
def send_badge_messages ( self , badge_award ) : user_message = getattr ( badge_award . badge , "user_message" , None ) if callable ( user_message ) : message = user_message ( badge_award ) else : message = user_message if message is not None : badge_award . user . message_set . create ( message = message )
If the Badge class defines a message send it to the user who was just awarded the badge .
235,280
def visit_Print ( self , node ) : self . prints_used [ ( node . lineno , node . col_offset ) ] = VIOLATIONS [ "found" ] [ PRINT_FUNCTION_NAME ]
Only exists in python 2 .
235,281
def create_lockfile ( self ) : process = subprocess . Popen ( self . pin_command , stdout = subprocess . PIPE , stderr = subprocess . PIPE , ) stdout , stderr = process . communicate ( ) if process . returncode == 0 : self . fix_lockfile ( ) else : logger . critical ( "ERROR executing %s" , ' ' . join ( self . pin_comm...
Write recursive dependencies list to outfile with hard - pinned versions . Then fix it .
235,282
def infile ( self ) : return os . path . join ( OPTIONS [ 'base_dir' ] , '{0}.{1}' . format ( self . name , OPTIONS [ 'in_ext' ] ) )
Path of the input file
235,283
def outfile ( self ) : return os . path . join ( OPTIONS [ 'base_dir' ] , '{0}.{1}' . format ( self . name , OPTIONS [ 'out_ext' ] ) )
Path of the output file
235,284
def pin_command ( self ) : parts = [ 'pip-compile' , '--no-header' , '--verbose' , '--rebuild' , '--no-index' , '--output-file' , self . outfile , self . infile , ] if OPTIONS [ 'upgrade' ] : parts . insert ( 3 , '--upgrade' ) if self . add_hashes : parts . insert ( 1 , '--generate-hashes' ) return parts
Compose pip - compile shell command
235,285
def fix_lockfile ( self ) : with open ( self . outfile , 'rt' ) as fp : lines = [ self . fix_pin ( line ) for line in self . concatenated ( fp ) ] with open ( self . outfile , 'wt' ) as fp : fp . writelines ( [ line + '\n' for line in lines if line is not None ] )
Run each line of outfile through fix_pin
235,286
def fix_pin ( self , line ) : dep = Dependency ( line ) if dep . valid : if dep . package in self . ignore : ignored_version = self . ignore [ dep . package ] if ignored_version is not None : if dep . version and dep . version != ignored_version : logger . error ( "Package %s was resolved to different " "versions in di...
Fix dependency by removing post - releases from versions and loosing constraints on internal packages . Drop packages from ignore set
235,287
def add_references ( self , other_names ) : if not other_names : return with open ( self . outfile , 'rt' ) as fp : header , body = self . split_header ( fp ) with open ( self . outfile , 'wt' ) as fp : fp . writelines ( header ) fp . writelines ( '-r {0}.{1}\n' . format ( other_name , OPTIONS [ 'out_ext' ] ) for other...
Add references to other_names in outfile
235,288
def replace_header ( self , header_text ) : with open ( self . outfile , 'rt' ) as fp : _ , body = self . split_header ( fp ) with open ( self . outfile , 'wt' ) as fp : fp . write ( header_text ) fp . writelines ( body )
Replace pip - compile header with custom text
235,289
def order_by_refs ( envs ) : topology = { env [ 'name' ] : set ( env [ 'refs' ] ) for env in envs } by_name = { env [ 'name' ] : env for env in envs } return [ by_name [ name ] for name in toposort_flatten ( topology ) ]
Return topologicaly sorted list of environments . I . e . all referenced environments are placed before their references .
235,290
def is_compatible ( self ) : for pattern in OPTIONS [ 'compatible_patterns' ] : if fnmatch ( self . package . lower ( ) , pattern ) : return True return False
Check if package name is matched by compatible_patterns
235,291
def drop_post ( self ) : post_index = self . version . find ( '.post' ) if post_index >= 0 : self . version = self . version [ : post_index ]
Remove . postXXXX postfix from version
235,292
def verify_environments ( ) : env_confs = discover ( os . path . join ( OPTIONS [ 'base_dir' ] , '*.' + OPTIONS [ 'in_ext' ] , ) ) success = True for conf in env_confs : env = Environment ( name = conf [ 'name' ] ) current_comment = generate_hash_comment ( env . infile ) existing_comment = parse_hash_comment ( env . ou...
For each environment verify hash comments and report failures . If any failure occured exit with code 1 .
235,293
def generate_hash_comment ( file_path ) : with open ( file_path , 'rb' ) as fp : hexdigest = hashlib . sha1 ( fp . read ( ) . strip ( ) ) . hexdigest ( ) return "# SHA1:{0}\n" . format ( hexdigest )
Read file with given file_path and return string of format
235,294
def parse_value ( key , value ) : default = OPTIONS . get ( key ) if isinstance ( default , collections . Iterable ) : if not isinstance ( default , six . string_types ) : return [ item . strip ( ) for item in value . split ( ',' ) ] return value
Parse value as comma - delimited list if default value for it is list
235,295
def python_version_matchers ( ) : version = sys . version_info patterns = [ "{0}" , "{0}{1}" , "{0}.{1}" , ] matchers = [ pattern . format ( * version ) for pattern in patterns ] + [ None ] return set ( matchers )
Return set of string representations of current python version
235,296
def verify ( ctx ) : oks = run_configurations ( skipper ( verify_environments ) , read_sections , ) ctx . exit ( 0 if False not in oks else 1 )
Upgrade locked dependency versions
235,297
def skipper ( func ) : @ functools . wraps ( func ) def wrapped ( ) : key = ( OPTIONS [ 'base_dir' ] , OPTIONS [ 'in_ext' ] , OPTIONS [ 'out_ext' ] ) if key not in seen : seen [ key ] = func ( ) return seen [ key ] seen = { } return wrapped
Decorator that memorizes base_dir in_ext and out_ext from OPTIONS and skips execution for duplicates .
235,298
def run_configurations ( callback , sections_reader ) : base = dict ( OPTIONS ) sections = sections_reader ( ) if sections is None : logger . info ( "Configuration not found in .ini files. " "Running with default settings" ) recompile ( ) elif sections == [ ] : logger . info ( "Configuration does not match current runt...
Parse configurations and execute callback for matching .
235,299
def recompile ( ) : pinned_packages = { } env_confs = discover ( os . path . join ( OPTIONS [ 'base_dir' ] , '*.' + OPTIONS [ 'in_ext' ] , ) , ) if OPTIONS [ 'header_file' ] : with open ( OPTIONS [ 'header_file' ] ) as fp : base_header_text = fp . read ( ) else : base_header_text = DEFAULT_HEADER hashed_by_reference = ...
Compile requirements files for all environments .