signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_connection ( self , key , host , port , user , password , dbname , ssl , connect_fct , tags , use_cached = True ) :
"""Get and memoize connections to instances""" | if key in self . dbs and use_cached :
return self . dbs [ key ]
elif host != "" and user != "" :
try :
if host == 'localhost' and password == '' : # Use ident method
connection = connect_fct ( "user=%s dbname=%s" % ( user , dbname ) )
elif port != '' :
connection = connec... |
def coverage_lineplot ( self ) :
"""Make HTML for coverage line plots""" | # Add line graph to section
data = list ( )
data_labels = list ( )
if len ( self . rna_seqc_norm_high_cov ) > 0 :
data . append ( self . rna_seqc_norm_high_cov )
data_labels . append ( { 'name' : 'High Expressed' } )
if len ( self . rna_seqc_norm_medium_cov ) > 0 :
data . append ( self . rna_seqc_norm_mediu... |
def skeletonize_labels ( labels ) :
'''Skeletonize a labels matrix''' | # The trick here is to separate touching labels by coloring the
# labels matrix and then processing each color separately
colors = color_labels ( labels )
max_color = np . max ( colors )
if max_color == 0 :
return labels
result = np . zeros ( labels . shape , labels . dtype )
for i in range ( 1 , max_color + 1 ) :
... |
def pool_delete ( name , fast = True , ** kwargs ) :
'''Delete the resources of a defined libvirt storage pool .
: param name : libvirt storage pool name
: param fast : if set to False , zeroes out all the data .
Default value is True .
: param connection : libvirt connection URI , overriding defaults
: p... | conn = __get_conn ( ** kwargs )
try :
pool = conn . storagePoolLookupByName ( name )
flags = libvirt . VIR_STORAGE_POOL_DELETE_NORMAL
if fast :
flags = libvirt . VIR_STORAGE_POOL_DELETE_ZEROED
return not bool ( pool . delete ( flags ) )
finally :
conn . close ( ) |
def _get_metadap_dap ( name , version = '' ) :
'''Return data for dap of given or latest version .''' | m = metadap ( name )
if not m :
raise DapiCommError ( 'DAP {dap} not found.' . format ( dap = name ) )
if not version :
d = m [ 'latest_stable' ] or m [ 'latest' ]
if d :
d = data ( d )
else :
d = dap ( name , version )
if not d :
raise DapiCommError ( 'DAP {dap} doesn\'t have versio... |
def add_connector ( self , connector_type , begin_x , begin_y , end_x , end_y ) :
"""Add a newly created connector shape to the end of this shape tree .
* connector _ type * is a member of the : ref : ` MsoConnectorType `
enumeration and the end - point values are specified as EMU values . The
returned connec... | cxnSp = self . _add_cxnSp ( connector_type , begin_x , begin_y , end_x , end_y )
self . _recalculate_extents ( )
return self . _shape_factory ( cxnSp ) |
def event ( self , service_event , listener_dict ) :
"""A service has been received : this method can alter the list of
listeners to be notified of this event ( remove only ) .
It can also be used as a handler for the event that will be called
before any standard one .
: param service _ event : The ServiceE... | print ( "EventListenerHookImpl: service_event=" , service_event , ", listener_dict=" , listener_dict , sep = "" , )
# Remove it if it ' s our service context , has the " to _ filter " property
# and it ' s the 3rd time through the hook
svc_ref = service_event . get_service_reference ( )
to_filter = svc_ref . get_proper... |
def add_parser_options ( options : Dict [ str , Dict [ str , Any ] ] , parser_id : str , parser_options : Dict [ str , Dict [ str , Any ] ] , overwrite : bool = False ) :
"""Utility method to add options for a given parser , to the provided options structure
: param options :
: param parser _ id :
: param par... | if parser_id in options . keys ( ) and not overwrite :
raise ValueError ( 'There are already options in this dictionary for parser id ' + parser_id )
options [ parser_id ] = parser_options
return options |
def delete ( self ) :
"""Delete the message .""" | url = self . _imgur . _base_url + "/3/message/{0}" . format ( self . id )
return self . _imgur . _send_request ( url , method = 'DELETE' ) |
def getAttrs ( self , node ) :
"""Return a Collection of all attributes""" | attrs = { }
for k , v in node . _attrs . items ( ) :
attrs [ k ] = v . value
return attrs |
def _loop_no_cache ( self , helper_function , num , fragment ) :
"""Synthesize all fragments without using the cache""" | self . log ( [ u"Examining fragment %d (no cache)..." , num ] )
# synthesize and get the duration of the output file
voice_code = self . _language_to_voice_code ( fragment . language )
self . log ( u"Calling helper function" )
succeeded , data = helper_function ( text = fragment . filtered_text , voice_code = voice_cod... |
def delete_cell ( self , column_family_id , column , time_range = None ) :
"""Deletes cell in this row .
. . note : :
This method adds a mutation to the accumulated mutations on this
row , but does not make an API request . To actually
send an API request ( with the mutations ) to the Google Cloud
Bigtabl... | self . _delete_cells ( column_family_id , [ column ] , time_range = time_range , state = None ) |
def add_delete ( self , value ) :
"""Delete a tag or populator by value - these are processed before upserts""" | value = value . strip ( )
v = value . lower ( )
self . lower_val_to_val [ v ] = value
if len ( v ) == 0 :
raise ValueError ( "Invalid value for delete. Value is empty." )
self . deletes . add ( v ) |
def line_text ( self , line_nbr ) :
"""Gets the text of the specified line .
: param line _ nbr : The line number of the text to get
: return : Entire line ' s text
: rtype : str""" | doc = self . _editor . document ( )
block = doc . findBlockByNumber ( line_nbr )
return block . text ( ) |
def isNull ( self ) :
"""Returns whether or not this option set has been modified .
: return < bool >""" | check = self . raw_values . copy ( )
scope = check . pop ( 'scope' , { } )
return len ( check ) == 0 and len ( scope ) == 0 |
def child_removed ( self , child ) :
"""Reset the item cache when a child is removed""" | super ( AbstractItemView , self ) . child_removed ( child )
self . get_member ( '_items' ) . reset ( self ) |
async def open ( self ) -> 'HolderProver' :
"""Explicit entry . Perform ancestor opening operations ,
then parse cache from archive if so configured , and
synchronize revocation registry to tails tree content .
: return : current object""" | LOGGER . debug ( 'HolderProver.open >>>' )
await super ( ) . open ( )
if self . cfg . get ( 'parse-cache-on-open' , False ) :
Caches . parse ( self . dir_cache )
for path_rr_id in Tails . links ( self . _dir_tails ) :
await self . _sync_revoc ( basename ( path_rr_id ) )
LOGGER . debug ( 'HolderProver.open <<<' ... |
def save ( self , path = None , format = None , mode = None , partitionBy = None , ** options ) :
"""Saves the contents of the : class : ` DataFrame ` to a data source .
The data source is specified by the ` ` format ` ` and a set of ` ` options ` ` .
If ` ` format ` ` is not specified , the default data source... | self . mode ( mode ) . options ( ** options )
if partitionBy is not None :
self . partitionBy ( partitionBy )
if format is not None :
self . format ( format )
if path is None :
self . _jwrite . save ( )
else :
self . _jwrite . save ( path ) |
def main ( ) :
"""Main function""" | parser = OptionParser ( )
parser . add_option ( '-c' , '--config' , help = 'configuration file' , dest = 'filename' , type = 'str' , default = '/etc/sachannelupdate/sachannelupdate.ini' )
parser . add_option ( '-d' , '--delete' , help = 'Deletes existing rules' , dest = 'cleanup' , action = "store_true" , default = Fal... |
def list_nodes ( kwargs = None , call = None ) :
'''Return a list of all VMs and templates that are on the specified provider , with basic fields
CLI Example :
. . code - block : : bash
salt - cloud - f list _ nodes my - vmware - config
To return a list of all VMs and templates present on ALL configured pro... | if call == 'action' :
raise SaltCloudSystemExit ( 'The list_nodes function must be called ' 'with -f or --function.' )
ret = { }
vm_properties = [ "name" , "guest.ipAddress" , "config.guestFullName" , "config.hardware.numCPU" , "config.hardware.memoryMB" , "summary.runtime.powerState" ]
vm_list = salt . utils . vmw... |
def generate_meta_features ( path , base_learner_id ) :
"""Generates meta - features for specified base learner
After generation of meta - features , the file is saved into the meta - features folder
Args :
path ( str ) : Path to Xcessiv notebook
base _ learner _ id ( str ) : Base learner ID""" | with functions . DBContextManager ( path ) as session :
base_learner = session . query ( models . BaseLearner ) . filter_by ( id = base_learner_id ) . first ( )
if not base_learner :
raise exceptions . UserError ( 'Base learner {} ' 'does not exist' . format ( base_learner_id ) )
base_learner . job_... |
def _has_file_rolled ( self ) :
"""Check if the file has been rolled""" | # if the size is smaller then before , the file has
# probabilly been rolled
if self . _fh :
size = self . _getsize_of_current_file ( )
if size < self . oldsize :
return True
self . oldsize = size
return False |
def get_transient ( self , name ) :
'''Restores TransientFile object with given name .
Should be used when form is submitted with file name and no file''' | # security checks : basically no folders are allowed
assert not ( '/' in name or '\\' in name or name [ 0 ] in '.~' )
transient = TransientFile ( self . transient_root , name , self )
if not os . path . isfile ( transient . path ) :
raise OSError ( errno . ENOENT , 'Transient file has been lost' , transient . path ... |
def to_sky ( self , wcs , mode = 'all' ) :
"""Convert the aperture to a ` SkyEllipticalAnnulus ` object defined
in celestial coordinates .
Parameters
wcs : ` ~ astropy . wcs . WCS `
The world coordinate system ( WCS ) transformation to use .
mode : { ' all ' , ' wcs ' } , optional
Whether to do the tran... | sky_params = self . _to_sky_params ( wcs , mode = mode )
return SkyEllipticalAnnulus ( ** sky_params ) |
def _sample_item ( self , ** kwargs ) :
"""Sample an item from the pool""" | if self . replace : # Can sample from any of the items
loc = np . random . choice ( self . _n_items )
else : # Can only sample from items that have not been seen
# Find ids that haven ' t been seen yet
not_seen_ids = np . where ( np . isnan ( self . cached_labels_ ) ) [ 0 ]
loc = np . random . choice ( not_... |
def parse_rune_links ( html : str ) -> dict :
"""A function which parses the main Runeforge website into dict format .
Parameters
html : str
The string representation of the html obtained via a GET request .
Returns
dict
The nested rune _ links champ rune pages from runeforge .""" | soup = BeautifulSoup ( html , 'lxml' )
# Champs with only a single runepage
single_page_raw = soup . find_all ( 'li' , class_ = 'champion' )
single_page = { re . split ( '\W+' , x . a . div . div [ 'style' ] ) [ - 3 ] . lower ( ) : [ x . a [ 'href' ] ] for x in single_page_raw if x . a is not None }
# Champs with two (... |
def read ( self , size = - 1 ) :
"""! @ brief Return bytes read from the connection .""" | if self . connected is None :
return None
# Extract requested amount of data from the read buffer .
data = self . _get_input ( size )
return data |
def lmx_h3k_f12k ( ) :
"""HParams for training languagemodel _ lm1b32k _ packed . 880M Params .""" | hparams = lmx_base ( )
hparams . hidden_size = 3072
hparams . filter_size = 12288
hparams . batch_size = 2048
hparams . weight_dtype = "bfloat16"
return hparams |
def _do_load_results ( self ) :
"""Submit a query asking for the results for a particular problem .
To request the results of a problem : ` ` GET / problems / { problem _ id } / ` `
Note :
This method is always run inside of a daemon thread .""" | try :
while True : # Select a problem
future = self . _load_queue . get ( )
# ` None ` task signifies thread termination
if future is None :
break
_LOGGER . debug ( "Loading results of: %s" , future . id )
# Submit the query
query_string = 'problems/{}/' .... |
def upload_to_pypi ( dists : str = 'sdist bdist_wheel' , username : str = None , password : str = None , skip_existing : bool = False ) :
"""Creates the wheel and uploads to pypi with twine .
: param dists : The dists string passed to setup . py . Default : ' bdist _ wheel '
: param username : PyPI account user... | if username is None or password is None or username == "" or password == "" :
raise ImproperConfigurationError ( 'Missing credentials for uploading' )
run ( 'rm -rf build dist' )
run ( 'python setup.py {}' . format ( dists ) )
run ( 'twine upload -u {} -p {} {} {}' . format ( username , password , '--skip-existing'... |
def _parse_networks ( self , config ) :
"""Parses config file for the networks advertised
by the OSPF process
Args :
config ( str ) : Running configuration
Returns :
list : dict :
keys : network ( str )
netmask ( str )
area ( str )""" | networks = list ( )
regexp = r'network (.+)/(\d+) area (\d+\.\d+\.\d+\.\d+)'
matches = re . findall ( regexp , config )
for ( network , netmask , area ) in matches :
networks . append ( dict ( network = network , netmask = netmask , area = area ) )
return dict ( networks = networks ) |
def show ( self ) :
"""Override the QWidget : : show ( ) method to properly recalculate the
editor viewport .""" | if self . isHidden ( ) :
QWidget . show ( self )
self . _qpart . updateViewport ( ) |
def transform_system ( principal_vec , principal_default , other_vecs , matrix = None ) :
"""Transform vectors with either ` ` matrix ` ` or based on ` ` principal _ vec ` ` .
The logic of this function is as follows :
- If ` ` matrix ` ` is not ` ` None ` ` , transform ` ` principal _ vec ` ` and
all vectors... | transformed_vecs = [ ]
principal_vec = np . asarray ( principal_vec , dtype = float )
ndim = principal_vec . shape [ 0 ]
if matrix is None : # Separate into dilation and rotation . The dilation is only used
# for comparison , not in the final matrix .
principal_default = np . asarray ( principal_default , dtype = f... |
def _parse_parameter_options ( self , options ) :
"""Select all unknown options .
Select all unknown options ( not query string , API , or request
options )""" | return self . _select_options ( options , self . ALL_OPTIONS , invert = True ) |
def walk_egg ( egg_dir ) :
"""Walk an unpacked egg ' s contents , skipping the metadata directory""" | walker = sorted_walk ( egg_dir )
base , dirs , files = next ( walker )
if 'EGG-INFO' in dirs :
dirs . remove ( 'EGG-INFO' )
yield base , dirs , files
for bdf in walker :
yield bdf |
def autoconf ( self ) :
"""Implements Munin Plugin Auto - Configuration Option .
@ return : True if plugin can be auto - configured , False otherwise .""" | opcinfo = OPCinfo ( self . _host , self . _port , self . _user , self . _password , self . _monpath , self . _ssl )
return opcinfo is not None |
def get_object_by_record ( record ) :
"""Find an object by a given record
Inspects request the record to locate an object
: param record : A dictionary representation of an object
: type record : dict
: returns : Found Object or None
: rtype : object""" | # nothing to do here
if not record :
return None
if record . get ( "uid" ) :
return get_object_by_uid ( record [ "uid" ] )
if record . get ( "path" ) :
return get_object_by_path ( record [ "path" ] )
if record . get ( "parent_path" ) and record . get ( "id" ) :
path = "/" . join ( [ record [ "parent_pat... |
def unmap_vc ( self , port1 , dlci1 , port2 , dlci2 ) :
"""Deletes a Virtual Circuit connection ( unidirectional ) .
: param port1 : input port
: param dlci1 : input DLCI
: param port2 : output port
: param dlci2 : output DLCI""" | if port1 not in self . _nios :
raise DynamipsError ( "Port {} is not allocated" . format ( port1 ) )
if port2 not in self . _nios :
raise DynamipsError ( "Port {} is not allocated" . format ( port2 ) )
nio1 = self . _nios [ port1 ]
nio2 = self . _nios [ port2 ]
yield from self . _hypervisor . send ( 'frsw delet... |
def parseCmdline ( rh ) :
"""Parse the request command input .
Input :
Request Handle
Output :
Request Handle updated with parsed input .
Return code - 0 : ok , non - zero : error""" | rh . printSysLog ( "Enter powerVM.parseCmdline" )
if rh . totalParms >= 2 :
rh . userid = rh . request [ 1 ] . upper ( )
else : # Userid is missing .
msg = msgs . msg [ '0010' ] [ 1 ] % modId
rh . printLn ( "ES" , msg )
rh . updateResults ( msgs . msg [ '0010' ] [ 0 ] )
rh . printSysLog ( "Exit powe... |
def idempotency_key ( self , idempotency_key ) :
"""Sets the idempotency _ key of this BatchUpsertCatalogObjectsRequest .
A value you specify that uniquely identifies this request among all your requests . A common way to create a valid idempotency key is to use a Universally unique identifier ( UUID ) . If you '... | if idempotency_key is None :
raise ValueError ( "Invalid value for `idempotency_key`, must not be `None`" )
if len ( idempotency_key ) < 1 :
raise ValueError ( "Invalid value for `idempotency_key`, length must be greater than or equal to `1`" )
self . _idempotency_key = idempotency_key |
def __build_sign_query ( saml_data , relay_state , algorithm , saml_type , lowercase_urlencoding = False ) :
"""Build sign query
: param saml _ data : The Request data
: type saml _ data : str
: param relay _ state : The Relay State
: type relay _ state : str
: param algorithm : The Signature Algorithm
... | sign_data = [ '%s=%s' % ( saml_type , OneLogin_Saml2_Utils . escape_url ( saml_data , lowercase_urlencoding ) ) ]
if relay_state is not None :
sign_data . append ( 'RelayState=%s' % OneLogin_Saml2_Utils . escape_url ( relay_state , lowercase_urlencoding ) )
sign_data . append ( 'SigAlg=%s' % OneLogin_Saml2_Utils . ... |
def are_genes_in_api ( my_clue_api_client , gene_symbols ) :
"""determine if genes are present in the API
Args :
my _ clue _ api _ client :
gene _ symbols : collection of gene symbols to query the API with
Returns : set of the found gene symbols""" | if len ( gene_symbols ) > 0 :
query_gene_symbols = gene_symbols if type ( gene_symbols ) is list else list ( gene_symbols )
query_result = my_clue_api_client . run_filter_query ( resource_name , { "where" : { "gene_symbol" : { "inq" : query_gene_symbols } } , "fields" : { "gene_symbol" : True } } )
logger .... |
def job_success ( self , job , queue , job_result ) :
"""Update the queue ' s dates and number of jobs managed , and save into the
job the result received by the callback .""" | # display what was done
obj = job . get_object ( )
message = '[%s|%s] %s [%s]' % ( queue . name . hget ( ) , obj . pk . get ( ) , job_result , threading . current_thread ( ) . name )
self . log ( message )
# default stuff : update job and queue statuses , and do logging
super ( FullNameWorker , self ) . job_success ( j... |
def Generate ( self , items , token = None ) :
"""Generates archive from a given collection .
Iterates the collection and generates an archive by yielding contents
of every referenced AFF4Stream .
Args :
items : Iterable of rdf _ client _ fs . StatEntry objects
token : User ' s ACLToken .
Yields :
Bin... | del token
# unused , to be removed with AFF4 code
client_ids = set ( )
for item_batch in collection . Batch ( items , self . BATCH_SIZE ) :
client_paths = set ( )
for item in item_batch :
try :
client_path = flow_export . CollectionItemToClientPath ( item , self . client_id )
except ... |
def createNetworkFromSelected ( self , networkId , title , verbose = None ) :
"""Creates new sub - network from current selection , with the name specified by the ` title ` parameter .
Returns the SUID of the new sub - network .
: param networkId : SUID of the network containing the selected nodes and edges
:... | PARAMS = set_param ( [ 'networkId' , 'title' ] , [ networkId , title ] )
response = api ( url = self . ___url + 'networks/' + str ( networkId ) + '' , PARAMS = PARAMS , method = "POST" , verbose = verbose )
return response |
def choose_init ( module ) :
"""Select a init system
Returns the name of a init system ( upstart , sysvinit . . . ) .""" | if module . normalized_release . int_major < 7 :
return 'sysvinit'
if not module . conn . remote_module . path_exists ( "/usr/lib/systemd/system/ceph.target" ) :
return 'sysvinit'
if is_systemd ( module . conn ) :
return 'systemd'
return 'systemd' |
def filter ( self , event ) :
"""If the ID of ` ` event . _ chat _ peer ` ` isn ' t in the chats set ( or it is
but the set is a blacklist ) returns ` ` None ` ` , otherwise the event .
The events must have been resolved before this can be called .""" | if not self . resolved :
return None
if self . chats is not None : # Note : the ` event . chat _ id ` property checks if it ' s ` None ` for us
inside = event . chat_id in self . chats
if inside == self . blacklist_chats : # If this chat matches but it ' s a blacklist ignore .
# If it doesn ' t match bu... |
def p_let_arr_substr_in_args ( p ) :
"""statement : LET ARRAY _ ID LP arguments TO RP EQ expr
| ARRAY _ ID LP arguments TO RP EQ expr""" | i = 2 if p [ 1 ] . upper ( ) == 'LET' else 1
id_ = p [ i ]
arg_list = p [ i + 2 ]
substr = ( arg_list . children . pop ( ) . value , make_number ( gl . MAX_STRSLICE_IDX , lineno = p . lineno ( i + 3 ) ) )
expr_ = p [ i + 6 ]
p [ 0 ] = make_array_substr_assign ( p . lineno ( i ) , id_ , arg_list , substr , expr_ ) |
def cluster_uniform_time ( data = None , k = None , stride = 1 , metric = 'euclidean' , n_jobs = None , chunksize = None , skip = 0 , ** kwargs ) :
r"""Uniform time clustering
If given data , performs a clustering that selects data points uniformly in
time and then assigns the data using a Voronoi discretizatio... | from pyemma . coordinates . clustering . uniform_time import UniformTimeClustering
res = UniformTimeClustering ( k , metric = metric , n_jobs = n_jobs , skip = skip , stride = stride )
from pyemma . util . reflection import get_default_args
cs = _check_old_chunksize_arg ( chunksize , get_default_args ( cluster_uniform_... |
def qualified_name ( obj ) :
'''Returns the fully - qualified name of the given object''' | if not hasattr ( obj , '__module__' ) :
obj = obj . __class__
module = obj . __module__
if module is None or module == str . __class__ . __module__ :
return obj . __qualname__
return '{}.{}' . format ( module , obj . __qualname__ ) |
def _valid_table_name ( name ) :
"""Verify if a given table name is valid for ` rows `
Rules :
- Should start with a letter or ' _ '
- Letters can be capitalized or not
- Accepts letters , numbers and _""" | if name [ 0 ] not in "_" + string . ascii_letters or not set ( name ) . issubset ( "_" + string . ascii_letters + string . digits ) :
return False
else :
return True |
def qloguniform ( low , high , q , random_state ) :
'''low : an float that represent an lower bound
high : an float that represent an upper bound
q : sample step
random _ state : an object of numpy . random . RandomState''' | return np . round ( loguniform ( low , high , random_state ) / q ) * q |
def load_igor_genomic_data ( self , params_file_name , V_anchor_pos_file , J_anchor_pos_file ) :
"""Set attributes by loading in genomic data from IGoR parameter file .
Sets attributes genV , max _ delV _ palindrome , cutV _ genomic _ CDR3 _ segs ,
genD , max _ delDl _ palindrome , max _ delDr _ palindrome ,
... | self . genV = read_igor_V_gene_parameters ( params_file_name )
self . genD = read_igor_D_gene_parameters ( params_file_name )
self . genJ = read_igor_J_gene_parameters ( params_file_name )
self . anchor_and_curate_genV_and_genJ ( V_anchor_pos_file , J_anchor_pos_file )
self . read_VDJ_palindrome_parameters ( params_fil... |
def column_spec_path ( cls , project , location , dataset , table_spec , column_spec ) :
"""Return a fully - qualified column _ spec string .""" | return google . api_core . path_template . expand ( "projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}/columnSpecs/{column_spec}" , project = project , location = location , dataset = dataset , table_spec = table_spec , column_spec = column_spec , ) |
def add_transition ( self , input_symbol , state , action = None , next_state = None ) :
'''This adds a transition that associates :
( input _ symbol , current _ state ) - - > ( action , next _ state )
The action may be set to None in which case the process ( ) method will
ignore the action and only set the n... | if next_state is None :
next_state = state
self . state_transitions [ ( input_symbol , state ) ] = ( action , next_state ) |
def precompute_begin_state ( self ) :
"""Caches the summation calculation and available choices for BEGIN * state _ size .
Significantly speeds up chain generation on large corpuses . Thanks , @ schollz !""" | begin_state = tuple ( [ BEGIN ] * self . state_size )
choices , weights = zip ( * self . model [ begin_state ] . items ( ) )
cumdist = list ( accumulate ( weights ) )
self . begin_cumdist = cumdist
self . begin_choices = choices |
def cleanupFilename ( self , name ) :
"""Generate a unique id which doesn ' t match the system generated ids""" | context = self . context
id = ''
name = name . replace ( '\\' , '/' )
# Fixup Windows filenames
name = name . split ( '/' ) [ - 1 ]
# Throw away any path part .
for c in name :
if c . isalnum ( ) or c in '._' :
id += c
# Raise condition here , but not a lot we can do about that
if context . check_id ( id ) ... |
def parse_result ( self , data ) :
"""Return True if the AEAD was stored sucessfully .""" | # typedef struct {
# uint8 _ t publicId [ YSM _ PUBLIC _ ID _ SIZE ] ; / / Public id ( nonce )
# uint32 _ t keyHandle ; / / Key handle
# YSM _ STATUS status ; / / Validation status
# } YSM _ DB _ YUBIKEY _ AEAD _ STORE _ RESP ;
public_id , key_handle , self . status = struct . unpack ( "< %is I B" % ( pyhsm . defines .... |
def getWindows ( input ) :
"""Get a source ' s windows""" | with rasterio . open ( input ) as src :
return [ [ window , ij ] for ij , window in src . block_windows ( ) ] |
def ReadString ( self ) :
"""Read a string from the stream .
Returns :
str :""" | length = self . ReadUInt8 ( )
return self . unpack ( str ( length ) + 's' , length ) |
def get_key ( dotenv_path , key_to_get , verbose = False ) :
"""Gets the value of a given key from the given . env
If the . env path given doesn ' t exist , fails
: param dotenv _ path : path
: param key _ to _ get : key
: param verbose : verbosity flag , raise warning if path does not exist
: return : va... | key_to_get = str ( key_to_get )
if not os . path . exists ( dotenv_path ) :
if verbose :
warnings . warn ( f"Can't read {dotenv_path}, it doesn't exist." )
return None
dotenv_as_dict = dotenv_values ( dotenv_path )
if key_to_get in dotenv_as_dict :
return dotenv_as_dict [ key_to_get ]
else :
if ... |
def format_time_large ( seconds ) :
"""Same as format _ time ( ) but always uses the format dd : hh : mm : ss .""" | if not isinstance ( seconds , ( int , float ) ) :
return str ( seconds )
if math . isnan ( seconds ) :
return "-"
seconds = int ( round ( seconds ) )
if abs ( seconds ) < 60 :
return "{:d}" . format ( seconds )
else :
minutes = int ( seconds / 60 )
seconds %= 60
if abs ( minutes ) < 60 :
... |
def _set_is_address_family_v6 ( self , v , load = False ) :
"""Setter method for is _ address _ family _ v6 , mapped from YANG variable / isis _ state / router _ isis _ config / is _ address _ family _ v6 ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ is ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = is_address_family_v6 . is_address_family_v6 , is_container = 'container' , presence = False , yang_name = "is-address-family-v6" , rest_name = "is-address-family-v6" , parent = self , path_helper = self . _path_helper , extme... |
def transitions ( self , omega_min = None , omega_max = None ) :
r"""Find all allowed transitions .
This function finds all allowed transitions ( by electric - dipole
selection rules ) in the atom .
> > > atom = Atom ( " Rb " , 85)
> > > transitions = atom . transitions ( )
> > > print ( len ( transitions... | states = self . states ( )
transitions = states
transitions = [ ]
for i in range ( len ( states ) ) :
si = states [ i ]
for j in range ( i ) :
sj = states [ j ]
t = Transition ( sj , si )
if t . allowed :
transitions += [ t ]
if omega_min is not None :
transitions = [ ti ... |
def containing_simplex_and_bcc ( self , xi , yi ) :
"""Returns the simplices containing ( xi , yi )
and the local barycentric , normalised coordinates .
Parameters
xi : float / array of floats , shape ( l , )
Cartesian coordinates in the x direction
yi : float / array of floats , shape ( l , )
Cartesian... | pts = np . column_stack ( [ xi , yi ] )
tri = np . empty ( ( pts . shape [ 0 ] , 3 ) , dtype = np . int )
# simplices
bcc = np . empty_like ( tri , dtype = np . float )
# barycentric coords
for i , pt in enumerate ( pts ) :
t = _tripack . trfind ( 3 , pt [ 0 ] , pt [ 1 ] , self . _x , self . _y , self . lst , self ... |
def delete_events ( self , event_collection , params ) :
"""Deletes events via the Keen IO API . A master key must be set first .
: param event _ collection : string , the event collection from which event are being deleted""" | url = "{0}/{1}/projects/{2}/events/{3}" . format ( self . base_url , self . api_version , self . project_id , event_collection )
headers = utilities . headers ( self . master_key )
response = self . fulfill ( HTTPMethods . DELETE , url , params = params , headers = headers , timeout = self . post_timeout )
self . _erro... |
def rot2 ( theta ) :
"""Args :
theta ( float ) : Angle in radians
Return :
Rotation matrix of angle theta around the Y - axis""" | return np . array ( [ [ np . cos ( theta ) , 0 , - np . sin ( theta ) ] , [ 0 , 1 , 0 ] , [ np . sin ( theta ) , 0 , np . cos ( theta ) ] ] ) |
def render_children ( node : Node , ** child_args ) :
"""Render node children""" | for xml_node in node . xml_node . children :
child = render ( xml_node , ** child_args )
node . add_child ( child ) |
def _dimensions_to_values ( dimensions ) :
"""Replace dimensions specs with their ` dimension `
values , and ignore those without""" | values = [ ]
for dimension in dimensions :
if isinstance ( dimension , dict ) :
if 'extractionFn' in dimension :
values . append ( dimension )
elif 'dimension' in dimension :
values . append ( dimension [ 'dimension' ] )
else :
values . append ( dimension )
return... |
def get ( self , name ) :
"""Gets the module with the given name if it exists in
this code parser .""" | if name not in self . modules :
self . load_dependency ( name , False , False , False )
if name in self . modules :
return self . modules [ name ]
else :
return None |
def p_expression_Xnor ( self , p ) :
'expression : expression XNOR expression' | p [ 0 ] = Xnor ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def write_config ( self , outfile ) :
"""Write the configuration dictionary to an output file .""" | utils . write_yaml ( self . config , outfile , default_flow_style = False ) |
def context ( params ) :
"""Function that add somes variable to the context before template rendering
: param dict params : The context dictionary used to render templates .
: return : The ` ` params ` ` dictionary with the key ` ` settings ` ` set to
: obj : ` django . conf . settings ` .
: rtype : dict""" | params [ "settings" ] = settings
params [ "message_levels" ] = DEFAULT_MESSAGE_LEVELS
if settings . CAS_NEW_VERSION_HTML_WARNING :
LAST_VERSION = last_version ( )
params [ "VERSION" ] = VERSION
params [ "LAST_VERSION" ] = LAST_VERSION
if LAST_VERSION is not None :
params [ "upgrade_available" ] ... |
def download_datapackage ( self , dataset_key , dest_dir ) :
"""Download and unzip a dataset ' s datapackage
: param dataset _ key : Dataset identifier , in the form of owner / id
: type dataset _ key : str
: param dest _ dir : Directory under which datapackage should be saved
: type dest _ dir : str or pat... | if path . isdir ( dest_dir ) :
raise ValueError ( 'dest_dir must be a new directory, ' 'but {} already exists' . format ( dest_dir ) )
owner_id , dataset_id = parse_dataset_key ( dataset_key )
url = "{0}://{1}/datapackage/{2}/{3}" . format ( self . _protocol , self . _download_host , owner_id , dataset_id )
headers... |
def bind_ ( cls , kls ) :
"""To bind application that needs the ' app ' object to init
: param app : callable function that will receive ' Flask . app ' as first arg""" | if not hasattr ( kls , "__call__" ) :
raise TypeError ( "From Pylot.bind_: '%s' is not callable" % kls )
cls . _bind . add ( kls )
return kls |
def send_event ( self , name , * args , ** kwargs ) :
"""Send an event to the native handler . This call is queued and
batched .
Parameters
name : str
The event name to be processed by MainActivity . processMessages .
* args : args
The arguments required by the event .
* * kwargs : kwargs
Options fo... | n = len ( self . _bridge_queue )
# Add to queue
self . _bridge_queue . append ( ( name , args ) )
if n == 0 : # First event , send at next available time
self . _bridge_last_scheduled = time ( )
self . deferred_call ( self . _bridge_send )
return
elif kwargs . get ( 'now' ) :
self . _bridge_send ( now =... |
def make_flag_qrect ( self , value ) :
"""Make flag QRect""" | if self . slider :
position = self . value_to_position ( value + 0.5 )
# The 0.5 offset is used to align the flags with the center of
# their corresponding text edit block before scaling .
return QRect ( self . FLAGS_DX / 2 , position - self . FLAGS_DY / 2 , self . WIDTH - self . FLAGS_DX , self . FLAGS... |
def get_vmpolicy_macaddr_output_vmpolicy_macaddr_datacenter ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vmpolicy_macaddr = ET . Element ( "get_vmpolicy_macaddr" )
config = get_vmpolicy_macaddr
output = ET . SubElement ( get_vmpolicy_macaddr , "output" )
vmpolicy_macaddr = ET . SubElement ( output , "vmpolicy-macaddr" )
datacenter = ET . SubElement ( vmpolicy_macaddr , "datacenter" )... |
def tokenize_tags ( tags_string ) :
"""This function is responsible to extract usable tags from a text .
: param tags _ string : a string of text
: return : a string of comma separated tags""" | # text is parsed in two steps :
# the first step extract every single world that is 3 > chars long
# and that contains only alphanumeric characters , underscores and dashes
tags_string = tags_string . lower ( ) . strip ( "," )
single_words = set ( [ w [ : 100 ] for w in re . split ( ';|,|\*|\n| ' , tags_string ) if len... |
def ids ( self , content_ids , object_ids ) :
"""Appends the content and object ids how RETS expects them""" | result = [ ]
content_ids = self . split ( content_ids , False )
object_ids = self . split ( object_ids )
for cid in content_ids :
result . append ( '{}:{}' . format ( cid , ':' . join ( object_ids ) ) )
return result |
def db_url_config ( cls , url , engine = None ) :
"""Pulled from DJ - Database - URL , parse an arbitrary Database URL .
Support currently exists for PostgreSQL , PostGIS , MySQL , Oracle and SQLite .
SQLite connects to file based databases . The same URL format is used , omitting the hostname ,
and using the... | if not isinstance ( url , cls . URL_CLASS ) :
if url == 'sqlite://:memory:' : # this is a special case , because if we pass this URL into
# urlparse , urlparse will choke trying to interpret " memory "
# as a port number
return { 'ENGINE' : cls . DB_SCHEMES [ 'sqlite' ] , 'NAME' : ':memory:' }
... |
def _tracing_information ( ) :
"""Gets B3 distributed tracing information , if available .
This is returned as a list , ready to be formatted into Spring Cloud Sleuth compatible format .""" | # We ' ll collate trace information if the B3 headers have been collected :
values = b3 . values ( )
if values [ b3 . b3_trace_id ] : # Trace information would normally be sent to Zipkin if either of sampled or debug ( " flags " ) is set to 1
# However we ' re not currently using Zipkin , so it ' s always false
# expor... |
def map_reduce ( iterable , keyfunc , valuefunc = None , reducefunc = None ) :
"""Return a dictionary that maps the items in * iterable * to categories
defined by * keyfunc * , transforms them with * valuefunc * , and
then summarizes them by category with * reducefunc * .
* valuefunc * defaults to the identit... | valuefunc = ( lambda x : x ) if ( valuefunc is None ) else valuefunc
ret = defaultdict ( list )
for item in iterable :
key = keyfunc ( item )
value = valuefunc ( item )
ret [ key ] . append ( value )
if reducefunc is not None :
for key , value_list in ret . items ( ) :
ret [ key ] = reducefunc (... |
def get_name_deadlines ( self , name_rec , namespace_rec , block_number ) :
"""Get the expiry and renewal deadlines for a ( registered ) name .
NOTE : expire block here is NOT the block at which the owner loses the name , but the block at which lookups fail .
The name owner has until renewal _ deadline to renew... | if namespace_rec [ 'op' ] != NAMESPACE_READY : # name cannot be in grace period , since the namespace is not ready
return None
namespace_id = namespace_rec [ 'namespace_id' ]
namespace_lifetime_multiplier = get_epoch_namespace_lifetime_multiplier ( block_number , namespace_id )
namespace_lifetime_grace_period = get... |
def ilr ( data_frame , voxmats , ilr_formula , verbose = False ) :
"""Image - based linear regression .
This function simplifies calculating p - values from linear models
in which there is a similar formula that is applied many times
with a change in image - based predictors . Image - based variables
are st... | nvoxmats = len ( voxmats )
if nvoxmats < 1 :
raise ValueError ( 'Pass at least one matrix to voxmats list' )
keylist = list ( voxmats . keys ( ) )
firstmat = keylist [ 0 ]
voxshape = voxmats [ firstmat ] . shape
nvox = voxshape [ 1 ]
nmats = len ( keylist )
for k in keylist :
if voxmats [ firstmat ] . shape != ... |
def after_config_matches ( ini , envlist ) :
"""Determine if this job should wait for the others .""" | section = ini . sections . get ( 'travis:after' , { } )
if not section :
return False
# Never wait if it ' s not configured
if 'envlist' in section or 'toxenv' in section :
if 'toxenv' in section :
print ( 'The "toxenv" key of the [travis:after] section is ' 'deprecated in favor of the "envlist" key.' ,... |
def translate ( self , hWndFrom = HWND_DESKTOP , hWndTo = HWND_DESKTOP ) :
"""Translate coordinates from one window to another .
@ see : L { client _ to _ screen } , L { screen _ to _ client }
@ type hWndFrom : int or L { HWND } or L { system . Window }
@ param hWndFrom : Window handle to translate from .
U... | points = [ ( self . left , self . top ) , ( self . right , self . bottom ) ]
return MapWindowPoints ( hWndFrom , hWndTo , points ) |
def deferred_cleanup ( fn ) :
"""Go defer style cleanups - - in reality , just a convenience wrapper over try - finally""" | @ functools . wraps ( fn )
def ret ( * args , ** kwargs ) :
defers = [ ]
try :
ret = fn ( lambda * args : defers . extend ( args ) , * args , ** kwargs )
finally :
for defer in reversed ( defers ) :
defer ( )
return ret
return ret |
def matrix2sheet ( self , float_row , float_col ) :
"""Convert a floating - point location ( float _ row , float _ col ) in
matrix coordinates to its corresponding location ( x , y ) in
sheet coordinates .
Valid for scalar or array float _ row and float _ col .
Inverse of sheet2matrix ( ) .""" | xoffset = float_col * self . __xstep
if isinstance ( self . lbrt [ 0 ] , datetime_types ) :
xoffset = np . timedelta64 ( int ( round ( xoffset ) ) , self . _time_unit )
x = self . lbrt [ 0 ] + xoffset
yoffset = float_row * self . __ystep
if isinstance ( self . lbrt [ 3 ] , datetime_types ) :
yoffset = np . time... |
def var_case_name ( self , name ) :
"""Provides stored name ( case preserved ) for case insensitive input
If name is not found ( case - insensitive check ) then name is returned ,
as input . This function is intended to be used to help ensure the
case of a given variable name is the same across the Meta objec... | lower_name = name . lower ( )
if name in self :
for i in self . keys ( ) :
if lower_name == i . lower ( ) :
return i
for i in self . keys_nD ( ) :
if lower_name == i . lower ( ) :
return i
return name |
def category_names ( self ) :
'''Returns category names of 1000 ImageNet classes .''' | if hasattr ( self , '_category_names' ) :
return self . _category_names
with open ( os . path . join ( os . path . dirname ( __file__ ) , 'category_names.txt' ) , 'r' ) as fd :
self . _category_names = fd . read ( ) . splitlines ( )
return self . _category_names |
def get_model_classes ( self ) :
"""Return all : class : ` ~ fluent _ contents . models . ContentItem ` model classes which are exposed by plugins .""" | self . _import_plugins ( )
return [ plugin . model for plugin in self . plugins . values ( ) ] |
def parse_branches ( self , branchset_node , branchset , validate ) :
"""Create and attach branches at ` ` branchset _ node ` ` to ` ` branchset ` ` .
: param branchset _ node :
Same as for : meth : ` parse _ branchset ` .
: param branchset :
An instance of : class : ` BranchSet ` .
: param validate :
W... | weight_sum = 0
branches = branchset_node . nodes
values = [ ]
for branchnode in branches :
weight = ~ branchnode . uncertaintyWeight
weight_sum += weight
value_node = node_from_elem ( branchnode . uncertaintyModel )
if value_node . text is not None :
values . append ( value_node . text . strip (... |
def find_contours ( array , level , fully_connected = 'low' , positive_orientation = 'low' ) :
"""Find iso - valued contours in a 2D array for a given level value .
Uses the " marching squares " method to compute a the iso - valued contours of
the input 2D array for a particular level value . Array values are l... | array = np . asarray ( array , dtype = np . double )
if array . ndim != 2 :
raise ValueError ( 'Only 2D arrays are supported.' )
level = float ( level )
if ( fully_connected not in _param_options or positive_orientation not in _param_options ) :
raise ValueError ( 'Parameters "fully_connected" and' ' "positive_... |
def display_data_item ( self , data_item : DataItem , source_display_panel = None , source_data_item = None ) :
"""Display a new data item and gives it keyboard focus . Uses existing display if it is already displayed .
. . versionadded : : 1.0
Status : Provisional
Scriptable : Yes""" | for display_panel in self . __document_controller . workspace_controller . display_panels :
if display_panel . data_item == data_item . _data_item :
display_panel . request_focus ( )
return DisplayPanel ( display_panel )
result_display_panel = self . __document_controller . next_result_display_panel... |
def _precision ( self , value ) :
"""Return the precision of the number
: param str value : The value to find the precision of
: rtype : int""" | value = str ( value )
decimal = value . rfind ( '.' )
if decimal == - 1 :
return 0
return len ( value ) - decimal - 1 |
def tabify ( text , options ) :
"""tabify ( text : str , options : argparse . Namespace | str ) - > str
> > > tabify ( ' ( println " hello world " ) ' , ' - - tab = 3 ' )
' \t \t ( println " hello world " ) '
Replace spaces with tabs""" | opts = parse_options ( options )
if opts . tab_size < 1 :
return text
else :
tab_equiv = ' ' * opts . tab_size
return text . replace ( tab_equiv , '\t' ) |
def pixel_coords ( self , latlon , reverse = False ) :
'''return pixel coordinates in the map image for a ( lat , lon )
if reverse is set , then return lat / lon for a pixel coordinate''' | state = self . state
if reverse :
( x , y ) = latlon
return self . coordinates ( x , y )
( lat , lon ) = ( latlon [ 0 ] , latlon [ 1 ] )
return state . mt . coord_to_pixel ( state . lat , state . lon , state . width , state . ground_width , lat , lon ) |
def create_client ( self ) -> "google.cloud.storage.Client" :
"""Construct GCS API client .""" | # Client should be imported here because grpc starts threads during import
# and if you call fork after that , a child process will be hang during exit
from google . cloud . storage import Client
if self . credentials :
client = Client . from_service_account_json ( self . credentials )
else :
client = Client ( ... |
def _populate ( self , json ) :
"""Allows population of " from _ date " from the returned " from " attribute which
is a reserved word in python . Also populates " to _ date " to be complete .""" | super ( InvoiceItem , self ) . _populate ( json )
self . from_date = datetime . strptime ( json [ 'from' ] , DATE_FORMAT )
self . to_date = datetime . strptime ( json [ 'to' ] , DATE_FORMAT ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.