signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def load_probe ( name ) :
"""Load one of the built - in probes .""" | if op . exists ( name ) : # The argument can be either a path to a PRB file .
path = name
else : # Or the name of a built - in probe .
curdir = op . realpath ( op . dirname ( __file__ ) )
path = op . join ( curdir , 'probes/{}.prb' . format ( name ) )
if not op . exists ( path ) :
raise IOError ( "The p... |
def _solve_conflict ( list_c , s2p , n_cluster ) :
"""Make sure sequences are counts once .
Resolve by most - vote or exclussion
: params list _ c : dict of objects cluster
: param s2p : dict of [ loci ] . coverage = # num of seqs
: param n _ cluster : number of clusters
return dict : new set of clusters"... | logger . debug ( "_solve_conflict: count once" )
if parameters . decision_cluster == "bayes" :
return decide_by_bayes ( list_c , s2p )
loci_similarity = _calculate_similarity ( list_c )
loci_similarity = sorted ( loci_similarity . iteritems ( ) , key = operator . itemgetter ( 1 ) , reverse = True )
common = sum ( [... |
def draw_multi_dispersion_chart ( self , nan_locs ) :
"""Draws a multi dimensional dispersion chart , each color corresponds
to a different target variable .""" | for index , nan_values in enumerate ( nan_locs ) :
label , nan_locations = nan_values
# if features passed in then , label as such
if self . classes_ is not None :
label = self . classes_ [ index ]
color = self . colors [ index ]
x_ , y_ = list ( zip ( * nan_locations ) )
self . ax . sca... |
def replace ( self , new_node ) :
"""Replace a node after first checking integrity of node stack .""" | cur_node = self . cur_node
nodestack = self . nodestack
cur = nodestack . pop ( )
prev = nodestack [ - 1 ]
index = prev [ - 1 ] - 1
oldnode , name = prev [ - 2 ] [ index ]
assert cur [ 0 ] is cur_node is oldnode , ( cur [ 0 ] , cur_node , prev [ - 2 ] , index )
parent = prev [ 0 ]
if isinstance ( parent , list ) :
... |
def notes_placeholder ( self ) :
"""Return the notes placeholder on this notes slide , the shape that
contains the actual notes text . Return | None | if no notes placeholder
is present ; while this is probably uncommon , it can happen if the
notes master does not have a body placeholder , or if the notes
p... | for placeholder in self . placeholders :
if placeholder . placeholder_format . type == PP_PLACEHOLDER . BODY :
return placeholder
return None |
def _Rphideriv ( self , R , phi = 0. , t = 0. ) :
"""NAME :
_ Rphideriv
PURPOSE :
evaluate the mixed radial - azimuthal derivative
INPUT :
phi
OUTPUT :
d2phi / dRdphi
HISTORY :
2016-06-02 - Written - Bovy ( UofT )""" | return self . _Pot . Rphideriv ( R , 0. , phi = phi , t = t , use_physical = False ) |
def translate_ref_to_url ( self , ref , in_comment = None ) :
"""Translates an @ see or @ link reference to a URL . If the ref is of the
form # methodName , it looks for a method of that name on the class
` in _ comment ` or parent class of method ` in _ comment ` . In this case , it
returns a local hash URL ... | if ref . startswith ( '#' ) :
method_name = ref [ 1 : ]
if isinstance ( in_comment , FunctionDoc ) and in_comment . member :
search_in = self . all_classes [ in_comment . member ]
elif isinstance ( in_comment , ClassDoc ) :
search_in = in_comment
else :
search_in = None
try :... |
def parseLayoutFeatures ( font ) :
"""Parse OpenType layout features in the UFO and return a
feaLib . ast . FeatureFile instance .""" | featxt = tounicode ( font . features . text or "" , "utf-8" )
if not featxt :
return ast . FeatureFile ( )
buf = UnicodeIO ( featxt )
# the path is used by the lexer to resolve ' include ' statements
# and print filename in error messages . For the UFO spec , this
# should be the path of the UFO , not the inner fea... |
def get_importer ( cls , name ) :
"""Get an importer for the given registered type .
: param cls : class to import
: type cls : : class : ` type `
: param name : registered name of importer
: type name : : class : ` str `
: return : an importer instance of the given type
: rtype : : class : ` Importer `... | if name not in importer_index :
raise TypeError ( ( "importer type '%s' is not registered: " % name ) + ( "registered types: %r" % sorted ( importer_index . keys ( ) ) ) )
for base_class in importer_index [ name ] :
if issubclass ( cls , base_class ) :
return importer_index [ name ] [ base_class ] ( cls... |
def cdf_info ( self ) :
"""Returns a dictionary that shows the basic CDF information .
This information includes
| [ ' CDF ' ] | the name of the CDF |
| [ ' Version ' ] | the version of the CDF |
| [ ' Encoding ' ] | the endianness of the CDF |
| [ ' Majority ' ] | the row / column majority |
| [ ' zVar... | mycdf_info = { }
mycdf_info [ 'CDF' ] = self . file
mycdf_info [ 'Version' ] = self . _version
mycdf_info [ 'Encoding' ] = self . _encoding
mycdf_info [ 'Majority' ] = self . _majority
mycdf_info [ 'rVariables' ] , mycdf_info [ 'zVariables' ] = self . _get_varnames ( )
mycdf_info [ 'Attributes' ] = self . _get_attnames... |
def Difference ( left : vertex_constructor_param_types , right : vertex_constructor_param_types , label : Optional [ str ] = None ) -> Vertex :
"""Subtracts one vertex from another
: param left : the vertex that will be subtracted from
: param right : the vertex to subtract""" | return Double ( context . jvm_view ( ) . DifferenceVertex , label , cast_to_double_vertex ( left ) , cast_to_double_vertex ( right ) ) |
def timeout ( self , duration = 3600 ) :
"""Timeout the uploader of this file""" | self . room . check_owner ( )
self . conn . make_call ( "timeoutFile" , self . fid , duration ) |
def to_contracts ( instruments , prices , multipliers , desired_ccy = None , instr_fx = None , fx_rates = None , rounder = None ) :
"""Convert notional amount of tradeable instruments to number of instrument
contracts , rounding to nearest integer number of contracts .
Parameters
instruments : pandas . Series... | contracts = _instr_conv ( instruments , prices , multipliers , False , desired_ccy , instr_fx , fx_rates )
if rounder is None :
rounder = pd . Series . round
contracts = rounder ( contracts )
contracts = contracts . astype ( int )
return contracts |
def get_traindata ( self ) -> np . ndarray :
"""Pulls all available data and concatenates for model training
: return : 2d array of points""" | traindata = None
for key , value in self . data . items ( ) :
if key not in [ '__header__' , '__version__' , '__globals__' ] :
if traindata is None :
traindata = value [ np . where ( value [ : , 4 ] != 0 ) ]
else :
traindata = np . concatenate ( ( traindata , value [ np . whe... |
def iteration ( self , node_status = True ) :
"""Execute a single model iteration
: return : Iteration _ id , Incremental node status ( dictionary node - > status )""" | self . clean_initial_status ( self . available_statuses . values ( ) )
actual_status = { node : nstatus for node , nstatus in future . utils . iteritems ( self . status ) }
if self . actual_iteration == 0 :
self . actual_iteration += 1
delta , node_count , status_delta = self . status_delta ( actual_status )
... |
def _get_offset ( text , visible_width , unicode_aware = True ) :
"""Find the character offset within some text for a given visible offset ( taking into account the
fact that some character glyphs are double width ) .
: param text : The text to analyze
: param visible _ width : The required location within th... | result = 0
width = 0
if unicode_aware :
for c in text :
if visible_width - width <= 0 :
break
result += 1
width += wcwidth ( c )
if visible_width - width < 0 :
result -= 1
else :
result = min ( len ( text ) , visible_width )
return result |
def get_form_kwargs ( self ) :
"""Returns the keyword arguments to provide tp the associated form .""" | kwargs = super ( ModelFormMixin , self ) . get_form_kwargs ( )
kwargs [ 'poll' ] = self . object
return kwargs |
def run ( X_train , X_test , y_train , y_test , PARAMS ) :
'''Train model and predict result''' | model . fit ( X_train , y_train )
predict_y = model . predict ( X_test )
score = r2_score ( y_test , predict_y )
LOG . debug ( 'r2 score: %s' % score )
nni . report_final_result ( score ) |
def export_to_dict ( session , recursive , back_references , include_defaults ) :
"""Exports databases and druid clusters to a dictionary""" | logging . info ( 'Starting export' )
dbs = session . query ( Database )
databases = [ database . export_to_dict ( recursive = recursive , include_parent_ref = back_references , include_defaults = include_defaults ) for database in dbs ]
logging . info ( 'Exported %d %s' , len ( databases ) , DATABASES_KEY )
cls = sessi... |
def save ( self , path , compress = True ) :
"""Writes the ` ` . proteins ` ` and ` ` . peptides ` ` entries to the hard disk
as a ` ` proteindb ` ` file .
. . note : :
If ` ` . save ( ) ` ` is called and no ` ` proteindb ` ` file is present in the
specified path a new files is generated , otherwise the old... | with aux . PartiallySafeReplace ( ) as msr :
filename = self . info [ 'name' ] + '.proteindb'
filepath = aux . joinpath ( path , filename )
with msr . open ( filepath , mode = 'w+b' ) as openfile :
self . _writeContainer ( openfile , compress = compress ) |
def _set_camera_properties ( self , msg ) :
"""Set the camera intrinsics from an info msg .""" | focal_x = msg . K [ 0 ]
focal_y = msg . K [ 4 ]
center_x = msg . K [ 2 ]
center_y = msg . K [ 5 ]
im_height = msg . height
im_width = msg . width
self . _camera_intr = CameraIntrinsics ( self . _frame , focal_x , focal_y , center_x , center_y , height = im_height , width = im_width ) |
def _do_cb ( self , cb , error_cb , * args , ** kw ) :
"""Called internally by callback ( ) . Does cb and error _ cb selection .""" | try :
res = self . work ( * args , ** kw )
except Exception as e :
if error_cb is None :
show_err ( )
elif error_cb :
error_cb ( e )
else : # Success , let ' s call away !
cb ( res ) |
def hex2web ( hex ) :
"""Converts HEX representation to WEB
: param rgb : 3 hex char or 6 hex char string representation
: rtype : web string representation ( human readable if possible )
WEB representation uses X11 rgb . txt to define conversion
between RGB and english color names .
Usage
> > > from co... | dec_rgb = tuple ( int ( v * 255 ) for v in hex2rgb ( hex ) )
if dec_rgb in RGB_TO_COLOR_NAMES : # # take the first one
color_name = RGB_TO_COLOR_NAMES [ dec_rgb ] [ 0 ]
# # Enforce full lowercase for single worded color name .
return color_name if len ( re . sub ( r"[^A-Z]" , "" , color_name ) ) > 1 else co... |
def communicate ( self ) :
"""Retrieve information .""" | self . _communicate_first = True
self . _process . waitForFinished ( )
if self . _partial_stdout is None :
raw_stdout = self . _process . readAllStandardOutput ( )
stdout = handle_qbytearray ( raw_stdout , _CondaAPI . UTF8 )
else :
stdout = self . _partial_stdout
raw_stderr = self . _process . readAllStanda... |
def regress ( self , method = 'lstsq' ) :
"""regress performs linear least squares regression of the designmatrix on the data .
: param method : method , or backend to be used for the regression analysis .
: type method : string , one of [ ' lstsq ' , ' sm _ ols ' ]
: returns : instance variables ' betas ' ( ... | if method is 'lstsq' :
self . betas , residuals_sum , rank , s = LA . lstsq ( self . design_matrix . T , self . resampled_signal . T )
self . residuals = self . resampled_signal - self . predict_from_design_matrix ( self . design_matrix )
elif method is 'sm_ols' :
import statsmodels . api as sm
assert s... |
def encode ( self , encoding = 'utf-8' , errors = 'strict' ) :
"""Returns bytes
Encode S using the codec registered for encoding . Default encoding
is ' utf - 8 ' . errors may be given to set a different error
handling scheme . Default is ' strict ' meaning that encoding errors raise
a UnicodeEncodeError . ... | from future . types . newbytes import newbytes
# Py2 unicode . encode ( ) takes encoding and errors as optional parameter ,
# not keyword arguments as in Python 3 str .
# For the surrogateescape error handling mechanism , the
# codecs . register _ error ( ) function seems to be inadequate for an
# implementation of it ... |
async def mailed_confirm ( self , ** params ) :
"""Sends mail to user after offer receiveing
Accepts :
- cid
- buyer address
- price
- offer _ type
- point
- coinid""" | if not params :
return { "error" : 400 , "reason" : "Missed required fields" }
# Check if required fields exists
cid = params . get ( "cid" )
buyer_address = params . get ( "buyer_address" )
price = params . get ( "price" )
offer_type = params . get ( "offer_type" )
coinid = params . get ( "coinid" ) . upper ( )
tr... |
def get_species ( taxdump_file , select_divisions = None , exclude_divisions = None , nrows = None ) :
"""Get a dataframe with species information .""" | if select_divisions and exclude_divisions :
raise ValueError ( 'Cannot specify "select_divisions" and ' '"exclude_divisions" at the same time.' )
select_taxon_ids = _get_species_taxon_ids ( taxdump_file , select_divisions = select_divisions , exclude_divisions = exclude_divisions )
select_taxon_ids = set ( select_t... |
def _timer ( self , state_transition_event = None ) :
"""Timer loop used to keep track of the time while roasting or
cooling . If the time remaining reaches zero , the roaster will call the
supplied state transistion function or the roaster will be set to
the idle state .""" | while not self . _teardown . value :
state = self . get_roaster_state ( )
if ( state == 'roasting' or state == 'cooling' ) :
time . sleep ( 1 )
self . total_time += 1
if ( self . time_remaining > 0 ) :
self . time_remaining -= 1
else :
if ( state_transitio... |
def find_unique ( self , product_type , short_name , include_hidden = False ) :
"""Find the unique provider of a given product by its short name .
This function will ensure that the product is only provided by exactly
one tile ( either this tile or one of its dependencies and raise a
BuildError if not .
Arg... | prods = self . find_all ( product_type , short_name , include_hidden )
if len ( prods ) == 0 :
raise BuildError ( "Could not find product by name in find_unique" , name = short_name , type = product_type )
if len ( prods ) > 1 :
raise BuildError ( "Multiple providers of the same product in find_unique" , name =... |
def repr_parameter ( param : inspect . Parameter ) -> str :
"""Provides a ` ` repr ` ` - style representation of a function parameter .""" | return ( "Parameter(name={name}, annotation={annotation}, kind={kind}, " "default={default}" . format ( name = param . name , annotation = param . annotation , kind = param . kind , default = param . default ) ) |
def format_ft_def ( func , full_name : str = None ) -> str :
"Format and link ` func ` definition to show in documentation" | sig = inspect . signature ( func )
name = f'<code>{full_name or func.__name__}</code>'
fmt_params = [ format_param ( param ) for name , param in sig . parameters . items ( ) if name not in ( 'self' , 'cls' ) ]
arg_str = f"({', '.join(fmt_params)})"
if sig . return_annotation and ( sig . return_annotation != sig . empty... |
def alwaysCalledWithExactly ( self , * args , ** kwargs ) : # pylint : disable = invalid - name
"""Determining whether args / kwargs are the ONLY fully matched args / kwargs called previously
Eg .
f ( 1 , 2 , 3)
spy . alwaysCalledWith ( 1 , 2 , 3 ) will return True , because they are fully matched
f ( 1 , 2... | self . __remove_args_first_item ( )
if args and kwargs :
return True if ( uch . tuple_in_list_always ( self . args , args ) and uch . dict_in_list_always ( self . kwargs , kwargs ) ) else False
elif args :
return True if uch . tuple_in_list_always ( self . args , args ) else False
elif kwargs :
return True ... |
def set_data_path ( self , pth ) :
"""Set the location of the measures data directory .
: param pth : The absolute path to the measures data directory .""" | if os . path . exists ( pth ) :
if not os . path . exists ( os . path . join ( pth , 'data' , 'geodetic' ) ) :
raise IOError ( "The given path doesn't contain a 'data' " "subdirectory" )
os . environ [ "AIPSPATH" ] = "%s dummy dummy" % pth |
def get_meter ( id = None , name = None , maxS = 2 , maxW = 2 , splitheavies = 0 , constraints = DEFAULT_CONSTRAINTS , return_dict = False ) :
"""{ ' constraints ' : [ ' footmin - w - resolution / 1 ' ,
' footmin - f - resolution / 1 ' ,
' strength . w = > - p / 1 ' ,
' headedness ! = rising / 1 ' ,
' numbe... | if 'Meter.Meter' in str ( id . __class__ ) :
return id
if not id :
id = 'Meter_%s' % now ( )
if not name :
name = id + '[' + ' ' . join ( constraints ) + ']'
config = locals ( )
import prosodic
if id in prosodic . config [ 'meters' ] :
return prosodic . config [ 'meters' ] [ id ]
if return_dict :
re... |
def remove_handler ( self , handler ) :
"""Detach active handler from the session
` handler `
Handler to remove""" | super ( Session , self ) . remove_handler ( handler )
self . promote ( )
self . stop_heartbeat ( ) |
def empty ( val ) :
"""Checks if value is empty .
All unknown data types considered as empty values .
@ return : bool""" | if val == None :
return True
if isinstance ( val , str ) and len ( val ) > 0 :
return False
return True |
def check_unique ( self ) :
"""Check the user ' s email is unique""" | emails = yield self . view . values ( key = self . email )
user_id = getattr ( self , 'id' , None )
users = { x for x in emails if x != user_id and x }
if users :
raise exceptions . ValidationError ( "User with email '{}' already exists" . format ( self . email ) ) |
def scale_and_crop_with_subject_location ( im , size , subject_location = False , zoom = None , crop = False , upscale = False , ** kwargs ) :
"""Like ` ` easy _ thumbnails . processors . scale _ and _ crop ` ` , but will use the
coordinates in ` ` subject _ location ` ` to make sure that that part of the
image... | subject_location = normalize_subject_location ( subject_location )
if not ( subject_location and crop ) : # use the normal scale _ and _ crop
return processors . scale_and_crop ( im , size , zoom = zoom , crop = crop , upscale = upscale , ** kwargs )
# for here on we have a subject _ location and cropping is on
# -... |
def mask_loss ( input_tensor , binary_tensor ) :
"""Mask a loss by using a tensor filled with 0 or 1.
: param input _ tensor : A float tensor of shape [ batch _ size , . . . ] representing the loss / cross _ entropy
: param binary _ tensor : A float tensor of shape [ batch _ size , . . . ] representing the mask... | with tf . variable_scope ( "mask_loss" ) :
mask = tf . cast ( tf . cast ( binary_tensor , tf . bool ) , tf . float32 )
return input_tensor * mask |
def process ( self , pair ) : # TODO : check docstring
"""Processes a pair of nodes into the current solution
MUST CREATE A NEW INSTANCE , NOT CHANGE ANY INSTANCE ATTRIBUTES
Returns a new instance ( deep copy ) of self object
Args
pair : type
description
Returns
type
Description ( Copy of self ? )""... | a , b = pair
new_solution = self . clone ( )
i , j = new_solution . get_pair ( ( a , b ) )
route_i = i . route_allocation ( )
route_j = j . route_allocation ( )
inserted = False
if ( ( route_i is not None and route_j is not None ) and ( route_i != route_j ) ) :
if route_i . _nodes . index ( i ) == 0 and route_j . _... |
def fitPlaneSVD ( XYZ ) :
"""Fit a plane to input point data using SVD""" | [ rows , cols ] = XYZ . shape
# Set up constraint equations of the form AB = 0,
# where B is a column vector of the plane coefficients
# in the form b ( 1 ) * X + b ( 2 ) * Y + b ( 3 ) * Z + b ( 4 ) = 0.
p = ( np . ones ( ( rows , 1 ) ) )
AB = np . hstack ( [ XYZ , p ] )
[ u , d , v ] = np . linalg . svd ( AB , 0 )
# S... |
def filter_visited ( curr_dir , subdirs , already_visited , follow_dirlinks , on_error ) :
"""Filter subdirs that have already been visited .
This is used to avoid loops in the search performed by os . walk ( ) in
index _ files _ by _ size .
curr _ dir is the path of the current directory , as returned by os ... | filtered = [ ]
to_visit = set ( )
_already_visited = already_visited . copy ( )
try : # mark the current directory as visited , so we catch symlinks to it
# immediately instead of after one iteration of the directory loop
file_info = os . stat ( curr_dir ) if follow_dirlinks else os . lstat ( curr_dir )
_alread... |
def dependency_check ( self , task_cls , skip_unresolved = False ) :
"""Check dependency of task for irresolvable conflicts ( like task to task mutual dependency )
: param task _ cls : task to check
: param skip _ unresolved : flag controls this method behaviour for tasks that could not be found . When False , ... | def check ( check_task_cls , global_dependencies ) :
if check_task_cls . __registry_tag__ in global_dependencies :
raise RuntimeError ( 'Recursion dependencies for %s' % task_cls . __registry_tag__ )
dependencies = global_dependencies . copy ( )
dependencies . append ( check_task_cls . __registry_ta... |
def capitalize ( string ) :
"""Capitalize a sentence .
Parameters
string : ` str `
String to capitalize .
Returns
` str `
Capitalized string .
Examples
> > > capitalize ( ' worD WORD WoRd ' )
' Word word word '""" | if not string :
return string
if len ( string ) == 1 :
return string . upper ( )
return string [ 0 ] . upper ( ) + string [ 1 : ] . lower ( ) |
def append_rows ( self , rows , between , refresh_presision ) :
"""Transform the rows of data to Measurements .
Keyword arguments :
rows - - an array of arrays [ datetime , integral _ measurement ]
between - - time between integral _ measurements in seconds
refresh _ presision - - time between sensor values... | for r in rows :
Measurement . register_or_check ( finish = r [ 0 ] , mean = r [ 1 ] / between , between = between , refresh_presision = refresh_presision , configuration = self ) |
def subsample_input ( infiles ) :
"""Returns a random subsample of the input files .
- infiles : a list of input files for analysis""" | logger . info ( "--subsample: %s" , args . subsample )
try :
samplesize = float ( args . subsample )
except TypeError : # Not a number
logger . error ( "--subsample must be int or float, got %s (exiting)" , type ( args . subsample ) )
sys . exit ( 1 )
if samplesize <= 0 : # Not a positive value
logger .... |
def install_sql_hook ( ) : # type : ( ) - > None
"""If installed this causes Django ' s queries to be captured .""" | try :
from django . db . backends . utils import CursorWrapper
# type : ignore
except ImportError :
from django . db . backends . util import CursorWrapper
# type : ignore
try :
real_execute = CursorWrapper . execute
real_executemany = CursorWrapper . executemany
except AttributeError : # This won '... |
def get_default ( self ) :
"""Return the default value to use when validating data if no input
is provided for this field .
If a default has not been set for this field then this will simply
return ` empty ` , indicating that no value should be set in the
validated data for this field .""" | if self . default is empty :
raise SkipField ( )
if callable ( self . default ) :
if hasattr ( self . default , 'set_context' ) :
self . default . set_context ( self )
return self . default ( )
return self . default |
def remove_page ( self , route ) :
"""Remove a proxied page from the Web UI .
Parameters
route : str
The route for the proxied page . Must be a valid path * segment * in a
url ( e . g . ` ` foo ` ` in ` ` / foo / bar / baz ` ` ) . Routes must be unique
across the application .""" | req = proto . RemoveProxyRequest ( route = route )
self . _client . _call ( 'RemoveProxy' , req ) |
def ChoiceHumanReadable ( choices , choice ) :
"""Return the human readable representation for a list of choices .
@ see https : / / docs . djangoproject . com / en / dev / ref / models / fields / # choices""" | if choice == None :
raise NoChoiceError ( )
for _choice in choices :
if _choice [ 0 ] == choice :
return _choice [ 1 ]
raise NoChoiceMatchError ( "The choice '%s' does not exist in '%s'" % ( choice , ", " . join ( [ choice [ 0 ] for choice in choices ] ) ) ) |
def write_csv ( self , file : str , table : str , libref : str = "" , nosub : bool = False , dsopts : dict = None , opts : dict = None ) -> 'The LOG showing the results of the step' :
"""This method will export a SAS Data Set to a file in CSV format .
file - the OS filesystem path of the file to be created ( expo... | dsopts = dsopts if dsopts is not None else { }
opts = opts if opts is not None else { }
code = "options nosource;\n"
code += "filename x \"" + file + "\";\n"
code += "proc export data=" + libref + "." + table + self . _sb . _dsopts ( dsopts ) + " outfile=x dbms=csv replace; "
code += self . _sb . _expopts ( opts ) + " ... |
def get_version ( module ) :
"""Attempts to read a version attribute from the given module that
could be specified via several different names and formats .""" | version_names = [ "__version__" , "get_version" , "version" ]
version_names . extend ( [ name . upper ( ) for name in version_names ] )
for name in version_names :
try :
version = getattr ( module , name )
except AttributeError :
continue
if callable ( version ) :
version = version (... |
def updateStaticEC2Instances ( ) :
"""Generates a new python file of fetchable EC2 Instances by region with current prices and specs .
Takes a few ( ~ 3 + ) minutes to run ( you ' ll need decent internet ) .
: return : Nothing . Writes a new ' generatedEC2Lists . py ' file .""" | logger . info ( "Updating Toil's EC2 lists to the most current version from AWS's bulk API. " "This may take a while, depending on your internet connection." )
dirname = os . path . dirname ( __file__ )
# the file Toil uses to get info about EC2 instance types
origFile = os . path . join ( dirname , 'generatedEC2Lists... |
def get_indels ( sbjct_seq , qry_seq , start_pos ) :
"""This function uses regex to find inserts and deletions in sequences
given as arguments . A list of these indels are returned . The list
includes , type of mutations ( ins / del ) , subject codon no of found
mutation , subject sequence position , insert /... | seqs = [ sbjct_seq , qry_seq ]
indels = [ ]
gap_obj = re . compile ( r"-+" )
for i in range ( len ( seqs ) ) :
for match in gap_obj . finditer ( seqs [ i ] ) :
pos = int ( match . start ( ) )
gap = match . group ( )
# Find position of the mutation corresponding to the subject sequence
... |
def dtype_for ( t ) :
"""return my dtype mapping , whether number or name""" | if t in dtype_dict :
return dtype_dict [ t ]
return np . typeDict . get ( t , t ) |
async def get_access_token ( self , code , loop = None , redirect_uri = None , ** payload ) :
"""Get an access _ token from OAuth provider .
: returns : ( access _ token , provider _ data )""" | # Possibility to provide REQUEST DATA to the method
payload . setdefault ( 'grant_type' , 'authorization_code' )
payload . update ( { 'client_id' : self . client_id , 'client_secret' : self . client_secret } )
if not isinstance ( code , str ) and self . shared_key in code :
code = code [ self . shared_key ]
payload... |
def get_color ( self ) :
"""Return the array of rgba colors ( same order as lStruct )""" | col = np . full ( ( self . _dStruct [ 'nObj' ] , 4 ) , np . nan )
ii = 0
for k in self . _dStruct [ 'lorder' ] :
k0 , k1 = k . split ( '_' )
col [ ii , : ] = self . _dStruct [ 'dObj' ] [ k0 ] [ k1 ] . get_color ( )
ii += 1
return col |
def subscribe ( self , objectID , varIDs = ( tc . VAR_ROAD_ID , tc . VAR_LANEPOSITION ) , begin = 0 , end = 2 ** 31 - 1 ) :
"""subscribe ( string , list ( integer ) , int , int ) - > None
Subscribe to one or more object values for the given interval .""" | Domain . subscribe ( self , objectID , varIDs , begin , end ) |
def subdivide ( self ) :
r"""Split the curve : math : ` B ( s ) ` into a left and right half .
Takes the interval : math : ` \ left [ 0 , 1 \ right ] ` and splits the curve into
: math : ` B _ 1 = B \ left ( \ left [ 0 , \ frac { 1 } { 2 } \ right ] \ right ) ` and
: math : ` B _ 2 = B \ left ( \ left [ \ fra... | left_nodes , right_nodes = _curve_helpers . subdivide_nodes ( self . _nodes )
left = Curve ( left_nodes , self . _degree , _copy = False )
right = Curve ( right_nodes , self . _degree , _copy = False )
return left , right |
def encode_data ( self ) :
"""Encode the data back into a dict .""" | output_data = { }
output_data [ "groupTypeList" ] = encode_array ( self . group_type_list , 4 , 0 )
output_data [ "xCoordList" ] = encode_array ( self . x_coord_list , 10 , 1000 )
output_data [ "yCoordList" ] = encode_array ( self . y_coord_list , 10 , 1000 )
output_data [ "zCoordList" ] = encode_array ( self . z_coord... |
def _sql_expand_update ( self , spec , key_prefix = '' , col_prefix = '' ) :
"""Expand a dict so it fits in a INSERT clause""" | sql = ', ' . join ( col_prefix + key + ' = %(' + key_prefix + key + ')s' for key in spec )
params = { }
for key in spec :
params [ key_prefix + key ] = spec [ key ]
return sql , params |
def validate_tree ( self ) :
"""Validate all nodes in this tree recusively .
Args : None
Returns : boolean indicating if tree is valid""" | self . validate ( )
for child in self . children :
assert child . validate_tree ( )
return True |
def create_dialog ( self ) :
"""Create the dialog .""" | box0 = QGroupBox ( 'Info' )
self . name = FormStr ( )
self . name . setText ( 'sw' )
self . idx_group . activated . connect ( self . update_channels )
form = QFormLayout ( box0 )
form . addRow ( 'Event name' , self . name )
form . addRow ( 'Channel group' , self . idx_group )
form . addRow ( 'Channel(s)' , self . idx_c... |
def set_iprouting ( self , value = None , default = False , disable = False ) :
"""Configures the state of global ip routing
EosVersion :
4.13.7M
Args :
value ( bool ) : True if ip routing should be enabled or False if
ip routing should be disabled
default ( bool ) : Controls the use of the default keyw... | if value is False :
disable = True
cmd = self . command_builder ( 'ip routing' , value = value , default = default , disable = disable )
return self . configure ( cmd ) |
def _set_static_route_nh ( self , v , load = False ) :
"""Setter method for static _ route _ nh , mapped from YANG variable / rbridge _ id / vrf / address _ family / ipv6 / unicast / ipv6 / route / static _ route _ nh ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ s... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "static_route_dest static_route_next_hop" , static_route_nh . static_route_nh , yang_name = "static-route-nh" , rest_name = "static-route-nh" , parent = self , is_container = 'list' , user_ordered = False , pat... |
def update ( self , sha , force = False ) :
"""Update this reference .
: param str sha : ( required ) , sha of the reference
: param bool force : ( optional ) , force the update or not
: returns : bool""" | data = { 'sha' : sha , 'force' : force }
json = self . _json ( self . _patch ( self . _api , data = dumps ( data ) ) , 200 )
if json :
self . _update_ ( json )
return True
return False |
def get_unused_sauce_port ( ) :
"""This returns an unused port among those that Sauce Connect
forwards . Note that this function does * * not * * lock the port !
: returns : A presumably free port that Sauce Connect forwards .
: rtype : int""" | # We exclude 80 , 443 , 888 from the list since they are reserved .
sc_ports = [ 8000 , 8001 , 8003 , 8031 , 8080 , 8081 , 8765 , 8777 , 8888 , 9000 , 9001 , 9080 , 9090 , 9876 , 9877 , 9999 , 49221 , 55001 ]
for candidate in sc_ports :
candidate_str = str ( candidate )
# lsof will report a hit whenever * eithe... |
def run_spy ( group , port , verbose ) :
"""Runs the multicast spy
: param group : Multicast group
: param port : Multicast port
: param verbose : If True , prints more details""" | # Create the socket
socket , group = multicast . create_multicast_socket ( group , port )
print ( "Socket created:" , group , "port:" , port )
# Set the socket as non - blocking
socket . setblocking ( 0 )
# Prepare stats storage
stats = { "total_bytes" : 0 , "total_count" : 0 , "sender_bytes" : { } , "sender_count" : {... |
def hpd_credible_interval ( mu_in , post , alpha = 0.9 , tolerance = 1e-3 ) :
'''Returns the minimum and maximum rate values of the HPD
( Highest Posterior Density ) credible interval for a posterior
post defined at the sample values mu _ in . Samples need not be
uniformly spaced and posterior need not be nor... | if alpha == 1 :
nonzero_samples = mu_in [ post > 0 ]
mu_low = numpy . min ( nonzero_samples )
mu_high = numpy . max ( nonzero_samples )
elif 0 < alpha < 1 : # determine the highest PDF for which the region with
# higher density has sufficient coverage
pthresh = hpd_threshold ( mu_in , post , alpha , tol... |
def random_targets ( gt , nb_classes ) :
"""Take in an array of correct labels and randomly select a different label
for each label in the array . This is typically used to randomly select a
target class in targeted adversarial examples attacks ( i . e . , when the
search algorithm takes in both a source clas... | # If the ground truth labels are encoded as one - hot , convert to labels .
if len ( gt . shape ) == 2 :
gt = np . argmax ( gt , axis = 1 )
# This vector will hold the randomly selected labels .
result = np . zeros ( gt . shape , dtype = np . int32 )
for class_ind in xrange ( nb_classes ) : # Compute all indices in... |
async def main ( ) :
"""Main code""" | # Create Client from endpoint string in Duniter format
client = Client ( BMAS_ENDPOINT )
# Get the node summary infos to test the connection
response = await client ( bma . node . summary )
print ( response )
# capture current block to get version and currency and blockstamp
current_block = await client ( bma . blockch... |
def create_call ( self , raw_request , ** kwargs ) :
"""create a call object that has endpoints understandable request and response
instances""" | req = self . create_request ( raw_request , ** kwargs )
res = self . create_response ( ** kwargs )
rou = self . create_router ( ** kwargs )
c = self . call_class ( req , res , rou )
return c |
def get ( self , collection , doc_id , ** kwargs ) :
""": param str collection : The name of the collection for the request
: param str doc _ id : ID of the document to be retrieved .
Retrieve document from Solr based on the ID . : :
> > > solr . get ( ' SolrClient _ unittest ' , ' changeme ' )""" | resp , con_inf = self . transport . send_request ( method = 'GET' , endpoint = 'get' , collection = collection , params = { 'id' : doc_id } , ** kwargs )
if 'doc' in resp and resp [ 'doc' ] :
return resp [ 'doc' ]
raise NotFoundError |
def validate_object_id ( object_id ) :
"""It ' s easy to make a mistake entering these , validate the format""" | result = re . match ( OBJECT_ID_RE , str ( object_id ) )
if not result :
print ( "'%s' appears not to be a valid 990 object_id" % object_id )
raise RuntimeError ( OBJECT_ID_MSG )
return object_id |
def all_time ( self ) :
"""Access the all _ time
: returns : twilio . rest . api . v2010 . account . usage . record . all _ time . AllTimeList
: rtype : twilio . rest . api . v2010 . account . usage . record . all _ time . AllTimeList""" | if self . _all_time is None :
self . _all_time = AllTimeList ( self . _version , account_sid = self . _solution [ 'account_sid' ] , )
return self . _all_time |
def set_temp_url_key ( self , key = None ) :
"""Sets the key for the Temporary URL for the account . It should be a key
that is secret to the owner .
If no key is provided , a UUID value will be generated and used . It can
later be obtained by calling get _ temp _ url _ key ( ) .""" | if key is None :
key = uuid . uuid4 ( ) . hex
meta = { "Temp-Url-Key" : key }
self . set_account_metadata ( meta )
self . _cached_temp_url_key = key |
def build ( path = None , repository = None , tag = None , cache = True , rm = True , api_response = False , fileobj = None , dockerfile = None , buildargs = None , network_mode = None , labels = None , cache_from = None , target = None ) :
'''. . versionchanged : : 2018.3.0
If the built image should be tagged , ... | _prep_pull ( )
if repository or tag :
if not repository and tag : # Have to have both or neither
raise SaltInvocationError ( 'If tagging, both a repository and tag are required' )
else :
if not isinstance ( repository , six . string_types ) :
repository = six . text_type ( repository... |
def _value_loss ( self , observ , reward , length ) :
"""Compute the loss function for the value baseline .
The value loss is the difference between empirical and approximated returns
over the collected episodes . Returns the loss tensor and a summary strin .
Args :
observ : Sequences of observations .
re... | with tf . name_scope ( 'value_loss' ) :
value = self . _network ( observ , length ) . value
return_ = utility . discounted_return ( reward , length , self . _config . discount )
advantage = return_ - value
value_loss = 0.5 * self . _mask ( advantage ** 2 , length )
summary = tf . summary . merge ( [... |
def report ( self , meter = None , include_bounded = False , reverse = True ) :
"""Print all parses and their violations in a structured format .""" | ReportStr = ''
if not meter :
from Meter import Meter
meter = Meter . genDefault ( )
if ( hasattr ( self , 'allParses' ) ) :
self . om ( unicode ( self ) )
allparses = self . allParses ( meter = meter , include_bounded = include_bounded )
numallparses = len ( allparses )
# allparses = reversed (... |
def _types_match ( type1 , type2 ) :
"""Returns False only if it can show that no value of type1
can possibly match type2.
Supports only a limited selection of types .""" | if isinstance ( type1 , six . string_types ) and isinstance ( type2 , six . string_types ) :
type1 = type1 . rstrip ( '?' )
type2 = type2 . rstrip ( '?' )
if type1 != type2 :
return False
return True |
def slowlog_get ( self , length = None ) :
"""Returns the Redis slow queries log .""" | if length is not None :
if not isinstance ( length , int ) :
raise TypeError ( "length must be int or None" )
return self . execute ( b'SLOWLOG' , b'GET' , length )
else :
return self . execute ( b'SLOWLOG' , b'GET' ) |
def _fetch_contribution_info ( self ) :
"""Build the list of information entries for contributions of the event""" | self . contributions = { }
query = ( Contribution . query . with_parent ( self . event ) . options ( joinedload ( 'legacy_mapping' ) , joinedload ( 'timetable_entry' ) . lazyload ( '*' ) ) )
for contribution in query :
if not contribution . start_dt :
continue
cid = ( contribution . legacy_mapping . leg... |
def estimate ( self , upgrades ) :
"""Estimate the time needed to apply upgrades .
If an upgrades does not specify and estimate it is assumed to be
in the order of 1 second .
: param upgrades : List of upgrades sorted in topological order .""" | val = 0
for u in upgrades :
val += u . estimate ( )
return val |
def gunzip ( gzipfile , template = None , runas = None , options = None ) :
'''Uses the gunzip command to unpack gzip files
template : None
Can be set to ' jinja ' or another supported template engine to render
the command arguments before execution :
. . code - block : : bash
salt ' * ' archive . gunzip ... | cmd = [ 'gunzip' ]
if options :
cmd . append ( options )
cmd . append ( '{0}' . format ( gzipfile ) )
return __salt__ [ 'cmd.run' ] ( cmd , template = template , runas = runas , python_shell = False ) . splitlines ( ) |
def ensure_sink ( self ) :
"""Ensure the log sink and its pub sub topic exist .""" | topic_info = self . pubsub . ensure_topic ( )
scope , sink_path , sink_info = self . get_sink ( topic_info )
client = self . session . client ( 'logging' , 'v2' , '%s.sinks' % scope )
try :
sink = client . execute_command ( 'get' , { 'sinkName' : sink_path } )
except HttpError as e :
if e . resp . status != 404... |
def _clear_context ( ) :
'''Clear any lxc variables set in _ _ context _ _''' | for var in [ x for x in __context__ if x . startswith ( 'lxc.' ) ] :
log . trace ( 'Clearing __context__[\'%s\']' , var )
__context__ . pop ( var , None ) |
def run_process ( self , analysis , action_name , message = '__nomessagetoken__' ) :
"""Executes an process in the analysis with the given message .
It also handles the start and stop signals in case a process _ id
is given .""" | if action_name == 'connect' :
analysis . on_connect ( self . executable , self . zmq_publish )
while not analysis . zmq_handshake :
yield tornado . gen . sleep ( 0.1 )
log . debug ( 'sending action {}' . format ( action_name ) )
analysis . zmq_send ( { 'signal' : action_name , 'load' : message } )
if action_nam... |
def client ( self , container ) :
"""Return a client instance that is bound to that container .
: param container : container id
: return : Client object bound to the specified container id
Return a ContainerResponse from container . create""" | self . _client_chk . check ( container )
return ContainerClient ( self . _client , int ( container ) ) |
def is_instance_running ( self , instance_id ) :
"""Check whether the instance is up and running .
: param str instance _ id : instance identifier
: reutrn : True if instance is running , False otherwise""" | items = self . list_instances ( filter = ( 'name eq "%s"' % instance_id ) )
for item in items :
if item [ 'status' ] == 'RUNNING' :
return True
return False |
def _getPOS ( self , token , onlyFirst = True ) :
'''Returns POS of the current token .''' | if onlyFirst :
return token [ ANALYSIS ] [ 0 ] [ POSTAG ]
else :
return [ a [ POSTAG ] for a in token [ ANALYSIS ] ] |
def random ( self , size , n_and , max_in , n = 1 ) :
"""Generates ` n ` random logical networks with given size range , number of AND gates and maximum
input signals for AND gates . Logical networks are saved in the attribute : attr : ` networks ` .
Parameters
n : int
Number of random logical networks to b... | args = [ '-c minsize=%s' % size [ 0 ] , '-c maxsize=%s' % size [ 1 ] , '-c minnand=%s' % n_and [ 0 ] , '-c maxnand=%s' % n_and [ 1 ] , '-c maxin=%s' % max_in ]
encodings = [ 'guess' , 'random' ]
self . networks . reset ( )
clingo = self . __get_clingo__ ( args , encodings )
clingo . conf . solve . models = str ( n )
cl... |
def _imm_merge_class ( cls , parent ) :
'''_ imm _ merge _ class ( imm _ class , parent ) updates the given immutable class imm _ class to have the
appropriate attributes of its given parent class . The parents should be passed through this
function in method - resolution order .''' | # If this is not an immutable parent , ignore it
if not hasattr ( parent , '_pimms_immutable_data_' ) :
return cls
# otherwise , let ' s look at the data
cdat = cls . _pimms_immutable_data_
pdat = parent . _pimms_immutable_data_
# for params , values , and checks , we add them to cls only if they do not already exi... |
def draw_group_labels ( self ) :
"""Renders group labels to the figure .""" | for i , label in enumerate ( self . groups ) :
label_x = self . group_label_coords [ "x" ] [ i ]
label_y = self . group_label_coords [ "y" ] [ i ]
label_ha = self . group_label_aligns [ "has" ] [ i ]
label_va = self . group_label_aligns [ "vas" ] [ i ]
color = self . group_label_color [ i ]
self... |
def get_dependencies ( self ) :
"""Returns the set of data dependencies as producer infos corresponding to data requirements .""" | producer_infos = set ( )
for product_type in self . _dependencies :
producer_infos . update ( self . _get_producer_infos_by_product_type ( product_type ) )
return producer_infos |
def do_child_watch ( self , params ) :
"""\x1b [1mNAME \x1b [0m
child _ watch - Watch a path for child changes
\x1b [1mSYNOPSIS \x1b [0m
child _ watch < path > [ verbose ]
\x1b [1mOPTIONS \x1b [0m
* verbose : prints list of znodes ( default : false )
\x1b [1mEXAMPLES \x1b [0m
# only prints the current... | get_child_watcher ( self . _zk , print_func = self . show_output ) . update ( params . path , params . verbose ) |
def present ( name , Name = None , ScheduleExpression = None , EventPattern = None , Description = None , RoleArn = None , State = None , Targets = None , region = None , key = None , keyid = None , profile = None ) :
'''Ensure trail exists .
name
The name of the state definition
Name
Name of the event rule... | ret = { 'name' : Name , 'result' : True , 'comment' : '' , 'changes' : { } }
Name = Name if Name else name
if isinstance ( Targets , six . string_types ) :
Targets = salt . utils . json . loads ( Targets )
if Targets is None :
Targets = [ ]
r = __salt__ [ 'boto_cloudwatch_event.exists' ] ( Name = Name , region ... |
def isAuthorized ( self , request ) :
"""Is the user authorized for the requested action with this event ?""" | restrictions = self . get_view_restrictions ( )
if restrictions and request is None :
return False
else :
return all ( restriction . accept_request ( request ) for restriction in restrictions ) |
def parse_commit_log ( name , content , releases , get_head_fn ) :
"""Parses the given commit log
: param name : str , package name
: param content : list , directory paths
: param releases : list , releases
: param get _ head _ fn : function
: return : dict , changelog""" | log = ""
raw_log = ""
for path , _ in content :
log += "\n" . join ( changelog ( repository = GitRepos ( path ) , tag_filter_regexp = r"v?\d+\.\d+(\.\d+)?" ) )
raw_log += "\n" + subprocess . check_output ( [ "git" , "-C" , path , "--no-pager" , "log" , "--decorate" ] ) . decode ( "utf-8" )
shutil . rmtree (... |
def mandelbrot ( x , y , params ) :
"""Computes the number of iterations of the given plane - space coordinates .
: param x : X coordinate on the plane .
: param y : Y coordinate on the plane .
: param params : Current application parameters .
: type params : params . Params
: return : Discrete number of ... | mb_x , mb_y = get_coords ( x , y , params )
mb = mandelbrot_iterate ( mb_x + 1j * mb_y , params . max_iterations , params . julia_seed )
return mb [ 1 ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.