signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def anonymize_column ( self , col ) : """Map the values of column to new ones of the same type . It replaces the values from others generated using ` faker ` . It will however , keep the original distribution . That mean that the generated ` probability _ map ` for both will have the same values , but differe...
column = col [ self . col_name ] generator = self . get_generator ( ) original_values = column [ ~ pd . isnull ( column ) ] . unique ( ) new_values = [ generator ( ) for x in range ( len ( original_values ) ) ] if len ( new_values ) != len ( set ( new_values ) ) : raise ValueError ( 'There are not enought different...
def summarize_sed_results ( sed_table ) : """Build a stats summary table for a table that has all the SED results"""
del_cols = [ 'dnde' , 'dnde_err' , 'dnde_errp' , 'dnde_errn' , 'dnde_ul' , 'e2dnde' , 'e2dnde_err' , 'e2dnde_errp' , 'e2dnde_errn' , 'e2dnde_ul' , 'norm' , 'norm_err' , 'norm_errp' , 'norm_errn' , 'norm_ul' , 'ts' ] stats_cols = [ 'dnde' , 'dnde_ul' , 'e2dnde' , 'e2dnde_ul' , 'norm' , 'norm_ul' ] table_out = Table ( se...
def make_triple ( sub , pred , obj ) : """Takes a subject predicate and object and joins them with a space in between Args : sub - - Subject pred - - Predicate obj - - Object Returns str"""
return "{s} {p} {o} ." . format ( s = sub , p = pred , o = obj )
def create_telnet_shell ( shell , loop = None ) : """Run a shell application with a telnet frontend : param application : An EmbedShell instance : param loop : The event loop : returns : Telnet server"""
if loop is None : loop = asyncio . get_event_loop ( ) def factory ( reader , writer ) : return ShellConnection ( reader , writer , shell , loop ) return AsyncioTelnetServer ( binary = True , echo = True , naws = True , connection_factory = factory )
def iter_orgs ( username , number = - 1 , etag = None ) : """List the organizations associated with ` ` username ` ` . : param str username : ( required ) , login of the user : param int number : ( optional ) , number of orgs to return . Default : - 1, return all of the issues : param str etag : ( optional ...
return gh . iter_orgs ( username , number , etag ) if username else [ ]
def form_valid_bridge ( self , form , field , model , related_field , error_message ) : """call from form _ valid . @ form : it is form of form _ valid ( type : form ) @ field : name of the form field referring to the brigde ( type : string ) @ model : form ' s model ( type class ) @ related _ field : name ...
# get instance of selected external object external = form . cleaned_data [ field ] object_edit = model . objects . get ( pk = form . instance . pk ) if object_edit . external == external : answer = super ( GenUpdateBridge , self ) . form_valid ( form ) else : related_object = get_external_model ( model ) . obj...
def load ( cls , model , opt , meta , flag_gpu = None ) : '''Loads in model as a class instance with with the specified model and optimizer states . Parameters model : str Path to the model state file . opt : str Path to the optimizer state file . meta : str Path to the class metadata state file . ...
mess = "Model file {0} does not exist. Please check the file path." assert os . path . exists ( model ) , mess . format ( model ) assert os . path . exists ( opt ) , mess . format ( opt ) assert os . path . exists ( meta ) , mess . format ( meta ) with open ( meta , 'r' ) as f : meta = json . load ( f ) if flag_gpu...
def disassemble_sparse_matrix ( matrix : scipy . sparse . spmatrix ) -> dict : """Transform a scipy . sparse matrix into the serializable collection of : class : ` numpy . ndarray ` - s . : func : ` assemble _ sparse _ matrix ( ) ` does the inverse . : param matrix : : mod : ` scipy . sparse ` matrix ; csr , csc ...
fmt = matrix . getformat ( ) if fmt not in ( "csr" , "csc" , "coo" ) : raise ValueError ( "Unsupported scipy.sparse matrix format: %s." % fmt ) result = { "shape" : matrix . shape , "format" : fmt } if isinstance ( matrix , ( scipy . sparse . csr_matrix , scipy . sparse . csc_matrix ) ) : lengths = numpy . conc...
def _ensure_node ( node : Union [ str , AbstractNode ] ) -> AbstractNode : """Ensure to be node . If ` ` node ` ` is string , convert it to ` ` Text ` ` node ."""
if isinstance ( node , str ) : return Text ( node ) elif isinstance ( node , Node ) : return node else : raise TypeError ( 'Invalid type to append: {}' . format ( node ) )
def addStencilBranch ( self , disp , weight ) : """Set or overwrite the stencil weight for the given direction @ param disp displacement vector @ param weight stencil weight"""
self . stencil [ tuple ( disp ) ] = weight self . __setPartionLogic ( disp )
def x_rolls ( self , number , count = 0 ) : '''Iterator of number dice rolls . : param count : [ 0 ] Return list of ` ` count ` ` sums'''
for x in range ( number ) : yield super ( FuncRoll , self ) . roll ( count , self . _func )
def requires ( self , require = None ) : """Requires Sets the require rules used to validate the Parent Arguments : require { dict } - - A dictionary expressing requirements of fields Raises : ValueError Returns : None"""
# If require is None , this is a getter if require is None : return self . _requires # If it ' s not a valid dict if not isinstance ( require , dict ) : raise ValueError ( '__require__' ) # Go through each key and make sure it goes with a field for k , v in iteritems ( require ) : # If the field doesn ' t exist...
def get_coords ( data , coords ) : """Subselects xarray dataset object to provided coords . Raises exception if fails . Raises ValueError If coords name are not available in data KeyError If coords dims are not available in data Returns data : xarray xarray . Dataset object"""
try : return data . sel ( ** coords ) except ValueError : invalid_coords = set ( coords . keys ( ) ) - set ( data . coords . keys ( ) ) raise ValueError ( "Coords {} are invalid coordinate keys" . format ( invalid_coords ) ) except KeyError as err : raise KeyError ( ( "Coords should follow mapping forma...
def random ( args ) : """% prog random fasta 100 > random100 . fasta Take number of records randomly from fasta"""
from random import sample p = OptionParser ( random . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fastafile , N = args N = int ( N ) assert N > 0 f = Fasta ( fastafile ) fw = must_open ( "stdout" , "w" ) for key in sample ( f . keys ( ) , N ) : re...
def diagonalized_iter ( size ) : r"""TODO : generalize to more than 2 dimensions to be more like itertools . product . CommandLine : python - m utool . util _ alg - - exec - diagonalized _ iter python - m utool . util _ alg - - exec - diagonalized _ iter - - size = 5 Example : > > > # ENABLE _ DOCTEST ...
for i in range ( 0 , size + 1 ) : for r , c in zip ( reversed ( range ( i ) ) , ( range ( i ) ) ) : yield ( r , c ) for i in range ( 1 , size ) : for r , c in zip ( reversed ( range ( i , size ) ) , ( range ( i , size ) ) ) : yield ( r , c )
def _apply_dvportgroup_security_policy ( pg_name , sec_policy , sec_policy_conf ) : '''Applies the values in sec _ policy _ conf to a security policy object pg _ name The name of the portgroup sec _ policy The vim . DVSTrafficShapingPolicy to apply the config to sec _ policy _ conf The out shaping confi...
log . trace ( 'Building portgroup\'s \'%s\' security policy ' , pg_name ) if 'allow_promiscuous' in sec_policy_conf : sec_policy . allowPromiscuous = vim . BoolPolicy ( ) sec_policy . allowPromiscuous . value = sec_policy_conf [ 'allow_promiscuous' ] if 'forged_transmits' in sec_policy_conf : sec_policy . f...
def _get_conn ( profile ) : '''Get a connection to CouchDB'''
DEFAULT_BASE_URL = _construct_uri ( profile ) or 'http://localhost:5984' server = couchdb . Server ( ) if profile [ 'database' ] not in server : server . create ( profile [ 'database' ] ) return server
def get_states ( self ) : """Add states to variable of BIF Returns dict : dict of type { variable : a list of states } Example > > > from pgmpy . readwrite import BIFReader , BIFWriter > > > model = BIFReader ( ' dog - problem . bif ' ) . get _ model ( ) > > > writer = BIFWriter ( model ) > > > writer...
variable_states = { } cpds = self . model . get_cpds ( ) for cpd in cpds : variable = cpd . variable variable_states [ variable ] = [ ] for state in range ( cpd . get_cardinality ( [ variable ] ) [ variable ] ) : variable_states [ variable ] . append ( str ( variable ) + '_' + str ( state ) ) return...
def verify_signature ( message , signature , certs ) : """Verify an RSA cryptographic signature . Checks that the provided ` ` signature ` ` was generated from ` ` bytes ` ` using the private key associated with the ` ` cert ` ` . Args : message ( Union [ str , bytes ] ) : The plaintext message . signatur...
if isinstance ( certs , ( six . text_type , six . binary_type ) ) : certs = [ certs ] for cert in certs : verifier = rsa . RSAVerifier . from_string ( cert ) if verifier . verify ( message , signature ) : return True return False
def warn_if_nans_exist ( X ) : """Warn if nans exist in a numpy array ."""
null_count = count_rows_with_nans ( X ) total = len ( X ) percent = 100 * null_count / total if null_count > 0 : warning_message = 'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' 'complete rows will be plotted.' . format ( null_count , total , percent ) warnings . warn ( warning_message , DataW...
def project_process ( index , start , end ) : """Compute the metrics for the project process section of the enriched github issues index . Returns a dictionary containing " bmi _ metrics " , " time _ to _ close _ metrics " , " time _ to _ close _ review _ metrics " and patchsets _ metrics as the keys and th...
results = { "bmi_metrics" : [ BMIPR ( index , start , end ) ] , "time_to_close_metrics" : [ ] , "time_to_close_review_metrics" : [ DaysToClosePRAverage ( index , start , end ) , DaysToClosePRMedian ( index , start , end ) ] , "patchsets_metrics" : [ ] } return results
def find_by_index ( self , cls , index_name , value ) : """Required functionality ."""
table_name = cls . get_table_name ( ) index_name_vals = [ ( index_name , value ) ] final_results = [ ] for db_result in read_by_indexes ( table_name , index_name_vals ) : obj = cls . from_data ( db_result [ 'value' ] ) final_results . append ( obj ) return final_results
def _apply_groups_to_backend ( cls , obj , options , backend , clone ) : "Apply the groups to a single specified backend"
obj_handle = obj if options is None : if clone : obj_handle = obj . map ( lambda x : x . clone ( id = None ) ) else : obj . map ( lambda x : setattr ( x , 'id' , None ) ) elif clone : obj_handle = obj . map ( lambda x : x . clone ( id = x . id ) ) return StoreOptions . set_options ( obj_hand...
def give_str_indented ( self , tags = False ) : """Give indented string representation of the callable . This is used in : ref : ` automate - webui ` ."""
args = self . _args [ : ] kwargs = self . _kwargs rv = self . _give_str_indented ( args , kwargs , tags ) if not tags : rv = self . strip_color_tags ( rv ) return rv
def point_on_line ( ab , c ) : '''point _ on _ line ( ( a , b ) , c ) yields True if point x is on line ( a , b ) and False otherwise .'''
( a , b ) = ab abc = [ np . asarray ( u ) for u in ( a , b , c ) ] if any ( len ( u . shape ) == 2 for u in abc ) : ( a , b , c ) = [ np . reshape ( u , ( len ( u ) , - 1 ) ) for u in abc ] else : ( a , b , c ) = abc vca = a - c vcb = b - c uba = czdivide ( vba , np . sqrt ( np . sum ( vba ** 2 , axis = 0 ) ) )...
def expand_annotations ( src_dir , dst_dir ) : """Expand annotations in user code . Return dst _ dir if annotation detected ; return src _ dir if not . src _ dir : directory path of user code ( str ) dst _ dir : directory to place generated files ( str )"""
if src_dir [ - 1 ] == slash : src_dir = src_dir [ : - 1 ] if dst_dir [ - 1 ] == slash : dst_dir = dst_dir [ : - 1 ] annotated = False for src_subdir , dirs , files in os . walk ( src_dir ) : assert src_subdir . startswith ( src_dir ) dst_subdir = src_subdir . replace ( src_dir , dst_dir , 1 ) os . m...
def fix_config ( self , options ) : """Fixes the options , if necessary . I . e . , it adds all required elements to the dictionary . : param options : the options to fix : type options : dict : return : the ( potentially ) fixed options : rtype : dict"""
opt = "setup" if opt not in options : options [ opt ] = filters . Filter ( classname = "weka.filters.AllFilter" ) if opt not in self . help : self . help [ opt ] = "The filter to apply to the dataset (Filter)." opt = "keep_relationname" if opt not in options : options [ opt ] = False if opt not in self . he...
def run ( self , image , command = None , create_kwargs = None , start_kwargs = None , volume_bindings = None , privileged = None ) : """create container from provided image and start it for more info , see documentation of REST API calls : * containers / { } / start * container / create : param image : Ima...
logger . info ( "creating container from image '%s' and running it" , image ) create_kwargs = create_kwargs or { } if 'host_config' not in create_kwargs : conf = { } if volume_bindings is not None : conf [ 'binds' ] = volume_bindings if privileged is not None : conf [ 'privileged' ] = privil...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'feedback' ) and self . feedback is not None : _dict [ 'feedback' ] = [ x . _to_dict ( ) for x in self . feedback ] return _dict
def _get_valid_endpoint ( resp , name , entry_type ) : """Parse the service catalog returned by the Identity API for an endpoint matching the Nova service with the requested version Sends a CRITICAL service check when no viable candidates are found in the Catalog"""
catalog = resp . get ( 'token' , { } ) . get ( 'catalog' , [ ] ) for entry in catalog : if ( entry . get ( 'name' ) and entry . get ( 'type' ) and entry . get ( 'name' ) == name and entry . get ( 'type' ) == entry_type ) : # Collect any endpoints on the public or internal interface valid_endpoints = { } ...
def _GetDirectory ( self ) : """Retrieves a directory . Returns : OSDirectory : a directory object or None if not available ."""
if self . entry_type != definitions . FILE_ENTRY_TYPE_DIRECTORY : return None return OSDirectory ( self . _file_system , self . path_spec )
def show_pageitems ( _ , token ) : """Show page items . Usage : . . code - block : : html + django { % show _ pageitems per _ page % }"""
# Validate args . if len ( token . contents . split ( ) ) != 1 : msg = '%r tag takes no arguments' % token . contents . split ( ) [ 0 ] raise template . TemplateSyntaxError ( msg ) # Call the node . return ShowPageItemsNode ( )
def virt_customize ( self , options ) : """Handler for ' virt - customize ' note : if ' ssh - inject ' option was specified without a path to a key , the prefix ' key will be copied to the vm . Args : options ( lst of str ) : Options and arguments for ' virt - customize ' Returns : callable : which hand...
cmd = [ 'virt-customize' , '-a' , self . disk_path ] if 'ssh-inject' in options and not options [ 'ssh-inject' ] : options [ 'ssh-inject' ] = 'root:file:{}' . format ( self . paths . ssh_id_rsa_pub ( ) ) options = self . normalize_options ( options ) cmd . extend ( options ) return Command ( 'virt-customize' , cmd ...
async def _get_packet_from_stream ( self , stream , existing_data , got_first_packet = True , psml_structure = None ) : """A coroutine which returns a single packet if it can be read from the given StreamReader . : return a tuple of ( packet , remaining _ data ) . The packet will be None if there was not enough X...
# yield each packet in existing _ data if self . use_json : packet , existing_data = self . _extract_packet_json_from_data ( existing_data , got_first_packet = got_first_packet ) else : packet , existing_data = self . _extract_tag_from_data ( existing_data ) if packet : if self . use_json : packet =...
def from_html ( html , url = None , download_date = None ) : """Extracts relevant information from an HTML page given as a string . This function does not invoke scrapy but only uses the article extractor . If you have the original URL make sure to provide it as this helps NewsPlease to extract the publishing d...
extractor = article_extractor . Extractor ( [ 'newspaper_extractor' , 'readability_extractor' , 'date_extractor' , 'lang_detect_extractor' ] ) title_encoded = '' . encode ( ) if not url : url = '' # if an url was given , we can use that as the filename filename = urllib . parse . quote_plus ( url ) + '.json' item =...
def gaussian_variogram_model ( m , d ) : """Gaussian model , m is [ psill , range , nugget ]"""
psill = float ( m [ 0 ] ) range_ = float ( m [ 1 ] ) nugget = float ( m [ 2 ] ) return psill * ( 1. - np . exp ( - d ** 2. / ( range_ * 4. / 7. ) ** 2. ) ) + nugget
def rotateInDeclination ( v1 , theta_deg ) : """Rotation is chosen so a rotation of 90 degrees from zenith ends up at ra = 0 , dec = 0"""
axis = np . array ( [ 0 , - 1 , 0 ] ) return rotateAroundVector ( v1 , axis , theta_deg )
def create_lv ( self , name , length , units ) : """Creates a logical volume and returns the LogicalVolume instance associated with the lv _ t handle : : from lvm2py import * lvm = LVM ( ) vg = lvm . get _ vg ( " myvg " , " w " ) lv = vg . create _ lv ( " mylv " , 40 , " MiB " ) * Args : * * name ( st...
if units != "%" : size = size_units [ units ] * length else : if not ( 0 < length <= 100 ) or type ( length ) is float : raise ValueError ( "Length not supported." ) size = ( self . size ( "B" ) / 100 ) * length self . open ( ) lvh = lvm_vg_create_lv_linear ( self . handle , name , c_ulonglong ( siz...
def translate_text ( estimator , subtokenizer , txt ) : """Translate a single string ."""
encoded_txt = _encode_and_add_eos ( txt , subtokenizer ) def input_fn ( ) : ds = tf . data . Dataset . from_tensors ( encoded_txt ) ds = ds . batch ( _DECODE_BATCH_SIZE ) return ds predictions = estimator . predict ( input_fn ) translation = next ( predictions ) [ "outputs" ] translation = _trim_and_decode ...
def sanitize_resources ( resource ) : """Cleans up incoming scene data : param resource : The dict with scene data to be sanitized . : returns : Cleaned up dict ."""
try : resource [ ATTR_HUB_NAME_UNICODE ] = base64_to_unicode ( resource [ ATTR_HUB_NAME ] ) return resource except ( KeyError , TypeError ) : LOGGER . debug ( "no data available" ) return None
def get_last_doc ( self ) : """Returns the last document stored in Mongo ."""
def docs_by_ts ( ) : for meta_collection_name in self . _meta_collections ( ) : meta_coll = self . meta_database [ meta_collection_name ] for ts_ns_doc in meta_coll . find ( limit = - 1 ) . sort ( "_ts" , - 1 ) : yield ts_ns_doc return max ( docs_by_ts ( ) , key = lambda x : x [ "_ts" ] ...
def strip_prefix ( string , strip ) : """Strips a prefix from a string , if the string starts with the prefix . : param string : String that should have its prefix removed : param strip : Prefix to be removed : return : string with the prefix removed if it has the prefix , or else it just returns the origin...
import re strip_esc = re . escape ( strip ) if re . match ( strip_esc , string ) : return string [ len ( strip ) : ] else : return string
def check_membership ( self , group ) : """Check required group ( s )"""
user_groups = self . request . user . groups . values_list ( "name" , flat = True ) if isinstance ( group , ( list , tuple ) ) : for req_group in group : if req_group in user_groups : return True is_member = group in user_groups if not is_member : messages . add_message ( self . request , me...
def validate_brackets ( input_string : str ) : """Returns True if all opened brackets in the string are closed properly . Brackets in the string are " ( " and " ) " . Arguments : input _ string ( str ) : String of brackets Return : bool : True if brackets are correctly balanced , False otherwise . Examp...
balance_level = 0 for bracket in input_string : if bracket == "(" : balance_level += 1 else : balance_level -= 1 if balance_level < 0 : return False return balance_level == 0
def _post_init ( self ) : """The standard rootpy _ post _ init method that is used to initialize both new Trees and Trees retrieved from a File ."""
if not hasattr ( self , '_buffer' ) : # only set _ buffer if model was not specified in the _ _ init _ _ self . _buffer = TreeBuffer ( ) self . read_branches_on_demand = False self . _branch_cache = { } self . _current_entry = 0 self . _always_read = [ ] self . userdata = UserData ( ) self . _inited = True
def assoc_host ( self , hostname , env ) : """Associate a host with an environment . hostname is opaque to Jones . Any string which uniquely identifies a host is acceptable ."""
dest = self . _get_view_path ( env ) self . associations . set ( hostname , dest )
def me ( self ) : """Get the currently - logged in user . Note : To access a user ’ s private data , the user is required to authorize the ' read _ user ' scope . Without it , this request will return a ' 403 Forbidden ' response . Note : Without a Bearer token ( i . e . using a Client - ID token ) this r...
url = "/me" result = self . _get ( url ) return UserModel . parse ( result )
def delete_document ( self , doc_uri ) : """Delete a document from an item : param doc _ uri : the URI that references the document : type doc _ uri : String : rtype : String : returns : a message confirming that the document was deleted : raises : APIError if the request was not successful"""
result = self . api_request ( doc_uri , method = 'DELETE' ) return self . __check_success ( result )
def get_rsa_key ( self , username ) : """Get rsa key for a given username : param username : username : type username : : class : ` str ` : return : json response : rtype : : class : ` dict ` : raises HTTPError : any problem with http request , timeouts , 5xx , 4xx etc"""
try : resp = self . session . post ( 'https://steamcommunity.com/login/getrsakey/' , timeout = 15 , data = { 'username' : username , 'donotchache' : int ( time ( ) * 1000 ) , } , ) . json ( ) except requests . exceptions . RequestException as e : raise HTTPError ( str ( e ) ) return resp
def monotonic ( values , mode = "<" , atol = 1.e-8 ) : """Returns False if values are not monotonic ( decreasing | increasing ) . mode is " < " for a decreasing sequence , " > " for an increasing sequence . Two numbers are considered equal if they differ less that atol . . . warning : Not very efficient for...
if len ( values ) == 1 : return True if mode == ">" : for i in range ( len ( values ) - 1 ) : v , vp = values [ i ] , values [ i + 1 ] if abs ( vp - v ) > atol and vp <= v : return False elif mode == "<" : for i in range ( len ( values ) - 1 ) : v , vp = values [ i ] , va...
def legal_module_name ( self , name ) : """Legal module names are dotted strings where each part is a valid Python identifier . ( and not a keyword , and support unicode identifiers in Python3 , . . )"""
if name in self . _legal_mnames : return self . _legal_mnames [ name ] for part in name . split ( '.' ) : try : exec ( "%s = 42" % part , { } , { } ) except : # pragma : nocover self . _legal_mnames [ name ] = False return False self . _legal_mnames [ name ] = True return True
def parse_args ( ) : """Parse arguments from the command line"""
parser = argparse . ArgumentParser ( description = TO_KIBANA5_DESC_MSG ) parser . add_argument ( '-s' , '--source' , dest = 'src_path' , required = True , help = 'source directory' ) parser . add_argument ( '-d' , '--dest' , dest = 'dest_path' , required = True , help = 'destination directory' ) parser . add_argument (...
def blueprint ( self ) : """: return : blueprint : rtype : dict"""
blueprint = dict ( ) for key in self . keys ( ) : blueprint [ key ] = self . is_attribute_visible ( key ) return blueprint
def get_datetime_now ( ) : """Returns datetime object with current point in time . In Django 1.4 + it uses Django ' s django . utils . timezone . now ( ) which returns an aware or naive datetime that represents the current point in time when ` ` USE _ TZ ` ` in project ' s settings is True or False respective...
try : from django . utils import timezone return timezone . now ( ) except ImportError : return datetime . datetime . now ( )
def setEnv ( self , name , value = None ) : """Set an environment variable for the worker process before it is launched . The worker process will typically inherit the environment of the machine it is running on but this method makes it possible to override specific variables in that inherited environment bef...
if value is None : try : value = os . environ [ name ] except KeyError : raise RuntimeError ( "%s does not exist in current environment" , name ) self . environment [ name ] = value
def get_parcel ( self , product , version ) : """Lookup a parcel by product and version . @ param product : the product name @ param version : the product version @ return : An ApiParcel object"""
return parcels . get_parcel ( self . _get_resource_root ( ) , product , version , self . name )
def group_by_match ( self , variant ) : '''Given a variant , split the PileupCollection based on whether it the data supports the reference allele , the alternate allele , or neither . Parameters variant : Variant The variant . Must have fields ' locus ' , ' ref ' , and ' alt ' . Returns A MatchingEvide...
locus = to_locus ( variant ) if len ( variant . ref ) != len ( locus . positions ) : logging . warning ( "Ref is length %d but locus has %d bases in variant: %s" % ( len ( variant . ref ) , len ( locus . positions ) , str ( variant ) ) ) alleles_dict = self . group_by_allele ( locus ) single_base_loci = [ Locus . f...
def jsonrpc ( self , request ) : """JSON - RPC 2.0 handler ."""
if request . method != "POST" : return HttpResponseNotAllowed ( [ "POST" ] ) request_str = request . body . decode ( 'utf8' ) try : jsonrpc_request = JSONRPCRequest . from_json ( request_str ) except ( TypeError , ValueError , JSONRPCInvalidRequestException ) : response = JSONRPCResponseManager . handle ( r...
def get_changed_files_from ( old_commit_sha , new_commit_sha ) : """Returns a list of the files changed between two commits"""
return check_output ( "git diff-tree --no-commit-id --name-only -r {0}..{1}" . format ( old_commit_sha , new_commit_sha ) . split ( " " ) ) . decode ( 'utf-8' ) . strip ( )
def format_graylog_v0 ( self , record ) : '''Graylog ' raw ' format is essentially the raw record , minimally munged to provide the bare minimum that td - agent requires to accept and route the event . This is well suited to a config where the client td - agents log directly to Graylog .'''
message_dict = { 'message' : record . getMessage ( ) , 'timestamp' : self . formatTime ( record ) , # Graylog uses syslog levels , not whatever it is Python does . . . 'level' : syslog_levels . get ( record . levelname , 'ALERT' ) , 'tag' : self . tag } if record . exc_info : exc_info = self . formatException ( rec...
def fetch_module ( self , module ) : """Download and verify kernel module : type module : str : param module : kernel module path"""
tm = int ( time . time ( ) ) datestamp = datetime . utcfromtimestamp ( tm ) . isoformat ( ) filename = "lime-{0}-{1}.ko" . format ( datestamp , module [ 'version' ] ) url = "{0}/{1}" . format ( self . url , module [ 'location' ] ) logger . info ( "downloading {0} as {1}" . format ( url , filename ) ) req = requests . g...
def get_optparser ( self ) : """Override to allow specification of the maildir"""
p = Cmdln . get_optparser ( self ) p . add_option ( "-M" , "--maildir" , action = "store" , dest = "maildir" ) p . add_option ( "-V" , "--verbose" , action = "store_true" , dest = "verbose" ) return p
def update ( self , session , lookup_keys , updates , * args , ** kwargs ) : """Updates the model with the specified lookup _ keys and returns the dictified object . : param Session session : The SQLAlchemy session to use : param dict lookup _ keys : A dictionary mapping the fields and their expected values...
model = self . _get_model ( lookup_keys , session ) model = self . _set_values_on_model ( model , updates , fields = self . update_fields ) session . commit ( ) return self . serialize_model ( model )
def build_unprocessable_error ( cls , errors = None ) : """Utility method to build a HTTP 422 Parameter Error object"""
errors = [ errors ] if not isinstance ( errors , list ) else errors return cls ( Status . UNPROCESSABLE_ENTITY , errors )
def config_make ( config_file ) : """Create config . ini on first use , make dir and copy sample ."""
from pkg_resources import resource_filename import shutil if not os . path . exists ( CONFIG_DIR ) : os . makedirs ( CONFIG_DIR ) filename = resource_filename ( "mcc" , "config.ini" ) try : shutil . copyfile ( filename , config_file ) except IOError : print ( "Error copying sample config file: {}" . format ...
def remove_invalid_fields ( self , queryset , fields , view ) : """Remove invalid fields from an ordering . Overwrites the DRF default remove _ invalid _ fields method to return both the valid orderings and any invalid orderings ."""
valid_orderings = [ ] invalid_orderings = [ ] # for each field sent down from the query param , # determine if its valid or invalid for term in fields : stripped_term = term . lstrip ( '-' ) # add back the ' - ' add the end if necessary reverse_sort_term = '' if len ( stripped_term ) is len ( term ) else '-...
def match_path_to_api_path ( path_definitions , target_path , base_path = '' , context = None ) : """Match a request or response path to one of the api paths . Anything other than exactly one match is an error condition ."""
if context is None : context = { } assert isinstance ( context , collections . Mapping ) if target_path . startswith ( base_path ) : # Convert all of the api paths into Path instances for easier regex # matching . normalized_target_path = re . sub ( NORMALIZE_SLASH_REGEX , '/' , target_path ) matching_api_p...
def replace_namespace_with_prefix ( tag_str , ns_reverse_dict = None ) : """Convert XML tag names with namespace on the form ` ` { namespace } tag ` ` to form ` ` prefix : tag ` ` . Args : tag _ str : str Tag name with namespace . E . g . : ` ` { http : / / www . openarchives . org / ore / terms / } Resou...
ns_reverse_dict = ns_reverse_dict or NS_REVERSE_DICT for namespace_str , prefix_str in ns_reverse_dict . items ( ) : tag_str = tag_str . replace ( '{{{}}}' . format ( namespace_str ) , '{}:' . format ( prefix_str ) ) return tag_str
def setup_auditlog_catalog ( portal ) : """Setup auditlog catalog"""
logger . info ( "*** Setup Audit Log Catalog ***" ) catalog_id = auditlog_catalog . CATALOG_AUDITLOG catalog = api . get_tool ( catalog_id ) for name , meta_type in auditlog_catalog . _indexes . iteritems ( ) : indexes = catalog . indexes ( ) if name in indexes : logger . info ( "*** Index '%s' already ...
def identify_hook ( path ) : """Verify that the file at path is the therapist hook and return the hash"""
with open ( path , 'r' ) as f : f . readline ( ) # Discard the shebang line version_line = f . readline ( ) if version_line . startswith ( '# THERAPIST' ) : return version_line . split ( ) [ 2 ]
def _fake_openenumerateinstances ( self , namespace , ** params ) : """Implements WBEM server responder for : meth : ` ~ pywbem . WBEMConnection . OpenEnumerationInstances ` with data from the instance repository ."""
self . _validate_namespace ( namespace ) self . _validate_open_params ( ** params ) result_t = self . _fake_enumerateinstances ( namespace , ** params ) return self . _open_response ( result_t [ 0 ] [ 2 ] , namespace , 'PullInstancesWithPath' , ** params )
def controlled ( m : np . ndarray ) -> np . ndarray : """Make a one - qubit - controlled version of a matrix . : param m : A matrix . : return : A controlled version of that matrix ."""
rows , cols = m . shape assert rows == cols n = rows I = np . eye ( n ) Z = np . zeros ( ( n , n ) ) controlled_m = np . bmat ( [ [ I , Z ] , [ Z , m ] ] ) return controlled_m
def cpu_throttling ( self , cpu_throttling ) : """Sets the percentage of CPU allowed . : param cpu _ throttling : integer"""
log . info ( 'QEMU VM "{name}" [{id}] has set the percentage of CPU allowed to {cpu}' . format ( name = self . _name , id = self . _id , cpu = cpu_throttling ) ) self . _cpu_throttling = cpu_throttling self . _stop_cpulimit ( ) if cpu_throttling : self . _set_cpu_throttling ( )
def _found_barcode ( self , record , sample , barcode = None ) : """Hook called when barcode is found"""
assert record . id == self . current_record [ 'sequence_name' ] self . current_record [ 'sample' ] = sample
def _get_previous_open_tag ( self , obj ) : """Return the open tag of the previous sibling"""
prev_instance = self . get_previous_instance ( obj ) if prev_instance and prev_instance . plugin_type == self . __class__ . __name__ : return prev_instance . glossary . get ( 'open_tag' )
def _pick_selected_option ( cls ) : """Select handler for authors ."""
for option in cls . select_el : # if the select is empty if not hasattr ( option , "selected" ) : return None if option . selected : return option . value return None
def list_container_object_names ( self , container , limit = None , marker = None , prefix = None , delimiter = None , full_listing = False ) : """Returns the names of all the objects in the specified container , optionally limited by the pagination parameters ."""
return self . _manager . list_object_names ( container , marker = marker , limit = limit , prefix = prefix , delimiter = delimiter , full_listing = full_listing )
def get_snpeff_info ( snpeff_string , snpeff_header ) : """Make the vep annotations into a dictionaries A snpeff dictionary will have the snpeff column names as keys and the vep annotations as values . The dictionaries are stored in a list . One dictionary for each transcript . Args : snpeff _ string ( ...
snpeff_annotations = [ dict ( zip ( snpeff_header , snpeff_annotation . split ( '|' ) ) ) for snpeff_annotation in snpeff_string . split ( ',' ) ] return snpeff_annotations
def tree_iter_nexson_proxy ( nexson_proxy ) : """Iterates over NexsonTreeProxy objects in order determined by the nexson blob"""
nexml_el = nexson_proxy . _nexml_el tg_order = nexml_el [ '^ot:treesElementOrder' ] tgd = nexml_el [ 'treesById' ] for tg_id in tg_order : tg = tgd [ tg_id ] tree_order = tg [ '^ot:treeElementOrder' ] tbid = tg [ 'treeById' ] otus = tg [ '@otus' ] for k in tree_order : v = tbid [ k ] ...
def get_next_state ( self , state , ret , oper ) : """Returns the next state for a create or delete operation ."""
if oper == fw_const . FW_CR_OP : return self . get_next_create_state ( state , ret ) else : return self . get_next_del_state ( state , ret )
def ldGet ( self , what , key ) : """List - aware get ."""
if isListKey ( key ) : return what [ listKeyIndex ( key ) ] else : return what [ key ]
def all_departed_units ( self ) : """Collection of all units that were previously part of any relation on this endpoint but which have since departed . This collection is persistent and mutable . The departed units will be kept until they are explicitly removed , to allow for reasonable cleanup of units tha...
if self . _all_departed_units is None : self . _all_departed_units = CachedKeyList . load ( 'reactive.endpoints.departed.{}' . format ( self . endpoint_name ) , RelatedUnit . _deserialize , 'unit_name' ) return self . _all_departed_units
def delete_board ( self , id ) : """Delete an agile board ."""
board = Board ( self . _options , self . _session , raw = { 'id' : id } ) board . delete ( )
def n_frames_total ( self , stride = 1 , skip = 0 ) : r"""Returns total number of frames . Parameters stride : int return value is the number of frames in trajectories when running through them with a step size of ` stride ` . skip : int , default = 0 skip the first initial n frames per trajectory . R...
if not IteratorState . is_uniform_stride ( stride ) : return len ( stride ) return sum ( self . trajectory_lengths ( stride = stride , skip = skip ) )
def connect_async ( self , connection_id , connection_string , callback ) : """Connect to a device by its connection _ string This function asynchronously connects to a device by its BLE address passed in the connection _ string parameter and calls callback when finished . Callback is called on either success...
self . _try_connect ( connection_string ) def _on_finished ( _name , control_info , exception ) : if exception is not None : callback ( connection_id , self . id , False , str ( exception ) ) return if control_info is not None : self . _control_info = control_info callback ( connecti...
def historical_rates ( self , date , symbols = None ) : """Get historical rates for any day since ` date ` . : param date : a date : type date : date or str : param symbols : currency symbols to request specific exchange rates . : type symbols : list or tuple : return : the historical rates for any day si...
try : if isinstance ( date , datetime . date ) : # Convert date to ISO 8601 format . date = date . isoformat ( ) symbols = symbols or self . symbols payload = self . _create_payload ( symbols ) url = BASE_URL + date response = requests . get ( url , params = payload ) response . raise_fo...
def one ( self ) : """Return exactly one result or raise an exception . Raises fulfil _ client . exc . NoResultFound if the query selects no rows . Raises fulfil _ client . exc . MultipleResultsFound if multiple rows are found ."""
results = self . rpc_model . search_read ( self . domain , 2 , None , self . _order_by , self . fields , context = self . context ) if not results : raise fulfil_client . exc . NoResultFound if len ( results ) > 1 : raise fulfil_client . exc . MultipleResultsFound return results [ 0 ]
def truncate ( self , size = 0 ) : """Truncates the stream to the specified length . @ param size : The length of the stream , in bytes . @ type size : C { int }"""
if size == 0 : self . _buffer = StringIO ( ) self . _len_changed = True return cur_pos = self . tell ( ) self . seek ( 0 ) buf = self . read ( size ) self . _buffer = StringIO ( ) self . _buffer . write ( buf ) self . seek ( cur_pos ) self . _len_changed = True
def pool ( self , host , port , db , pools = { } , ** options ) : '''Fetch a redis conenction pool for the unique combination of host and port . Will create a new one if there isn ' t one already .'''
key = ( host , port , db ) rval = pools . get ( key ) if not isinstance ( rval , ConnectionPool ) : rval = ConnectionPool ( host = host , port = port , db = db , ** options ) pools [ key ] = rval return rval
def _get_new_block_mem_instance ( op_param , mem_map , block_out ) : """gets the instance of the memory in the new block that is associated with a memory in a old block"""
memid , old_mem = op_param if old_mem not in mem_map : new_mem = old_mem . _make_copy ( block_out ) new_mem . id = old_mem . id mem_map [ old_mem ] = new_mem return memid , mem_map [ old_mem ]
def color_to_rgb ( color ) : """Converts web color names like " red " or hexadecimal values like " # 36c " , " # FFFFF " and RGB tuples like ` ` ( 255 , 255 255 ) ` ` into a ( R , G , B ) tuple . : param color : A web color name ( i . e . ` ` darkblue ` ` ) or a hexadecimal value ( ` ` # RGB ` ` or ` ` # RRGG...
rgb = color_to_rgb_or_rgba ( color ) if len ( rgb ) != 3 : raise ValueError ( 'The alpha channel {0} in color "{1}" cannot be ' 'converted to RGB' . format ( rgb [ 3 ] , color ) ) return rgb
def enable ( profile = 'allprofiles' ) : '''. . versionadded : : 2015.5.0 Enable firewall profile Args : profile ( Optional [ str ] ) : The name of the profile to enable . Default is ` ` allprofiles ` ` . Valid options are : - allprofiles - domainprofile - privateprofile - publicprofile Returns : ...
cmd = [ 'netsh' , 'advfirewall' , 'set' , profile , 'state' , 'on' ] ret = __salt__ [ 'cmd.run_all' ] ( cmd , python_shell = False , ignore_retcode = True ) if ret [ 'retcode' ] != 0 : raise CommandExecutionError ( ret [ 'stdout' ] ) return True
def searchForPages ( self , name , limit = 10 ) : """Find and get page by its name : param name : Name of the page : return : : class : ` models . Page ` objects , ordered by relevance : rtype : list : raises : FBchatException if request failed"""
params = { "search" : name , "limit" : limit } j = self . graphql_request ( GraphQL ( query = GraphQL . SEARCH_PAGE , params = params ) ) return [ Page . _from_graphql ( node ) for node in j [ name ] [ "pages" ] [ "nodes" ] ]
def make_group_layer ( self , ch_in : int , num_blocks : int , stride : int = 1 ) : "starts with conv layer - ` ch _ in ` channels in - then has ` num _ blocks ` ` ResLayer `"
return [ conv_bn_lrelu ( ch_in , ch_in * 2 , stride = stride ) ] + [ ( ResLayer ( ch_in * 2 ) ) for i in range ( num_blocks ) ]
def _cz_gate ( self , lines ) : """Return the TikZ code for an n - controlled Z - gate . : param lines : List of all qubits involved . : type : list [ int ]"""
line = lines [ 0 ] delta_pos = self . _gate_offset ( Z ) gate_width = self . _gate_width ( Z ) gate_str = self . _phase ( line , self . pos [ line ] ) for ctrl in lines [ 1 : ] : gate_str += self . _phase ( ctrl , self . pos [ line ] ) gate_str += self . _line ( ctrl , line ) new_pos = self . pos [ line ] + del...
def set_torrent_upload_limit ( self , infohash_list , limit ) : """Set upload speed limit of the supplied torrents . : param infohash _ list : Single or list ( ) of infohashes . : param limit : Speed limit in bytes ."""
data = self . _process_infohash_list ( infohash_list ) data . update ( { 'limit' : limit } ) return self . _post ( 'command/setTorrentsUpLimit' , data = data )
def djoin ( * args ) : """' dotless ' join , for nicer paths ."""
from os . path import join i = 0 alen = len ( args ) while i < alen and ( args [ i ] == '' or args [ i ] == '.' ) : i += 1 if i == alen : return '.' return join ( * args [ i : ] )
def handle_page_crumb ( func ) : """Decorator for handling the current page in the breadcrumbs ."""
@ wraps ( func ) def wrapper ( path , model , page , root_name ) : path = PAGE_REGEXP . sub ( '' , path ) breadcrumbs = func ( path , model , root_name ) if page : if page . number > 1 : breadcrumbs [ - 1 ] . url = path page_crumb = Crumb ( _ ( 'Page %s' ) % page . number ) ...
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : DocumentContext for this DocumentInstance : rtype : twilio . rest . preview . sync . service . document . DocumentContext"...
if self . _context is None : self . _context = DocumentContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , sid = self . _solution [ 'sid' ] , ) return self . _context
def single ( self ) : """Whether or not the user is only interested in people that are single ."""
return 'display: none;' not in self . _looking_for_xpb . li ( id = 'ajax_single' ) . one_ ( self . _profile . profile_tree ) . attrib [ 'style' ]