signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def orientality ( obj , sun ) : """Returns if an object is oriental or occidental to the sun ."""
dist = angle . distance ( sun . lon , obj . lon ) return OCCIDENTAL if dist < 180 else ORIENTAL
def substitute_minor_for_major ( progression , substitute_index , ignore_suffix = False ) : """Substitute minor chords for its major equivalent . ' m ' and ' m7 ' suffixes recognized , and [ ' II ' , ' III ' , ' VI ' ] if there is no suffix . Examples : > > > substitute _ minor _ for _ major ( [ ' VI ' ] , ...
( roman , acc , suff ) = parse_string ( progression [ substitute_index ] ) res = [ ] # Minor to major substitution if suff == 'm' or suff == 'm7' or suff == '' and roman in [ 'II' , 'III' , 'VI' ] or ignore_suffix : n = skip ( roman , 2 ) a = interval_diff ( roman , n , 3 ) + acc if suff == 'm' or ignore_su...
def groupby_field ( records , field_name , skip_none = True ) : """Given a list of objects , group them into a dictionary by the unique values of a given field name ."""
return apply_groupby ( records , lambda obj : getattr ( obj , field_name ) , skip_none = skip_none )
def get_policies_from_git ( self ) : """Retrieve policies from the Git repo . Returns a dictionary containing all the roles and policies Returns : : obj : ` dict ` of ` str ` : ` dict `"""
fldr = mkdtemp ( ) try : url = 'https://{token}:x-oauth-basic@{server}/{repo}' . format ( ** { 'token' : self . dbconfig . get ( 'git_auth_token' , self . ns ) , 'server' : self . dbconfig . get ( 'git_server' , self . ns ) , 'repo' : self . dbconfig . get ( 'git_repo' , self . ns ) } ) policies = { 'GLOBAL' : ...
def _fix_genotypes_object ( self , genotypes , variant_info ) : """Fixes a genotypes object ( variant name , multi - allelic value ."""
# Checking the name ( if there were duplications ) if self . has_index and variant_info . name != genotypes . variant . name : if not variant_info . name . startswith ( genotypes . variant . name ) : raise ValueError ( "Index file not synced with IMPUTE2 file" ) genotypes . variant . name = variant_info...
def discard_saved_state ( self , f_remove_file ) : """Forcibly resets the machine to " Powered Off " state if it is currently in the " Saved " state ( previously created by : py : func : ` save _ state ` ) . Next time the machine is powered up , a clean boot will occur . This operation is equivalent to resett...
if not isinstance ( f_remove_file , bool ) : raise TypeError ( "f_remove_file can only be an instance of type bool" ) self . _call ( "discardSavedState" , in_p = [ f_remove_file ] )
def get_min_distance ( element ) : """Gets the minimum sampling distance of the x - and y - coordinates in a grid ."""
try : from scipy . spatial . distance import pdist return pdist ( element . array ( [ 0 , 1 ] ) ) . min ( ) except : return _get_min_distance_numpy ( element )
def apply_tile_groups ( self , tile_groups ) : """Increase mana , xp , money , anvils and scrolls based on tile groups ."""
self_increase_types = ( 'r' , 'g' , 'b' , 'y' , 'x' , 'm' , 'h' , 'c' ) attack_types = ( 's' , '*' ) total_attack = 0 for tile_group in tile_groups : group_type = None type_count = 0 type_multiplier = 1 for tile in tile_group : # try to get the group type if not group_type : # try to set the gro...
def get_related_node ( self , node , relation ) : """Looks for an edge from node to some other node , such that the edge is annotated with the given relation . If there exists such an edge , returns the name of the node it points to . Otherwise , returns None ."""
G = self . G for edge in G . edges ( node ) : to = edge [ 1 ] to_relation = G . edges [ node , to ] [ 'relation' ] if to_relation == relation : return to return None
def get_ntlm2_response ( password , server_challenge , client_challenge ) : """Generate the Unicode MD4 hash for the password associated with these credentials ."""
md5 = hashlib . new ( 'md5' ) md5 . update ( server_challenge + client_challenge ) ntlm2_session_hash = md5 . digest ( ) [ : 8 ] ntlm_hash = PasswordAuthentication . ntowfv1 ( password . encode ( 'utf-16le' ) ) response = PasswordAuthentication . _encrypt_des_block ( ntlm_hash [ : 7 ] , ntlm2_session_hash ) response +=...
def nic_add ( self , container , nic ) : """Hot plug a nic into a container : param container : container ID : param nic : { ' type ' : nic _ type # one of default , bridge , zerotier , macvlan , passthrough , vlan , or vxlan ( note , vlan and vxlan only supported by ovs ) ' id ' : id # depends on the type ...
args = { 'container' : container , 'nic' : nic } self . _nic_add . check ( args ) return self . _client . json ( 'corex.nic-add' , args )
def read_moc_fits_hdu ( moc , hdu , include_meta = False ) : """Read data from a FITS table HDU into a MOC ."""
if include_meta : header = hdu . header if 'MOCTYPE' in header : moc . type = header [ 'MOCTYPE' ] if 'MOCID' in header : moc . id = header [ 'MOCID' ] if 'ORIGIN' in header : moc . origin = header [ 'ORIGIN' ] if 'EXTNAME' in header : moc . name = header [ 'EXTNAME' ...
def rouge ( hypotheses , references ) : """Calculates average rouge scores for a list of hypotheses and references"""
# Filter out hyps that are of 0 length # hyps _ and _ refs = zip ( hypotheses , references ) # hyps _ and _ refs = [ _ for _ in hyps _ and _ refs if len ( _ [ 0 ] ) > 0] # hypotheses , references = zip ( * hyps _ and _ refs ) # Calculate ROUGE - 1 F1 , precision , recall scores rouge_1 = [ rouge_n ( [ hyp ] , [ ref ] ,...
def ic45 ( msg ) : """Icing . Args : msg ( String ) : 28 bytes hexadecimal message string Returns : int : Icing level . 0 = NIL , 1 = Light , 2 = Moderate , 3 = Severe"""
d = hex2bin ( data ( msg ) ) if d [ 9 ] == '0' : return None ic = bin2int ( d [ 10 : 12 ] ) return ic
def import_process_element ( process_elements_dict , process_element ) : """Adds attributes of BPMN process element to appropriate field process _ attributes . Diagram inner representation contains following process attributes : - id - assumed to be required in XML file , even thought BPMN 2.0 schema doesn ' t ...
process_id = process_element . getAttribute ( consts . Consts . id ) process_element_attributes = { consts . Consts . id : process_element . getAttribute ( consts . Consts . id ) , consts . Consts . name : process_element . getAttribute ( consts . Consts . name ) if process_element . hasAttribute ( consts . Consts . na...
def focusPrev ( self , event ) : """Set focus to previous item in sequence"""
try : event . widget . tk_focusPrev ( ) . focus_set ( ) except TypeError : # see tkinter equivalent code for tk _ focusPrev to see # commented original version name = event . widget . tk . call ( 'tk_focusPrev' , event . widget . _w ) event . widget . _nametowidget ( str ( name ) ) . focus_set ( )
def prefer_master ( nodes : List [ DiscoveredNode ] ) -> Optional [ DiscoveredNode ] : """Select the master if available , otherwise fall back to a replica ."""
return max ( nodes , key = attrgetter ( "state" ) )
def match_sr ( self , svc_ref , cid = None ) : # type : ( ServiceReference , Optional [ Tuple [ str , str ] ] ) - > bool """Checks if this export registration matches the given service reference : param svc _ ref : A service reference : param cid : A container ID : return : True if the service matches this ex...
with self . __lock : our_sr = self . get_reference ( ) if our_sr is None : return False sr_compare = our_sr == svc_ref if cid is None : return sr_compare our_cid = self . get_export_container_id ( ) if our_cid is None : return False return sr_compare and our_cid == ci...
def dot_product ( t1 , t2 , keep_dims = False , name = None , reduction_dim = None ) : """Computes the dot product of t1 and t2. Args : t1 : A rank 2 tensor . t2 : A tensor that is the same size as t1. keep _ dims : If true , reduction does not change the rank of the input . name : Optional name for this ...
with tf . name_scope ( name , 'dot' , [ t1 , t2 ] ) as scope : t1 = tf . convert_to_tensor ( t1 , name = 't1' ) t2 = tf . convert_to_tensor ( t2 , name = 't2' ) mul = tf . multiply ( t1 , t2 ) if not reduction_dim : reduction_dim = _last_index ( mul , 1 ) return tf . reduce_sum ( mul , reduc...
def dtypes_summary ( df ) : """Takes in a dataframe and returns a dataframe with information on the data - types present in each column . Parameters : df - DataFrame Dataframe to summarize"""
output_df = pd . DataFrame ( [ ] ) row_count = df . shape [ 0 ] row_indexes = [ 'rows_numerical' , 'rows_string' , 'rows_date_time' , 'category_count' , 'largest_category' , 'rows_na' , 'rows_total' ] for colname in df : data = df [ colname ] # data is the pandas series associated with this column # number ...
def find_rdataset ( self , rdclass , rdtype , covers = dns . rdatatype . NONE , create = False ) : """Find an rdataset matching the specified properties in the current node . @ param rdclass : The class of the rdataset @ type rdclass : int @ param rdtype : The type of the rdataset @ type rdtype : int @ ...
for rds in self . rdatasets : if rds . match ( rdclass , rdtype , covers ) : return rds if not create : raise KeyError rds = dns . rdataset . Rdataset ( rdclass , rdtype ) self . rdatasets . append ( rds ) return rds
def search_artists_by_name ( self , artist_name : str , limit : int = 5 ) -> List [ NameExternalIDPair ] : """Returns zero or more artist name - external ID pairs that match the specified artist name . Arguments : artist _ name ( str ) : The artist name to search in the Spotify API . limit ( int ) : The maxim...
response : requests . Response = requests . get ( self . _API_URL_TEMPLATE . format ( "search" ) , params = { "q" : artist_name , "type" : "artist" , "limit" : limit } , headers = { "Authorization" : "Bearer {}" . format ( self . _token . access_token ) } ) # TODO : handle API rate limiting response . raise_for_status ...
def match ( self , source_obj_features , target_obj_features ) : """Matches features between two graspable objects based on a full distance matrix . Parameters source _ obj _ features : : obj : ` BagOfFeatures ` bag of the source objects features target _ obj _ features : : obj : ` BagOfFeatures ` bag of ...
if not isinstance ( source_obj_features , f . BagOfFeatures ) : raise ValueError ( 'Must supply source bag of object features' ) if not isinstance ( target_obj_features , f . BagOfFeatures ) : raise ValueError ( 'Must supply target bag of object features' ) # source feature descriptors and keypoints source_desc...
def fits_recarray_to_dict ( table ) : """Convert a FITS recarray to a python dictionary ."""
cols = { } for icol , col in enumerate ( table . columns . names ) : col_data = table . data [ col ] if type ( col_data [ 0 ] ) == np . float32 : cols [ col ] = np . array ( col_data , dtype = float ) elif type ( col_data [ 0 ] ) == np . float64 : cols [ col ] = np . array ( col_data , dtype...
def list_kinesis_applications ( region , filter_by_kwargs ) : """List all the kinesis applications along with the shards for each stream"""
conn = boto . kinesis . connect_to_region ( region ) streams = conn . list_streams ( ) [ 'StreamNames' ] kinesis_streams = { } for stream_name in streams : shard_ids = [ ] shards = conn . describe_stream ( stream_name ) [ 'StreamDescription' ] [ 'Shards' ] for shard in shards : shard_ids . append ( ...
def _set_counts_state ( self , v , load = False ) : """Setter method for counts _ state , mapped from YANG variable / counts _ state ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ counts _ state is considered as a private method . Backends looking to po...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = counts_state . counts_state , is_container = 'container' , presence = False , yang_name = "counts-state" , rest_name = "counts-state" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , reg...
def get_model_class ( klass , api = None , use_request_api = True ) : """Generates the Model Class based on the klass loads automatically the corresponding json schema file form schemes folder : param klass : json schema filename : param use _ request _ api : if True autoinitializes request class if api is No...
if api is None and use_request_api : api = APIClient ( ) _type = klass if isinstance ( klass , dict ) : _type = klass [ 'type' ] schema = loaders . load_schema_raw ( _type ) model_cls = model_factory ( schema , base_class = RemoteResource ) model_cls . __api__ = api return model_cls
def checkIsMember ( self , CorpNum ) : """회원가입여부 확인 args CorpNum : 회원 사업자번호 return 회원가입여부 True / False raise PopbillException"""
if CorpNum == None or CorpNum == '' : raise PopbillException ( - 99999999 , "사업자번호가 입력되지 않았습니다." ) return self . _httpget ( '/Join?CorpNum=' + CorpNum + '&LID=' + self . __linkID , None , None )
def websafe_dither ( self ) : """Return the two websafe colors nearest to this one . Returns : A tuple of two grapefruit . Color instances which are the two web safe colors closest this one . > > > c = Color . from _ rgb ( 1.0 , 0.45 , 0.0) > > > c1 , c2 = c . websafe _ dither ( ) > > > c1 Color ( 1.0...
return ( Color ( rgb_to_websafe ( * self . __rgb ) , 'rgb' , self . __a , self . __wref ) , Color ( rgb_to_websafe ( alt = True , * self . __rgb ) , 'rgb' , self . __a , self . __wref ) )
def parse_query ( self , query ) : """Creates a tinydb Query ( ) object from the query dict : param query : object containing the dictionary representation of the query : return : composite Query ( )"""
logger . debug ( u'query to parse2: {}' . format ( query ) ) # this should find all records if query == { } or query is None : return Query ( ) . _id != u'-1' # noqa q = None # find the final result of the generator for c in self . parse_condition ( query ) : if q is None : q = c else : q = ...
def stack_nll ( shape , components , ylims , weights = None ) : """Combine the log - likelihoods from a number of components . Parameters shape : tuple The shape of the return array components : ` ~ fermipy . castro . CastroData _ Base ` The components to be stacked weights : array - like Returns no...
n_bins = shape [ 0 ] n_vals = shape [ 1 ] if weights is None : weights = np . ones ( ( len ( components ) ) ) norm_vals = np . zeros ( shape ) nll_vals = np . zeros ( shape ) nll_offsets = np . zeros ( ( n_bins ) ) for i in range ( n_bins ) : log_min = np . log10 ( ylims [ 0 ] ) log_max = np . log10 ( ylims...
def main ( ) : """process the main task"""
args = get_args ( ) args . start = date_parser . parse ( args . start ) args . end = date_parser . parse ( args . end ) args . step = timedelta ( args . step ) config = Config ( args . config ) times = [ args . start + i * args . step for i in range ( int ( ( args . end - args . start ) / args . step ) ) ] for i , time...
def entropy_of_contacts ( records , normalize = False ) : """The entropy of the user ' s contacts . Parameters normalize : boolean , default is False Returns a normalized entropy between 0 and 1."""
counter = Counter ( r . correspondent_id for r in records ) raw_entropy = entropy ( counter . values ( ) ) n = len ( counter ) if normalize and n > 1 : return raw_entropy / math . log ( n ) else : return raw_entropy
def get_command_from_module ( command_module , remote_connection : environ . RemoteConnection ) : """Returns the execution command to use for the specified module , which may be different depending upon remote connection : param command _ module : : param remote _ connection : : return :"""
use_remote = ( remote_connection . active and hasattr ( command_module , 'execute_remote' ) ) return ( command_module . execute_remote if use_remote else command_module . execute )
def AuthorizeUser ( self , user , subject ) : """Allow given user access to a given subject ."""
user_set = self . authorized_users . setdefault ( subject , set ( ) ) user_set . add ( user )
def aug_sysargv ( cmdstr ) : """DEBUG FUNC modify argv to look like you ran a command"""
import shlex argv = shlex . split ( cmdstr ) sys . argv . extend ( argv )
def filter_out_empty_lists ( input_list ) : """Function to remove all empty lists from a given list of lists . Args : input _ list ( List ) : A list possibly containing empty lists alongside other items . Returns : List : A list containing only non - empty items from the input list . Examples : > > > fi...
filtered_list = [ element for element in input_list if element ] return filtered_list
def Spearman ( poly , dist , sample = 10000 , retall = False , ** kws ) : """Calculate Spearman ' s rank - order correlation coefficient . Args : poly ( Poly ) : Polynomial of interest . dist ( Dist ) : Defines the space where correlation is taken . sample ( int ) : Number of samples used in estimatio...
samples = dist . sample ( sample , ** kws ) poly = polynomials . flatten ( poly ) Y = poly ( * samples ) if retall : return spearmanr ( Y . T ) return spearmanr ( Y . T ) [ 0 ]
def extend ( self , clauses , weights = None ) : """Add several clauses to WCNF formula . The clauses should be given in the form of list . For every clause in the list , method : meth : ` append ` is invoked . The clauses can be hard or soft depending on the ` ` weights ` ` argument . If no weights are set...
if weights : # clauses are soft for i , cl in enumerate ( clauses ) : self . append ( cl , weight = weights [ i ] ) else : # clauses are hard for cl in clauses : self . append ( cl )
def get_incremental_uncovered_lines ( abs_path : str , base_commit : str , actual_commit : Optional [ str ] ) -> List [ Tuple [ int , str , str ] ] : """Uses git diff and the annotation files created by ` pytest - - cov - report annotate ` to find touched but uncovered lines in the given file . Args : abs _...
# Deleted files don ' t have any lines that need to be covered . if not os . path . isfile ( abs_path ) : return [ ] unified_diff_lines_str = shell_tools . output_of ( 'git' , 'diff' , '--unified=0' , base_commit , actual_commit , '--' , abs_path ) unified_diff_lines = [ e for e in unified_diff_lines_str . split ( ...
def send ( self , message ) : """Make a Twilio SendGrid v3 API request with the request body generated by the Mail object : param message : The Twilio SendGrid v3 API request body generated by the Mail object : type message : Mail"""
if isinstance ( message , dict ) : response = self . client . mail . send . post ( request_body = message ) else : response = self . client . mail . send . post ( request_body = message . get ( ) ) return response
def nonrepeats ( inlist ) : """Returns items that are NOT duplicated in the first dim of the passed list . Usage : nonrepeats ( inlist )"""
nonrepeats = [ ] for i in range ( len ( inlist ) ) : if inlist . count ( inlist [ i ] ) == 1 : nonrepeats . append ( inlist [ i ] ) return nonrepeats
def close ( self ) : """Close the connection and all associated cursors . This will implicitly roll back any uncommitted operations ."""
for c in self . cursors : c . close ( ) self . cursors = [ ] self . impl = None
def check_format ( format , subtype = None , endian = None ) : """Check if the combination of format / subtype / endian is valid . Examples > > > import soundfile as sf > > > sf . check _ format ( ' WAV ' , ' PCM _ 24 ' ) True > > > sf . check _ format ( ' FLAC ' , ' VORBIS ' ) False"""
try : return bool ( _format_int ( format , subtype , endian ) ) except ( ValueError , TypeError ) : return False
def create_releasenotes ( project_dir = os . curdir , bugtracker_url = '' ) : """Creates the release notes file , if not in a package . Args : project _ dir ( str ) : Path to the git repo of the project . bugtracker _ url ( str ) : Url to the bug tracker for the issues . Returns : None Raises : Runtim...
pkg_info_file = os . path . join ( project_dir , 'PKG-INFO' ) if os . path . exists ( pkg_info_file ) : return with open ( 'RELEASE_NOTES' , 'wb' ) as releasenotes_fd : releasenotes_fd . write ( get_releasenotes ( project_dir = project_dir , bugtracker_url = bugtracker_url , ) . encode ( 'utf-8' ) + b'\n' )
def sortrows ( a , i = 0 , index_out = False , recurse = True ) : """Sorts array " a " by columns i Parameters a : np . ndarray array to be sorted i : int ( optional ) column to be sorted by , taken as 0 by default index _ out : bool ( optional ) return the index I such that a ( I ) = sortrows ( a , i...
I = np . argsort ( a [ : , i ] ) a = a [ I , : ] # We recursively call sortrows to make sure it is sorted best by every # column if recurse & ( len ( a [ 0 ] ) > i + 1 ) : for b in np . unique ( a [ : , i ] ) : ids = a [ : , i ] == b colids = range ( i ) + range ( i + 1 , len ( a [ 0 ] ) ) a...
def call ( self ) : """Make the API call again and fetch fresh data ."""
data = self . _downloader . download ( ) # Only try to pass errors arg if supported if sys . version >= "2.7" : data = data . decode ( "utf-8" , errors = "ignore" ) else : data = data . decode ( "utf-8" ) self . update ( json . loads ( data ) ) self . _fetched = True
def calculate_total ( d : dict ) -> int : """Function to compute the total of all values in the specified dictionary . Args : d ( dict ) : dictionary with values to be summed . Returns : int : the sum of all values in the dictionary . Examples : > > > calculate _ total ( { ' a ' : 100 , ' b ' : 200 , ' ...
total = sum ( d . values ( ) ) return total
def _check_for_legal_children ( self , name , elt , mustqualify = 1 ) : '''Check if all children of this node are elements or whitespace - only text nodes .'''
inheader = name == "Header" for n in _children ( elt ) : t = n . nodeType if t == _Node . COMMENT_NODE : continue if t != _Node . ELEMENT_NODE : if t == _Node . TEXT_NODE and n . nodeValue . strip ( ) == "" : continue raise ParseException ( "Non-element child in " + name ...
def _single_resource_json_response ( resource , depth = 0 ) : """Return the JSON representation of * resource * . : param resource : : class : ` sandman . model . Model ` to render : type resource : : class : ` sandman . model . Model ` : rtype : : class : ` flask . Response `"""
links = resource . links ( ) response = jsonify ( ** resource . as_dict ( depth ) ) response . headers [ 'Link' ] = '' for link in links : response . headers [ 'Link' ] += '<{}>; rel="{}",' . format ( link [ 'uri' ] , link [ 'rel' ] ) response . headers [ 'Link' ] = response . headers [ 'Link' ] [ : - 1 ] return re...
def time_delta_pusher ( please_stop , appender , queue , interval ) : """appender - THE FUNCTION THAT ACCEPTS A STRING queue - FILLED WITH LOG ENTRIES { " template " : template , " params " : params } TO WRITE interval - timedelta USE IN A THREAD TO BATCH LOGS BY TIME INTERVAL"""
next_run = time ( ) + interval while not please_stop : profiler = Thread . current ( ) . cprofiler profiler . disable ( ) ( Till ( till = next_run ) | please_stop ) . wait ( ) profiler . enable ( ) next_run = time ( ) + interval logs = queue . pop_all ( ) if not logs : continue l...
def get_instance ( self , payload ) : """Build an instance of NewKeyInstance : param dict payload : Payload response from the API : returns : twilio . rest . api . v2010 . account . new _ key . NewKeyInstance : rtype : twilio . rest . api . v2010 . account . new _ key . NewKeyInstance"""
return NewKeyInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , )
def autodiscover ( cls , module_paths : List [ str ] , subclass : 'Container' = None ) -> None : """Load all modules automatically and find bases and eggs . : param module _ paths : List of paths that should be discovered : param subclass : Optional Container subclass that should be used"""
def find_base ( bases : set , implementation : Type ) : found = { b for b in bases if issubclass ( implementation , b ) } if not found : raise ConfigurationError ( "No base defined for %r" % implementation ) elif len ( found ) > 1 : raise ConfigurationError ( "More than one base found for %r...
def _memory_profile ( with_gc = False ) : """Helper for memory debugging . Mostly just a namespace where I experiment with guppy and heapy . References : http : / / stackoverflow . com / questions / 2629680 / deciding - between - subprocess - multiprocessing - and - thread - in - python Reset Numpy Memory :...
import utool as ut if with_gc : garbage_collect ( ) import guppy hp = guppy . hpy ( ) print ( '[hpy] Waiting for heap output...' ) heap_output = hp . heap ( ) print ( heap_output ) print ( '[hpy] total heap size: ' + ut . byte_str2 ( heap_output . size ) ) ut . util_resources . memstats ( )
def get_properties ( obj ) : """Get values of all properties in specified object and returns them as a map . : param obj : an object to get properties from . : return : a map , containing the names of the object ' s properties and their values ."""
properties = { } for property_name in dir ( obj ) : property = getattr ( obj , property_name ) if PropertyReflector . _is_property ( property , property_name ) : properties [ property_name ] = property return properties
def get_source_by_name ( self , name ) : """Return a single source in the ROI with the given name . The input name string can match any of the strings in the names property of the source object . Case and whitespace are ignored when matching name strings . If no sources are found or multiple sources then an...
srcs = self . get_sources_by_name ( name ) if len ( srcs ) == 1 : return srcs [ 0 ] elif len ( srcs ) == 0 : raise Exception ( 'No source matching name: ' + name ) elif len ( srcs ) > 1 : raise Exception ( 'Multiple sources matching name: ' + name )
def send_complete ( self ) : """Verify if connection should be closed based on amount of data that was sent ."""
self . active = True if self . should_finish ( ) : self . _detach ( ) # Avoid race condition when waiting for write callback and session getting closed in between if not self . _finished : self . safe_finish ( ) else : if self . session : self . session . flush ( )
def peer_retrieve ( key , relation_name = 'cluster' ) : """Retrieve a named key from peer relation ` relation _ name ` ."""
cluster_rels = relation_ids ( relation_name ) if len ( cluster_rels ) > 0 : cluster_rid = cluster_rels [ 0 ] return relation_get ( attribute = key , rid = cluster_rid , unit = local_unit ( ) ) else : raise ValueError ( 'Unable to detect' 'peer relation {}' . format ( relation_name ) )
def load_module ( self , module , module_uri = None ) : """load _ module Attempts to load module by name , if it is not available , loads it by url"""
# Check to see that module isn ' t availble in python path try : import_module ( module ) except ImportError , e : if module_uri is None : raise e else : return module if not CACHE_DOWNLOADS : module_name = self . _unique_module_name ( module ) else : module_name = self . _sanitize_module_na...
def add_lifecycle_set_storage_class_rule ( self , storage_class , ** kw ) : """Add a " delete " rule to lifestyle rules configured for this bucket . See https : / / cloud . google . com / storage / docs / lifecycle and https : / / cloud . google . com / storage / docs / json _ api / v1 / buckets . . literalin...
rules = list ( self . lifecycle_rules ) rules . append ( LifecycleRuleSetStorageClass ( storage_class , ** kw ) ) self . lifecycle_rules = rules
def update ( self , permission ) : """In - place update of permissions ."""
self . needs . update ( permission . needs ) self . excludes . update ( permission . excludes )
def reset ( self ) : """Reset the statistics data for this object ."""
self . _count = 0 self . _exception_count = 0 self . _stat_start_time = None self . _time_sum = float ( 0 ) self . _time_min = float ( 'inf' ) self . _time_max = float ( 0 ) self . _server_time_sum = float ( 0 ) self . _server_time_min = float ( 'inf' ) self . _server_time_max = float ( 0 ) self . _server_time_stored =...
def _readData ( self , id3 , data ) : """Raises ID3JunkFrameError ; Returns leftover data"""
for reader in self . _framespec : if len ( data ) or reader . handle_nodata : try : value , data = reader . read ( id3 , self , data ) except SpecError as e : raise ID3JunkFrameError ( e ) else : raise ID3JunkFrameError ( "no data left" ) self . _setattr ( rea...
def find_resource_ids ( self ) : """Given a resource path and API Id , find resource Id ."""
all_resources = self . client . get_resources ( restApiId = self . api_id ) parent_id = None resource_id = None for resource in all_resources [ 'items' ] : if resource [ 'path' ] == "/" : parent_id = resource [ 'id' ] if resource [ 'path' ] == self . trigger_settings [ 'resource' ] : resource_id...
def set_page_artid ( self , page_start = None , page_end = None , artid = None ) : """Add artid , start , end pages to publication info of a reference . Args : page _ start ( Optional [ string ] ) : value for the field page _ start page _ end ( Optional [ string ] ) : value for the field page _ end artid ( ...
if page_end and not page_start : raise ValueError ( 'End_page provided without start_page' ) self . _ensure_reference_field ( 'publication_info' , { } ) publication_info = self . obj [ 'reference' ] [ 'publication_info' ] if page_start : publication_info [ 'page_start' ] = page_start if page_end : publicati...
def get_info ( cls ) : """Return information about backend and its availability . : return : A BackendInfo tuple if the import worked , none otherwise ."""
mod = try_import ( cls . mod_name ) if not mod : return None version = getattr ( mod , '__version__' , None ) or getattr ( mod , 'version' , None ) return BackendInfo ( version or 'deprecated' , '' )
def api ( name , version , description = None , hostname = None , audiences = None , scopes = None , allowed_client_ids = None , canonical_name = None , auth = None , owner_domain = None , owner_name = None , package_path = None , frontend_limits = None , title = None , documentation = None , auth_level = None , issuer...
if auth_level is not None : _logger . warn ( _AUTH_LEVEL_WARNING ) return _ApiDecorator ( name , version , description = description , hostname = hostname , audiences = audiences , scopes = scopes , allowed_client_ids = allowed_client_ids , canonical_name = canonical_name , auth = auth , owner_domain = owner_domain...
def convert_obatoms_to_molecule ( self , atoms , residue_name = None , site_property = "ff_map" ) : """Convert list of openbabel atoms to MOlecule . Args : atoms ( [ OBAtom ] ) : list of OBAtom objects residue _ name ( str ) : the key in self . map _ residue _ to _ mol . Usec to restore the site properties ...
restore_site_props = True if residue_name is not None else False if restore_site_props and not hasattr ( self , "map_residue_to_mol" ) : self . _set_residue_map ( ) coords = [ ] zs = [ ] for atm in atoms : coords . append ( list ( atm . coords ) ) zs . append ( atm . atomicnum ) mol = Molecule ( zs , coords...
def _decode_addr_key ( self , obj_dict ) : """Callback function to handle the decoding of the ' Addr ' field . Serf msgpack ' Addr ' as an IPv6 address , and the data needs to be unpack using socket . inet _ ntop ( ) . See : https : / / github . com / KushalP / serfclient - py / issues / 20 : param obj _ di...
key = b'Addr' if key in obj_dict : try : # Try to convert a packed IPv6 address . # Note : Call raises ValueError if address is actually IPv4. ip_addr = socket . inet_ntop ( socket . AF_INET6 , obj_dict [ key ] ) # Check if the address is an IPv4 mapped IPv6 address : # ie . : : ffff : x...
def batch ( iterable , n , fillvalue = None ) : """Batches the elements of given iterable . Resulting iterable will yield tuples containing at most ` ` n ` ` elements ( might be less if ` ` fillvalue ` ` isn ' t specified ) . : param n : Number of items in every batch : param fillvalue : Value to fill the l...
ensure_iterable ( iterable ) if not isinstance ( n , Integral ) : raise TypeError ( "invalid number of elements in a batch" ) if not ( n > 0 ) : raise ValueError ( "number of elements in a batch must be positive" ) # since we must use ` ` izip _ longest ` ` # ( ` ` izip ` ` fails if ` ` n ` ` is greater than le...
def _create_figure ( self ) : """Create Matplotlib figure and axes"""
# Good for development if get_option ( 'close_all_figures' ) : plt . close ( 'all' ) figure = plt . figure ( ) axs = self . facet . make_axes ( figure , self . layout . layout , self . coordinates ) # Dictionary to collect matplotlib objects that will # be targeted for theming by the themeables figure . _themeable ...
def ARPLimitExceeded_originator_switch_info_switchVcsId ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) ARPLimitExceeded = ET . SubElement ( config , "ARPLimitExceeded" , xmlns = "http://brocade.com/ns/brocade-notification-stream" ) originator_switch_info = ET . SubElement ( ARPLimitExceeded , "originator-switch-info" ) switchVcsId = ET . SubElement ( originator_switch_info , "switchVcs...
def process_event ( self , event , hover_focus ) : """Process any input event . : param event : The event that was triggered . : param hover _ focus : Whether to trigger focus change on mouse moves . : returns : None if the Effect processed the event , else the original event ."""
# Check whether this Layout is read - only - i . e . has no active focus . if self . _live_col < 0 or self . _live_widget < 0 : # Might just be that we ' ve unset the focus - so check we can ' t find a focus . self . _find_next_widget ( 1 ) if self . _live_col < 0 or self . _live_widget < 0 : return eve...
def _add_to_publish_stack ( self , exchange , routing_key , message , properties ) : """Temporarily add the message to the stack to publish to RabbitMQ : param str exchange : The exchange to publish to : param str routing _ key : The routing key to publish with : param str message : The message body : param...
global message_stack message_stack . append ( ( exchange , routing_key , message , properties ) )
def uses_na_format ( station : str ) -> bool : """Returns True if the station uses the North American format , False if the International format"""
if station [ 0 ] in NA_REGIONS : return True if station [ 0 ] in IN_REGIONS : return False if station [ : 2 ] in M_NA_REGIONS : return True if station [ : 2 ] in M_IN_REGIONS : return False raise BadStation ( "Station doesn't start with a recognized character set" )
def write_functions ( self ) : '''Writes out a python function for each WDL " task " object . : return : a giant string containing the meat of the job defs .'''
# toil cannot technically start with multiple jobs , so an empty # ' initialize _ jobs ' function is always called first to get around this fn_section = 'def initialize_jobs(job):\n' + ' job.fileStore.logToMaster("initialize_jobs")\n' for job in self . tasks_dictionary : fn_section += self . write_function ( job...
def get_assessment_results_session ( self , proxy ) : """Gets an ` ` AssessmentResultsSession ` ` to retrieve assessment results . arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . assessment . AssessmentResultsSession ) - an assessment results session for this service raise : NullArgument - ...
if not self . supports_assessment_results ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . AssessmentResultsSession ( proxy = proxy , runtime = self . _runtime )
def _silence ( ) : """A context manager that silences sys . stdout and sys . stderr ."""
old_stdout = sys . stdout old_stderr = sys . stderr sys . stdout = _DummyFile ( ) sys . stderr = _DummyFile ( ) exception_occurred = False try : yield except : exception_occurred = True # Go ahead and clean up so that exception handling can work normally sys . stdout = old_stdout sys . stderr = old_...
def save_to_filename ( self , file_name , sep = '\n' ) : """Read all messages from the queue and persist them to local file . Messages are written to the file and the ' sep ' string is written in between messages . Messages are deleted from the queue after being written to the file . Returns the number of m...
fp = open ( file_name , 'wb' ) n = self . save_to_file ( fp , sep ) fp . close ( ) return n
def add_filter ( self , component , filter_group = "pyxley-filter" ) : """Add a filter to the layout ."""
if getattr ( component , "name" ) != "Filter" : raise Exception ( "Component is not an instance of Filter" ) if filter_group not in self . filters : self . filters [ filter_group ] = [ ] self . filters [ filter_group ] . append ( component )
def tile_read ( source , bounds , tilesize , ** kwargs ) : """Read data and mask . Attributes source : str or rasterio . io . DatasetReader input file path or rasterio . io . DatasetReader object bounds : list Mercator tile bounds ( left , bottom , right , top ) tilesize : int Output image size kwar...
if isinstance ( source , DatasetReader ) : return _tile_read ( source , bounds , tilesize , ** kwargs ) else : with rasterio . open ( source ) as src_dst : return _tile_read ( src_dst , bounds , tilesize , ** kwargs )
def user_find_by_user_string ( self , username , start = 0 , limit = 50 , include_inactive_users = False , include_active_users = True ) : """Fuzzy search using username and display name : param username : Use ' . ' to find all users : param start : OPTIONAL : The start point of the collection to return . Defau...
url = 'rest/api/2/user/search' url += "?username={username}&includeActive={include_active}&includeInactive={include_inactive}&startAt={start}&maxResults={limit}" . format ( username = username , include_inactive = include_inactive_users , include_active = include_active_users , start = start , limit = limit ) return se...
def send_report ( report , config ) : """Sends the report to IOpipe ' s collector . : param report : The report to be sent . : param config : The IOpipe agent configuration ."""
headers = { "Authorization" : "Bearer {}" . format ( config [ "token" ] ) } url = "https://{host}{path}" . format ( ** config ) try : response = session . post ( url , json = report , headers = headers , timeout = config [ "network_timeout" ] ) response . raise_for_status ( ) except Exception as e : logger ...
def date_0utc ( date ) : """Get the 0 UTC date for a date Parameters date : ee . Date Returns ee . Date"""
return ee . Date . fromYMD ( date . get ( 'year' ) , date . get ( 'month' ) , date . get ( 'day' ) )
def cigar_to_seq ( a , gap = '*' ) : """Accepts a pysam row . cigar alignment is presented as a list of tuples ( operation , length ) . For example , the tuple [ ( 0,3 ) , ( 1,5 ) , ( 0,2 ) ] refers to an alignment with 3 matches , 5 insertions and another 2 matches . Op BAM Description M 0 alignment matc...
seq , cigar = a . seq , a . cigar start = 0 subseqs = [ ] npadded = 0 if cigar is None : return None , npadded for operation , length in cigar : end = start if operation == 2 else start + length if operation == 0 : # match subseq = seq [ start : end ] elif operation == 1 : # insertion su...
def get_atom ( value ) : """atom = [ CFWS ] 1 * atext [ CFWS ]"""
atom = Atom ( ) if value and value [ 0 ] in CFWS_LEADER : token , value = get_cfws ( value ) atom . append ( token ) if value and value [ 0 ] in ATOM_ENDS : raise errors . HeaderParseError ( "expected atom but found '{}'" . format ( value ) ) token , value = get_atext ( value ) atom . append ( token ) if va...
def chempot_plot_addons ( self , plt , xrange , ref_el , axes , pad = 2.4 , rect = [ - 0.047 , 0 , 0.84 , 1 ] , ylim = [ ] ) : """Helper function to a chempot plot look nicer . Args : plt ( Plot ) Plot to add things to . xrange ( list ) : xlim parameter ref _ el ( str ) : Element of the referenced chempot ....
# Make the figure look nice plt . legend ( bbox_to_anchor = ( 1.01 , 1 ) , loc = 2 , borderaxespad = 0. ) axes . set_xlabel ( r"Chemical potential $\Delta\mu_{%s}$ (eV)" % ( ref_el ) ) ylim = ylim if ylim else axes . get_ylim ( ) plt . xticks ( rotation = 60 ) plt . ylim ( ylim ) xlim = axes . get_xlim ( ) plt . xlim (...
def concatmap ( source , func , * more_sources , task_limit = None ) : """Apply a given function that creates a sequence from the elements of one or several asynchronous sequences , and generate the elements of the created sequences in order . The function is applied as described in ` map ` , and must return ...
return concat . raw ( combine . smap . raw ( source , func , * more_sources ) , task_limit = task_limit )
def build ( tagname_or_element , ns_uri = None , adapter = None ) : """Return a : class : ` ~ xml4h . builder . Builder ` that represents an element in a new or existing XML DOM and provides " chainable " methods focussed specifically on adding XML content . : param tagname _ or _ element : a string name for ...
if adapter is None : adapter = best_adapter if isinstance ( tagname_or_element , basestring ) : doc = adapter . create_document ( tagname_or_element , ns_uri = ns_uri ) element = doc . root elif isinstance ( tagname_or_element , xml4h . nodes . Element ) : element = tagname_or_element else : raise x...
def get_unique_sample_files ( file_samples ) : """Filter file _ sample data frame to only keep one file per sample . Params file _ samples : ` pandas . DataFrame ` A data frame containing a mapping between file IDs and sample barcodes . This type of data frame is returned by : meth : ` get _ file _ samples ...
assert isinstance ( file_samples , pd . DataFrame ) df = file_samples # use shorter variable name # sort data frame by file ID df = df . sort_values ( 'file_id' ) # - some samples have multiple files with the same barcode , # corresponding to different aliquots # get rid of those duplicates logger . info ( 'Original nu...
def quickVisual ( G , showLabel = False ) : """Just makes a simple _ matplotlib _ figure and displays it , with each node coloured by its type . You can add labels with _ showLabel _ . This looks a bit nicer than the one provided my _ networkx _ ' s defaults . # Parameters _ showLabel _ : ` optional [ bool ] ` ...
colours = "brcmykwg" f = plt . figure ( 1 ) ax = f . add_subplot ( 1 , 1 , 1 ) ndTypes = [ ] ndColours = [ ] layout = nx . spring_layout ( G , k = 4 / math . sqrt ( len ( G . nodes ( ) ) ) ) for nd in G . nodes ( data = True ) : if 'type' in nd [ 1 ] : if nd [ 1 ] [ 'type' ] not in ndTypes : ndT...
def almost_equal ( self , mat2 , places = 7 ) : """Return True if the values in mat2 equal the values in this matrix ."""
if not hasattr ( mat2 , "data" ) : return False for i in range ( 4 ) : if not ( _float_almost_equal ( self . data [ i ] [ 0 ] , mat2 . data [ i ] [ 0 ] , places ) and _float_almost_equal ( self . data [ i ] [ 1 ] , mat2 . data [ i ] [ 1 ] , places ) and _float_almost_equal ( self . data [ i ] [ 2 ] , mat2 . dat...
def run ( self ) : """Perform phantomas run"""
self . _logger . info ( "running for <{url}>" . format ( url = self . _url ) ) args = format_args ( self . _options ) self . _logger . debug ( "command: `{cmd}` / args: {args}" . format ( cmd = self . _cmd , args = args ) ) # run the process try : process = Popen ( args = [ self . _cmd ] + args , stdin = PIPE , std...
def get_file_download ( self , file_id ) : """Get a file download object that contains temporary url settings needed to download the contents of a file . : param file _ id : str : uuid of the file : return : FileDownload"""
return self . _create_item_response ( self . data_service . get_file_url ( file_id ) , FileDownload )
def instantiate_object_id_field ( object_id_class_or_tuple = models . TextField ) : """Instantiates and returns a model field for FieldHistory . object _ id . object _ id _ class _ or _ tuple may be either a Django model field class or a tuple of ( model _ field , kwargs ) , where kwargs is a dict passed to m...
if isinstance ( object_id_class_or_tuple , ( list , tuple ) ) : object_id_class , object_id_kwargs = object_id_class_or_tuple else : object_id_class = object_id_class_or_tuple object_id_kwargs = { } if not issubclass ( object_id_class , models . fields . Field ) : raise TypeError ( 'settings.%s must be ...
def centerdistance ( image , voxelspacing = None , mask = slice ( None ) ) : r"""Takes a simple or multi - spectral image and returns its voxel - wise center distance in mm . A multi - spectral image must be supplied as a list or tuple of its spectra . Optionally a binary mask can be supplied to select the voxe...
if type ( image ) == tuple or type ( image ) == list : image = image [ 0 ] return _extract_feature ( _extract_centerdistance , image , mask , voxelspacing = voxelspacing )
def multiple_devices_data_message ( self , registration_ids = None , condition = None , collapse_key = None , delay_while_idle = False , time_to_live = None , restricted_package_name = None , low_priority = False , dry_run = False , data_message = None , content_available = None , timeout = 5 , extra_notification_kwarg...
if not isinstance ( registration_ids , list ) : raise InvalidDataError ( 'Invalid registration IDs (should be list)' ) payloads = [ ] registration_id_chunks = self . registration_id_chunks ( registration_ids ) for registration_ids in registration_id_chunks : # appends a payload with a chunk of registration ids here...
def double ( self ) : """Doubles this point . Returns : JacobianPoint : The point corresponding to ` 2 * self ` ."""
X1 , Y1 , Z1 = self . X , self . Y , self . Z if Y1 == 0 : return POINT_AT_INFINITY S = ( 4 * X1 * Y1 ** 2 ) % self . P M = ( 3 * X1 ** 2 + self . a * Z1 ** 4 ) % self . P X3 = ( M ** 2 - 2 * S ) % self . P Y3 = ( M * ( S - X3 ) - 8 * Y1 ** 4 ) % self . P Z3 = ( 2 * Y1 * Z1 ) % self . P return JacobianPoint ( X3 , ...
def Softsign ( a ) : """Softsign op ."""
return np . divide ( a , np . add ( np . abs ( a ) , 1 ) ) ,
def get_new_client ( request_session = False ) : """Return a new ConciergeClient , pulling secrets from the environment ."""
from . client import ConciergeClient client = ConciergeClient ( access_key = os . environ [ "MS_ACCESS_KEY" ] , secret_key = os . environ [ "MS_SECRET_KEY" ] , association_id = os . environ [ "MS_ASSOCIATION_ID" ] ) if request_session : client . request_session ( ) return client