signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_authentication_tokens ( self ) : """get _ auth _ url ( self ) Returns an authorization URL for a user to hit ."""
callback_url = self . callback_url or 'oob' request_args = { } if OAUTH_LIB_SUPPORTS_CALLBACK : request_args [ 'callback_url' ] = callback_url resp , content = self . client . request ( self . request_token_url , "GET" , ** request_args ) if resp [ 'status' ] != '200' : raise AuthError ( "Seems something couldn...
def endBy1 ( p , sep ) : '''` endBy1 ( p , sep ) parses one or more occurrences of ` p ` , separated and ended by ` sep ` . Returns a list of values returned by ` p ` .'''
return separated ( p , sep , 1 , maxt = float ( 'inf' ) , end = True )
def _raw_name_string ( bufr , strings_offset , str_offset , length ) : """Return the * length * bytes comprising the encoded string in * bufr * at * str _ offset * in the strings area beginning at * strings _ offset * ."""
offset = strings_offset + str_offset tmpl = '%ds' % length return unpack_from ( tmpl , bufr , offset ) [ 0 ]
def size ( self , table = None ) : """Return the size , in bytes , of the profile or * table * . If * table * is ` None ` , this function returns the size of the whole profile ( i . e . the sum of the table sizes ) . Otherwise , it returns the size of * table * . Note : if the file is gzipped , it returns t...
size = 0 if table is None : for table in self . relations : size += self . size ( table ) else : try : fn = _table_filename ( os . path . join ( self . root , table ) ) size += os . stat ( fn ) . st_size except ItsdbError : pass return size
def id ( self ) : """Computes the signature of the record , a SHA - 512 of significant values : return : SHa - 512 Hex string"""
h = hashlib . new ( 'sha512' ) for value in ( self . machine . name , self . machine . os , self . user , self . application . name , self . application . path , self . event . report_type , self . event . type , self . event . time . isoformat ( ) ) : h . update ( str ( value ) . encode ( 'utf-8' ) ) for parameter...
def create_intent ( self , workspace_id , intent , description = None , examples = None , ** kwargs ) : """Create intent . Create a new intent . This operation is limited to 2000 requests per 30 minutes . For more information , see * * Rate limiting * * . : param str workspace _ id : Unique identifier of th...
if workspace_id is None : raise ValueError ( 'workspace_id must be provided' ) if intent is None : raise ValueError ( 'intent must be provided' ) if examples is not None : examples = [ self . _convert_model ( x , Example ) for x in examples ] headers = { } if 'headers' in kwargs : headers . update ( kwa...
def _type_insert ( self , handle , key , value ) : '''Insert the value into the series .'''
if value != 0 : if isinstance ( value , float ) : handle . incrbyfloat ( key , value ) else : handle . incr ( key , value )
def ask_list ( question : str , default : list = None ) -> list : """Asks for a comma seperated list of strings"""
default_q = " [default: {0}]: " . format ( "," . join ( default ) ) if default is not None else "" answer = input ( "{0} [{1}]: " . format ( question , default_q ) ) if answer == "" : return default return [ ans . strip ( ) for ans in answer . split ( "," ) ]
def _file_size ( file_path , uncompressed = False ) : """Return size of a single file , compressed or uncompressed"""
_ , ext = os . path . splitext ( file_path ) if uncompressed : if ext in { ".gz" , ".gzip" } : with gzip . GzipFile ( file_path , mode = "rb" ) as fp : try : fp . seek ( 0 , os . SEEK_END ) return fp . tell ( ) except ValueError : # on python2 , cannot...
def _lstree ( files , dirs ) : """Make git ls - tree like output ."""
for f , sha1 in files : yield "100644 blob {}\t{}\0" . format ( sha1 , f ) for d , sha1 in dirs : yield "040000 tree {}\t{}\0" . format ( sha1 , d )
def to_team ( team ) : """Serializes team to id string : param team : object to serialize : return : string id"""
from sevenbridges . models . team import Team if not team : raise SbgError ( 'Team is required!' ) elif isinstance ( team , Team ) : return team . id elif isinstance ( team , six . string_types ) : return team else : raise SbgError ( 'Invalid team parameter!' )
def wb_db004 ( self , value = None ) : """Corresponds to IDD Field ` wb _ db004 ` mean coincident wet - bulb temperature to Dry - bulb temperature corresponding to 0.4 % annual cumulative frequency of occurrence ( warm conditions ) Args : value ( float ) : value for IDD Field ` wb _ db004 ` Unit : C if ...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `wb_db004`' . format ( value ) ) self . _wb_db004 = value
def _cx_counters_psutil ( self , tags = None ) : """Collect metrics about interfaces counters using psutil"""
tags = [ ] if tags is None else tags for iface , counters in iteritems ( psutil . net_io_counters ( pernic = True ) ) : metrics = { 'bytes_rcvd' : counters . bytes_recv , 'bytes_sent' : counters . bytes_sent , 'packets_in.count' : counters . packets_recv , 'packets_in.error' : counters . errin , 'packets_out.count'...
def load ( self ) : """Loads the prefixes that are available is the workdir Returns : None Raises : MalformedWorkdir : if the wordir is malformed"""
if self . loaded : LOGGER . debug ( 'Already loaded' ) return try : basepath , dirs , _ = os . walk ( self . path ) . next ( ) except StopIteration : raise MalformedWorkdir ( 'Empty dir %s' % self . path ) full_path = partial ( os . path . join , basepath ) found_current = False for dirname in dirs : ...
def update_checksum ( self , progress_callback = None , chunk_size = None , checksum_kwargs = None , ** kwargs ) : """Update checksum based on file ."""
self . checksum = self . storage ( ** kwargs ) . checksum ( progress_callback = progress_callback , chunk_size = chunk_size , ** ( checksum_kwargs or { } ) )
def _validate_name ( name ) : '''Checks if the provided name fits Linode ' s labeling parameters . . . versionadded : : 2015.5.6 name The VM name to validate'''
name = six . text_type ( name ) name_length = len ( name ) regex = re . compile ( r'^[a-zA-Z0-9][A-Za-z0-9_-]*[a-zA-Z0-9]$' ) if name_length < 3 or name_length > 48 : ret = False elif not re . match ( regex , name ) : ret = False else : ret = True if ret is False : log . warning ( 'A Linode label may on...
def save_function_effect ( module ) : """Recursively save function effect for pythonic functions ."""
for intr in module . values ( ) : if isinstance ( intr , dict ) : # Submodule case save_function_effect ( intr ) else : fe = FunctionEffects ( intr ) IntrinsicArgumentEffects [ intr ] = fe if isinstance ( intr , intrinsic . Class ) : save_function_effect ( intr . fiel...
def handle_program_options ( ) : """Uses the built - in argparse module to handle command - line options for the program . : return : The gathered command - line options specified by the user : rtype : argparse . ArgumentParser"""
parser = argparse . ArgumentParser ( description = "Convert Sanger-sequencing \ derived data files for use with the \ metagenomics analysis program QIIME, by \ extracting Sample ID information, adding\ ...
def kill_raylet ( self , check_alive = True ) : """Kill the raylet . Args : check _ alive ( bool ) : Raise an exception if the process was already dead ."""
self . _kill_process_type ( ray_constants . PROCESS_TYPE_RAYLET , check_alive = check_alive )
def init_user ( ) : """Create and populate the ~ / . config / rapport directory tree if it ' s not existing . Doesn ' t interfere with already existing directories or configuration files ."""
if not os . path . exists ( USER_CONFIG_DIR ) : if rapport . config . get_int ( "rapport" , "verbosity" ) >= 1 : print ( "Create user directory {0}" . format ( USER_CONFIG_DIR ) ) os . makedirs ( USER_CONFIG_DIR ) for subdir in [ "plugins" , "reports" , "templates/plugin" , "templates/email" , "template...
def modify ( self , entry_id , ** kw ) : '''Incremental version of : meth : ` update ` : instead of updating all attributes of the entry to the specified values , this method only updates the specified keywords . Returns True on success , or raises an exception on failure . Note : the default implementation...
entry = self . read ( entry_id ) for k , v in kw . items ( ) : setattr ( entry , k , v ) self . update ( entry ) return True
def symbol_scores ( self , symbol ) : """Find matches for symbol . : param symbol : A . separated symbol . eg . ' os . path . basename ' : returns : A list of tuples of ( score , package , reference | None ) , ordered by score from highest to lowest ."""
scores = [ ] path = [ ] # sys . path sys path - > import sys # os . path . basename os . path basename - > import os . path # basename os . path basename - > from os . path import basename # path . basename os . path basename - > from os import path def fixup ( module , variable ) : prefix = module . split ( '.' ) ...
def get_bounce_dump ( bounce_id , api_key = None , secure = None , test = None , ** request_args ) : '''Get the raw email dump for a single bounce . : param bounce _ id : The bounce ' s id . Get the id with : func : ` get _ bounces ` . : param api _ key : Your Postmark API key . Required , if ` test ` is not ` ...
return _default_bounce_dump . get ( bounce_id , api_key = api_key , secure = secure , test = test , ** request_args )
def _add_jobs ( self ) : """Add configured jobs ."""
for name , params in self . jobs . items ( ) : if params . active : params . handler = params . handler ( params ) self . sched . add_cron_job ( params . handler . run , ** params . schedule )
def authorized_handler ( self , f ) : """Decorator for the route that is used as the callback for authorizing with GitHub . This callback URL can be set in the settings for the app or passed in during authorization ."""
@ wraps ( f ) def decorated ( * args , ** kwargs ) : if 'code' in request . args : data = self . _handle_response ( ) else : data = self . _handle_invalid_response ( ) return f ( * ( ( data , ) + args ) , ** kwargs ) return decorated
def shape ( self ) -> Tuple [ int , int ] : """Required shape of | NetCDFVariableAgg . array | . For the default configuration , the first axis corresponds to the number of devices , and the second one to the number of timesteps . We show this for the 1 - dimensional input sequence | lland _ fluxes . NKor | :...
return self . sort_timeplaceentries ( len ( hydpy . pub . timegrids . init ) , len ( self . sequences ) )
def register_composite ( cls , name , handle = None , factory = None ) : """Maps a Postgresql type to this class . If the class ' s * table * attribute is empty , and the class has an attribute * pg _ type * of tuple ( schema , type ) , it is calculated and set by querying Postgres . Register inherited / inheri...
class CustomCompositeCaster ( psycopg2 . extras . CompositeCaster ) : def make ( self , values ) : d_out ( "CustomCompositeCaster.make: cls={0} values={1}" . format ( repr ( cls ) , repr ( values ) ) ) return cls ( ** dict ( list ( zip ( self . attnames , values ) ) ) ) PG_TYPE_SQL = """SELECT array...
def mutationhash ( strings , nedit ) : """produce a hash with each key a nedit distance substitution for a set of strings . values of the hash is the set of strings the substitution could have come from"""
maxlen = max ( [ len ( string ) for string in strings ] ) indexes = generate_idx ( maxlen , nedit ) muthash = defaultdict ( set ) for string in strings : muthash [ string ] . update ( [ string ] ) for x in substitution_set ( string , indexes ) : muthash [ x ] . update ( [ string ] ) return muthash
def parse_quotes ( cmd , quotes = True , string = True ) : """parses quotes"""
import shlex try : args = shlex . split ( cmd ) if quotes else cmd . split ( ) except ValueError as exception : logger . error ( exception ) return [ ] return [ str ( arg ) for arg in args ] if string else args
def OSLibraries ( self ) : """Microsoft Windows SDK Libraries"""
if self . vc_ver <= 10.0 : arch_subdir = self . pi . target_dir ( hidex86 = True , x64 = True ) return [ os . path . join ( self . si . WindowsSdkDir , 'Lib%s' % arch_subdir ) ] else : arch_subdir = self . pi . target_dir ( x64 = True ) lib = os . path . join ( self . si . WindowsSdkDir , 'lib' ) li...
def getWinner ( self , type = 'activation' ) : """Returns the winner of the type specified { ' activation ' or ' target ' } ."""
maxvalue = - 10000 maxpos = - 1 ttlvalue = 0 if type == 'activation' : ttlvalue = Numeric . add . reduce ( self . activation ) maxpos = Numeric . argmax ( self . activation ) maxvalue = self . activation [ maxpos ] elif type == 'target' : # note that backprop ( ) resets self . targetSet flag if self . v...
def join ( self ) : """Wait for root state to finish execution"""
self . _root_state . join ( ) # execution finished , close execution history log file ( if present ) if len ( self . _execution_histories ) > 0 : if self . _execution_histories [ - 1 ] . execution_history_storage is not None : set_read_and_writable_for_all = global_config . get_config_value ( "EXECUTION_LOG...
def do_exists ( self , params ) : """\x1b [1mNAME \x1b [0m exists - Gets the znode ' s stat information \x1b [1mSYNOPSIS \x1b [0m exists < path > [ watch ] [ pretty _ date ] \x1b [1mOPTIONS \x1b [0m * watch : set a ( data ) watch on the path ( default : false ) \x1b [1mEXAMPLES \x1b [0m exists / foo ...
watcher = lambda evt : self . show_output ( str ( evt ) ) kwargs = { "watch" : watcher } if params . watch else { } pretty = params . pretty_date path = self . resolve_path ( params . path ) stat = self . _zk . exists ( path , ** kwargs ) if stat : session = stat . ephemeralOwner if stat . ephemeralOwner else 0 ...
def between ( min_value , max_value ) : 'Numerical values limit'
message = N_ ( 'value should be between %(min)d and %(max)d' ) % dict ( min = min_value , max = max_value ) @ validator ( message ) def wrapper ( conv , value ) : if value is None : # it meens that this value is not required return True if value < min_value : return False if value > max_valu...
def _htpasswd ( username , password , ** kwargs ) : '''Provide authentication via Apache - style htpasswd files'''
from passlib . apache import HtpasswdFile pwfile = HtpasswdFile ( kwargs [ 'filename' ] ) # passlib below version 1.6 uses ' verify ' function instead of ' check _ password ' if salt . utils . versions . version_cmp ( kwargs [ 'passlib_version' ] , '1.6' ) < 0 : return pwfile . verify ( username , password ) else :...
def template ( * args , ** kwargs ) : '''Get a rendered template as a string iterator . You can use a name , a filename or a template string as first parameter . Template rendering arguments can be passed as dictionaries or directly ( as keyword arguments ) .'''
tpl = args [ 0 ] if args else None template_adapter = kwargs . pop ( 'template_adapter' , SimpleTemplate ) if tpl not in TEMPLATES or DEBUG : settings = kwargs . pop ( 'template_settings' , { } ) lookup = kwargs . pop ( 'template_lookup' , TEMPLATE_PATH ) if isinstance ( tpl , template_adapter ) : T...
def replace_if_changed ( localfile , jottapath , JFS ) : """Compare md5 hash to determine if contents have changed . Upload a file from local disk and replace file on JottaCloud if the md5s differ , or continue uploading if the file is incompletely uploaded . Returns the JottaFile object"""
jf = JFS . getObject ( jottapath ) lf_hash = getxattrhash ( localfile ) # try to read previous hash , stored in xattr if lf_hash is None : # no valid hash found in xattr , with open ( localfile ) as lf : lf_hash = calculate_md5 ( lf ) # ( re ) calculate it if type ( jf ) == JFSIncompleteFile : l...
def keys ( self , history = None ) : """Get the set of I { all } property names . @ param history : A history of nodes checked to prevent circular hunting . @ type history : [ L { Properties } , . . ] @ return : A set of property names . @ rtype : list"""
if history is None : history = [ ] history . append ( self ) keys = set ( ) keys . update ( self . definitions . keys ( ) ) for x in self . links : if x in history : continue keys . update ( x . keys ( history ) ) history . remove ( self ) return keys
def childgroup ( self , field ) : """Return a list of fields stored by row regarding the configured grid : param field : The original field this widget is attached to"""
grid = getattr ( self , "grid" , None ) named_grid = getattr ( self , "named_grid" , None ) if grid is not None : childgroup = self . _childgroup ( field . children , grid ) elif named_grid is not None : childgroup = self . _childgroup_by_name ( field . children , named_grid ) else : raise AttributeError ( ...
def quit_banner ( self ) -> None : """Print a banner for running the system"""
print ( "=" * 80 ) print ( "Done." ) print ( dtm . datetime . now ( ) . strftime ( "%Y/%m/%d - %H:%M:%S" ) ) print ( "=" * 80 )
from typing import List from collections import Counter def count_element_frequency ( elements : List [ int ] ) -> dict : """Calculate frequency of each element in the given list . Examples : > > > count _ element _ frequency ( [ 10 , 10 , 10 , 10 , 20 , 20 , 20 , 20 , 40 , 40 , 50 , 50 , 30 ] ) {10 : 4 , 20 ...
return Counter ( elements )
def to_plain_text ( str ) : '''Return a plain - text version of a given string This is a dumb approach that tags and then removing entity markers but this is fine for the content from biocyc where entities are & beta ; etc . Stripping in this way turns these into plaintext ' beta ' which is preferable to un...
str = strip_tags_re . sub ( '' , str ) str = strip_entities_re . sub ( '' , str ) return str
def connect_delete_namespaced_pod_proxy ( self , name , namespace , ** kwargs ) : # noqa : E501 """connect _ delete _ namespaced _ pod _ proxy # noqa : E501 connect DELETE requests to proxy of Pod # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , pl...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . connect_delete_namespaced_pod_proxy_with_http_info ( name , namespace , ** kwargs ) # noqa : E501 else : ( data ) = self . connect_delete_namespaced_pod_proxy_with_http_info ( name , namespace , ** kwargs ) # noqa...
def _keyword_expander ( word , language , lemmatized = False , threshold = 0.70 ) : """Find similar terms in Word2Vec models . Accepts string and returns a list of terms of n similarity . : rtype : list"""
try : from cltk . vector . word2vec import get_sims except ImportError as imp_err : print ( imp_err ) raise similar_vectors = get_sims ( word , language , lemmatized = lemmatized , threshold = threshold ) return similar_vectors
def get_catalog_metadata ( catalog , exclude_meta_fields = None ) : """Devuelve sólo la metadata de nivel catálogo ."""
exclude_meta_fields = exclude_meta_fields or [ ] catalog_dict_copy = catalog . copy ( ) del catalog_dict_copy [ "dataset" ] for excluded_meta_field in exclude_meta_fields : catalog_dict_copy . pop ( excluded_meta_field , None ) return catalog_dict_copy
def setdefault ( self , sid , value , dtype = F64 ) : """Works like ` dict . setdefault ` : if the ` sid ` key is missing , it fills it with an array and returns the associate ProbabilityCurve : param sid : site ID : param value : value used to fill the returned ProbabilityCurve : param dtype : dtype used i...
try : return self [ sid ] except KeyError : array = numpy . empty ( ( self . shape_y , self . shape_z ) , dtype ) array . fill ( value ) pc = ProbabilityCurve ( array ) self [ sid ] = pc return pc
def compiled_init_func ( self ) : """Returns compiled init function"""
def get_column_assignment ( column_name ) : return ALCHEMY_TEMPLATES . col_assignment . safe_substitute ( col_name = column_name ) def get_compiled_args ( arg_name ) : return ALCHEMY_TEMPLATES . func_arg . safe_substitute ( arg_name = arg_name ) join_string = "\n" + self . tab + self . tab column_assignments = ...
def process_entries ( self , omimids , transform , included_fields = None , graph = None , limit = None , globaltt = None ) : """Given a list of omim ids , this will use the omim API to fetch the entries , according to the ` ` ` included _ fields ` ` ` passed as a parameter . If a transformation function is s...
omimparams = { } # add the included _ fields as parameters if included_fields is not None and included_fields : omimparams [ 'include' ] = ',' . join ( included_fields ) processed_entries = list ( ) # scrub any omim prefixes from the omimids before processing # cleanomimids = set ( ) # for omimid in omimids : # scr...
def weighted_random ( sample , embedding ) : """Determines the sample values by weighed random choice . Args : sample ( dict ) : A sample of the form { v : val , . . . } where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler . embedding ...
unembeded = { } for v , chain in iteritems ( embedding ) : vals = [ sample [ u ] for u in chain ] # pick a random element uniformly from all vals , this weights them by # the proportion of each unembeded [ v ] = random . choice ( vals ) yield unembeded
def insertFile ( self , qInserts = False ) : """API to insert a list of file into DBS in DBS . Up to 10 files can be inserted in one request . : param qInserts : True means that inserts will be queued instead of done immediately . INSERT QUEUE Manager will perform the inserts , within few minutes . : type qInse...
if qInserts in ( False , 'False' ) : qInserts = False try : body = request . body . read ( ) indata = cjson . decode ( body ) [ "files" ] if not isinstance ( indata , ( list , dict ) ) : dbsExceptionHandler ( "dbsException-invalid-input" , "Invalid Input DataType" , self . logger . exception , "...
def parse_cstring ( stream , offset ) : """parse _ cstring will parse a null - terminated string in a bytestream . The string will be decoded with UTF - 8 decoder , of course since we are doing this byte - a - byte , it won ' t really work for all Unicode strings . TODO : add proper Unicode support"""
stream . seek ( offset ) string = "" while True : char = struct . unpack ( 'c' , stream . read ( 1 ) ) [ 0 ] if char == b'\x00' : return string else : string += char . decode ( )
def earth_orientation ( date ) : """Earth orientation as a rotating matrix"""
x_p , y_p , s_prime = np . deg2rad ( _earth_orientation ( date ) ) return rot3 ( - s_prime ) @ rot2 ( x_p ) @ rot1 ( y_p )
def validate ( self , body , params = None ) : """: arg body : The job config"""
if body in SKIP_IN_PATH : raise ValueError ( "Empty value passed for a required argument 'body'." ) return self . transport . perform_request ( "POST" , "/_ml/anomaly_detectors/_validate" , params = params , body = body )
def _process_info ( raw_info : VideoInfo ) -> VideoInfo : """Process raw information about the video ( parse date , etc . ) ."""
raw_date = raw_info . date date = datetime . strptime ( raw_date , '%Y-%m-%d %H:%M' ) # 2018-04-05 17:00 video_info = raw_info . _replace ( date = date ) return video_info
def unpack_nested_exception ( error ) : """If exception are stacked , return the first one : param error : A python exception with possible exception embeded within : return : A python exception with no exception embeded within"""
i = 0 while True : if error . args [ i : ] : if isinstance ( error . args [ i ] , Exception ) : error = error . args [ i ] i = 0 else : i += 1 else : break return error
def set_result ( self , msg , valid = True , overwrite = False ) : """Set result string and validity ."""
if self . has_result and not overwrite : log . warn ( LOG_CHECK , "Double result %r (previous %r) for %s" , msg , self . result , self ) else : self . has_result = True if not isinstance ( msg , unicode ) : log . warn ( LOG_CHECK , "Non-unicode result for %s: %r" , self , msg ) elif not msg : log . warn...
def load_dataset ( date ) : """Load the dataset for a single date Parameters date : the date ( string ) for which to load the data & dataset Returns ds : the dataset object"""
LAB_DIR = "/home/annaho/TheCannon/data/lamost" WL_DIR = "/home/annaho/TheCannon/code/lamost/mass_age/cn" SPEC_DIR = "/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels/output" wl = np . load ( WL_DIR + "/wl_cols.npz" ) [ 'arr_0' ] [ 0 : 3626 ] # no cols ds = dataset . Dataset ( wl , [ ] , [ ] , [ ] , [ ] , [ ] , ...
def power_modulo_p ( n : int , p : int ) -> int : """Return 2 ^ n modulo p . This function computes the value of 2 ^ n modulo p . Args : n ( int ) : The exponent to which 2 should be raised . p ( int ) : The modulus against which the resulting value should be determined . Returns : int : The result of t...
if p == 0 : raise ValueError ( "Modulo by zero is undefined." ) return pow ( 2 , n , p )
def set_field_value ( self , field_name , value ) : """Set value of response field named ` field _ name ` . If response contains single item , its field is set . If response contains multiple items , all the items in response are edited . To edit response meta ( e . g . ' count ' ) edit response directly at...
if self . response is None : return if 'data' in self . response : items = self . response [ 'data' ] else : items = [ self . response ] for item in items : item [ field_name ] = value
def modify_symbol ( sym : ast . Symbol , scope : ast . InstanceClass ) -> None : """Apply a modification to a symbol if the scope matches ( or is None ) : param sym : symbol to apply modifications for : param scope : scope of modification"""
# We assume that we do not screw up the order of applying modifications # when " moving up " with the scope . apply_args = [ x for x in sym . class_modification . arguments if x . scope is None or x . scope . full_reference ( ) . to_tuple ( ) == scope . full_reference ( ) . to_tuple ( ) ] skip_args = [ x for x in sym ....
def set_selected_pair ( self , component , local_foundation , remote_foundation ) : """Force the selected candidate pair . If the remote party does not support ICE , you should using this instead of calling : meth : ` connect ` ."""
# find local candidate protocol = None for p in self . _protocols : if ( p . local_candidate . component == component and p . local_candidate . foundation == local_foundation ) : protocol = p break # find remote candidate remote_candidate = None for c in self . _remote_candidates : if c . compon...
async def async_get_api_key ( session , host , port , username = None , password = None , ** kwargs ) : """Get a new API key for devicetype ."""
url = 'http://{host}:{port}/api' . format ( host = host , port = str ( port ) ) auth = None if username and password : auth = aiohttp . BasicAuth ( username , password = password ) data = b'{"devicetype": "pydeconz"}' response = await async_request ( session . post , url , auth = auth , data = data ) api_key = resp...
def _unload ( self , ) : """Unloads the plugin : raises : errors . PluginUninitError"""
super ( JB_MayaPlugin , self ) . _unload ( ) try : if not jukeboxmaya . STANDALONE_INITIALIZED : self . uninit_ui ( ) except Exception : log . exception ( "Unload Ui failed!" )
def send ( self , soapenv ) : """Send SOAP message . Depending on how the ` ` nosend ` ` & ` ` retxml ` ` options are set , may do one of the following : * Return a constructed web service operation request without sending it to the web service . * Invoke the web service operation and return its SOAP repl...
location = self . __location ( ) log . debug ( "sending to (%s)\nmessage:\n%s" , location , soapenv ) plugins = PluginContainer ( self . options . plugins ) plugins . message . marshalled ( envelope = soapenv . root ( ) ) if self . options . prettyxml : soapenv = soapenv . str ( ) else : soapenv = soapenv . pla...
def delete ( self , constraint ) : """Delete a record from the repository"""
results = self . _get_repo_filter ( Service . objects ) . extra ( where = [ constraint [ 'where' ] ] , params = constraint [ 'values' ] ) . all ( ) deleted = len ( results ) results . delete ( ) return deleted
def _invite ( self , name , method , email , uuid , event , password = "" ) : """Actually invite a given user"""
props = { 'uuid' : std_uuid ( ) , 'status' : 'Open' , 'name' : name , 'method' : method , 'email' : email , 'password' : password , 'timestamp' : std_now ( ) } enrollment = objectmodels [ 'enrollment' ] ( props ) enrollment . save ( ) self . log ( 'Enrollment stored' , lvl = debug ) self . _send_invitation ( enrollment...
def resource_string ( package_or_requirement , resource_name ) : """Similar to pkg _ resources . resource _ string but if the resource it not found via pkg _ resources it also looks in a predefined list of paths in order to find the resource : param package _ or _ requirement : the module in which the resource ...
with open ( resource_filename ( package_or_requirement , resource_name ) , 'r' ) as resource_file : return resource_file . read ( )
def find_related ( self , fullname ) : """Return a list of non - stdlib modules that are imported directly or indirectly by ` fullname ` , plus their parents . This method is like : py : meth : ` find _ related _ imports ` , but also recursively searches any modules which are imported by ` fullname ` . : pa...
stack = [ fullname ] found = set ( ) while stack : name = stack . pop ( 0 ) names = self . find_related_imports ( name ) stack . extend ( set ( names ) . difference ( set ( found ) . union ( stack ) ) ) found . update ( names ) found . discard ( fullname ) return sorted ( found )
def scatterAlign ( seq1 , seq2 , window = 7 ) : """Visually align two sequences ."""
d1 = defaultdict ( list ) d2 = defaultdict ( list ) for ( seq , section_dict ) in [ ( seq1 , d1 ) , ( seq2 , d2 ) ] : for i in range ( len ( seq ) - window ) : section = seq [ i : i + window ] section_dict [ section ] . append ( i ) matches = set ( d1 ) . intersection ( d2 ) print ( '%i unique match...
def local_asn ( self , ** kwargs ) : """Set BGP local ASN . Args : local _ as ( str ) : Local ASN of NOS deice . vrf ( str ) : The VRF for this BGP process . rbridge _ id ( str ) : The rbridge ID of the device on which BGP will be configured in a VCS fabric . get ( bool ) : Get config instead of editing...
vrf = kwargs . pop ( 'vrf' , 'default' ) is_get_config = kwargs . pop ( 'get' , False ) if not is_get_config : local_as = kwargs . pop ( 'local_as' ) else : local_as = '' rbridge_id = kwargs . pop ( 'rbridge_id' , '1' ) callback = kwargs . pop ( 'callback' , self . _callback ) bgp_args = dict ( vrf_name = vrf ,...
def _add_node ( self , idx , unique_idx , frac_coords ) : """Add information about a node describing a critical point . : param idx : unique index : param unique _ idx : index of unique CriticalPoint , used to look up more information of point ( field etc . ) : param frac _ coord : fractional co - ordinates...
self . nodes [ idx ] = { 'unique_idx' : unique_idx , 'frac_coords' : frac_coords }
def extend_partial ( self , times , obs_times , obs_losses , config = None ) : """extends a partially observed curve Parameters : times : numpy array times where to predict the loss obs _ times : numpy array times where the curve has already been observed obs _ losses : numpy array corresponding obser...
return self . predict_unseen ( times , config )
def indent ( self , space = 4 ) : '''Return an indented Newick string , just like ` ` nw _ indent ` ` in Newick Utilities Args : ` ` space ` ` ( ` ` int ` ` ) : The number of spaces a tab should equal Returns : ` ` str ` ` : An indented Newick string'''
if not isinstance ( space , int ) : raise TypeError ( "space must be an int" ) if space < 0 : raise ValueError ( "space must be a non-negative integer" ) space = ' ' * space ; o = [ ] ; l = 0 for c in self . newick ( ) : if c == '(' : o . append ( '(\n' ) ; l += 1 ; o . append ( spac...
def list_plugins ( ) : '''List all the munin plugins CLI Example : . . code - block : : bash salt ' * ' munin . list _ plugins'''
pluginlist = os . listdir ( PLUGINDIR ) ret = [ ] for plugin in pluginlist : # Check if execute bit statf = os . path . join ( PLUGINDIR , plugin ) try : executebit = stat . S_IXUSR & os . stat ( statf ) [ stat . ST_MODE ] except OSError : pass if executebit : ret . append ( plug...
def map_permissions_check ( view_func ) : """Used for URLs dealing with the map ."""
@ wraps ( view_func ) def wrapper ( request , * args , ** kwargs ) : map_inst = get_object_or_404 ( Map , pk = kwargs [ 'map_id' ] ) user = request . user kwargs [ 'map_inst' ] = map_inst # Avoid rerequesting the map in the view if map_inst . edit_status >= map_inst . EDITORS : can_edit = ma...
def get_all_chunks_for_term ( self , termid ) : """Returns all the chunks in which the term is contained @ type termid : string @ param termid : the term identifier @ rtype : list @ return : list of chunks"""
terminal_id = self . terminal_for_term . get ( termid ) paths = self . paths_for_terminal [ terminal_id ] for path in paths : for node in path : this_type = self . label_for_nonter [ node ] subsumed = self . terms_subsumed_by_nonter . get ( node ) if subsumed is not None : yield ...
def _batch_load ( project , workspace , headerline , entity_data , chunk_size = 500 ) : """Submit a large number of entity updates in batches of chunk _ size"""
if fcconfig . verbosity : print ( "Batching " + str ( len ( entity_data ) ) + " updates to Firecloud..." ) # Parse the entity type from the first cell , e . g . " entity : sample _ id " # First check that the header is valid if not _valid_headerline ( headerline ) : eprint ( "Invalid loadfile header:\n" + heade...
def filter_tasks ( self , task_names , keep_dependencies = False ) : """If filter is applied only tasks with given name and its dependencies ( if keep _ keep _ dependencies = True ) are kept in the list of tasks ."""
new_tasks = { } for task_name in task_names : task = self . get_task ( task_name ) if task not in new_tasks : new_tasks [ task . name ] = task if keep_dependencies : for dependency in task . ordered_dependencies ( ) : if dependency not in new_tasks : new_tasks [ d...
def extract_subject_info_extension ( cert_obj ) : """Extract DataONE SubjectInfo XML doc from certificate . Certificates issued by DataONE may include an embedded XML doc containing additional information about the subject specified in the certificate DN . If present , the doc is stored as an extension with a...
try : subject_info_der = cert_obj . extensions . get_extension_for_oid ( cryptography . x509 . oid . ObjectIdentifier ( DATAONE_SUBJECT_INFO_OID ) ) . value . value return str ( pyasn1 . codec . der . decoder . decode ( subject_info_der ) [ 0 ] ) except Exception as e : logging . debug ( 'SubjectInfo not ex...
def validate_user_threaded_json ( pjson ) : """Takes a parsed JSON dict representing a set of tests in the user - threaded format and validates it ."""
tests = pjson [ "tests" ] # Verify that ' tests ' is a two dimensional list is_2d_list = lambda ls : len ( ls ) == len ( filter ( lambda l : type ( l ) is list , ls ) ) if type ( tests ) is not list or not is_2d_list ( tests ) : raise ParseError ( "'tests' should be a two-dimensional list of strings when '--user-de...
def urlfetch_async ( self , url , method = 'GET' , headers = None , payload = None , deadline = None , callback = None , follow_redirects = False ) : """Make an async urlfetch ( ) call . This is an async wrapper around urlfetch ( ) . It adds an authentication header . Args : url : the url to fetch . metho...
headers = { } if headers is None else dict ( headers ) headers . update ( self . user_agent ) try : self . token = yield self . get_token_async ( ) except app_identity . InternalError , e : if os . environ . get ( 'DATACENTER' , '' ) . endswith ( 'sandman' ) : self . token = None logging . warni...
def _get_json ( endpoint , params , referer = 'scores' ) : """Internal method to streamline our requests / json getting Args : endpoint ( str ) : endpoint to be called from the API params ( dict ) : parameters to be passed to the API Raises : HTTPError : if requests hits a status code ! = 200 Returns : ...
h = dict ( HEADERS ) h [ 'referer' ] = 'http://stats.nba.com/{ref}/' . format ( ref = referer ) _get = get ( BASE_URL . format ( endpoint = endpoint ) , params = params , headers = h ) # print _ get . url _get . raise_for_status ( ) return _get . json ( )
def parse_cache_url ( url ) : """Parses a cache URL ."""
config = { } url = urlparse . urlparse ( url ) # Update with environment configuration . config [ 'BACKEND' ] = CACHE_SCHEMES [ url . scheme ] if url . scheme in ( 'file' , 'uwsgi' ) : config [ 'LOCATION' ] = url . path return config elif url . scheme in ( 'redis' , 'hiredis' ) : if url . netloc == 'unix' :...
def annotate ( g , fname , tables , feature_strand = False , in_memory = False , header = None , out = sys . stdout , _chrom = None , parallel = False ) : """annotate bed file in fname with tables . distances are integers for distance . and intron / exon / utr5 etc for gene - pred tables . if the annotation fea...
close = False if isinstance ( out , basestring ) : out = nopen ( out , "w" ) close = True if parallel : import multiprocessing import signal p = multiprocessing . Pool ( initializer = lambda : signal . signal ( signal . SIGINT , signal . SIG_IGN ) ) chroms = _split_chroms ( fname ) def write...
def new_dataset ( data , identifier = None ) : """Initialize a new RT - DC dataset Parameters data : can be one of the following : - dict - . tdms file - . rtdc file - subclass of ` RTDCBase ` ( will create a hierarchy child ) identifier : str A unique identifier for this dataset . If set to ` N...
if isinstance ( data , dict ) : return fmt_dict . RTDC_Dict ( data , identifier = identifier ) elif isinstance ( data , ( str_types ) ) or isinstance ( data , pathlib . Path ) : return load_file ( data , identifier = identifier ) elif isinstance ( data , RTDCBase ) : return fmt_hierarchy . RTDC_Hierarchy ( ...
def main ( argv = None ) : '''Command line options .'''
program_name = os . path . basename ( sys . argv [ 0 ] ) program_version = version program_build_date = "%s" % __updated__ program_version_string = '%%prog %s (%s)' % ( program_version , program_build_date ) # program _ usage = ' ' ' usage : spam two eggs ' ' ' # optional - will be autogenerated by optparse program_lon...
def _norm ( self , x ) : """Return the norm of ` ` x ` ` . This method is intended to be private . Public callers should resort to ` norm ` which is type - checked ."""
return float ( np . sqrt ( self . inner ( x , x ) . real ) )
def keys ( self ) : """Return ids of all indexed documents ."""
result = [ ] if self . fresh_index is not None : result += self . fresh_index . keys ( ) if self . opt_index is not None : result += self . opt_index . keys ( ) return result
def get_directory_nodes ( self , path ) : """Returns the : class : ` umbra . components . factory . script _ editor . nodes . DirectoryNode ` class Nodes with given path . : param path : Directory path . : type path : unicode : return : DirectoryNode nodes . : rtype : list"""
return [ directory_node for directory_node in self . list_directory_nodes ( ) if directory_node . path == path ]
def wrap ( self , message ) : """[ MS - NLMP ] v28.0 2016-07-14 3.4.6 GSS _ WrapEx ( ) Emulates the GSS _ Wrap ( ) implementation to sign and seal messages if the correct flags are set . @ param message : The message data that will be wrapped @ return message : The message that has been sealed if flags ar...
if self . negotiate_flags & NegotiateFlags . NTLMSSP_NEGOTIATE_SEAL : encrypted_message = self . _seal_message ( message ) signature = self . _get_signature ( message ) message = encrypted_message elif self . negotiate_flags & NegotiateFlags . NTLMSSP_NEGOTIATE_SIGN : signature = self . _get_signature (...
def get_email_logs ( self ) : '''Returns a string representation of logs . Only displays errors and warnings in the email logs to avoid being verbose'''
message = "" for log in self . record : if log [ "log_type" ] in [ ERROR , WARNING ] : message += self . format_message ( ** log ) return message
def packages ( self ) : """Show all packages"""
pattern = re . compile ( r'package:(/[^=]+\.apk)=([^\s]+)' ) packages = [ ] for line in self . shell ( 'pm' , 'list' , 'packages' , '-f' ) . splitlines ( ) : m = pattern . match ( line ) if not m : continue path , name = m . group ( 1 ) , m . group ( 2 ) packages . append ( self . Package ( name...
def _loglr ( self ) : r"""Computes the log likelihood ratio , . . math : : \ log \ mathcal { L } ( \ Theta ) = I _ 0 \ left ( \ left | \ sum _ i O ( h ^ 0 _ i , d _ i ) \ right | \ right ) - \ frac { 1 } { 2 } \ left < h ^ 0 _ i , h ^ 0 _ i \ right > , at the current point in parameter space : math : ` \ ...
params = self . current_params try : wfs = self . _waveform_generator . generate ( ** params ) except NoWaveformError : return self . _nowaveform_loglr ( ) hh = 0. hd = 0j for det , h in wfs . items ( ) : # the kmax of the waveforms may be different than internal kmax kmax = min ( len ( h ) , self . _kmax )...
def select ( self , table , fields = [ '*' ] , where = None , orderby = None , limit = None , offset = None ) : """Query and return list of records . > > > import getpass > > > s = DB ( dbname = ' test ' , user = getpass . getuser ( ) , host = ' localhost ' , . . . password = ' ' ) > > > s . execute ( ' dro...
( sql , values ) = sqlselect ( table , fields , where , orderby , limit , offset ) self . execute ( sql , values ) return self . fetchall ( )
def cleanup ( self , cluster ) : """Deletes the inventory file used last recently used . : param cluster : cluster to clear up inventory file for : type cluster : : py : class : ` elasticluster . cluster . Cluster `"""
if self . _storage_path and os . path . exists ( self . _storage_path ) : fname = '%s.%s' % ( AnsibleSetupProvider . inventory_file_ending , cluster . name ) inventory_path = os . path . join ( self . _storage_path , fname ) if os . path . exists ( inventory_path ) : try : os . unlink ( ...
def select ( self , axis : AxisIdentifier , index , force_copy : bool = False ) -> HistogramBase : """Select in an axis . Parameters axis : int or str Axis , in which we select . index : int or slice Index of bin ( as in numpy ) . force _ copy : bool If True , identity slice force a copy to be made ."...
if index == slice ( None ) and not force_copy : return self axis_id = self . _get_axis ( axis ) array_index = [ slice ( None , None , None ) for i in range ( self . ndim ) ] array_index [ axis_id ] = index frequencies = self . _frequencies [ tuple ( array_index ) ] . copy ( ) errors2 = self . _errors2 [ tuple ( arr...
def build ( self , builder ) : """Build XML by appending to builder"""
params = dict ( OID = self . oid , Name = self . name ) if self . field_number is not None : params [ "FieldNumber" ] = str ( self . field_number ) builder . start ( "mdsol:LabelDef" , params ) for translation in self . translations : translation . build ( builder ) for view_restriction in self . view_restricti...
def type_check ( func_handle ) : """Ensure arguments have the type specified in the annotation signature . Example : : def foo ( a , b : str , c : int = 0 , d : ( int , list ) = None ) : pass This function accepts an arbitrary parameter for ` ` a ` ` , a string for ` ` b ` ` , an integer for ` ` c ` ` whi...
def checkType ( var_name , var_val , annot ) : # Retrieve the annotation for this variable and determine # if the type of that variable matches with the annotation . # This annotation is stored in the dictionary ` ` annot ` ` # but contains only variables for such an annotation exists , # hence the if / else branch . ...
def get_min_max_bounds ( self ) : """Return a dict of min - and max - values for the given column . This is required to estimate the bounds of images ."""
bound = Bound ( 999999.0 , 0.0 ) for bp in Breakpoint : bound . extend ( self . get_bound ( bp ) ) return { 'min' : bound . min , 'max' : bound . max }
def _exception_gather_guard ( self , fn ) : """A higher order function to trap UserExceptions and then log them . This is to present nicer output to the user when failures are occuring in another thread of execution that may not end up at the catch - all try / except in main ( ) ."""
@ functools . wraps ( fn ) def wrapper ( * args , ** kwargs ) : try : return fn ( * args , ** kwargs ) except UserException as e : self . exceptions . append ( e ) return wrapper