signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def sendmail_proxy ( subject , email , template , ** context ) : """Cast the lazy _ gettext ' ed subject to string before passing to Celery"""
sendmail . delay ( subject . value , email , template , ** context )
def get ( self ) : """Get a JSON - ready representation of this BCCSettings . : returns : This BCCSettings , ready for use in a request body . : rtype : dict"""
bcc_settings = { } if self . enable is not None : bcc_settings [ "enable" ] = self . enable if self . email is not None : bcc_settings [ "email" ] = self . email . get ( ) return bcc_settings
def verifybamid_table ( self ) : """Create a table with all the columns from verify BAM ID"""
# create an ordered dictionary to preserve the order of columns headers = OrderedDict ( ) # add each column and the title and description ( taken from verifyBAMID website ) headers [ 'RG' ] = { 'title' : 'Read Group' , 'description' : 'ReadGroup ID of sequenced lane.' , 'hidden' : all ( [ s [ 'RG' ] == 'ALL' for s in s...
def calculate_positions ( positions ) : """Calculates position information"""
current_position = { 'data-x' : 0 , 'data-y' : 0 , 'data-z' : 0 , 'data-rotate-x' : 0 , 'data-rotate-y' : 0 , 'data-rotate-z' : 0 , 'data-scale' : 1 , } positer = iter ( positions ) position = next ( positer ) _update_position ( current_position , position ) while True : if 'path' in position : # Start of a new pat...
def _wavGetInfo ( f : Union [ IO , str ] ) -> Tuple [ SndInfo , Dict [ str , Any ] ] : """Read the info of a wav file . taken mostly from scipy . io . wavfile if extended : returns also fsize and bigendian"""
if isinstance ( f , ( str , bytes ) ) : f = open ( f , 'rb' ) needsclosing = True else : needsclosing = False fsize , bigendian = _wavReadRiff ( f ) fmt = ">i" if bigendian else "<i" while ( f . tell ( ) < fsize ) : chunk_id = f . read ( 4 ) if chunk_id == b'fmt ' : chunksize , sampfmt , cha...
def main ( prog_args = None ) : """What do you expect ?"""
if prog_args is None : prog_args = sys . argv parser = optparse . OptionParser ( ) parser . usage = """Usage: %[prog] [options] [<path>]""" parser . add_option ( "-t" , "--test-program" , dest = "test_program" , default = "nose" , help = "specifies the test-program to use. Valid values" " include `nose` (or `nosete...
def map2salm ( map , s , lmax ) : """Convert values of spin - weighted function on a grid to mode weights Parameters map : array _ like , complex , shape ( . . . , Ntheta , Nphi ) Values of the spin - weighted function on grid points of the sphere . This array may have more than two dimensions , where initi...
import numpy as np map = np . ascontiguousarray ( map , dtype = np . complex128 ) salm = np . empty ( map . shape [ : - 2 ] + ( N_lm ( lmax ) , ) , dtype = np . complex128 ) if map . ndim > 2 : s = np . ascontiguousarray ( s , dtype = np . intc ) if s . ndim != map . ndim - 2 or np . product ( s . shape ) != np...
def DeregisterDefinition ( self , artifact_definition ) : """Deregisters an artifact definition . Artifact definitions are identified based on their lower case name . Args : artifact _ definition ( ArtifactDefinition ) : an artifact definition . Raises : KeyError : if an artifact definition is not set for...
artifact_definition_name = artifact_definition . name . lower ( ) if artifact_definition_name not in self . _artifact_definitions : raise KeyError ( 'Artifact definition not set for name: {0:s}.' . format ( artifact_definition . name ) ) del self . _artifact_definitions [ artifact_definition_name ]
def bed ( args ) : """% prog bed bedfile bamfiles Convert bam files to bed ."""
p = OptionParser ( bed . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 2 : sys . exit ( not p . print_help ( ) ) bedfile = args [ 0 ] bamfiles = args [ 1 : ] for bamfile in bamfiles : cmd = "bamToBed -i {0}" . format ( bamfile ) sh ( cmd , outfile = bedfile , append = True )
def deleteUnused ( self ) : """Delete any old snapshots in path , if not kept ."""
( count , size ) = ( 0 , 0 ) for ( diff , path ) in self . extraKeys . items ( ) : if path . startswith ( "/" ) : continue keyName = self . _keyName ( diff . toUUID , diff . fromUUID , path ) count += 1 size += diff . size if self . _skipDryRun ( logger , 'INFO' ) ( "Trash: %s" , diff ) : ...
def _is_missing_tags_strict ( self ) : """Return whether missing _ tags is set to strict ."""
val = self . missing_tags if val == MissingTags . strict : return True elif val == MissingTags . ignore : return False raise Exception ( "Unsupported 'missing_tags' value: %s" % repr ( val ) )
def set_min_level_to_save ( self , level ) : """Allow to change save level after creation"""
self . min_log_level_to_save = level handler_class = logging . handlers . TimedRotatingFileHandler self . _set_min_level ( handler_class , level )
def add ( self , anchor ) : """Add a new anchor to the repository . This will create a new ID for the anchor and provision new storage for it . Returns : The storage ID for the Anchor which can be used to retrieve the anchor later ."""
anchor_id = uuid . uuid4 ( ) . hex anchor_path = self . _anchor_path ( anchor_id ) with anchor_path . open ( mode = 'wt' ) as f : save_anchor ( f , anchor , self . root ) return anchor_id
def reassign_label ( cls , destination_cluster , label ) : """Reassign a label from one cluster to another . Args : ` destination _ cluster ` : id / label of the cluster to move the label to ` label ` : label to be moved from the source cluster"""
conn = Qubole . agent ( version = Cluster . api_version ) data = { "destination_cluster" : destination_cluster , "label" : label } return conn . put ( cls . rest_entity_path + "/reassign-label" , data )
def acquire_lock ( self ) : """Acquire the global lock for the root directory associated with this context . When a goal requires serialization , it will call this to acquire the lock . : API : public"""
if self . options . for_global_scope ( ) . lock : if not self . _lock . acquired : self . _lock . acquire ( )
def _rm_parse_header_line ( parts , meta_data ) : """parse a repeatmasker alignment header line and place the extracted meta - data into the provided dictionary . An example header line is : : 239 29.42 1.92 0.97 chr1 11 17 ( 41 ) C XX # YY ( 74 ) 104 1 m _ b1s502i1 4 If the alignment is to the consensus , th...
meta_data [ ALIG_SCORE_KEY ] = parts [ 0 ] meta_data [ PCENT_SUBS_KEY ] = float ( parts [ 1 ] ) meta_data [ PCENT_S1_INDELS_KEY ] = float ( parts [ 2 ] ) meta_data [ PCENT_S2_INDELS_KEY ] = float ( parts [ 3 ] ) meta_data [ ANNOTATION_KEY ] = "" if parts [ 8 ] == "C" : meta_data [ UNKNOWN_RM_HEADER_FIELD_KEY ] = pa...
def make_gaussian_sources_image ( shape , source_table , oversample = 1 ) : """Make an image containing 2D Gaussian sources . Parameters shape : 2 - tuple of int The shape of the output 2D image . source _ table : ` ~ astropy . table . Table ` Table of parameters for the Gaussian sources . Each row of the...
model = Gaussian2D ( x_stddev = 1 , y_stddev = 1 ) if 'x_stddev' in source_table . colnames : xstd = source_table [ 'x_stddev' ] else : xstd = model . x_stddev . value # default if 'y_stddev' in source_table . colnames : ystd = source_table [ 'y_stddev' ] else : ystd = model . y_stddev . value # def...
def save ( self ) : """save or update this entity on Ariane server : return :"""
LOGGER . debug ( "InjectorUITreeEntity.save" ) if self . id and self . value and self . type : ok = True if InjectorUITreeService . find_ui_tree_entity ( self . id ) is None : # SAVE self_string = str ( self . injector_ui_tree_menu_entity_2_json ( ignore_genealogy = True ) ) . replace ( "'" , '"' ) ...
def geneinfo ( args ) : """% prog geneinfo pineapple . 20141004 . bed liftover . bed pineapple . 20150413 . bed note . txt interproscan . txt Build gene info table from various sources . The three beds contain information on the original scaffolds , linkage groups , and final selected loci ( after removal of ...
p = OptionParser ( geneinfo . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 5 : sys . exit ( not p . print_help ( ) ) scfbed , liftoverbed , lgbed , note , ipr = args note = DictFile ( note , delimiter = "\t" ) scfbed = Bed ( scfbed ) lgorder = Bed ( lgbed ) . order liftover = Bed ( liftoverbed...
def _register_handler ( event , fun , external = False ) : """Register a function to be an event handler"""
registry = core . HANDLER_REGISTRY if external : registry = core . EXTERNAL_HANDLER_REGISTRY if not isinstance ( event , basestring ) : # If not basestring , it is a BaseEvent subclass . # This occurs when class methods are registered as handlers event = core . parse_event_to_name ( event ) if event in registry...
def set_sequestered ( self , sequestered ) : """Sets the sequestered flag . arg : sequestered ( boolean ) : the new sequestered flag raise : InvalidArgument - ` ` sequestered ` ` is invalid raise : NoAccess - ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` ` * compliance : mandatory - - This method must be ...
if sequestered is None : raise errors . NullArgument ( ) if self . get_sequestered_metadata ( ) . is_read_only ( ) : raise errors . NoAccess ( ) if not isinstance ( sequestered , bool ) : raise errors . InvalidArgument ( ) self . _my_map [ 'sequestered' ] = sequestered
def to_sint ( self ) : """Converts the word to a BinInt , treating it as a signed number ."""
if self . _width == 0 : return BinInt ( 0 ) sbit = 1 << ( self . _width - 1 ) return BinInt ( ( self . _val - sbit ) ^ - sbit )
def validate_wrap ( self , value ) : '''Checks that value is a ` ` dict ` ` , that every key is a valid MongoDB key , and that every value validates based on DictField . value _ type'''
if not isinstance ( value , dict ) : self . _fail_validation_type ( value , dict ) for k , v in value . items ( ) : self . _validate_key_wrap ( k ) try : self . value_type . validate_wrap ( v ) except BadValueException as bve : self . _fail_validation ( value , 'Bad value for key %s' % k...
def read_magic_file ( self , path , sort_by_this_name ) : """reads a magic formated data file from path and sorts the keys according to sort _ by _ this _ name Parameters path : path to file to read sort _ by _ this _ name : variable to sort data by"""
DATA = { } try : with open ( path , 'r' ) as finput : lines = list ( finput . readlines ( ) [ 1 : ] ) except FileNotFoundError : return [ ] # fin = open ( path , ' r ' ) # fin . readline ( ) line = lines [ 0 ] header = line . strip ( '\n' ) . split ( '\t' ) error_strings = [ ] for line in lines [ 1 : ] ...
def status_reblogged_by ( self , id ) : """Fetch a list of users that have reblogged a status . Does not require authentication for publicly visible statuses . Returns a list of ` user dicts ` _ ."""
id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/reblogged_by' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
def graph_from_incidence_matrix ( matrix , node_prefix = '' , directed = False ) : """Creates a basic graph out of an incidence matrix . The matrix has to be a list of rows of values representing an incidence matrix . The values can be anything : bool , int , float , as long as they can evaluate to True or ...
if directed : graph = Dot ( graph_type = 'digraph' ) else : graph = Dot ( graph_type = 'graph' ) for row in matrix : nodes = [ ] c = 1 for node in row : if node : nodes . append ( c * node ) c += 1 nodes . sort ( ) if len ( nodes ) == 2 : graph . add_edge ...
def get_assets_by_search ( self , asset_query , asset_search ) : """Gets the search results matching the given search query using the given search . arg : asset _ query ( osid . repository . AssetQuery ) : the asset query arg : asset _ search ( osid . repository . AssetSearch ) : the asset search return :...
# Implemented from template for # osid . resource . ResourceSearchSession . get _ resources _ by _ search _ template # Copied from osid . resource . ResourceQuerySession . get _ resources _ by _ query _ template and_list = list ( ) or_list = list ( ) for term in asset_query . _query_terms : and_list . append ( { te...
def flexifunction_read_req_send ( self , target_system , target_component , read_req_type , data_index , force_mavlink1 = False ) : '''Reqest reading of flexifunction data target _ system : System ID ( uint8 _ t ) target _ component : Component ID ( uint8 _ t ) read _ req _ type : Type of flexifunction data r...
return self . send ( self . flexifunction_read_req_encode ( target_system , target_component , read_req_type , data_index ) , force_mavlink1 = force_mavlink1 )
def SVD ( stream_list , full = False ) : """Depreciated . Use svd ."""
warnings . warn ( 'Depreciated, use svd instead.' ) return svd ( stream_list = stream_list , full = full )
def importData ( directory ) : """Parse the input files and return two dictionnaries"""
dataTask = OrderedDict ( ) dataQueue = OrderedDict ( ) for fichier in sorted ( os . listdir ( directory ) ) : try : with open ( "{directory}/{fichier}" . format ( ** locals ( ) ) , 'rb' ) as f : fileName , fileType = fichier . rsplit ( '-' , 1 ) if fileType == "QUEUE" : ...
def _set_area ( self , v , load = False ) : """Setter method for area , mapped from YANG variable / routing _ system / interface / ve / ip / interface _ vlan _ ospf _ conf / ospf1 / area ( ospf - area - id ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ area is consid...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_dict = { 'pattern' : u'((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.)(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[...
def set_folder ( self , folder = 'assets' ) : """Changes the file folder to look at : param folder : str [ images , assets ] : return : None"""
folder = folder . replace ( '/' , '.' ) self . _endpoint = 'files/{folder}' . format ( folder = folder )
def load ( self , id_code ) : """Loads a workflow identified by id _ code id _ code - unique identifier , previously must have called save with same id _ code"""
filestream = open ( '{0}/{1}' . format ( self . data_path , id_code ) , 'rb' ) workflow = pickle . load ( filestream ) return workflow
def doControl ( self , controlCode , bytes = [ ] ) : """Transmit a control command to the reader and return response . controlCode : control command bytes : command data to transmit ( list of bytes ) return : response are the response bytes ( if any )"""
CardConnection . doControl ( self , controlCode , bytes ) hresult , response = SCardControl ( self . hcard , controlCode , bytes ) if hresult != 0 : raise SmartcardException ( 'Failed to control ' + SCardGetErrorMessage ( hresult ) ) data = [ ( x + 256 ) % 256 for x in response ] return list ( data )
def resolve_aliases ( self , chunks ) : '''Preserve backward compatibility by rewriting the ' state ' key in the low chunks if it is using a legacy type .'''
for idx , _ in enumerate ( chunks ) : new_state = self . aliases . get ( chunks [ idx ] [ 'state' ] ) if new_state is not None : chunks [ idx ] [ 'state' ] = new_state
def from_bytes ( self , raw ) : '''Return an Ethernet object reconstructed from raw bytes , or an Exception if we can ' t resurrect the packet .'''
if len ( raw ) < UDP . _MINLEN : raise NotEnoughDataError ( "Not enough bytes ({}) to reconstruct an UDP object" . format ( len ( raw ) ) ) fields = struct . unpack ( UDP . _PACKFMT , raw [ : UDP . _MINLEN ] ) self . _src = fields [ 0 ] self . _dst = fields [ 1 ] self . _len = fields [ 2 ] self . _checksum = fields...
def get_message_id ( self ) : """Method to get messageId of group created ."""
message_id = self . json_response . get ( "messageId" , None ) self . logger . info ( "%s\t%s" % ( self . request_method , self . request_url ) ) return message_id
def gen_age ( output , ascii_props = False , append = False , prefix = "" ) : """Generate ` age ` property ."""
obj = { } all_chars = ALL_ASCII if ascii_props else ALL_CHARS with codecs . open ( os . path . join ( HOME , 'unicodedata' , UNIVERSION , 'DerivedAge.txt' ) , 'r' , 'utf-8' ) as uf : for line in uf : if not line . startswith ( '#' ) : data = line . split ( '#' ) [ 0 ] . split ( ';' ) ...
def urlopen ( self , method , url , ** kw ) : "Same as HTTP ( S ) ConnectionPool . urlopen , ` ` url ` ` must be absolute ."
kw [ 'assert_same_host' ] = False return self . proxy_pool . urlopen ( method , url , ** kw )
def update_vm_result ( self , context , msg ) : """Update VM ' s result field in the DB . The result reflects the success of failure of operation when an agent processes the vm info ."""
args = jsonutils . loads ( msg ) agent = context . get ( 'agent' ) port_id = args . get ( 'port_uuid' ) result = args . get ( 'result' ) LOG . debug ( 'update_vm_result received from %(agent)s: ' '%(port_id)s %(result)s' , { 'agent' : agent , 'port_id' : port_id , 'result' : result } ) # Add the request into queue for ...
def buildTables ( self ) : """Compile OpenType feature tables from the source . Raises a FeaLibError if the feature compilation was unsuccessful . * * This should not be called externally . * * Subclasses may override this method to handle the table compilation in a different way if desired ."""
if not self . features : return # the path is used by the lexer to follow ' include ' statements ; # if we generated some automatic features , includes have already been # resolved , and we work from a string which does ' t exist on disk path = self . ufo . path if not self . featureWriters else None try : addO...
def add_data_set ( self , data , series_type = "line" , name = None , ** kwargs ) : """set data for series option in highcharts"""
self . data_set_count += 1 if not name : name = "Series %d" % self . data_set_count kwargs . update ( { 'name' : name } ) if series_type == 'treemap' : self . add_JSsource ( 'http://code.highcharts.com/modules/treemap.js' ) series_data = Series ( data , series_type = series_type , ** kwargs ) series_data . __op...
def to_json ( record , extraneous = True , prop = None ) : """JSON conversion function : a ' visitor ' function which implements marshall out ( to JSON data form ) , honoring JSON property types / hints but does not require them . To convert to an actual JSON document , pass the return value to ` ` json . dum...
if prop : if isinstance ( prop , basestring ) : prop = type ( record ) . properties [ prop ] val = prop . __get__ ( record ) if hasattr ( prop , "to_json" ) : return prop . to_json ( val , extraneous , _json_data ) else : return _json_data ( val , extraneous ) elif isinstance ( r...
def _check_avail ( cmd ) : '''Check to see if the given command can be run'''
if isinstance ( cmd , list ) : cmd = ' ' . join ( [ six . text_type ( x ) if not isinstance ( x , six . string_types ) else x for x in cmd ] ) bret = True wret = False if __salt__ [ 'config.get' ] ( 'cmd_blacklist_glob' ) : blist = __salt__ [ 'config.get' ] ( 'cmd_blacklist_glob' , [ ] ) for comp in blist :...
def apply_modification ( self ) : """Modifications on the right side need to be committed"""
self . __changing_model = True if self . adding_model : self . model . add ( self . adding_model ) elif self . editing_model and self . editing_iter : # notifies the currencies model path = self . model . get_path ( self . editing_iter ) self . model . row_changed ( path , self . editing_iter ) pass sel...
def dynacRepresentation ( self ) : """Return the Pynac representation of this Set4DAperture instance ."""
details = [ self . energyDefnFlag . val , self . energy . val , self . phase . val , self . x . val , self . y . val , self . radius . val , ] return [ 'REJECT' , [ details ] ]
def add_user_email ( self , user , ** kwargs ) : """Add a UserEmail object , with properties specified in ` ` * * kwargs ` ` ."""
# If User and UserEmail are separate classes if self . UserEmailClass : user_email = self . UserEmailClass ( user = user , ** kwargs ) self . db_adapter . add_object ( user_email ) # If there is only one User class else : for key , value in kwargs . items ( ) : setattr ( user , key , value ) use...
def requires_swimlane_version ( min_version = None , max_version = None ) : """Decorator for SwimlaneResolver methods verifying Swimlane server build version is within a given inclusive range Raises : InvalidVersion : Raised before decorated method call if Swimlane server version is out of provided range Valu...
if min_version is None and max_version is None : raise ValueError ( 'Must provide either min_version, max_version, or both' ) if min_version and max_version and compare_versions ( min_version , max_version ) < 0 : raise ValueError ( 'min_version must be <= max_version ({}, {})' . format ( min_version , max_vers...
def autogroups_states_changed ( sender , instance , action , reverse , model , pk_set , * args , ** kwargs ) : """Trigger group membership update when a state is added or removed from an autogroup config ."""
if action . startswith ( 'post_' ) : for pk in pk_set : try : state = State . objects . get ( pk = pk ) instance . update_group_membership_for_state ( state ) except State . DoesNotExist : # Deleted States handled by the profile state change pass
def horizontal_infrared_radiation_intensity ( self , value = 9999.0 ) : """Corresponds to IDD Field ` horizontal _ infrared _ radiation _ intensity ` Args : value ( float ) : value for IDD Field ` horizontal _ infrared _ radiation _ intensity ` Unit : Wh / m2 value > = 0.0 Missing value : 9999.0 if ` va...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `horizontal_infrared_radiation_intensity`' . format ( value ) ) if value < 0.0 : raise ValueError ( 'value need to be greater or equal 0.0 ' 'fo...
def _getproject ( self , config , section , ** kwargs ) : """Creates a VSG project from a configparser instance . : param object config : The instance of the configparser class : param str section : The section name to read . : param kwargs : List of additional keyworded arguments to be passed into the VSGPro...
if section not in config : raise ValueError ( 'Section [{}] not found in [{}]' . format ( section , ', ' . join ( config . sections ( ) ) ) ) type = config . get ( section , 'type' , fallback = None ) if not type : raise ValueError ( 'Section [{}] mandatory option "{}" not found' . format ( section , "type" ) )...
def exception_to_unicode ( e , traceback = False ) : """Convert an ` Exception ` to an ` unicode ` object . In addition to ` to _ unicode ` , this representation of the exception also contains the class name and optionally the traceback ."""
message = '%s: %s' % ( e . __class__ . __name__ , to_unicode ( e ) ) if traceback : from docido_sdk . toolbox import get_last_traceback traceback_only = get_last_traceback ( ) . split ( '\n' ) [ : - 2 ] message = '\n%s\n%s' % ( to_unicode ( '\n' . join ( traceback_only ) ) , message ) return message
def skip_storing_namespace ( self , namespace : Optional [ str ] ) -> bool : """Check if the namespace should be skipped . : param namespace : The keyword of the namespace to check ."""
return ( namespace is not None and namespace in self . namespace_url and self . namespace_url [ namespace ] in self . uncached_namespaces )
def get_kb_mapping ( kb_name = "" , key = "" , value = "" , match_type = "e" , default = "" , limit = None ) : """Get one unique mapping . If not found , return default . : param kb _ name : the name of the kb : param key : include only lines matching this on left side in the results : param value : include o...
mappings = get_kb_mappings ( kb_name , key = key , value = value , match_type = match_type , limit = limit ) if len ( mappings ) == 0 : return default else : return mappings [ 0 ]
def stage_subset ( self , * files_to_add : str ) : """Stages a subset of files : param files _ to _ add : files to stage : type files _ to _ add : str"""
LOGGER . info ( 'staging files: %s' , files_to_add ) self . repo . git . add ( * files_to_add , A = True )
def add_config_file ( self , config_filename ) : """Parses the content . types file and updates the content types database . : param config _ filename : The path to the configuration file ."""
with open ( config_filename , 'rb' ) as f : content = f . read ( ) config = yaml . load ( content ) self . add_config ( config , config_filename )
def complete_definition ( subj : Node , source_graph : Graph , target_graph : Optional [ Graph ] = None ) -> PrettyGraph : """Return the transitive closure of subject . : param subj : URI or BNode for subject : param source _ graph : Graph containing defininition : param target _ graph : return graph ( for re...
if target_graph is None : target_graph = PrettyGraph ( ) for p , o in source_graph . predicate_objects ( subj ) : target_graph . add ( ( subj , p , o ) ) if isinstance ( o , BNode ) : complete_definition ( o , source_graph , target_graph ) return target_graph
def polygon_diameter ( points ) : '''Compute the maximun euclidian distance between any two points in a list of points'''
return max ( point_dist ( p0 , p1 ) for ( p0 , p1 ) in combinations ( points , 2 ) )
def query_position ( self , strand , chr , genome_coord ) : """Provides the relative position on the coding sequence for a given genomic position . Parameters chr : str chromosome , provided to check validity of query genome _ coord : int 0 - based position for mutation , actually used to get relative c...
# first check if valid pos = None # initialize to invalid pos if chr != self . chrom : # logger . debug ( ' Wrong chromosome queried . You provided { 0 } but gene is ' # ' on { 1 } . ' . format ( chr , self . chrom ) ) # return pos pass if type ( genome_coord ) is list : # handle case for indels pos_left = self...
def elem_find ( self , field , value ) : """Return the indices of elements whose field first satisfies the given values ` ` value ` ` should be unique in self . field . This function does not check the uniqueness . : param field : name of the supplied field : param value : value of field of the elemtn to fi...
if isinstance ( value , ( int , float , str ) ) : value = [ value ] f = list ( self . __dict__ [ field ] ) uid = np . vectorize ( f . index ) ( value ) return self . get_idx ( uid )
def cli ( ctx , group_id , new_name ) : """Update the name of a group Output : a dictionary containing group information"""
return ctx . gi . groups . update_group ( group_id , new_name )
def read_table ( filename , usecols = ( 0 , 1 ) , sep = '\t' , comment = '#' , encoding = 'utf-8' , skip = 0 ) : """Parse data files from the data directory Parameters filename : string Full path to file usecols : list , default [ 0 , 1] A list of two elements representing the columns to be parsed into a ...
with io . open ( filename , 'r' , encoding = encoding ) as f : # skip initial lines for _ in range ( skip ) : next ( f ) # filter comment lines lines = ( line for line in f if not line . startswith ( comment ) ) d = dict ( ) for line in lines : columns = line . split ( sep ) ...
def create_record ( self , bucket_name , record_key , record_data , record_metadata = None , record_mimetype = '' , record_encoding = '' , overwrite = True ) : '''a method for adding a record to an S3 bucket : param bucket _ name : string with name of bucket : param record _ key : string with name of key ( path...
title = '%s.create_record' % self . __class__ . __name__ import sys from hashlib import md5 from base64 import b64encode # define size limitations metadata_max = self . fields . metadata [ 'limits' ] [ 'metadata_max_bytes' ] record_max = self . fields . metadata [ 'limits' ] [ 'record_max_bytes' ] record_optimal = self...
def update ( preset , clean ) : """Update a local preset This command will cause ` be ` to pull a preset already available locally . Usage : $ be update ad Updating " ad " . ."""
if self . isactive ( ) : lib . echo ( "ERROR: Exit current project first" ) sys . exit ( lib . USER_ERROR ) presets = _extern . github_presets ( ) if preset not in presets : sys . stdout . write ( "\"%s\" not found" % preset ) sys . exit ( lib . USER_ERROR ) lib . echo ( "Are you sure you want to update...
def webui_data_stores_data_store_value ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) webui = ET . SubElement ( config , "webui" , xmlns = "http://tail-f.com/ns/webui" ) data_stores = ET . SubElement ( webui , "data-stores" ) data_store = ET . SubElement ( data_stores , "data-store" ) key_key = ET . SubElement ( data_store , "key" ) key_key . text = kwargs . pop ( 'key...
def sync_file ( self , clusters ) : """Generates new HAProxy config file content and writes it to the file at ` haproxy _ config _ path ` . If a restart is not necessary the nodes configured in HAProxy will be synced on the fly . If a restart * is * necessary , one will be triggered ."""
logger . info ( "Updating HAProxy config file." ) if not self . restart_required : self . sync_nodes ( clusters ) version = self . control . get_version ( ) with open ( self . haproxy_config_path , "w" ) as f : f . write ( self . config_file . generate ( clusters , version = version ) ) if self . restart_requir...
def intty ( cls ) : """Check if we are in a tty ."""
# XXX : temporary hack until we can detect if we are in a pipe or not return True if hasattr ( sys . stdout , 'isatty' ) and sys . stdout . isatty ( ) : return True return False
def location_gmap ( context , location ) : """Display a link to Google maps iff we are using WagtailGMaps"""
gmapq = None if getattr ( MapFieldPanel , "UsingWagtailGMaps" , False ) : gmapq = location return { 'gmapq' : gmapq }
def Boi ( compiler , cont ) : '''end of parse _ state'''
return il . If ( il . Le ( il . GetItem ( il . parse_state , il . Integer ( 1 ) ) , 0 ) , cont ( TRUE ) , il . failcont ( FALSE ) )
def digit ( m : Union [ int , pd . Series ] , n : int ) -> Union [ int , pd . Series ] : """Returns the nth digit of each number in m ."""
return ( m // ( 10 ** n ) ) % 10
def validate ( self , obj , ** kwargs ) : """Check if a thing is a valid date ."""
obj = stringify ( obj ) if obj is None : return False return self . DATE_RE . match ( obj ) is not None
def postinit ( self , type = None , name = None , body = None ) : """Do some setup after initialisation . : param type : The types that the block handles . : type type : Tuple or NodeNG or None : param name : The name that the caught exception is assigned to . : type name : AssignName or None : param body...
self . type = type self . name = name self . body = body
def send ( self , msg , timeout = None ) : """Sends one CAN message . When a transmission timeout is set the firmware tries to send a message within this timeout . If it could not be sent the firmware sets the " auto delete " state . Within this state all transmit CAN messages for this channel will be delet...
if timeout is not None and timeout >= 0 : self . _ucan . set_tx_timeout ( self . channel , int ( timeout * 1000 ) ) message = CanMsg ( msg . arbitration_id , MsgFrameFormat . MSG_FF_STD | ( MsgFrameFormat . MSG_FF_EXT if msg . is_extended_id else 0 ) | ( MsgFrameFormat . MSG_FF_RTR if msg . is_remote_frame else 0 )...
def add_stack_frame ( self , stack_frame ) : """Add StackFrame to frames list ."""
if len ( self . stack_frames ) >= MAX_FRAMES : self . dropped_frames_count += 1 else : self . stack_frames . append ( stack_frame . format_stack_frame_json ( ) )
def matchiter ( r , s , flags = 0 ) : """Yields contiguous MatchObjects of r in s . Raises ValueError if r eventually doesn ' t match contiguously ."""
if isinstance ( r , basestring ) : r = re . compile ( r , flags ) i = 0 while s : m = r . match ( s ) g = m and m . group ( 0 ) if not m or not g : raise ValueError ( "{}: {!r}" . format ( i , s [ : 50 ] ) ) i += len ( g ) s = s [ len ( g ) : ] yield m
def list_cards ( self , * args , ** kwargs ) : """List the cards of the customer . : param page : the page number : type page : int | None : param per _ page : number of customers per page . It ' s a good practice to increase this number if you know that you will need a lot of payments . : type per _ page...
return payplug . Card . list ( self , * args , ** kwargs )
def set_mindays ( name , mindays ) : '''Set the minimum number of days between password changes . See man passwd . CLI Example : . . code - block : : bash salt ' * ' shadow . set _ mindays username 7'''
pre_info = info ( name ) if mindays == pre_info [ 'min' ] : return True cmd = 'passwd -n {0} {1}' . format ( mindays , name ) __salt__ [ 'cmd.run' ] ( cmd , python_shell = False ) post_info = info ( name ) if post_info [ 'min' ] != pre_info [ 'min' ] : return post_info [ 'min' ] == mindays return False
def getProperty ( self , orgresource , dummy = 56184 ) : """GetProperty Args : dummy : ? ? ? orgresource : File path Returns : FileInfo object : False : Failed to get property"""
url = nurls [ 'getProperty' ] data = { 'userid' : self . user_id , 'useridx' : self . useridx , 'dummy' : dummy , 'orgresource' : orgresource , } r = self . session . post ( url = url , data = data ) j = json . loads ( r . text ) if self . resultManager ( r . text ) : f = FileInfo ( ) result = j [ 'resultvalue'...
def script_file ( self ) : """Returns the startup script file for this VPCS VM . : returns : path to startup script file"""
# use the default VPCS file if it exists path = os . path . join ( self . working_dir , 'startup.vpc' ) if os . path . exists ( path ) : return path else : return None
def _get_all_forecast_from_api ( api_result : dict ) -> OrderedDict : """Converts results fråm API to SmhiForeCast list"""
# Total time in hours since last forecast total_hours_last_forecast = 1.0 # Last forecast time last_time = None # Need the ordered dict to get # the days in order in next stage forecasts_ordered = OrderedDict ( ) # Get the parameters for forecast in api_result [ 'timeSeries' ] : valid_time = datetime . strptime ( f...
def ptb_producer ( raw_data , batch_size , num_steps , name = None ) : """Iterate on the raw PTB data . This chunks up raw _ data into batches of examples and returns Tensors that are drawn from these batches . Args : raw _ data : one of the raw data outputs from ptb _ raw _ data . batch _ size : int , th...
with tf . name_scope ( name , "PTBProducer" , [ raw_data , batch_size , num_steps ] ) : raw_data = tf . convert_to_tensor ( raw_data , name = "raw_data" , dtype = tf . int32 ) data_len = tf . size ( raw_data ) batch_len = data_len // batch_size data = tf . reshape ( raw_data [ 0 : batch_size * batch_len...
def mouseUp ( x = None , y = None , button = 'left' , duration = 0.0 , tween = linear , pause = None , _pause = True ) : """Performs releasing a mouse button up ( but not down beforehand ) . The x and y parameters detail where the mouse event happens . If None , the current mouse position is used . If a float v...
if button not in ( 'left' , 'middle' , 'right' , 1 , 2 , 3 ) : raise ValueError ( "button argument must be one of ('left', 'middle', 'right', 1, 2, 3), not %s" % button ) _failSafeCheck ( ) x , y = _unpackXY ( x , y ) _mouseMoveDrag ( 'move' , x , y , 0 , 0 , duration = 0 , tween = None ) x , y = platformModule . _...
def init ( parser = None ) : """module needs to be initialized by ' init ' . Can be called with parser to use a pre - built parser , otherwise a simple default parser is created"""
global p , subparsers if parser is None : p = argparse . ArgumentParser ( ) else : p = parser arg = p . add_argument subparsers = p . add_subparsers ( )
def to_string_monkey ( df , highlight_cols = None , latex = False ) : """monkey patch to pandas to highlight the maximum value in specified cols of a row Example : > > > from utool . experimental . pandas _ highlight import * > > > import pandas as pd > > > df = pd . DataFrame ( > > > np . array ( [ [ 0...
try : import pandas as pd import utool as ut import numpy as np import six if isinstance ( highlight_cols , six . string_types ) and highlight_cols == 'all' : highlight_cols = np . arange ( len ( df . columns ) ) # kwds = dict ( buf = None , columns = None , col _ space = None , header =...
def synchronize ( self ) : """Perform sync of the security groups between ML2 and EOS ."""
# Get expected ACLs and rules expected_acls = self . get_expected_acls ( ) # Get expected interface to ACL mappings all_expected_bindings = self . get_expected_bindings ( ) # Check that config is correct on every registered switch for switch_ip in self . _switches . keys ( ) : expected_bindings = all_expected_bindi...
def normalize_frame ( self , module = None , function = None , file = None , line = None , module_offset = None , offset = None , normalized = None , ** kwargs # eat any extra kwargs passed in ) : """Normalizes a single frame Returns a structured conglomeration of the input parameters to serve as a signature . ...
# If there ' s a cached normalized value , use that so we don ' t spend time # figuring it out again if normalized is not None : return normalized if function : # If there ' s a filename and it ends in . rs , then normalize using # Rust rules if file and ( parse_source_file ( file ) or '' ) . endswith ( '.rs' )...
def children ( self ) : """~ TermList : the children of all the terms in the list ."""
return TermList ( unique_everseen ( y for x in self for y in x . children ) )
def get_permissions ( self ) : """: returns : list of dicts , or an empty list if there are no permissions ."""
path = Client . urls [ 'all_permissions' ] conns = self . _call ( path , 'GET' ) return conns
def checkState ( self ) : """Returns Qt . Checked or Qt . Unchecked if all children are checked or unchecked , else returns Qt . PartiallyChecked"""
# commonData = self . childItems [ 0 ] . data if self . childItems else Qt . PartiallyChecked commonData = None for child in self . childItems : if isinstance ( child , BoolCti ) : if commonData is not None and child . data != commonData : return Qt . PartiallyChecked commonData = child ...
def resetToPreviousLoc ( self ) : """Resets the loc of the dragger to place where dragging started . This could be used in a test situation if the dragger was dragged to an incorrect location ."""
self . rect . left = self . startDraggingX self . rect . top = self . startDraggingY
def give_zip_element_z_and_names ( element_name ) : '''create 2 indexes that , given the name of the element / specie , give the atomic number .'''
# import numpy as np global z_bismuth z_bismuth = 83 global z_for_elem z_for_elem = [ ] global index_stable index_stable = [ ] i_for_stable = 1 i_for_unstable = 0 for i in range ( z_bismuth ) : z_for_elem . append ( int ( i + 1 ) ) # the only elements below bismuth with no stable isotopes are Tc and Pm if i...
def cleanup ( self ) : """Release resources used during memory capture"""
if self . sock is not None : self . sock . close ( ) if self . outfile is not None : self . outfile . close ( ) if self . bar is not None : self . update_progress ( complete = True )
def describe_all ( self , full = False ) : """Prints description information about all tables registered Args : full ( bool ) : Also prints description of post processors ."""
for table in self . tabs : yield self . tabs [ table ] ( ) . describe ( full )
def bootstrap_counts ( dtrajs , lagtime , corrlength = None ) : """Generates a randomly resampled count matrix given the input coordinates . See API function for full documentation ."""
from scipy . stats import rv_discrete # if we have just one trajectory , put it into a one - element list : if ( isinstance ( dtrajs [ 0 ] , six . integer_types ) ) : dtrajs = [ dtrajs ] ntraj = len ( dtrajs ) # can we do the estimate ? lengths = determine_lengths ( dtrajs ) Lmax = np . max ( lengths ) Ltot = np . ...
def download_if_not_exists ( url : str , filename : str , skip_cert_verify : bool = True , mkdir : bool = True ) -> None : """Downloads a URL to a file , unless the file already exists ."""
if os . path . isfile ( filename ) : log . info ( "No need to download, already have: {}" , filename ) return if mkdir : directory , basename = os . path . split ( os . path . abspath ( filename ) ) mkdir_p ( directory ) download ( url = url , filename = filename , skip_cert_verify = skip_cert_verify )
def SURFstar_compute_scores ( inst , attr , nan_entries , num_attributes , mcmap , NN_near , NN_far , headers , class_type , X , y , labels_std , data_type ) : """Unique scoring procedure for SURFstar algorithm . Scoring based on nearest neighbors within defined radius , as well as ' anti - scoring ' of far insta...
scores = np . zeros ( num_attributes ) for feature_num in range ( num_attributes ) : if len ( NN_near ) > 0 : scores [ feature_num ] += compute_score ( attr , mcmap , NN_near , feature_num , inst , nan_entries , headers , class_type , X , y , labels_std , data_type ) # Note that we are using the near sc...
def subpoint ( self ) : """Return the latitude and longitude directly beneath this position . Returns a : class : ` ~ skyfield . toposlib . Topos ` whose ` ` longitude ` ` and ` ` latitude ` ` are those of the point on the Earth ' s surface directly beneath this position , and whose ` ` elevation ` ` is the ...
if self . center != 399 : # TODO : should an _ _ init _ _ ( ) check this ? raise ValueError ( "you can only ask for the geographic subpoint" " of a position measured from Earth's center" ) t = self . t xyz_au = einsum ( 'ij...,j...->i...' , t . M , self . position . au ) lat , lon , elevation_m = reverse_terra ( xy...
def get_internal_classpath_entries_for_targets ( self , targets , respect_excludes = True ) : """Gets the internal classpath products for the given targets . Products are returned in order , optionally respecting target excludes , and the products only include internal artifact classpath elements ( ie : no reso...
classpath_tuples = self . get_classpath_entries_for_targets ( targets , respect_excludes = respect_excludes ) return [ ( conf , cp_entry ) for conf , cp_entry in classpath_tuples if ClasspathEntry . is_internal_classpath_entry ( cp_entry ) ]
def ExpandWindowsPath ( cls , path , environment_variables ) : """Expands a Windows path containing environment variables . Args : path ( str ) : Windows path with environment variables . environment _ variables ( list [ EnvironmentVariableArtifact ] ) : environment variables . Returns : str : expanded ...
if environment_variables is None : environment_variables = [ ] lookup_table = { } if environment_variables : for environment_variable in environment_variables : attribute_name = environment_variable . name . upper ( ) attribute_value = environment_variable . value if not isinstance ( att...
def find_grid_embedding ( dim , m , n = None , t = 4 ) : """Find an embedding for a grid in a Chimera graph . Given a target : term : ` Chimera ` graph size , and grid dimensions , attempts to find an embedding . Args : dim ( iterable [ int ] ) : Sizes of each grid dimension . Length can be between 1 and 3....
m , n , t , target_edges = _chimera_input ( m , n , t , None ) indexer = dnx . generators . chimera . chimera_coordinates ( m , n , t ) dim = list ( dim ) num_dim = len ( dim ) if num_dim == 1 : def _key ( row , col , aisle ) : return row dim . extend ( [ 1 , 1 ] ) elif num_dim == 2 : def _key ( row...