signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def z_score ( self ) :
"""Calculate the Z - Score between this alternative and the project control .
Statistical formulas based on :
http : / / 20bits . com / article / statistical - analysis - and - ab - testing""" | control = VariantStat ( self . experiment . control , self . experiment )
alternative = self
if control . name == alternative . name :
return 'N/A'
conv_c = control . conversion_rate
conv_a = alternative . conversion_rate
num_c = control . participant_count
num_a = alternative . participant_count
if conv_c == 0 or ... |
def add_sister ( self , sister = None , name = None , dist = None ) :
"""Adds a sister to this node . If sister node is not supplied
as an argument , a new TreeNode instance will be created and
returned .""" | if self . up == None :
raise TreeError ( "A parent node is required to add a sister" )
else :
return self . up . add_child ( child = sister , name = name , dist = dist ) |
def remove_prefix ( self , args ) :
"""Remove a prefix .
Valid keys in the ` args ` - struct :
* ` auth ` [ struct ]
Authentication options passed to the : class : ` AuthFactory ` .
* ` prefix ` [ struct ]
Attributes used to select what prefix to remove .
* ` recursive ` [ boolean ]
When set to 1 , al... | try :
return self . nip . remove_prefix ( args . get ( 'auth' ) , args . get ( 'prefix' ) , args . get ( 'recursive' ) )
except ( AuthError , NipapError ) as exc :
self . logger . debug ( unicode ( exc ) )
raise Fault ( exc . error_code , unicode ( exc ) ) |
def wall_factor_fd ( mu , mu_wall , turbulent = True , liquid = False ) :
r'''Computes the wall correction factor for pressure drop due to friction
between a fluid and a wall . These coefficients were derived for internal
flow inside a pipe , but can be used elsewhere where appropriate data is
missing .
. .... | params = wall_factor_fd_defaults [ ( turbulent , liquid ) ]
return wall_factor ( mu = mu , mu_wall = mu_wall , ** params ) |
def rime_solver ( slvr_cfg ) :
"""Factory function that produces a RIME solver""" | from montblanc . impl . rime . tensorflow . RimeSolver import RimeSolver
return RimeSolver ( slvr_cfg ) |
def save_freesurfer_geometry ( filename , obj , volume_info = None , create_stamp = None ) :
'''save _ mgh ( filename , obj ) saves the given object to the given filename in the mgh format and
returns the filename .
All options that can be given to the to _ mgh function can also be passed to this function ; the... | obj = geo . to_mesh ( obj )
fsio . write_geometry ( filename , obj . coordinates . T , obj . tess . faces . T , volume_info = volume_info , create_stamp = create_stamp )
return filename |
def get_conn ( cls ) :
"""Return a connection object to the ldap database""" | conn = cls . _conn
if conn is None or conn . closed :
conn = ldap3 . Connection ( settings . CAS_LDAP_SERVER , settings . CAS_LDAP_USER , settings . CAS_LDAP_PASSWORD , client_strategy = "RESTARTABLE" , auto_bind = True )
cls . _conn = conn
return conn |
def ice_refractive ( file ) :
"""Interpolator for the refractive indices of ice .
Inputs :
File to read the refractive index lookup table from .
This is supplied as " ice _ refr . dat " , retrieved from
http : / / www . atmos . washington . edu / ice _ optical _ constants /
Returns :
A callable object t... | D = np . loadtxt ( file )
log_wl = np . log10 ( D [ : , 0 ] / 1000 )
re = D [ : , 1 ]
log_im = np . log10 ( D [ : , 2 ] )
iobj_re = interpolate . interp1d ( log_wl , re )
iobj_log_im = interpolate . interp1d ( log_wl , log_im )
def ref ( wl , snow_density ) :
lwl = np . log10 ( wl )
try :
len ( lwl )
... |
def acknowledge_svc_problem ( self , service , sticky , notify , author , comment ) :
"""Acknowledge a service problem
Format of the line that triggers function call : :
ACKNOWLEDGE _ SVC _ PROBLEM ; < host _ name > ; < service _ description > ; < sticky > ; < notify > ;
< persistent : obsolete > ; < author >... | notification_period = None
if getattr ( service , 'notification_period' , None ) is not None :
notification_period = self . daemon . timeperiods [ service . notification_period ]
service . acknowledge_problem ( notification_period , self . hosts , self . services , sticky , notify , author , comment ) |
def cell_thermal_mass ( temperature , conductivity ) :
"""Sample interval is measured in seconds .
Temperature in degrees .
CTM is calculated in S / m .""" | alpha = 0.03
# Thermal anomaly amplitude .
beta = 1.0 / 7
# Thermal anomaly time constant ( 1 / beta ) .
sample_interval = 1 / 15.0
a = 2 * alpha / ( sample_interval * beta + 2 )
b = 1 - ( 2 * a / alpha )
dCodT = 0.1 * ( 1 + 0.006 * [ temperature - 20 ] )
dT = np . diff ( temperature )
ctm = - 1.0 * b * conductivity + ... |
def sext ( self , n ) :
'''Sign - extend the variable to n bits .
n bits must be stricly larger than the actual number of bits , or a
ValueError is thrown''' | if n <= self . nbits :
raise ValueError ( "n must be > %d bits" % self . nbits )
mba_ret = self . __new_mba ( n )
ret = mba_ret . from_cst ( 0 )
for i in range ( self . nbits ) :
ret . vec [ i ] = self . vec [ i ]
last_bit = self . vec [ self . nbits - 1 ]
for i in range ( self . nbits , n ) :
ret . vec [ i... |
def uflat ( self ) :
"""return a flatten * * copy * * of the main numpy array with only the
dependant variables .
Be carefull , modification of these data will not be reflected on
the main array !""" | # noqa
aligned_arrays = [ self [ key ] . values [ [ ( slice ( None ) if c in coords else None ) for c in self . _coords ] ] . T for key , coords in self . dependent_variables_info ]
return np . vstack ( aligned_arrays ) . flatten ( "F" ) |
def readRGB ( self ) :
"""Read a RGB color""" | self . reset_bits_pending ( ) ;
r = self . readUI8 ( )
g = self . readUI8 ( )
b = self . readUI8 ( )
return ( 0xff << 24 ) | ( r << 16 ) | ( g << 8 ) | b |
def main ( ) :
"""NAME
bootams . py
DESCRIPTION
calculates bootstrap statistics for tensor data
SYNTAX
bootams . py [ - h ] [ command line options ]
OPTIONS :
- h prints help message and quits
- f FILE specifies input file name
- par specifies parametric bootstrap [ by whole data set ]
- n N spe... | # set options
ipar , nb = 0 , 5000
if '-h' in sys . argv :
print ( main . __doc__ )
sys . exit ( )
if '-f' in sys . argv :
ind = sys . argv . index ( '-f' )
file = sys . argv [ ind + 1 ]
Ss = np . loadtxt ( file )
# f = open ( file , ' r ' )
# data = f . readlines ( )
if '-par' in sys . argv... |
def from_learner ( cls , learn : Learner , ds_type : DatasetType = DatasetType . Valid ) :
"Create an instance of ` ClassificationInterpretation `" | preds = learn . get_preds ( ds_type = ds_type , with_loss = True )
return cls ( learn , * preds ) |
def Times ( self , val ) :
"""Returns a new point which is pointwise multiplied by val .""" | return Point ( self . x * val , self . y * val , self . z * val ) |
def sourcehook ( self , newfile , encoding = 'utf-8' ) :
"Hook called on a filename to be sourced ." | from codecs import open
if newfile [ 0 ] == '"' :
newfile = newfile [ 1 : - 1 ]
# This implements cpp - like semantics for relative - path inclusion .
if isinstance ( self . infile , basestring ) and not os . path . isabs ( newfile ) :
newfile = os . path . join ( os . path . dirname ( self . infile ) , newfile... |
def parse_args ( self , * args , ** kwargs ) :
"""Parse the arguments as usual , then add default processing .""" | if _debug :
ArgumentParser . _debug ( "parse_args" )
# pass along to the parent class
result_args = _ArgumentParser . parse_args ( self , * args , ** kwargs )
# check to dump labels
if result_args . buggers :
loggers = sorted ( logging . Logger . manager . loggerDict . keys ( ) )
for loggerName in loggers :... |
def add_analysis_dataset ( self , group_name , dataset_name , data , attrs = None ) :
"""Add a dataset to the specified group .
: param group _ name : The path of the group the dataset will be added to ,
relative to the " Analyses " group .
: param dataset _ name : The name of the new dataset .
: param data... | self . assert_writeable ( )
group_path = 'Analyses/{}' . format ( group_name )
if group_path not in self . handle :
msg = 'Dataset cannot be added to non-existent group: Analyses/{} in {}'
raise KeyError ( msg . format ( group_name , self . filename ) )
sanitized_data = _sanitize_data_for_writing ( data )
if np... |
def memory_error ( ) :
"""Display an error when there is not enough memory .""" | warning_heading = m . Heading ( tr ( 'Memory issue' ) , ** WARNING_STYLE )
warning_message = tr ( 'There is not enough free memory to run this analysis.' )
suggestion_heading = m . Heading ( tr ( 'Suggestion' ) , ** SUGGESTION_STYLE )
suggestion = tr ( 'Try zooming in to a smaller area or using a raster layer with a ' ... |
def _validate_cert_format ( name ) :
'''Ensure that the certificate format , as determind from user input , is valid .''' | cert_formats = [ 'cer' , 'pfx' ]
if name not in cert_formats :
message = ( "Invalid certificate format '{0}' specified. Valid formats:" ' {1}' ) . format ( name , cert_formats )
raise SaltInvocationError ( message ) |
def crypto_sign_ed25519ph_update ( edph , pmsg ) :
"""Update the hash state wrapped in edph
: param edph : the ed25519ph state being updated
: type edph : crypto _ sign _ ed25519ph _ state
: param pmsg : the partial message
: type pmsg : bytes
: rtype : None""" | ensure ( isinstance ( edph , crypto_sign_ed25519ph_state ) , 'edph parameter must be a ed25519ph_state object' , raising = exc . TypeError )
ensure ( isinstance ( pmsg , bytes ) , 'pmsg parameter must be a bytes object' , raising = exc . TypeError )
rc = lib . crypto_sign_ed25519ph_update ( edph . state , pmsg , len ( ... |
def get_axis_map ( ds , variable ) :
'''Returns an axis _ map dictionary that contains an axis key and the coordinate
names as values .
For example : :
{ ' X ' : [ ' longitude ' ] , ' Y ' : [ ' latitude ' ] , ' T ' : [ ' time ' ] }
The axis C is for compressed coordinates like a reduced grid , and U is for ... | all_coords = get_coordinate_variables ( ds ) + get_auxiliary_coordinate_variables ( ds )
latitudes = get_latitude_variables ( ds )
longitudes = get_longitude_variables ( ds )
times = get_time_variables ( ds )
heights = get_z_variables ( ds )
coordinates = getattr ( ds . variables [ variable ] , "coordinates" , None )
i... |
def search ( ** kw ) :
"""Search the catalog adapter
: returns : Catalog search results
: rtype : iterable""" | portal = get_portal ( )
catalog = ICatalog ( portal )
catalog_query = ICatalogQuery ( catalog )
query = catalog_query . make_query ( ** kw )
return catalog ( query ) |
def info ( device ) :
'''Get BTRFS filesystem information .
CLI Example :
. . code - block : : bash
salt ' * ' btrfs . info / dev / sda1''' | out = __salt__ [ 'cmd.run_all' ] ( "btrfs filesystem show {0}" . format ( device ) )
salt . utils . fsutils . _verify_run ( out )
return _parse_btrfs_info ( out [ 'stdout' ] ) |
def block_widths ( self ) :
"""Gets the widths of the blocks .
Note : This works with the property structure ` _ widths _ cache ` to avoid
having to recompute these values each time they are needed .""" | if self . _widths_cache is None :
try : # The first column will have the correct lengths . We have an
# invariant that requires that all blocks be the same width in a
# column of blocks .
self . _widths_cache = np . array ( ray . get ( [ obj . width ( ) . oid for obj in self . _partitions_cache [ 0 ... |
def __create_chunk ( self , frequency , play_time , sample_rate ) :
'''チャンクを生成する
Args :
frequency : 周波数
play _ time : 再生時間 ( 秒 )
sample _ rate : サンプルレート
Returns :
チャンクのnumpy配列''' | chunks = [ ]
wave_form = self . wave_form . create ( frequency , play_time , sample_rate )
chunks . append ( wave_form )
chunk = numpy . concatenate ( chunks )
return chunk |
def createCellsList ( self ) :
'''Create population cells based on list of individual cells''' | from . . import sim
cells = [ ]
self . tags [ 'numCells' ] = len ( self . tags [ 'cellsList' ] )
for i in self . _distributeCells ( len ( self . tags [ 'cellsList' ] ) ) [ sim . rank ] : # if ' cellModel ' in self . tags [ ' cellsList ' ] [ i ] :
# self . cellModelClass = getattr ( f , self . tags [ ' cellsList ' ] [ i... |
def get_objective_bank_form ( self , * args , ** kwargs ) :
"""Pass through to provider ObjectiveBankAdminSession . get _ objective _ bank _ form _ for _ update""" | # Implemented from kitosid template for -
# osid . resource . BinAdminSession . get _ bin _ form _ for _ update _ template
# This method might be a bit sketchy . Time will tell .
if isinstance ( args [ - 1 ] , list ) or 'objective_bank_record_types' in kwargs :
return self . get_objective_bank_form_for_create ( * a... |
def generate_password_hash ( password , method = 'pbkdf2:sha1' , salt_length = 8 ) :
"""Hash a password with the given method and salt with with a string of
the given length . The format of the string returned includes the method
that was used so that : func : ` check _ password _ hash ` can check the hash .
... | salt = method != 'plain' and gen_salt ( salt_length ) or ''
h , actual_method = _hash_internal ( method , salt , password )
return '%s$%s$%s' % ( actual_method , salt , h ) |
def _stringify_na_values ( na_values ) :
"""return a stringified and numeric for these values""" | result = [ ]
for x in na_values :
result . append ( str ( x ) )
result . append ( x )
try :
v = float ( x )
# we are like 999 here
if v == int ( v ) :
v = int ( v )
result . append ( "{value}.0" . format ( value = v ) )
result . append ( str ( v ) ... |
def render ( self , context , instance , placeholder ) :
"""Update the context with plugin ' s data""" | context = super ( CMSSelectedEntriesPlugin , self ) . render ( context , instance , placeholder )
context [ 'entries' ] = instance . entries . all ( )
return context |
def iter_entries ( cls , stream ) :
""": return : Iterator yielding RefLogEntry instances , one for each line read
sfrom the given stream .
: param stream : file - like object containing the revlog in its native format
or basestring instance pointing to a file to read""" | new_entry = RefLogEntry . from_line
if isinstance ( stream , string_types ) :
stream = file_contents_ro_filepath ( stream )
# END handle stream type
while True :
line = stream . readline ( )
if not line :
return
yield new_entry ( line . strip ( ) )
# END endless loop
stream . close ( ) |
def make_filter_string ( cls , filter_specification ) :
"""Converts the given filter specification to a CQL filter expression .""" | registry = get_current_registry ( )
visitor_cls = registry . getUtility ( IFilterSpecificationVisitor , name = EXPRESSION_KINDS . CQL )
visitor = visitor_cls ( )
filter_specification . accept ( visitor )
return str ( visitor . expression ) |
def Clear ( self ) :
"""Wipes the transaction log .""" | try :
with io . open ( self . logfile , "wb" ) as fd :
fd . write ( b"" )
except ( IOError , OSError ) :
pass |
def _make_defaults_hazard_table ( ) :
"""Build headers for a table related to hazard classes .
: return : A table with headers .
: rtype : m . Table""" | table = m . Table ( style_class = 'table table-condensed table-striped' )
row = m . Row ( )
# first row is for colour - we dont use a header here as some tables
# do not have colour . . .
row . add ( m . Cell ( tr ( '' ) , header = True ) )
row . add ( m . Cell ( tr ( 'Name' ) , header = True ) )
row . add ( m . Cell (... |
def attachviewers ( self , profiles ) :
"""Attach viewers * and converters * to file , automatically scan all profiles for outputtemplate or inputtemplate""" | if self . metadata :
template = None
for profile in profiles :
if isinstance ( self , CLAMInputFile ) :
for t in profile . input :
if self . metadata . inputtemplate == t . id :
template = t
break
elif isinstance ( self , CLAMOu... |
def put ( self , * args , ** kwargs ) :
"""place a new item into the pool to be handled by the workers
all positional and keyword arguments will be passed in as the arguments
to the function run by the pool ' s workers""" | self . inq . put ( ( self . _putcount , ( args , kwargs ) ) )
self . _putcount += 1 |
def add_layer_to_canvas ( layer , name ) :
"""Helper method to add layer to QGIS .
: param layer : The layer .
: type layer : QgsMapLayer
: param name : Layer name .
: type name : str""" | if qgis_version ( ) >= 21800 :
layer . setName ( name )
else :
layer . setLayerName ( name )
QgsProject . instance ( ) . addMapLayer ( layer , False ) |
def execute_run ( self , args , output_filename , stdin = None , hardtimelimit = None , softtimelimit = None , walltimelimit = None , cores = None , memlimit = None , memory_nodes = None , environments = { } , workingDir = None , maxLogfileSize = None , cgroupValues = { } , files_count_limit = None , files_size_limit =... | # Check argument values and call the actual method _ execute ( )
if stdin == subprocess . PIPE :
sys . exit ( 'Illegal value subprocess.PIPE for stdin' )
elif stdin is None :
stdin = DEVNULL
if hardtimelimit is not None :
if hardtimelimit <= 0 :
sys . exit ( "Invalid time limit {0}." . format ( hard... |
def p_duration_conversion ( self , p ) :
'duration : duration IN DURATION _ UNIT' | logger . debug ( 'duration = duration %s in duration unit %s' , p [ 1 ] , p [ 3 ] )
p [ 0 ] = '{0: {1}}' . format ( p [ 1 ] , p [ 3 ] ) |
def code_to_names ( category , code ) :
"""Given the code for a language , script , or region , get a dictionary of its
names in various languages .""" | trie_name = '{}_to_name' . format ( category )
if trie_name not in TRIES :
TRIES [ trie_name ] = load_trie ( data_filename ( 'trie/{}.marisa' . format ( trie_name ) ) )
trie = TRIES [ trie_name ]
lookup = code . lower ( ) + '@'
possible_keys = trie . keys ( lookup )
names = { }
for key in possible_keys :
target... |
def _create_virtual_network ( self , region , resource_group_name , vnet_name ) :
"""Create a vnet in the given resource group with default address space .""" | vnet_config = { 'location' : region , 'address_space' : { 'address_prefixes' : [ '10.0.0.0/27' ] } }
try :
vnet_setup = self . network . virtual_networks . create_or_update ( resource_group_name , vnet_name , vnet_config )
except Exception as error :
raise AzureCloudException ( 'Unable to create vnet: {0}.' . f... |
def respects_language ( fun ) :
"""Decorator for tasks with respect to site ' s current language .
You can use this decorator on your tasks together with default @ task
decorator ( remember that the task decorator must be applied last ) .
See also the with - statement alternative : func : ` respect _ language... | @ wraps ( fun )
def _inner ( * args , ** kwargs ) :
with respect_language ( kwargs . pop ( 'language' , None ) ) :
return fun ( * args , ** kwargs )
return _inner |
def visit_regex ( self , node , regex ) :
"""Return a ` ` Regex ` ` expression .""" | tilde , literal , flags , _ = regex
flags = flags . text . upper ( )
pattern = literal . literal
# Pull the string back out of the Literal
# object .
return Regex ( pattern , ignore_case = 'I' in flags , locale = 'L' in flags , multiline = 'M' in flags , dot_all = 'S' in flags , unicode = 'U' in flags , verbose = 'X' i... |
def start ( self , exit_on_stop = True , secondary_wait = 0 , reconnect = False ) :
"""If the DistributedEvaluator is in primary mode , starts the manager
process and returns . In this case , the ` ` exit _ on _ stop ` ` argument will
be ignored .
If the DistributedEvaluator is in secondary mode , it connects... | if self . started :
raise RuntimeError ( "DistributedEvaluator already started!" )
self . started = True
if self . mode == MODE_PRIMARY :
self . _start_primary ( )
elif self . mode == MODE_SECONDARY :
time . sleep ( secondary_wait )
self . _start_secondary ( )
self . _secondary_loop ( reconnect = re... |
def _symbol_or_keyword_handler ( c , ctx , is_field_name = False ) :
"""Handles the start of an unquoted text token .
This may be an operator ( if in an s - expression ) , an identifier symbol , or a keyword .""" | in_sexp = ctx . container . ion_type is IonType . SEXP
if c not in _IDENTIFIER_STARTS :
if in_sexp and c in _OPERATORS :
c_next , _ = yield
ctx . queue . unread ( c_next )
yield ctx . immediate_transition ( _operator_symbol_handler ( c , ctx ) )
_illegal_character ( c , ctx )
assert not ... |
def serializeG1 ( x , compress = True ) :
"""Converts G1 element @ x into an array of bytes . If @ compress is True ,
the point will be compressed resulting in a much shorter string of bytes .""" | assertType ( x , G1Element )
return _serialize ( x , compress , librelic . g1_size_bin_abi , librelic . g1_write_bin_abi ) |
def add_output_opt ( self , opt , out ) :
"""Add an option that determines an output""" | self . add_opt ( opt , out . _dax_repr ( ) )
self . _add_output ( out ) |
def from_dict ( data , ctx ) :
"""Instantiate a new ClientPrice from a dict ( generally from loading a
JSON response ) . The data used to instantiate the ClientPrice is a
shallow copy of the dict passed in , with any complex child types
instantiated appropriately .""" | data = data . copy ( )
if data . get ( 'bids' ) is not None :
data [ 'bids' ] = [ ctx . pricing_common . PriceBucket . from_dict ( d , ctx ) for d in data . get ( 'bids' ) ]
if data . get ( 'asks' ) is not None :
data [ 'asks' ] = [ ctx . pricing_common . PriceBucket . from_dict ( d , ctx ) for d in data . get ... |
def format_explanation ( explanation , original_msg = None ) :
"""This formats an explanation
Normally all embedded newlines are escaped , however there are
three exceptions : \n { , \n } and \n ~ . The first two are intended
cover nested explanations , see function and attribute explanations
for examples (... | if not conf . is_message_introspection_enabled ( ) and original_msg :
return original_msg
explanation = ecu ( explanation )
lines = _split_explanation ( explanation )
result = _format_lines ( lines )
return u ( '\n' ) . join ( result ) |
def make_bundle ( bundle , fixed_version = None ) :
"""Does all of the processing required to create a bundle and write it to disk , returning its hash version""" | tmp_output_file_name = '%s.%s.%s' % ( os . path . join ( bundle . bundle_file_root , bundle . bundle_filename ) , 'temp' , bundle . bundle_type )
iter_input = iter_bundle_files ( bundle )
output_pipeline = processor_pipeline ( bundle . processors , iter_input )
m = md5 ( )
with open ( tmp_output_file_name , 'wb' ) as o... |
def get_shapely ( self ) :
""": returns : shapely . Polygon object of the z = 0 projection of
this polygon .""" | if self . shapely == None :
from shapely . geometry import Polygon as shPolygon
self . shapely = shPolygon ( self . points [ : , : 2 ] )
# z = 0 projection !
return self . shapely |
def copy_plus ( orig , new ) :
"""Copy a fils , including biological index files .""" | for ext in [ "" , ".idx" , ".gbi" , ".tbi" , ".bai" ] :
if os . path . exists ( orig + ext ) and ( not os . path . lexists ( new + ext ) or not os . path . exists ( new + ext ) ) :
shutil . copyfile ( orig + ext , new + ext ) |
def rename ( self , name , cloud = None , api_key = None , version = None , ** kwargs ) :
"""If you ' d like to change the name you use to access a given collection , you can call the rename endpoint .
This is especially useful if the name you use for your model is not available for registration .
Inputs :
na... | kwargs [ 'name' ] = name
url_params = { "batch" : False , "api_key" : api_key , "version" : version , "method" : "rename" }
result = self . _api_handler ( None , cloud = cloud , api = "custom" , url_params = url_params , ** kwargs )
self . keywords [ 'collection' ] = name
return result |
def make_environment_relocatable ( home_dir ) :
"""Makes the already - existing environment use relative paths , and takes out
the # ! - based environment selection in scripts .""" | home_dir , lib_dir , inc_dir , bin_dir = path_locations ( home_dir )
activate_this = os . path . join ( bin_dir , 'activate_this.py' )
if not os . path . exists ( activate_this ) :
logger . fatal ( 'The environment doesn\'t have a file %s -- please re-run virtualenv ' 'on this environment to update it' % activate_t... |
def _mapping ( self ) :
"""Fetch the entire mapping for the specified index .
Returns :
dict : The full mapping for the index .""" | return ( self . __search_client . get ( "/unstable/index/{}/mapping" . format ( mdf_toolbox . translate_index ( self . index ) ) ) [ "mappings" ] ) |
def _add_uid ( self , uid , skip_handle = False ) :
"""Add unique identifier in correct field .
The ` ` skip _ handle ` ` flag is used when adding a uid through the add _ url function
since urls can be easily confused with handle elements .""" | # We might add None values from wherever . Kill them here .
uid = uid or ''
if is_arxiv ( uid ) :
self . _ensure_reference_field ( 'arxiv_eprint' , normalize_arxiv ( uid ) )
elif idutils . is_doi ( uid ) :
self . _ensure_reference_field ( 'dois' , [ ] )
self . obj [ 'reference' ] [ 'dois' ] . append ( iduti... |
def __buildLimit ( self , query , limitResMax ) :
"""Builds limit parameter .""" | limit = query . _getParameters ( ) [ 'limit' ]
if limitResMax > 0 and limitResMax < limit :
query = UpdateParameter ( query , 'limit' , limitResMax )
query = UpdateParameter ( query , 'nocount' , 'true' )
elif limitResMax > 0 and limitResMax >= limit :
query = UpdateParameter ( query , 'nocount' , 'true' )
... |
def _make_minimal ( dictionary ) :
"""This function removes all the keys whose value is either None or an empty
dictionary .""" | new_dict = { }
for key , value in dictionary . items ( ) :
if value is not None :
if isinstance ( value , dict ) :
new_value = _make_minimal ( value )
if new_value :
new_dict [ key ] = new_value
else :
new_dict [ key ] = value
return new_dict |
def delivery_report ( err , msg ) :
"""Callback called once for each produced message to indicate the final
delivery result . Triggered by poll ( ) or flush ( ) .
: param confluent _ kafka . KafkaError err : Information about any error
that occurred whilst producing the message .
: param confluent _ kafka .... | if err is not None :
log . exception ( u'Message delivery failed: {}' . format ( err ) )
raise confluent_kafka . KafkaException ( err )
else :
log . debug ( u'Message delivered to {} [{}]: {}' . format ( msg . topic ( ) , msg . partition ( ) , msg . value ( ) ) ) |
def run ( uri , user_entry_point , args , env_vars = None , wait = True , capture_error = False , runner = _runner . ProcessRunnerType , extra_opts = None ) : # type : ( str , str , List [ str ] , Dict [ str , str ] , bool , bool , _ runner . RunnerType , Dict [ str , str ] ) - > None
"""Download , prepare and exec... | env_vars = env_vars or { }
env_vars = env_vars . copy ( )
_files . download_and_extract ( uri , user_entry_point , _env . code_dir )
install ( user_entry_point , _env . code_dir , capture_error )
_env . write_env_vars ( env_vars )
return _runner . get ( runner , user_entry_point , args , env_vars , extra_opts ) . run (... |
def find_dups ( file_dict ) :
'''takes output from : meth : ` scan _ dir ` and returns list of duplicate files''' | found_hashes = { }
for f in file_dict :
if file_dict [ f ] [ 'md5' ] not in found_hashes :
found_hashes [ file_dict [ f ] [ 'md5' ] ] = [ ]
found_hashes [ file_dict [ f ] [ 'md5' ] ] . append ( f )
final_hashes = dict ( found_hashes )
for h in found_hashes :
if len ( found_hashes [ h ] ) < 2 :
... |
def _create_image ( self , matrix , width , height , pad ) :
"""Generates a PNG byte list""" | image = Image . new ( "RGB" , ( width + ( pad * 2 ) , height + ( pad * 2 ) ) , self . bg_colour )
image_draw = ImageDraw . Draw ( image )
# Calculate the block width and height .
block_width = float ( width ) / self . cols
block_height = float ( height ) / self . rows
# Loop through blocks in matrix , draw rectangles .... |
def beacon ( config ) :
'''Watch napalm function and fire events .''' | log . debug ( 'Executing napalm beacon with config:' )
log . debug ( config )
ret = [ ]
for mod in config :
if not mod :
continue
event = { }
fun = mod . keys ( ) [ 0 ]
fun_cfg = mod . values ( ) [ 0 ]
args = fun_cfg . pop ( '_args' , [ ] )
kwargs = fun_cfg . pop ( '_kwargs' , { } )
... |
def decompress ( zdata ) :
"""Unserializes an AstonFrame .
Parameters
zdata : bytes
Returns
Trace or Chromatogram""" | data = zlib . decompress ( zdata )
lc = struct . unpack ( '<L' , data [ 0 : 4 ] ) [ 0 ]
li = struct . unpack ( '<L' , data [ 4 : 8 ] ) [ 0 ]
c = json . loads ( data [ 8 : 8 + lc ] . decode ( 'utf-8' ) )
i = np . fromstring ( data [ 8 + lc : 8 + lc + li ] , dtype = np . float32 )
v = np . fromstring ( data [ 8 + lc + li... |
def escape_tabs_newlines ( s : str ) -> str :
"""Escapes CR , LF , tab , and backslashes .
Its counterpart is : func : ` unescape _ tabs _ newlines ` .""" | if not s :
return s
s = s . replace ( "\\" , r"\\" )
# replace \ with \ \
s = s . replace ( "\n" , r"\n" )
# escape \ n ; note ord ( " \ n " ) = = 10
s = s . replace ( "\r" , r"\r" )
# escape \ r ; note ord ( " \ r " ) = = 13
s = s . replace ( "\t" , r"\t" )
# escape \ t ; note ord ( " \ t " ) = = 9
return s |
def open ( self ) :
"""open : Opens zipfile to write to
Args : None
Returns : None""" | self . zf = zipfile . ZipFile ( self . write_to_path , self . mode ) |
def _allocate_tensors ( self ) :
"""Allocates the tensors in the dataset .""" | # init tensors dict
self . _tensors = { }
# allocate tensor for each data field
for field_name , field_spec in self . _config [ 'fields' ] . items ( ) : # parse attributes
field_dtype = np . dtype ( field_spec [ 'dtype' ] )
# parse shape
field_shape = [ self . _datapoints_per_file ]
if 'height' in field... |
def get_options ( ) :
"""get the command line options""" | parser = argparse . ArgumentParser ( description = "Script to batch process de" "novo clustering." )
parser . add_argument ( "--in" , dest = "input" , required = True , help = "Path to" "file listing known mutations in genes. See example file in data folder" "for format." )
parser . add_argument ( "--temp-dir" , requir... |
def train ( self ) :
"""This method generates the classifier . This method assumes that the
training data has been loaded""" | if not self . training_data :
self . import_training_data ( )
training_feature_set = [ ( self . extract_features ( line ) , label ) for ( line , label ) in self . training_data ]
self . classifier = nltk . NaiveBayesClassifier . train ( training_feature_set ) |
def create_storage_policy ( policy_name , policy_dict , service_instance = None ) :
'''Creates a storage policy .
Supported capability types : scalar , set , range .
policy _ name
Name of the policy to create .
The value of the argument will override any existing name in
` ` policy _ dict ` ` .
policy _... | log . trace ( 'create storage policy \'%s\', dict = %s' , policy_name , policy_dict )
profile_manager = salt . utils . pbm . get_profile_manager ( service_instance )
policy_create_spec = pbm . profile . CapabilityBasedProfileCreateSpec ( )
# Hardcode the storage profile resource type
policy_create_spec . resourceType =... |
def check_state ( self , token ) :
"""Check if state is in either the keys or values of our states list . Must come before the suffix .""" | # print " zip " , self . zip
if len ( token ) == 2 and self . state is None :
if token . capitalize ( ) in self . parser . states . keys ( ) :
self . state = self . _clean ( self . parser . states [ token . capitalize ( ) ] )
return True
elif token . upper ( ) in self . parser . states . values ... |
def comment_num ( self ) :
""": return : 答案下评论的数量
: rtype : int""" | comment = self . soup . select_one ( "div.answer-actions a.toggle-comment" )
comment_num_string = comment . text
number = comment_num_string . split ( ) [ 0 ]
return int ( number ) if number . isdigit ( ) else 0 |
def georadius ( self , key , longitude , latitude , radius , unit = 'm' , * , with_dist = False , with_hash = False , with_coord = False , count = None , sort = None , encoding = _NOTSET ) :
"""Query a sorted set representing a geospatial index to fetch members
matching a given maximum distance from a point .
R... | args = validate_georadius_options ( radius , unit , with_dist , with_hash , with_coord , count , sort )
fut = self . execute ( b'GEORADIUS' , key , longitude , latitude , radius , unit , * args , encoding = encoding )
if with_dist or with_hash or with_coord :
return wait_convert ( fut , make_geomember , with_dist =... |
def to_bytes ( self , frame , state ) :
"""Convert a single frame into bytes that can be transmitted on
the stream .
: param frame : The frame to convert . Should be the same type
of object returned by ` ` to _ frame ( ) ` ` .
: param state : An instance of ` ` FramerState ` ` . This object may
be used to... | # Encode the frame and append the delimiter
return six . binary_type ( self . variant . encode ( six . binary_type ( frame ) ) ) + b'\0' |
def get_stop_words ( language , cache = True ) :
""": type language : basestring
: rtype : list""" | try :
language = LANGUAGE_MAPPING [ language ]
except KeyError :
if language not in AVAILABLE_LANGUAGES :
raise StopWordError ( '{0}" language is unavailable.' . format ( language ) )
if cache and language in STOP_WORDS_CACHE :
return STOP_WORDS_CACHE [ language ]
language_filename = os . path . joi... |
def search_edges_with_bel ( self , bel : str ) -> List [ Edge ] :
"""Search edges with given BEL .
: param bel : A BEL string to use as a search""" | return self . session . query ( Edge ) . filter ( Edge . bel . like ( bel ) ) |
def startDrag ( self , index ) :
"""start a drag operation with a PandasCellPayload on defined index .
Args :
index ( QModelIndex ) : model index you want to start the drag operation .""" | if not index . isValid ( ) :
return
dataFrame = self . model ( ) . dataFrame ( )
# get all infos from dataFrame
dfindex = dataFrame . iloc [ [ index . row ( ) ] ] . index
columnName = dataFrame . columns [ index . column ( ) ]
dtype = dataFrame [ columnName ] . dtype
value = dataFrame [ columnName ] [ dfindex ]
# c... |
def shutdown ( self ) :
'Close all peer connections and stop listening for new ones' | log . info ( "shutting down" )
for peer in self . _dispatcher . peers . values ( ) :
peer . go_down ( reconnect = False )
if self . _listener_coro :
backend . schedule_exception ( errors . _BailOutOfListener ( ) , self . _listener_coro )
if self . _udp_listener_coro :
backend . schedule_exception ( errors .... |
def get_or_create_by_natural_key ( self , * args ) :
"""get _ or _ create + get _ by _ natural _ key""" | try :
return self . get_by_natural_key ( * args ) , False
except self . model . DoesNotExist :
return self . create_by_natural_key ( * args ) , True |
def schema_file ( self ) :
"""Gets the full path to the file in which to load configuration schema .""" | path = os . getcwd ( ) + '/' + self . lazy_folder
return path + self . schema_filename |
def ensure_tuple ( arg , len_ = None ) :
"""Checks whether argument is a tuple .
: param len _ : Optional expected length of the tuple
: return : Argument , if it ' s a tuple ( of given length , if any )
: raise TypeError : When argument is not a tuple ( of given length , if any )""" | if not is_tuple ( arg , len_ = len_ ) :
len_part = "" if len_ is None else " of length %s" % len_
raise TypeError ( "expected tuple%s, got %s" % ( len_part , _describe_type ( arg ) ) )
return arg |
def do_dq ( self , arg ) :
"""[ ~ thread ] dq < register > - show memory contents as qwords
[ ~ thread ] dq < register - register > - show memory contents as qwords
[ ~ thread ] dq < register > < size > - show memory contents as qwords
[ ~ process ] dq < address > - show memory contents as qwords
[ ~ proces... | self . print_memory_display ( arg , HexDump . hexblock_qword )
self . last_display_command = self . do_dq |
def _calculate_menu_wh ( self ) :
"""Calculate menu widht and height .""" | w = iw = 50
h = ih = 0
# menu . index returns None if there are no choices
index = self . _menu . index ( tk . END )
index = index if index is not None else 0
count = index + 1
# First calculate using the font paramters of root menu :
font = self . _menu . cget ( 'font' )
font = self . _get_font ( font )
for i in range... |
def contains ( self , desired ) :
'''Return the filter closure fully constructed .''' | field = self . __field
def aFilter ( testDictionary ) :
return ( desired in testDictionary [ field ] )
return aFilter |
def add_at ( self , moment : float , fn_process : Callable , * args : Any , ** kwargs : Any ) -> 'Process' :
"""Adds a process to the simulation , which is made to start at the given exact time on the simulated clock . Note
that times in the past when compared to the current moment on the simulated clock are forb... | delay = moment - self . now ( )
if delay < 0.0 :
raise ValueError ( f"The given moment to start the process ({moment:f}) is in the past (now is {self.now():f})." )
return self . add_in ( delay , fn_process , * args , ** kwargs ) |
def rotateDirection ( self , displayDirection ) :
"""\~english rotate screen direction
@ param displayDirection : Screen Direction . value can be chosen : 0 , 90 , 180 , 270
\~chinese 旋转显示屏方向
@ param displayDirection : 显示屏方向 。 可选值 : 0 , 90 , 180 , 270
@ note
\~english after rotate the View resize to scree... | if self . _needSwapWH ( self . _display_direction , displayDirection ) :
self . _display_size = ( self . _display_size [ 1 ] , self . _display_size [ 0 ] )
if self . redefineBuffer ( { "size" : self . _display_size , "color_mode" : self . _buffer_color_mode } ) :
self . View . resize ( self . _display_s... |
def list_nodes ( ) :
"""Return a list of all nodes""" | token = session . get ( 'token' )
node = nago . core . get_node ( token )
if not node . get ( 'access' ) == 'master' :
return jsonify ( status = 'error' , error = "You need master access to view this page" )
nodes = nago . core . get_nodes ( ) . values ( )
return render_template ( 'nodes.html' , ** locals ( ) ) |
def make_sign ( api_secret , params = [ ] ) :
"""> > > make _ sign ( " 123456 " , [ 1 , ' 2 ' , u ' 中文 ' ] )
'33C9065427EECA3490C5642C99165145'""" | _params = [ utils . safeunicode ( p ) for p in params if p is not None ]
_params . sort ( )
# print ' sorted params : ' , _ params
_params . insert ( 0 , api_secret )
strs = '' . join ( _params )
# print ' sign params : ' , strs
mds = md5 ( strs . encode ( 'utf-8' ) ) . hexdigest ( )
return mds . upper ( ) |
def unique ( self , values ) :
"""Place each entry in a table , while asserting that each entry occurs once""" | _ , count = self . count ( )
if not np . array_equiv ( count , 1 ) :
raise ValueError ( "Not every entry in the table is assigned a unique value" )
return self . sum ( values ) |
def get_slices_multi ( self , image_list , extended = False ) :
"""Returns the same cross - section from the multiple images supplied .
All images must be of the same shape as the original image defining this object .
Parameters
image _ list : Iterable
containing atleast 2 images
extended : bool
Flag to... | # ensure all the images have the same shape
for img in image_list :
if img . shape != self . _image . shape :
raise ValueError ( 'Supplied images are not compatible with this class. ' 'They must have the shape: {}' . format ( self . _image_shape ) )
for dim , slice_num in self . _slices :
multiple_slice... |
def cholesky ( L , b , P = None ) :
'''P A P ' = L L ' ''' | logger . debug ( 'Solving system of dim {} with cholesky factors' . format ( len ( b ) ) )
# # convert L and U to csr format
is_csr = scipy . sparse . isspmatrix_csr ( L )
is_csc = scipy . sparse . isspmatrix_csc ( L )
if not is_csr and not is_csc :
warnings . warn ( 'cholesky requires L be in CSR or CSC matrix for... |
def get_all_items_of_credit_note ( self , credit_note_id ) :
"""Get all items of credit note
This will iterate over all pages until it gets all elements .
So if the rate limit exceeded it will throw an Exception and you will get nothing
: param credit _ note _ id : the credit note id
: return : list""" | return self . _iterate_through_pages ( get_function = self . get_items_of_credit_note_per_page , resource = CREDIT_NOTE_ITEMS , ** { 'credit_note_id' : credit_note_id } ) |
def anchor_stream ( self , stream_id , converter = "rtc" ) :
"""Mark a stream as containing anchor points .""" | if isinstance ( converter , str ) :
converter = self . _known_converters . get ( converter )
if converter is None :
raise ArgumentError ( "Unknown anchor converter string: %s" % converter , known_converters = list ( self . _known_converters ) )
self . _anchor_streams [ stream_id ] = converter |
def subscribe_registration_ids_to_topic ( self , registration_ids , topic_name ) :
"""Subscribes a list of registration ids to a topic
Args :
registration _ ids ( list ) : ids to be subscribed
topic _ name ( str ) : name of topic
Returns :
True : if operation succeeded
Raises :
InvalidDataError : data... | url = 'https://iid.googleapis.com/iid/v1:batchAdd'
payload = { 'to' : '/topics/' + topic_name , 'registration_tokens' : registration_ids , }
response = self . requests_session . post ( url , json = payload )
if response . status_code == 200 :
return True
elif response . status_code == 400 :
error = response . j... |
def string_to_run ( self , qad , executable , stdin = None , stdout = None , stderr = None , exec_args = None ) :
"""Build and return a string with the command required to launch ` executable ` with the qadapter ` qad ` .
Args
qad : Qadapter instance .
executable ( str ) : Executable name or path
stdin ( st... | stdin = "< " + stdin if stdin is not None else ""
stdout = "> " + stdout if stdout is not None else ""
stderr = "2> " + stderr if stderr is not None else ""
if exec_args :
executable = executable + " " + " " . join ( list_strings ( exec_args ) )
basename = os . path . basename ( self . name )
if basename in [ "mpir... |
def add_reftrack ( self , reftrack ) :
"""Add a reftrack object to the root .
This will not handle row insertion in the model !
It is automatically done when setting the parent of the : class : ` Reftrack ` object .
: param reftrack : the reftrack object to add
: type reftrack : : class : ` Reftrack `
: r... | self . _reftracks . add ( reftrack )
refobj = reftrack . get_refobj ( )
if refobj :
self . _parentsearchdict [ refobj ] = reftrack |
def wwpn_alloc ( self ) :
"""Allocates a WWPN unique to this partition , in the range of
0xAFFEAFFE00008000 to 0xAFFEAFFE0000FFFF .
Returns :
string : The WWPN as 16 hexadecimal digits in upper case .
Raises :
ValueError : No more WWPNs available in that range .""" | wwpn_int = self . _wwpn_pool . alloc ( )
wwpn = "AFFEAFFE0000" + "{:04X}" . format ( wwpn_int )
return wwpn |
def show_dependencies ( self , stream = sys . stdout ) :
"""Writes to the given stream the ASCII representation of the dependency tree .""" | def child_iter ( node ) :
return [ d . node for d in node . deps ]
def text_str ( node ) :
return colored ( str ( node ) , color = node . status . color_opts [ "color" ] )
for task in self . iflat_tasks ( ) :
print ( draw_tree ( task , child_iter , text_str ) , file = stream ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.