signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def split ( self , point = None ) : """Split this sequence into two halves and return them . The original sequence remains unmodified . : param point : defines the split point , if None then the centre is used : return : two Sequence objects - - one for each side"""
if point is None : point = len ( self ) / 2 r1 = Sequence ( self . name + ".1" , self . sequenceData [ : point ] ) r2 = Sequence ( self . name + ".2" , self . sequenceData [ point : ] ) return r1 , r2
def ReadClientStats ( self , client_id , min_timestamp , max_timestamp ) : """Reads ClientStats for a given client and time range ."""
results = [ ] for timestamp , stats in iteritems ( self . client_stats [ client_id ] ) : if min_timestamp <= timestamp <= max_timestamp : results . append ( stats ) return results
def generate_bug_changes ( self , startday , endday , alt_startday , alt_endday ) : """Returns a list of dicts containing a bug id , a bug comment ( only for bugs whose total number of daily or weekly occurrences meet the appropriate threshold ) and potentially an updated whiteboard or priority status ."""
bug_stats , bug_ids = self . get_bug_stats ( startday , endday ) alt_date_bug_totals = self . get_alt_date_bug_totals ( alt_startday , alt_endday , bug_ids ) test_run_count = self . get_test_runs ( startday , endday ) # if fetch _ bug _ details fails , None is returned bug_info = self . fetch_all_bug_details ( bug_ids ...
def _create_project ( self , path ) : """Create a new project ."""
self . open_project ( path = path ) self . setup_menu_actions ( ) self . add_to_recent ( path )
def _find_im_paths ( self , subj_mp , obs_name , target_polarity , max_paths = 1 , max_path_length = 5 ) : """Check for a source / target path in the influence map . Parameters subj _ mp : pysb . MonomerPattern MonomerPattern corresponding to the subject of the Statement being checked . obs _ name : str ...
logger . info ( ( 'Running path finding with max_paths=%d,' ' max_path_length=%d' ) % ( max_paths , max_path_length ) ) # Find rules in the model corresponding to the input if subj_mp is None : input_rule_set = None else : input_rule_set = self . _get_input_rules ( subj_mp ) if not input_rule_set : ...
def clean_store ( self , store , display_progress = True ) : """Clean unused data in an external storage repository from unused blobs . This must be performed after delete _ garbage during low - usage periods to reduce risks of data loss ."""
spec = self . _get_store_spec ( store ) progress = tqdm if display_progress else lambda x : x if spec [ 'protocol' ] == 'file' : folder = os . path . join ( spec [ 'location' ] , self . database ) delete_list = set ( os . listdir ( folder ) ) . difference ( self . fetch ( 'hash' ) ) print ( 'Deleting %d unu...
def encode_request ( name , uuid , callable , partition_id ) : """Encode request into client _ message"""
client_message = ClientMessage ( payload_size = calculate_size ( name , uuid , callable , partition_id ) ) client_message . set_message_type ( REQUEST_TYPE ) client_message . set_retryable ( RETRYABLE ) client_message . append_str ( name ) client_message . append_str ( uuid ) client_message . append_data ( callable ) c...
def create_model ( config : dict , output_dir : Optional [ str ] , dataset : AbstractDataset , restore_from : Optional [ str ] = None ) -> AbstractModel : """Create a model object either from scratch of from the checkpoint in ` ` resume _ dir ` ` . Cxflow allows the following scenarios 1 . Create model : leave ...
logging . info ( 'Creating a model' ) model_config = config [ 'model' ] # workaround for ruamel . yaml expansion bug ; see # 222 model_config = dict ( model_config . items ( ) ) assert 'class' in model_config , '`model.class` not present in the config' model_module , model_class = parse_fully_qualified_name ( model_con...
def alleles_to_retrieve ( df ) : """Alleles to retrieve from genome fasta Get a dict of the genome fasta contig title to a list of blastn results of the allele sequences that must be retrieved from the genome contig . Args : df ( pandas . DataFrame ) : blastn results dataframe Returns : { str : [ pandas...
contig_blastn_records = defaultdict ( list ) markers = df . marker . unique ( ) for m in markers : dfsub = df [ df . marker == m ] for i , r in dfsub . iterrows ( ) : if r . coverage < 1.0 : contig_blastn_records [ r . stitle ] . append ( r ) break return contig_blastn_records
def fractal_dimension ( image ) : '''Estimates the fractal dimension of an image with box counting . Counts pixels with value 0 as empty and everything else as non - empty . Input image has to be grayscale . See , e . g ` Wikipedia < https : / / en . wikipedia . org / wiki / Fractal _ dimension > ` _ . : pa...
pixels = [ ] for i in range ( image . shape [ 0 ] ) : for j in range ( image . shape [ 1 ] ) : if image [ i , j ] > 0 : pixels . append ( ( i , j ) ) lx = image . shape [ 1 ] ly = image . shape [ 0 ] pixels = np . array ( pixels ) if len ( pixels ) < 2 : return 0 scales = np . logspace ( 1 ,...
def run_needle_alignment_on_files ( id_a , faa_a , id_b , faa_b , gapopen = 10 , gapextend = 0.5 , outdir = '' , outfile = '' , force_rerun = False ) : """Run the needle alignment program for two fasta files and return the raw alignment result . More info : EMBOSS needle : http : / / www . bioinformatics . nl /...
# TODO : rewrite using utils functions so we can check for needle installation # # If you don ' t want to save the output file , just run the alignment and return the raw results # if not outfile and not outdir : # needle _ cline = NeedleCommandline ( asequence = faa _ a , bsequence = faa _ b , # gapopen = gapopen , ga...
def revoke_group_permission ( self , group_name , source_group_name , source_group_owner_id ) : """This is a convenience function that wraps the " authorize group " functionality of the C { authorize _ security _ group } method . For an explanation of the parameters , see C { revoke _ security _ group } ."""
d = self . revoke_security_group ( group_name , source_group_name = source_group_name , source_group_owner_id = source_group_owner_id ) return d
def ignore ( self , argument_dest , ** kwargs ) : """Register an argument with type knack . arguments . ignore _ type ( hidden / ignored ) : param argument _ dest : The destination argument to apply the ignore type to : type argument _ dest : str"""
self . _check_stale ( ) if not self . _applicable ( ) : return dest_option = [ '--__{}' . format ( argument_dest . upper ( ) ) ] self . argument ( argument_dest , arg_type = ignore_type , options_list = dest_option , ** kwargs )
def insertDatasetWOannex ( self , dataset , blockcontent , otptIdList , conn , insertDataset = True , migration = False ) : """_ insertDatasetOnly _ Insert the dataset and only the dataset Meant to be called after everything else is put into place . The insertDataset flag is set to false if the dataset alread...
tran = conn . begin ( ) try : # 8 Finally , we have everything to insert a dataset if insertDataset : # Then we have to get a new dataset ID dataset [ 'dataset_id' ] = self . datasetid . execute ( conn , dataset [ 'dataset' ] ) if dataset [ 'dataset_id' ] <= 0 : dataset [ 'dataset_id' ] ...
def json_encoder_default ( obj ) : """Handle more data types than the default JSON encoder . Specifically , it treats a ` set ` and a ` numpy . array ` like a ` list ` . Example usage : ` ` json . dumps ( obj , default = json _ encoder _ default ) ` `"""
if np is not None and hasattr ( obj , 'size' ) and hasattr ( obj , 'dtype' ) : if obj . size == 1 : if np . issubdtype ( obj . dtype , np . integer ) : return int ( obj ) elif np . issubdtype ( obj . dtype , np . floating ) : return float ( obj ) if isinstance ( obj , set ) :...
def get_agile_board_configuration ( self , board_id ) : """Get the board configuration . The response contains the following fields : id - Id of the board . name - Name of the board . filter - Reference to the filter used by the given board . subQuery ( Kanban only ) - JQL subquery used by the given board ....
url = 'rest/agile/1.0/board/{}/configuration' . format ( str ( board_id ) ) return self . get ( url )
def ServiceAccountCredentialsFromP12File ( service_account_name , private_key_filename , scopes , user_agent ) : """Create a new credential from the named . p12 keyfile ."""
private_key_filename = os . path . expanduser ( private_key_filename ) scopes = util . NormalizeScopes ( scopes ) if oauth2client . __version__ > '1.5.2' : # oauth2client > = 2.0.0 credentials = ( service_account . ServiceAccountCredentials . from_p12_keyfile ( service_account_name , private_key_filename , scopes =...
def update_global_variables_list_store ( self ) : """Updates the global variable list store Triggered after creation or deletion of a variable has taken place ."""
# logger . info ( " update " ) self . list_store_iterators = { } self . list_store . clear ( ) keys = self . model . global_variable_manager . get_all_keys ( ) keys . sort ( ) for key in keys : iter = self . list_store . append ( [ key , self . model . global_variable_manager . get_data_type ( key ) . __name__ , st...
def _get_error ( self , code , errors , indentation = 0 ) : """Get error and show the faulty line + some context Other GLIR implementations may omit this ."""
# Init results = [ ] lines = None if code is not None : lines = [ line . strip ( ) for line in code . split ( '\n' ) ] for error in errors . split ( '\n' ) : # Strip ; skip empy lines error = error . strip ( ) if not error : continue # Separate line number from description ( if we can ) line...
def _set_thing ( self , thing , value ) : """Convenience method for ` _ set _ year ` , ` _ set _ month ` . . ."""
try : value = int ( value ) except ( TypeError , ValueError ) : raise TypeError ( f'Changing the {thing} of a `Date` instance is only ' f'allowed via numbers, but the given value `{value}` ' f'is of type `{type(value)}` instead.' ) kwargs = { } for unit in ( 'year' , 'month' , 'day' , 'hour' , 'minute' , 'secon...
def CreateString ( self , s , encoding = 'utf-8' , errors = 'strict' ) : """CreateString writes a null - terminated byte string as a vector ."""
self . assertNotNested ( ) # # @ cond FLATBUFFERS _ INTERNAL self . nested = True # # @ endcond if isinstance ( s , compat . string_types ) : x = s . encode ( encoding , errors ) elif isinstance ( s , compat . binary_types ) : x = s else : raise TypeError ( "non-string passed to CreateString" ) self . Prep ...
def _pretty_xml ( xml_string ) : """Common function to produce pretty xml string from an input xml _ string . This function is NOT intended to be used in major code paths since it uses the minidom to produce the prettified xml and that uses a lot of memory"""
result_dom = minidom . parseString ( xml_string ) pretty_result = result_dom . toprettyxml ( indent = ' ' ) # remove extra empty lines return re . sub ( r'>( *[\r\n]+)+( *)<' , r'>\n\2<' , pretty_result )
def p_try_statement_2 ( self , p ) : """try _ statement : TRY block finally"""
p [ 0 ] = ast . Try ( statements = p [ 2 ] , fin = p [ 3 ] )
def _get_initialized_channels_dict_for_service ( self , org_id , service_id ) : '''return { channel _ id : channel }'''
fn = self . _get_channels_info_file ( org_id , service_id ) if ( os . path . isfile ( fn ) ) : return pickle . load ( open ( fn , "rb" ) ) else : return { }
def encode_contents ( self ) : """Encode the contents of this update record without including a record header . Returns : bytearray : The encoded contents ."""
if self . variable_size : resp_length = 1 else : resp_length = self . fixed_response_size << 1 header = struct . pack ( "<HBB" , self . rpc_id , self . address , resp_length ) return bytearray ( header ) + self . payload
def save_to_json ( self ) : """The method saves data to json from object"""
requestvalues = { 'id' : self . dataset , 'publicationDate' : self . publication_date . strftime ( '%Y-%m-%d' ) , 'source' : self . source , 'refUrl' : self . refernce_url , } return json . dumps ( requestvalues )
def GetIndex ( self ) : '''Reads and returns the index tree . This auxiliary function reads and returns the index tree file contents for the CHM archive .'''
if self . index is None : return None if self . index : res , ui = chmlib . chm_resolve_object ( self . file , self . index ) if ( res != chmlib . CHM_RESOLVE_SUCCESS ) : return None size , text = chmlib . chm_retrieve_object ( self . file , ui , 0l , ui . length ) if ( size == 0 ) : sys . stder...
def get ( self , key , default = None ) : """Get the value for ` key ` . Gives priority to command - line overrides . Args : key : str , the key to get the value for . Returns : object : The value for ` key `"""
if key in self . __cli : return self . __cli [ key ] if key in self . __config : return self . __config . get ( key ) if key in self . __defaults : return self . __defaults . get ( key ) return default
def watch_children ( kzclient , path , func , allow_session_lost = True , send_event = False , ChildrenWatch = ChildrenWatch ) : """Install a Kazoo : obj : ` ChildrenWatch ` on the given path . The given ` func ` will be called in the reactor thread when any children are created or deleted , or if the node itse...
def wrapped_func ( * args , ** kwargs ) : return blockingCallFromThread ( kzclient . reactor , func , * args , ** kwargs ) return deferToThreadPool ( kzclient . reactor , kzclient . pool , lambda : ChildrenWatch ( kzclient . kazoo_client , path , func = wrapped_func , allow_session_lost = allow_session_lost , send_...
def has_in_starred ( self , starred ) : """: calls : ` GET / user / starred / : owner / : repo < http : / / developer . github . com / v3 / activity / starring > ` _ : param starred : : class : ` github . Repository . Repository ` : rtype : bool"""
assert isinstance ( starred , github . Repository . Repository ) , starred status , headers , data = self . _requester . requestJson ( "GET" , "/user/starred/" + starred . _identity ) return status == 204
def translate_path ( self , orig_path ) : """Translates a path for a static file request . The server base path could be different from our cwd . Parameters path : string The path . Returns The absolute file path denoted by the original path ."""
init_path = orig_path orig_path = urlparse . urlparse ( orig_path ) [ 2 ] needs_redirect = False is_folder = len ( orig_path ) <= 1 or orig_path [ - 1 ] == '/' orig_path = posixpath . normpath ( urlparse_unquote ( orig_path ) ) if is_folder : orig_path += '/' path = None for ( name , fm ) in self . server . _folder...
def _covariance_matrix ( self , type = 'noise' ) : """Constructs the covariance matrix from PCA residuals"""
if type == 'sampling' : return self . sigma ** 2 / ( self . n - 1 ) elif type == 'noise' : return 4 * self . sigma * N . var ( self . rotated ( ) , axis = 0 )
def _init_handler ( self , session , reader , writer ) : """Create a BrokerProtocolHandler and attach to a session : return :"""
handler = BrokerProtocolHandler ( self . plugins_manager , self . _loop ) handler . attach ( session , reader , writer ) return handler
def determine_ticks ( low , high ) : """The function used to auto - generate ticks for an axis , based on its range of values . : param Number low : The lower bound of the axis . : param Number high : The upper bound of the axis . : rtype : ` ` tuple ` `"""
range_ = high - low tick_difference = 10 ** math . floor ( math . log10 ( range_ / 1.25 ) ) low_tick = math . floor ( low / tick_difference ) * tick_difference ticks = [ low_tick + tick_difference ] if low_tick < low else [ low_tick ] while ticks [ - 1 ] + tick_difference <= high : ticks . append ( ticks [ - 1 ] + ...
def _handle_401 ( self , data ) : """Handle Lain being helpful"""
ex = ConnectionError ( "Can't login to a protected room without a proper password" , data ) self . conn . reraise ( ex )
def copy ( self , deep = False ) : """Returns a copy of the list Parameters deep : bool If False ( default ) , only the list is copied and not the contained arrays , otherwise the contained arrays are deep copied"""
if not deep : return self . __class__ ( self [ : ] , attrs = self . attrs . copy ( ) , auto_update = not bool ( self . no_auto_update ) ) else : return self . __class__ ( [ arr . psy . copy ( deep ) for arr in self ] , attrs = self . attrs . copy ( ) , auto_update = not bool ( self . auto_update ) )
def authority_issuer_serial ( self ) : """: return : None or a byte string of the SHA - 256 hash of the isser from the authority key identifier extension concatenated with the ascii character " : " , concatenated with the serial number from the authority key identifier extension as an ascii string"""
if self . _authority_issuer_serial is False : akiv = self . authority_key_identifier_value if akiv and akiv [ 'authority_cert_issuer' ] . native : issuer = self . authority_key_identifier_value [ 'authority_cert_issuer' ] [ 0 ] . chosen # We untag the element since it is tagged via being a choic...
def options ( self , context , module_options ) : '''PROCESS Process to hook , only x86 processes are supported by NetRipper currently ( Choices : firefox , chrome , putty , winscp , outlook , lync )'''
self . process = None if 'PROCESS' in module_options : self . process = module_options [ 'PROCESS' ] else : context . log . error ( 'PROCESS option is required' ) exit ( 1 ) self . share_name = gen_random_string ( 5 ) . upper ( ) self . ps_script1 = obfs_ps_script ( 'cme_powershell_scripts/Invoke-PSInject.p...
def _timestamp_zero_start_handler ( c , ctx ) : """Handles numeric values that start with a zero followed by another digit . This is either a timestamp or an error ."""
val = ctx . value ctx . set_ion_type ( IonType . TIMESTAMP ) if val [ 0 ] == _MINUS : _illegal_character ( c , ctx , 'Negative year not allowed.' ) val . append ( c ) c , self = yield trans = ctx . immediate_transition ( self ) while True : if c in _TIMESTAMP_YEAR_DELIMITERS : trans = ctx . immediate_tr...
def reset ( self ) : """Reset the environment and convert the resulting observation . Returns : Converted observation ."""
observ = self . _env . reset ( ) observ = self . _convert_observ ( observ ) return observ
def get_writer_factory_for ( self , name , * , format = None ) : """Returns a callable to build a writer for the provided filename , eventually forcing a format . : param name : filename : param format : format : return : type"""
return self . get_factory_for ( WRITER , name , format = format )
def same_syllabic_feature ( ch1 , ch2 ) : '''Return True if ch1 and ch2 are both vowels or both consonants .'''
if ch1 == '.' or ch2 == '.' : return False ch1 = 'V' if ch1 in VOWELS else 'C' if ch1 in CONSONANTS else None ch2 = 'V' if ch2 in VOWELS else 'C' if ch2 in CONSONANTS else None return ch1 == ch2
from typing import List , Tuple from collections import Counter def highest_frequency_item ( numbers : List [ int ] ) -> Tuple [ int , int ] : """This function identifies the item with the highest frequency in a given list . Parameters : numbers ( List [ int ] ) : A list of integers . Returns : The result a...
frequency_counter = Counter ( numbers ) return frequency_counter . most_common ( 1 ) [ 0 ]
def cnvl_2D_gauss ( idxPrc , aryMdlParamsChnk , arySptExpInf , tplPngSize , queOut , strCrd = 'crt' ) : """Spatially convolve input with 2D Gaussian model . Parameters idxPrc : int Process ID of the process calling this function ( for CPU multi - threading ) . In GPU version , this parameter is 0 ( just one...
# Number of combinations of model parameters in the current chunk : varChnkSze = aryMdlParamsChnk . shape [ 0 ] # Number of conditions / time points of the input data varNumLstAx = arySptExpInf . shape [ - 1 ] # Output array with results of convolution : aryOut = np . zeros ( ( varChnkSze , varNumLstAx ) ) # Loop throu...
def get_linkroll_details ( destination_slug , num = 'All' , * args , ** kwargs ) : """Takes an optional number and destination ( by id ) and returns a list of links for the given linkroll . Given a number , return list limited to the given number . Given a destination slug , limit linkrolls to the matching dest...
links = Link . objects . filter ( destination__slug = destination_slug ) if num : links = links [ 0 : num ] return { 'link_list' : links }
def _relpath ( name ) : """Strip absolute components from path . Inspired from zipfile . write ( ) ."""
return os . path . normpath ( os . path . splitdrive ( name ) [ 1 ] ) . lstrip ( _allsep )
def timeseries_to_matrix ( image , mask = None ) : """Convert a timeseries image into a matrix . ANTsR function : ` timeseries2matrix ` Arguments image : image whose slices we convert to a matrix . E . g . a 3D image of size x by y by z will convert to a z by x * y sized matrix mask : ANTsImage ( optional...
temp = utils . ndimage_to_list ( image ) if mask is None : mask = temp [ 0 ] * 0 + 1 return image_list_to_matrix ( temp , mask )
def validate_units ( self ) : """Ensure that wavelenth and flux units belong to the correct classes . Raises TypeError Wavelength unit is not ` ~ pysynphot . units . WaveUnits ` or flux unit is not ` ~ pysynphot . units . FluxUnits ` ."""
if ( not isinstance ( self . waveunits , units . WaveUnits ) ) : raise TypeError ( "%s is not a valid WaveUnit" % self . waveunits ) if ( not isinstance ( self . fluxunits , units . FluxUnits ) ) : raise TypeError ( "%s is not a valid FluxUnit" % self . fluxunits )
def generate_prepared_request ( method , url , headers , data , params , handlers ) : """Add handlers and prepare a Request . Parameters method ( str ) HTTP Method . ( e . g . ' POST ' ) headers ( dict ) Headers to send . data ( JSON - formatted str ) Body to attach to the request . params ( dict ) ...
request = Request ( method = method , url = url , headers = headers , data = data , params = params , ) handlers . append ( error_handler ) for handler in handlers : request . register_hook ( 'response' , handler ) return request . prepare ( )
def clean_redirect_uri ( self ) : """: rfc : ` 3.1.2 ` The redirect value has to match what was saved on the authorization server ."""
redirect_uri = self . cleaned_data . get ( 'redirect_uri' ) if redirect_uri : if not redirect_uri == self . client . redirect_uri : raise OAuthValidationError ( { 'error' : 'invalid_request' , 'error_description' : _ ( "The requested redirect didn't " "match the client settings." ) } ) return redirect_uri
def write ( graph , fileformat = None , filename = None ) : """A basic graph writer ( to stdout ) for any of the sources . this will write raw triples in rdfxml , unless specified . to write turtle , specify format = ' turtle ' an optional file can be supplied instead of stdout : return : None"""
filewriter = None if fileformat is None : fileformat = 'turtle' if filename is not None : with open ( filename , 'wb' ) as filewriter : LOG . info ( "Writing triples in %s to %s" , fileformat , filename ) # rdflib serialize graph . serialize ( filewriter , format = fileformat ) else : ...
def ne ( self , key , value , includeMissing = False ) : '''Return entries where the key ' s value is NOT of equal ( ! = ) value . Example of use : > > > test = [ . . . { " name " : " Jim " , " age " : 18 , " income " : 93000 , " wigs " : 68 } , . . . { " name " : " Larry " , " age " : 18 , " wigs " : [ 3 ,...
( self . table , self . index_track ) = internal . select ( self . table , self . index_track , key , self . NOT_EQUAL , value , includeMissing ) return self
def get_cython_version ( ) : """Returns : Version as a pair of ints ( major , minor ) Raises : ImportError : Can ' t load cython or find version"""
import Cython . Compiler . Main match = re . search ( '^([0-9]+)\.([0-9]+)' , Cython . Compiler . Main . Version . version ) try : return map ( int , match . groups ( ) ) except AttributeError : raise ImportError
def sort_return_tuples ( response , ** options ) : """If ` ` groups ` ` is specified , return the response as a list of n - element tuples with n being the value found in options [ ' groups ' ]"""
if not response or not options . get ( 'groups' ) : return response n = options [ 'groups' ] return list ( izip ( * [ response [ i : : n ] for i in range ( n ) ] ) )
def getVulkanDeviceExtensionsRequired ( self , pchValue , unBufferSize ) : """[ Vulkan only ] return 0 . Otherwise it returns the length of the number of bytes necessary to hold this string including the trailing null . The string will be a space separated list of required device extensions to enable in VkCreat...
fn = self . function_table . getVulkanDeviceExtensionsRequired pPhysicalDevice = VkPhysicalDevice_T ( ) result = fn ( byref ( pPhysicalDevice ) , pchValue , unBufferSize ) return result , pPhysicalDevice
def create_node ( t , ref = None , debug = False ) : """Simple factory function"""
if t . ttype == "operand" : if t . tsubtype in [ "range" , "named_range" , "pointer" ] : # print ' Creating Node ' , t . tvalue , t . tsubtype return RangeNode ( t , ref , debug = debug ) else : return OperandNode ( t ) elif t . ttype == "function" : return FunctionNode ( t , ref , debug = d...
def _addFormFont ( self , name , font ) : """_ addFormFont ( self , name , font ) - > PyObject *"""
if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) return _fitz . Document__addFormFont ( self , name , font )
def normalize ( self ) : """Normalizes this Vector"""
vlength = self . length ( ) # Make sure the length isn ' t 0 if vlength > 0 : self . x /= vlength self . y /= vlength self . z /= vlength else : return Vector3 ( 0 , 0 , 0 )
def debug_log_template ( self , record ) : """Return the prefix for the log message . Template for Formatter . Parameters record : : py : class : ` logging . LogRecord ` This is passed in from inside the : py : meth : ` logging . Formatter . format ` record . Returns str Log template ."""
reset = Style . RESET_ALL levelname = ( LEVEL_COLORS . get ( record . levelname ) + Style . BRIGHT + '(%(levelname)1.1s)' + Style . RESET_ALL + ' ' ) asctime = ( '[' + Fore . BLACK + Style . DIM + Style . BRIGHT + '%(asctime)s' + Fore . RESET + Style . RESET_ALL + ']' ) name = ( ' ' + Fore . WHITE + Style . DIM + Style...
def check_predefined_conditions ( ) : """Check k8s predefined conditions for the nodes ."""
try : node_info = current_k8s_corev1_api_client . list_node ( ) for node in node_info . items : # check based on the predefined conditions about the # node status : MemoryPressure , OutOfDisk , KubeletReady # DiskPressure , PIDPressure , for condition in node . status . conditions : ...
def request_sensor_list ( self , req , msg ) : """Request the list of sensors . The list of sensors is sent as a sequence of # sensor - list informs . Parameters name : str , optional Name of the sensor to list ( the default is to list all sensors ) . If name starts and ends with ' / ' it is treated as a ...
exact , name_filter = construct_name_filter ( msg . arguments [ 0 ] if msg . arguments else None ) sensors = [ ( name , sensor ) for name , sensor in sorted ( self . _sensors . iteritems ( ) ) if name_filter ( name ) ] if exact and not sensors : return req . make_reply ( "fail" , "Unknown sensor name." ) self . _se...
def sections ( self ) : """List with tuples of section names and positions . Positions of section names are measured by cumulative word count ."""
sections = [ ] for match in texutils . section_pattern . finditer ( self . text ) : textbefore = self . text [ 0 : match . start ( ) ] wordsbefore = nlputils . wordify ( textbefore ) numwordsbefore = len ( wordsbefore ) sections . append ( ( numwordsbefore , match . group ( 1 ) ) ) self . _sections = se...
def _parseSimpleSelector ( self , src ) : """simple _ selector : [ namespace _ selector ] ? element _ name ? [ HASH | class | attrib | pseudo ] * S *"""
ctxsrc = src . lstrip ( ) nsPrefix , src = self . _getMatchResult ( self . re_namespace_selector , src ) name , src = self . _getMatchResult ( self . re_element_name , src ) if name : pass # already * successfully * assigned elif src [ : 1 ] in self . SelectorQualifiers : name = '*' else : raise self . ...
def _get_var_decl_init_value_single ( self , _ctype , child ) : """Handling of a single child for initialization value . Accepted types are expressions and declarations"""
init_value = None # FIXME : always return ( child . kind , child . value ) log . debug ( '_get_var_decl_init_value_single: _ctype: %s Child.kind: %s' , _ctype . kind , child . kind ) # shorcuts . if not child . kind . is_expression ( ) and not child . kind . is_declaration ( ) : raise CursorKindException ( child . ...
def remove_from_labels ( self , label ) : """: calls : ` DELETE / repos / : owner / : repo / issues / : number / labels / : name < http : / / developer . github . com / v3 / issues / labels > ` _ : param label : : class : ` github . Label . Label ` or string : rtype : None"""
assert isinstance ( label , ( github . Label . Label , str , unicode ) ) , label if isinstance ( label , github . Label . Label ) : label = label . _identity else : label = urllib . quote ( label ) headers , data = self . _requester . requestJsonAndCheck ( "DELETE" , self . issue_url + "/labels/" + label )
def connect_to_host ( cls , host = 'localhost' , port = 8000 , is_secure = False , session = None , access_key = None , secret_key = None , ** kwargs ) : """Connect to a specific host . This method has been deprecated in favor of : meth : ` ~ . connect ` Parameters host : str , optional Address of the host ...
warnings . warn ( "connect_to_host is deprecated and will be removed. " "Use connect instead." ) if session is None : session = botocore . session . get_session ( ) if access_key is not None : session . set_credentials ( access_key , secret_key ) url = "http://%s:%d" % ( host , port ) client = session ....
def walk ( self , leavesonly = True , maxdepth = None , _depth = 0 ) : """Depth - first search , walking through trie , returning all encounterd nodes ( by default only leaves )"""
if self . children : if not maxdepth or ( maxdepth and _depth < maxdepth ) : for key , child in self . children . items ( ) : if child . leaf ( ) : yield child else : for results in child . walk ( leavesonly , maxdepth , _depth + 1 ) : ...
def from_list ( lst ) : """Parses list : param lst : list of elements : return : LinkedList : Nodes from list"""
if not lst : return None head = Node ( lst [ 0 ] , None ) if len ( lst ) == 1 : return head head . next_node = LinkedList . from_list ( lst [ 1 : ] ) return head
def _make_size_legend ( self ) : """Draw a legend that shows relative sizes of the clusters at the 25th , 50th , and 75th percentile based on the current scoring metric ."""
# Compute the size of the markers and scale them to our figure size # NOTE : the marker size is the area of the plot , we need to compute the # radius of the markers . areas = self . _get_cluster_sizes ( ) radii = np . sqrt ( areas / np . pi ) scaled = np . interp ( radii , ( radii . min ( ) , radii . max ( ) ) , ( .1 ...
def filter_words ( words , filters_in = None , filters_out = None , flags = 0 ) : """Filters the words using the given filters . Usage : : > > > filter _ words ( [ " Users " , " are " , " John " , " Doe " , " Jane " , " Doe " , " Z6PO " ] , filters _ in = ( " John " , " Doe " ) ) [ u ' John ' , u ' Doe ' , u ...
filtered_words = [ ] for word in words : if filters_in : filter_matched = False for filter in filters_in : if not re . search ( filter , word , flags ) : LOGGER . debug ( "> '{0}' word skipped, filter in '{1}' not matched!" . format ( word , filter ) ) else : ...
def update_deployment_group ( applicationName = None , currentDeploymentGroupName = None , newDeploymentGroupName = None , deploymentConfigName = None , ec2TagFilters = None , onPremisesInstanceTagFilters = None , autoScalingGroups = None , serviceRoleArn = None , triggerConfigurations = None , alarmConfiguration = Non...
pass
def admin_tagify ( short_description = None , allow_tags = True ) : """Decorator that add short _ description and allow _ tags to ModelAdmin list _ display function . Example : class AlbumAdmin ( admin . ModelAdmin ) : list _ display = [ ' title ' , ' year ' , ' artist ' , ' total _ tacks ' , ' view _ track '...
def tagify ( func ) : func . allow_tags = bool ( allow_tags ) if short_description : func . short_description = short_description return func return tagify
def normalize_text ( text : str ) -> str : """Performs a normalization that is very similar to that done by the normalization functions in SQuAD and TriviaQA . This involves splitting and rejoining the text , and could be a somewhat expensive operation ."""
return ' ' . join ( [ token for token in text . lower ( ) . strip ( STRIPPED_CHARACTERS ) . split ( ) if token not in IGNORED_TOKENS ] )
def parse_cidr ( addr , infer = True , allow_host = False ) : """Takes a CIDR address or plain dotted - quad , and returns a tuple of address and count - of - network - bits . Can infer the network bits based on network classes if infer = True . Can also take a string in the form ' address / netmask ' , as lo...
def check ( r0 , r1 ) : a = int ( r0 ) b = r1 if ( not allow_host ) and ( a & ( ( 1 << b ) - 1 ) ) : raise RuntimeError ( "Host part of CIDR address is not zero (%s)" % ( addr , ) ) return ( r0 , 32 - r1 ) addr = addr . split ( '/' , 2 ) if len ( addr ) == 1 : if infer is False : ret...
def breakpoint_set ( self , addr , thumb = False , arm = False ) : """Sets a breakpoint at the specified address . If ` ` thumb ` ` is ` ` True ` ` , the breakpoint is set in THUMB - mode , while if ` ` arm ` ` is ` ` True ` ` , the breakpoint is set in ARM - mode , otherwise a normal breakpoint is set . Ar...
flags = enums . JLinkBreakpoint . ANY if thumb : flags = flags | enums . JLinkBreakpoint . THUMB elif arm : flags = flags | enums . JLinkBreakpoint . ARM handle = self . _dll . JLINKARM_SetBPEx ( int ( addr ) , flags ) if handle <= 0 : raise errors . JLinkException ( 'Breakpoint could not be set.' ) return ...
def to_juicer_repo ( self ) : """Returns a JuicerRepo ( ) object representing this pulp repo"""
repo_def = { } defaults = juicer . common . Constants . REPO_DEF_DEFAULTS repo_def [ 'name' ] = self [ 'name' ] for key in juicer . common . Constants . REPO_DEF_OPT_KEYS : repo_def [ key ] = self . spec . get ( key , defaults [ key ] ) juicer . utils . Log . log_debug ( "Defined %s as %s" % ( key , str ( self ...
def set_salt_view ( ) : '''Helper function that sets the salt design document . Uses get _ valid _ salt _ views and some hardcoded values .'''
options = _get_options ( ret = None ) # Create the new object that we will shove in as the design doc . new_doc = { } new_doc [ 'views' ] = get_valid_salt_views ( ) new_doc [ 'language' ] = "javascript" # Make the request to update the design doc . _response = _request ( "PUT" , options [ 'url' ] + options [ 'db' ] + "...
def interpret ( self , values = { } , functions = { } ) : """Like ` substitute ` , but forces the interpreter ( rather than the compiled version ) to be used . The interpreter includes exception - handling code for missing variables and buggy template functions but is much slower ."""
return self . expr . evaluate ( Environment ( values , functions ) )
def create_mailing_lists ( self , verbose = True ) : """Creates the mailing list for each registered notification ."""
responses = { } if ( settings . EMAIL_ENABLED and self . loaded and settings . EMAIL_BACKEND != "django.core.mail.backends.locmem.EmailBackend" ) : sys . stdout . write ( style . MIGRATE_HEADING ( f"Creating mailing lists:\n" ) ) for name , notification_cls in self . registry . items ( ) : message = Non...
def fetchUnseen ( self ) : """Get the unseen ( new ) thread list : return : List of unseen thread ids : rtype : list : raises : FBchatException if request failed"""
j = self . _post ( self . req_url . UNSEEN_THREADS , None , fix_request = True , as_json = True ) payload = j [ "payload" ] [ "unseen_thread_fbids" ] [ 0 ] return payload [ "thread_fbids" ] + payload [ "other_user_fbids" ]
def HandlePeerInfoReceived ( self , payload ) : """Process response of ` self . RequestPeerInfo ` ."""
addrs = IOHelper . AsSerializableWithType ( payload , 'neo.Network.Payloads.AddrPayload.AddrPayload' ) if not addrs : return for nawt in addrs . NetworkAddressesWithTime : self . leader . RemoteNodePeerReceived ( nawt . Address , nawt . Port , self . prefix )
def make_spindles ( events , power_peaks , powers , dat_det , dat_orig , time , s_freq ) : """Create dict for each spindle , based on events of time points . Parameters events : ndarray ( dtype = ' int ' ) N x 3 matrix with start , peak , end samples , and peak frequency power _ peaks : ndarray ( dtype = ' ...
i , events = _remove_duplicate ( events , dat_det ) power_peaks = power_peaks [ i ] spindles = [ ] for i , one_peak , one_pwr in zip ( events , power_peaks , powers ) : one_spindle = { 'start' : time [ i [ 0 ] ] , 'end' : time [ i [ 2 ] - 1 ] , 'peak_time' : time [ i [ 1 ] ] , 'peak_val_det' : dat_det [ i [ 1 ] ] ,...
def delete ( cls , cluster_id_label ) : """Delete the cluster with id / label ` cluster _ id _ label ` ."""
conn = Qubole . agent ( version = Cluster . api_version ) return conn . delete ( cls . element_path ( cluster_id_label ) )
def emit_message ( self , message ) : """Send a message to the channel . We also emit the message back to the sender ' s WebSocket ."""
try : nickname_color = self . nicknames [ self . nickname ] except KeyError : # Only accept messages if we ' ve joined . return message = message [ : settings . MAX_MESSAGE_LENGTH ] # Handle IRC commands . if message . startswith ( "/" ) : self . connection . send_raw ( message . lstrip ( "/" ) ) return...
def create ( self , num ) : """Creates the environment in your subclassed create function include the line below super ( ) . build ( arg1 , arg2 , arg2 , . . . )"""
self . log . record_process ( 'enviroment.py' , 'Creating ' + str ( num ) + ' environments - ' + self . name )
def acquire ( self , timeout = None ) : """Acquire the lock . Creates the PID file for this lock , or raises an error if the lock could not be acquired ."""
timeout = timeout is not None and timeout or self . timeout end_time = time . time ( ) if timeout is not None and timeout > 0 : end_time += timeout while True : try : write_pid_to_pidfile ( self . path ) except OSError as exc : if exc . errno == errno . EEXIST : # The lock creation failed . ...
def remove_dirs ( self , directory ) : """Delete a directory recursively . : param directory : $ PATH to directory . : type directory : ` ` str ` `"""
LOG . info ( 'Removing directory [ %s ]' , directory ) local_files = self . _drectory_local_files ( directory = directory ) for file_name in local_files : try : os . remove ( file_name [ 'local_object' ] ) except OSError as exp : LOG . error ( str ( exp ) ) # Build a list of all local directorie...
def getAsKmlPng ( self , session , path = None , documentName = None , colorRamp = ColorRampEnum . COLOR_RAMP_HUE , alpha = 1.0 , noDataValue = None , drawOrder = 0 , cellSize = None , resampleMethod = 'NearestNeighbour' ) : """Retrieve the raster as a PNG image ground overlay KML format . Coarse grid resolutions m...
if type ( self . raster ) != type ( None ) : # Set Document Name if documentName is None : try : documentName = self . filename except AttributeError : documentName = 'default' # Set no data value to default if noDataValue is None : noDataValue = self . defaul...
def plotit ( self , x , y , fields , colors = [ ] ) : '''plot a set of graphs using date for x axis'''
pylab . ion ( ) fig = pylab . figure ( num = 1 , figsize = ( 12 , 6 ) ) ax1 = fig . gca ( ) ax2 = None xrange = 0.0 for i in range ( 0 , len ( fields ) ) : if len ( x [ i ] ) == 0 : continue if self . lowest_x is None or x [ i ] [ 0 ] < self . lowest_x : self . lowest_x = x [ i ] [ 0 ] if se...
def get_cheapest_price_by_route ( self , ** params ) : """{ API _ HOST } / apiservices / browseroutes / v1.0 / { market } / { currency } / { locale } / { originPlace } / { destinationPlace } / { outboundPartialDate } / { inboundPartialDate } ? apiKey = { apiKey }"""
service_url = "{url}/{params_path}" . format ( url = self . BROWSE_ROUTES_SERVICE_URL , params_path = self . _construct_params ( params , self . _REQ_PARAMS , self . _OPT_PARAMS ) ) return self . make_request ( service_url , headers = self . _headers ( ) , ** params )
def ban_member_from_group ( self , group_jid , peer_jid ) : """Bans a member from the group : param group _ jid : The JID of the relevant group : param peer _ jid : The JID of the user to ban"""
log . info ( "[+] Requesting ban of user {} from group {}" . format ( peer_jid , group_jid ) ) return self . _send_xmpp_element ( group_adminship . BanMemberRequest ( group_jid , peer_jid ) )
def build_napalm_ansible_module_docs ( app ) : """Create documentation for Ansible modules ."""
# Add script to clone napalm - ansible repo status = subprocess . call ( "./build-ansible-module-docs.sh" , stdout = sys . stdout , stderr = sys . stderr ) if status != 0 : print ( "Something bad happened when processing the Ansible modules." ) sys . exit ( - 1 ) env = Environment ( loader = FileSystemLoader ( ...
def cVectorToPython ( x ) : """Convert the c vector data into the correct python data type ( numpy arrays or strings ) : param x : : return :"""
if isinstance ( x [ 0 ] , bool ) : return numpy . frombuffer ( x , dtype = numpy . bool ) . copy ( ) elif isinstance ( x [ 0 ] , int ) : return numpy . frombuffer ( x , dtype = numpy . int32 ) . copy ( ) elif isinstance ( x [ 0 ] , float ) : return numpy . frombuffer ( x , dtype = numpy . float64 ) . copy (...
def extend ( self , polymer ) : """Extends the ` Polymer ` with the contents of another ` Polymer ` . Notes Does not update labelling ."""
if isinstance ( polymer , Polymer ) : self . _monomers . extend ( polymer ) else : raise TypeError ( 'Only Polymer objects may be merged with a Polymer using unary operator "+".' ) return
def main ( ) : '''Base58 encode or decode FILE , or standard input , to standard output .'''
import sys import argparse stdout = buffer ( sys . stdout ) parser = argparse . ArgumentParser ( description = main . __doc__ ) parser . add_argument ( 'file' , metavar = 'FILE' , nargs = '?' , type = argparse . FileType ( 'r' ) , default = '-' ) parser . add_argument ( '-d' , '--decode' , action = 'store_true' , help ...
def idle_task ( self ) : '''run periodic tasks'''
now = time . time ( ) if now - self . last_chan_check >= 1 : self . last_chan_check = now self . update_channels ( )
def left_indent ( text , indent = 12 , end = '\n' ) : '''A bit of the ol ' ultraviolence : - /'''
indent = ' ' * indent lines = [ indent + line for line in text . splitlines ( True ) ] lines . append ( end ) return '' . join ( lines )
def set_time ( self , key_name , new_time ) : """Sets the time of key ."""
self . unbake ( ) kf = self . dct [ key_name ] kf [ 'time' ] = new_time self . bake ( )
def skewness ( x ) : """Returns the sample skewness of x ( calculated with the adjusted Fisher - Pearson standardized moment coefficient G1 ) . : param x : the time series to calculate the feature of : type x : numpy . ndarray : return : the value of this feature : return type : float"""
if not isinstance ( x , pd . Series ) : x = pd . Series ( x ) return pd . Series . skew ( x )
def configure ( username , password , domain ) : """Initial configuration . Used to specify your username , password and domain . Configuration is stored in ~ / . accountable / config . yaml ."""
art = r''' Welcome! __ ___. .__ _____ ____ ____ ____ __ __ _____/ |______ \_ |__ | | ____ \__ \ _/ ___\/ ___\/ _ \| | \/ \ __\__ \ | __ \| | _/ __ \ / __ \\ \__\ \__( <_> ) | / | \ | / __ \| \_\ \ |_\ ___/ (____ /\___ >___ >____/|____/|___| ...