signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def set ( args ) :
"""Set an Aegea configuration parameter to a given value""" | from . import config , tweak
class ConfigSaver ( tweak . Config ) :
@ property
def config_files ( self ) :
return [ config . config_files [ 2 ] ]
config_saver = ConfigSaver ( use_yaml = True , save_on_exit = False )
c = config_saver
for key in args . key . split ( "." ) [ : - 1 ] :
try :
c =... |
def get_variables_substitution_dictionaries ( self , lhs_graph , rhs_graph ) :
"""Looks for sub - isomorphisms of rhs into lhs
: param lhs _ graph : The graph to look sub - isomorphisms into ( the bigger graph )
: param rhs _ graph : The smaller graph
: return : The list of matching names""" | if not rhs_graph :
return { } , { } , { }
self . matching_code_container . add_graph_to_namespace ( lhs_graph )
self . matching_code_container . add_graph_to_namespace ( rhs_graph )
return self . __collect_variables_that_match_graph ( lhs_graph , rhs_graph ) |
def send_task ( self , body ) :
"""发送任务到任务队列
: param body : 消息
: return :""" | self . ch . basic_publish ( exchange = '' , routing_key = self . task_queue , properties = pika . BasicProperties ( delivery_mode = 2 ) , body = body ) |
def create_network ( self , action , n_name , ** kwargs ) :
"""Creates a configured network .
: param action : Action configuration .
: type action : dockermap . map . runner . ActionConfig
: param n _ name : Network name .
: type n _ name : unicode | str
: param kwargs : Additional keyword arguments to c... | c_kwargs = self . get_network_create_kwargs ( action , n_name , ** kwargs )
res = action . client . create_network ( ** c_kwargs )
self . _policy . network_names [ action . client_name ] [ n_name ] = res [ 'Id' ]
return res |
async def slice ( self , offs , size = None , iden = None ) :
'''Yield a number of items from the CryoTank starting at a given offset .
Args :
offs ( int ) : The index of the desired datum ( starts at 0)
size ( int ) : The max number of items to yield .
Yields :
( ( index , object ) ) : Index and item val... | if iden is not None :
self . setOffset ( iden , offs )
for i , ( indx , item ) in enumerate ( self . _items . iter ( offs ) ) :
if size is not None and i >= size :
return
yield indx , item |
def _sd_handler ( self , desc_type , unit , desc , show_on_keypad ) :
"""Text description""" | if desc_type not in self . _descriptions_in_progress :
LOG . debug ( "Text description response ignored for " + str ( desc_type ) )
return
( max_units , results , callback ) = self . _descriptions_in_progress [ desc_type ]
if unit < 0 or unit >= max_units :
callback ( results )
del self . _descriptions_... |
def name ( self ) :
"""Returns a name for this defect""" | poss_deflist = sorted ( self . bulk_structure . get_sites_in_sphere ( self . site . coords , 2 , include_index = True ) , key = lambda x : x [ 1 ] )
defindex = poss_deflist [ 0 ] [ 2 ]
return "Sub_{}_on_{}_mult{}" . format ( self . site . specie , self . bulk_structure [ defindex ] . specie , self . multiplicity ) |
def sort ( transactions ) :
"""Return a list of sorted transactions by date .""" | return transactions . sort ( key = lambda x : datetime . datetime . strptime ( x . split ( ':' ) [ 0 ] , '%Y-%m-%d' ) ) [ : ] |
def add ( workflow_definition : dict , templates_root : str ) :
"""Add a workflow definition to the Configuration Database .
Templates are expected to be found in a directory tree with the following
structure :
- workflow _ id :
| - workflow _ version
| - stage _ id
| - stage _ version
| - < templates... | schema_path = join ( dirname ( __file__ ) , 'schema' , 'workflow_definition.json' )
with open ( schema_path , 'r' ) as file :
schema = json . loads ( file . read ( ) )
jsonschema . validate ( workflow_definition , schema )
_id = workflow_definition [ 'id' ]
_version = workflow_definition [ 'version' ]
_load_templat... |
def create_from_template ( zone , template ) :
'''Create an in - memory configuration from a template for the specified zone .
zone : string
name of zone
template : string
name of template
. . warning : :
existing config will be overwritten !
CLI Example :
. . code - block : : bash
salt ' * ' zone... | ret = { 'status' : True }
# create from template
_dump_cfg ( template )
res = __salt__ [ 'cmd.run_all' ] ( 'zonecfg -z {zone} create -t {tmpl} -F' . format ( zone = zone , tmpl = template , ) )
ret [ 'status' ] = res [ 'retcode' ] == 0
ret [ 'message' ] = res [ 'stdout' ] if ret [ 'status' ] else res [ 'stderr' ]
if re... |
def get_samples ( self , n_samples , log_p_function , burn_in_steps = 50 ) :
"""Generates samples .
Parameters :
n _ samples - number of samples to generate
log _ p _ function - a function that returns log density for a specific sample
burn _ in _ steps - number of burn - in steps for sampling
Returns a t... | restarts = initial_design ( 'random' , self . space , n_samples )
sampler = emcee . EnsembleSampler ( n_samples , self . space . input_dim ( ) , log_p_function )
samples , samples_log , _ = sampler . run_mcmc ( restarts , burn_in_steps )
# make sure we have an array of shape ( n samples , space input dim )
if len ( sam... |
def apply_configs ( config ) :
"""Configures components . They can be enabled or disabled , have timeouts set
if applicable , and have metadata customized . Valid keys are name , enabled ,
metadata , and timeout .
Args :
config ( list ) : a list of dictionaries with the following keys :
default _ componen... | default_enabled = config . get ( 'default_component_enabled' , False )
delegate_keys = sorted ( dr . DELEGATES , key = dr . get_name )
for comp_cfg in config . get ( 'configs' , [ ] ) :
name = comp_cfg . get ( "name" )
for c in delegate_keys :
delegate = dr . DELEGATES [ c ]
cname = dr . get_nam... |
def geometric2geopotential ( z : float , latitude : float ) -> float :
"""Converts geometric height to geopoential height
Parameters
z : float
Geometric height ( meters )
latitude : float
Latitude ( degrees )
Returns
h : float
Geopotential Height ( meters ) above the reference ellipsoid""" | twolat = deg2rad ( 2 * latitude )
g = 9.80616 * ( 1 - 0.002637 * cos ( twolat ) + 0.0000059 * cos ( twolat ) ** 2 )
re = _geoid_radius ( latitude )
return z * g * re / ( re + z ) |
def validate_context ( context ) :
"""Set the key for the current context .
Args :
context : a populated EFVersionContext object""" | # Service must exist in service registry
if not context . service_registry . service_record ( context . service_name ) :
fail ( "service: {} not found in service registry: {}" . format ( context . service_name , context . service_registry . filespec ) )
service_type = context . service_registry . service_record ( c... |
def updated ( self , instance ) :
"""Convenience method for updating a model ( automatically commits it to
the database and returns the object with with an HTTP 200 status code )""" | self . session_manager . save ( instance , commit = True )
return instance |
def flush ( self ) :
"""Flush tables and arrays to disk""" | self . log . info ( 'Flushing tables and arrays to disk...' )
for tab in self . _tables . values ( ) :
tab . flush ( )
self . _write_ndarrays_cache_to_disk ( ) |
def drop_alembic_version_table ( ) :
"""Drop alembic _ version table .""" | if _db . engine . dialect . has_table ( _db . engine , 'alembic_version' ) :
alembic_version = _db . Table ( 'alembic_version' , _db . metadata , autoload_with = _db . engine )
alembic_version . drop ( bind = _db . engine ) |
def from_string ( cls , string ) :
"""Parse a single string representing all command line parameters .""" | if string is None :
string = ''
if not isinstance ( string , six . string_types ) :
raise TypeError ( 'string has to be a string type, got: {}' . format ( type ( string ) ) )
dictionary = { }
tokens = [ token . strip ( ) for token in shlex . split ( string ) ]
def list_tuples ( some_iterable ) :
items , nex... |
def start ( self , device ) :
"""Start serving access to this VirtualIOTileDevice
Args :
device ( VirtualIOTileDevice ) : The device we will be providing access to""" | super ( NativeBLEVirtualInterface , self ) . start ( device )
self . set_advertising ( True ) |
def rows ( self ) :
'''Returns an iterator of row tuples .''' | for line in self . text . splitlines ( ) :
yield tuple ( self . getcells ( line ) ) |
def reqs_yml ( self ) :
"""Export a requirements file in yml format .""" | default_yml_item = """
- src: '%src'
name: '%name'
scm: '%scm'
version: '%version'
"""
role_lines = "---\n"
for role in sorted ( self . report [ "roles" ] ) :
name = utils . normalize_role ( role , self . config )
galaxy_name = "{0}.{1}" . format ( self . config [ "scm_user" ] , name )
yml_... |
def getSegmentActivityLevel ( self , seg , activeState , connectedSynapsesOnly = False ) :
"""This routine computes the activity level of a segment given activeState .
It can tally up only connected synapses ( permanence > = connectedPerm ) , or
all the synapses of the segment , at either t or t - 1.""" | # todo : Computing in C , use function getSegmentActivityLevel
return getSegmentActivityLevel ( seg . syns , activeState , connectedSynapsesOnly , self . connectedPerm ) |
def encode_payload ( cls , payload ) :
'''Encode a Python object as JSON and convert it to bytes .''' | try :
return json . dumps ( payload ) . encode ( )
except TypeError :
msg = f'JSON payload encoding error: {payload}'
raise ProtocolError ( cls . INTERNAL_ERROR , msg ) from None |
def get_edit_url_link ( self , text = None , cls = None , icon_class = None , ** attrs ) :
"""Gets the html edit link for the object .""" | if text is None :
text = 'Edit'
return build_link ( href = self . get_edit_url ( ) , text = text , cls = cls , icon_class = icon_class , ** attrs ) |
def decode_step ( self , step_input , states ) :
"""One step decoding of the translation model .
Parameters
step _ input : NDArray
Shape ( batch _ size , )
states : list of NDArrays
Returns
step _ output : NDArray
Shape ( batch _ size , C _ out )
states : list
step _ additional _ outputs : list
... | step_output , states , step_additional_outputs = self . decoder ( self . tgt_embed ( step_input ) , states )
step_output = self . tgt_proj ( step_output )
return step_output , states , step_additional_outputs |
def add_field ( self , descriptor ) :
"""https : / / github . com / frictionlessdata / tableschema - py # schema""" | self . __current_descriptor . setdefault ( 'fields' , [ ] )
self . __current_descriptor [ 'fields' ] . append ( descriptor )
self . __build ( )
return self . __fields [ - 1 ] |
def auto_clear_shopping_cart ( self , auto_clear_shopping_cart ) :
"""Sets the auto _ clear _ shopping _ cart of this CartSettings .
: param auto _ clear _ shopping _ cart : The auto _ clear _ shopping _ cart of this CartSettings .
: type : str""" | allowed_values = [ "never" , "orderCreated" , "orderCompleted" ]
# noqa : E501
if auto_clear_shopping_cart is not None and auto_clear_shopping_cart not in allowed_values :
raise ValueError ( "Invalid value for `auto_clear_shopping_cart` ({0}), must be one of {1}" # noqa : E501
. format ( auto_clear_shopping_car... |
def _serialize_json ( obj , fp ) :
"""Serialize ` ` obj ` ` as a JSON formatted stream to ` ` fp ` `""" | json . dump ( obj , fp , indent = 4 , default = serialize ) |
def stop ( self ) :
"""Set the Event lock , this will break all threads ' loops .""" | self . running = False
# stop the command server
try :
self . commands_thread . kill ( )
except : # noqa e722
pass
try :
self . lock . set ( )
if self . config [ "debug" ] :
self . log ( "lock set, exiting" )
# run kill ( ) method on all py3status modules
for module in self . modules . v... |
def model_funcpointers ( vk , model ) :
"""Fill the model with function pointer
model [ ' funcpointers ' ] = { ' pfn _ name ' : ' struct _ name ' }""" | model [ 'funcpointers' ] = { }
funcs = [ x for x in vk [ 'registry' ] [ 'types' ] [ 'type' ] if x . get ( '@category' ) == 'funcpointer' ]
structs = [ x for x in vk [ 'registry' ] [ 'types' ] [ 'type' ] if x . get ( '@category' ) == 'struct' ]
for f in funcs :
pfn_name = f [ 'name' ]
for s in structs :
... |
def Xu_Fang_voidage ( x , rhol , rhog , m , D , g = g ) :
r'''Calculates void fraction in two - phase flow according to the model
developed in the review of [ 1 ] _ .
. . math : :
\ alpha = \ left [ 1 + \ left ( 1 + 2Fr _ { lo } ^ { - 0.2 } \ alpha _ h ^ { 3.5 } \ right ) \ left (
\ frac { 1 - x } { x } \ r... | G = m / ( pi / 4 * D ** 2 )
alpha_h = homogeneous ( x , rhol , rhog )
Frlo = G ** 2 / ( g * D * rhol ** 2 )
return ( 1 + ( 1 + 2 * Frlo ** - 0.2 * alpha_h ** 3.5 ) * ( ( 1 - x ) / x ) * ( rhog / rhol ) ) ** - 1 |
def cleanup ( self ) :
"""Used internally .
Cleans up the sched references in the proactor . If you use this don ' t use
it while the : class : ` Scheduler ` ( : func : ` run ` ) is still running .""" | if hasattr ( self , 'proactor' ) :
if hasattr ( self . proactor , 'scheduler' ) :
del self . proactor . scheduler
if hasattr ( self . proactor , 'close' ) :
self . proactor . close ( ) |
def get_what_txt ( self ) :
"""Overrides the base behaviour defined in ValidationError in order to add details about the function .
: return :""" | return 'input [{var}] for function [{func}]' . format ( var = self . get_variable_str ( ) , func = self . validator . get_validated_func_display_name ( ) ) |
def color_lines ( ax , labels , colors ) :
"""Color lines .
Instead of this function , one can pass annotate _ kwargs and plot _ kwargs to
plot _ line _ ids function .""" | assert len ( labels ) == len ( colors ) , "Equal no. of colors and lables must be given"
lines = ax . findobj ( mpl . lines . Line2D )
line_labels = [ i + "_line" for i in lineid_plot . unique_labels ( labels ) ]
for line in lines :
l = line . get_label ( )
try :
loc = line_labels . index ( l )
exce... |
def calculate_signatures ( self ) :
"""Calculate the signatures for this MAR file .
Returns :
A list of signature tuples : [ ( algorithm _ id , signature _ data ) , . . . ]""" | if not self . signing_algorithm :
return [ ]
algo_id = { 'sha1' : 1 , 'sha384' : 2 } [ self . signing_algorithm ]
hashers = [ ( algo_id , make_hasher ( algo_id ) ) ]
for block in get_signature_data ( self . fileobj , self . filesize ) :
[ h . update ( block ) for ( _ , h ) in hashers ]
signatures = [ ( algo_id ... |
def jackknife ( values , statistic ) :
"""Estimate standard error for ` statistic ` computed over ` values ` using
the jackknife .
Parameters
values : array _ like or tuple of array _ like
Input array , or tuple of input arrays .
statistic : function
The statistic to compute .
Returns
m : float
Me... | if isinstance ( values , tuple ) : # multiple input arrays
n = len ( values [ 0 ] )
masked_values = [ np . ma . asarray ( v ) for v in values ]
for m in masked_values :
assert m . ndim == 1 , 'only 1D arrays supported'
assert m . shape [ 0 ] == n , 'input arrays not of equal length'
... |
def check_version ( self , node_id = None , timeout = 2 , strict = False ) :
"""Attempt to guess the version of a Kafka broker .
Note : It is possible that this method blocks longer than the
specified timeout . This can happen if the entire cluster
is down and the client enters a bootstrap backoff sleep .
T... | self . _lock . acquire ( )
end = time . time ( ) + timeout
while time . time ( ) < end : # It is possible that least _ loaded _ node falls back to bootstrap ,
# which can block for an increasing backoff period
try_node = node_id or self . least_loaded_node ( )
if try_node is None :
self . _lock . releas... |
def offset ( self ) :
"""This property holds the vertical offset of the scroll flag area
relative to the top of the text editor .""" | vsb = self . editor . verticalScrollBar ( )
style = vsb . style ( )
opt = QStyleOptionSlider ( )
vsb . initStyleOption ( opt )
# Get the area in which the slider handle may move .
groove_rect = style . subControlRect ( QStyle . CC_ScrollBar , opt , QStyle . SC_ScrollBarGroove , self )
return groove_rect . y ( ) |
def version_str2tuple ( cls , version_str ) :
"""Version info .
tuple object . ex . ( ' 4 ' , ' 14 ' , ' 0 ' , ' rc1 ' )""" | if not isinstance ( version_str , str ) :
ValueError ( 'version_str invalid instance.' )
version_info_list = re . findall ( r'[0-9a-zA-Z]+' , version_str )
def convert_to_int ( string ) :
value = None
if re . match ( r'^\d+$' , string ) :
value = int ( string )
else :
value = string
... |
def versions_from_archive ( self ) :
"""Return Python versions extracted from trove classifiers .""" | py_vers = versions_from_trove ( self . classifiers )
return [ ver for ver in py_vers if ver != self . unsupported_version ] |
def download_data ( ) :
"""Downloads complete station dataset including catchment descriptors and amax records . And saves it into a cache
folder .""" | with urlopen ( _retrieve_download_url ( ) ) as f :
with open ( os . path . join ( CACHE_FOLDER , CACHE_ZIP ) , "wb" ) as local_file :
local_file . write ( f . read ( ) ) |
def cd ( directory ) :
"""Change the current working directory , temporarily .
Use as a context manager : with cd ( d ) : . . .""" | old_dir = os . getcwd ( )
try :
os . chdir ( directory )
yield
finally :
os . chdir ( old_dir ) |
def get ( self , request , * args , ** kwargs ) :
'''The queryset is filtered by measurements of animals which are part of that strain .''' | strain = get_object_or_404 ( Strain , Strain_slug = self . kwargs [ 'strain_slug' ] )
animals = Animal . objects . filter ( Strain = strain )
measurements = Measurement . objects . filter ( animal = animals )
return data_csv ( self . request , measurements ) |
def deleted_user_show ( self , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / users # show - deleted - user" | api_path = "/api/v2/deleted_users/{id}.json"
api_path = api_path . format ( id = id )
return self . call ( api_path , ** kwargs ) |
def remove_lock ( self ) :
"""Remove acquired lock .""" | key = '%s_lock' % self . scheduler_key
if self . _lock_acquired :
self . connection . delete ( key ) |
def has_keys ( self , keys ) :
"""Ensures : attr : ` subject ` is a : class : ` collections . Mapping ` and contains * keys * , which must be an iterable .""" | self . is_a ( Mapping )
self . contains_all_of ( keys )
return ChainInspector ( self . _subject ) |
def sample ( self , rstate = None ) :
"""Draw a sample uniformly distributed within the ellipsoid .
Returns
x : ` ~ numpy . ndarray ` with shape ( ndim , )
A coordinate within the ellipsoid .""" | if rstate is None :
rstate = np . random
return self . ctr + self . randoffset ( rstate = rstate ) |
def corruptDenseVector ( vector , noiseLevel ) :
"""Corrupts a binary vector by inverting noiseLevel percent of its bits .
@ param vector ( array ) binary vector to be corrupted
@ param noiseLevel ( float ) amount of noise to be applied on the vector .""" | size = len ( vector )
for i in range ( size ) :
rnd = random . random ( )
if rnd < noiseLevel :
if vector [ i ] == 1 :
vector [ i ] = 0
else :
vector [ i ] = 1 |
def set_xylims ( self , limits , axes = None , side = 'left' ) :
"set user - defined limits and apply them" | if axes is None :
axes = self . axes
if side == 'right' :
axes = self . get_right_axes ( )
self . conf . user_limits [ axes ] = limits
self . unzoom_all ( ) |
def _package_transform ( package , fqdn , start = 1 , * args , ** kwargs ) :
"""Applies the specified package transform with ` fqdn ` to the package .
Args :
package : imported package object .
fqdn ( str ) : fully - qualified domain name of function in the package . If it
does not include the package name ... | # Our only difficulty here is that package names can be chained . We ignore
# the first item since that was already checked for us by the calling
# method .
node = _obj_getattr ( package , fqdn , start )
# By the time this loop is finished , we should have a function to apply if
# the developer setting up the config di... |
def _update_dictionary ( self ) :
"""Update the word frequency object""" | self . _total_words = sum ( self . _dictionary . values ( ) )
self . _unique_words = len ( self . _dictionary . keys ( ) )
self . _letters = set ( )
for key in self . _dictionary :
self . _letters . update ( key ) |
def ResolveObject ( self , document ) :
'''Tries to locate a document in the archive .
This function tries to locate the document inside the archive . It
returns a tuple where the first element is zero if the function
was successful , and the second is the UnitInfo for that document .
The UnitInfo is used t... | if self . file :
path = os . path . abspath ( document )
return chmlib . chm_resolve_object ( self . file , path )
else :
return ( 1 , None ) |
def raise_on_packet ( self , pkt_cls , state , get_next_msg = True ) :
"""If the next message to be processed has type ' pkt _ cls ' , raise ' state ' .
If there is no message waiting to be processed , we try to get one with
the default ' get _ next _ msg ' parameters .""" | # Maybe we already parsed the expected packet , maybe not .
if get_next_msg :
self . get_next_msg ( )
if ( not self . buffer_in or not isinstance ( self . buffer_in [ 0 ] , pkt_cls ) ) :
return
self . cur_pkt = self . buffer_in [ 0 ]
self . buffer_in = self . buffer_in [ 1 : ]
raise state ( ) |
def filter ( self , table , volumes , filter_string ) :
"""Naive case - insensitive search .""" | q = filter_string . lower ( )
return [ volume for volume in volumes if q in volume . name . lower ( ) ] |
def shutdown ( self ) :
"""Signals worker to shutdown ( via sentinel ) then cleanly joins the thread""" | self . shutdownLocal ( )
newJobsQueue = self . newJobsQueue
self . newJobsQueue = None
newJobsQueue . put ( None )
self . worker . join ( ) |
def populate_data ( self , data ) :
"""Parse the outgoing schema""" | sch = MockItemSchema ( )
return Result ( ** { "callname" : self . context . get ( "callname" ) , "result" : sch . dump ( data ) , } ) |
def read ( string ) :
"""Read a graph from a XML document and return it . Nodes and edges specified in the input will
be added to the current graph .
@ type string : string
@ param string : Input string in XML format specifying a graph .
@ rtype : graph
@ return : Graph""" | dom = parseString ( string )
if dom . getElementsByTagName ( "graph" ) :
G = graph ( )
elif dom . getElementsByTagName ( "digraph" ) :
G = digraph ( )
elif dom . getElementsByTagName ( "hypergraph" ) :
return read_hypergraph ( string )
else :
raise InvalidGraphType
# Read nodes . . .
for each_node in do... |
def to_excel ( self , * args ) :
"""Dump all the data to excel , fname and path can be passed as args""" | path = os . getcwd ( )
fname = self . fname . replace ( ".ppl" , "_ppl" ) + ".xlsx"
if len ( args ) > 0 and args [ 0 ] != "" :
path = args [ 0 ]
if os . path . exists ( path ) == False :
os . mkdir ( path )
xl_file = pd . ExcelWriter ( path + os . sep + fname )
for idx in self . filter_data ( "" ) :
... |
def _check_time_series ( self , other ) :
"""Function used to check the type of the argument and raise an
informative error message if it ' s not a TimeSeries .""" | if not isinstance ( other , TimeSeries ) :
msg = "unsupported operand types(s) for +: %s and %s" % ( type ( self ) , type ( other ) )
raise TypeError ( msg ) |
def parse ( rmk : str ) -> RemarksData :
"""Finds temperature and dewpoint decimal values from the remarks""" | rmkdata = { }
for item in rmk . split ( ' ' ) :
if len ( item ) in [ 5 , 9 ] and item [ 0 ] == 'T' and item [ 1 : ] . isdigit ( ) :
rmkdata [ 'temperature_decimal' ] = core . make_number ( _tdec ( item [ 1 : 5 ] , None ) )
# type : ignore
rmkdata [ 'dewpoint_decimal' ] = core . make_number (... |
def move ( self , src , dst ) :
"""Moves ` ` DirEntry ` ` from src to dst""" | src_entry = self . find ( src )
if src_entry is None :
raise ValueError ( "src path does not exist: %s" % src )
if dst . endswith ( '/' ) :
dst += src_entry . name
if self . exists ( dst ) :
raise ValueError ( "dst path already exist: %s" % dst )
if dst == '/' or src == '/' :
raise ValueError ( "cannot ... |
def is_shaped ( self ) :
"""Return description containing array shape if exists , else None .""" | for description in ( self . description , self . description1 ) :
if not description :
return None
if description [ : 1 ] == '{' and '"shape":' in description :
return description
if description [ : 6 ] == 'shape=' :
return description
return None |
def _set_hwxy_attrs ( attr ) :
"""Using the bbox attribute , set the h , w , x0 , x1 , y0 , and y1
attributes .""" | bbox = attr [ 'bbox' ]
attr [ 'x0' ] = bbox [ 0 ]
attr [ 'x1' ] = bbox [ 2 ]
attr [ 'y0' ] = bbox [ 1 ]
attr [ 'y1' ] = bbox [ 3 ]
attr [ 'height' ] = attr [ 'y1' ] - attr [ 'y0' ]
attr [ 'width' ] = attr [ 'x1' ] - attr [ 'x0' ]
return attr |
def log_config ( log_level : Union [ str , int ] ) -> dict :
"""Setup default config . for dictConfig .
: param log _ level : str name or django debugging int
: return : dict suitable for ` ` logging . config . dictConfig ` `""" | if isinstance ( log_level , int ) : # to match django
log_level = { 3 : 'DEBUG' , 2 : 'INFO' } . get ( log_level , 'WARNING' )
assert log_level in { 'DEBUG' , 'INFO' , 'WARNING' , 'ERROR' } , 'wrong log level %s' % log_level
return { 'version' : 1 , 'disable_existing_loggers' : True , 'formatters' : { 'default' : {... |
def __get_default_location ( ) :
"""Returns the current process ' s default cache location folder .
The folder is determined lazily on first call .""" | if not FileCache . __default_location :
tmp = tempfile . mkdtemp ( "suds-default-cache" )
FileCache . __default_location = tmp
import atexit
atexit . register ( FileCache . __remove_default_location )
return FileCache . __default_location |
def configure ( self , config = None , ** kwargs ) :
"""We expect all of our config ( apart from the ENGINE ) to be
in a dictionary called ' config ' in our INSTALLED _ BACKENDS entry""" | self . config = config or { }
for key in [ 'messaging_token' , 'number' ] :
if key not in self . config :
msg = "Tropo backend config must set '%s'; config is %r" % ( key , config )
raise ImproperlyConfigured ( msg )
if kwargs :
msg = "All tropo backend config should be within the `config`" "ent... |
def resolve_path ( filename : Path ) -> typing . Union [ Path , None ] :
"""Find a file by walking up parent directories until the file is found .
Return the absolute path of the file .""" | current = Path . cwd ( )
# Stop search at home directory
sentinel_dir = Path . home ( ) . parent . resolve ( )
while current != sentinel_dir :
target = Path ( current ) / Path ( filename )
if target . exists ( ) :
return target . resolve ( )
else :
current = current . parent . resolve ( )
re... |
def escape_query ( query ) :
"""Escapes certain filter characters from an LDAP query .""" | return query . replace ( "\\" , r"\5C" ) . replace ( "*" , r"\2A" ) . replace ( "(" , r"\28" ) . replace ( ")" , r"\29" ) |
def get_annotation ( component , db_name , db_ref ) :
"""Construct model Annotations for each component .
Annotation formats follow guidelines at http : / / identifiers . org / .""" | url = get_identifiers_url ( db_name , db_ref )
if not url :
return None
subj = component
ann = Annotation ( subj , url , 'is' )
return ann |
def _move ( self , speed = 0 , steering = 0 , seconds = None ) :
"""Move robot .""" | self . drive_queue . put ( ( speed , steering ) )
if seconds is not None :
time . sleep ( seconds )
self . drive_queue . put ( ( 0 , 0 ) )
self . drive_queue . join ( ) |
def _get_sorted_mosaics ( dicom_input ) :
"""Search all mosaics in the dicom directory , sort and validate them""" | # Order all dicom files by acquisition number
sorted_mosaics = sorted ( dicom_input , key = lambda x : x . AcquisitionNumber )
for index in range ( 0 , len ( sorted_mosaics ) - 1 ) : # Validate that there are no duplicate AcquisitionNumber
if sorted_mosaics [ index ] . AcquisitionNumber >= sorted_mosaics [ index + ... |
def newDocComment ( self , content ) :
"""Creation of a new node containing a comment within a
document .""" | ret = libxml2mod . xmlNewDocComment ( self . _o , content )
if ret is None :
raise treeError ( 'xmlNewDocComment() failed' )
__tmp = xmlNode ( _obj = ret )
return __tmp |
def _auto_scroll ( self , * args ) :
"""Scroll to the end of the text view""" | adj = self [ 'scrollable' ] . get_vadjustment ( )
adj . set_value ( adj . get_upper ( ) - adj . get_page_size ( ) ) |
def ssh_sa_ssh_server_key_dsa ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
ssh_sa = ET . SubElement ( config , "ssh-sa" , xmlns = "urn:brocade.com:mgmt:brocade-sec-services" )
ssh = ET . SubElement ( ssh_sa , "ssh" )
server = ET . SubElement ( ssh , "server" )
key = ET . SubElement ( server , "key" )
dsa = ET . SubElement ( key , "dsa" )
callback = kwargs . ... |
def hack_find_packages ( include_str ) :
"""patches setuptools . find _ packages issue
setuptools . find _ packages ( path = ' ' ) doesn ' t work as intended
Returns :
list : append < include _ str > . onto every element of setuptools . find _ pacakges ( ) call""" | new_list = [ include_str ]
for element in find_packages ( include_str ) :
new_list . append ( include_str + '.' + element )
return new_list |
def _biobambam_dedup_sort ( data , tx_out_file ) :
"""Perform streaming deduplication and sorting with biobambam ' s bamsormadup""" | samtools = config_utils . get_program ( "samtools" , data [ "config" ] )
cores , mem = _get_cores_memory ( data , downscale = 2 )
tmp_file = "%s-sorttmp" % utils . splitext_plus ( tx_out_file ) [ 0 ]
if data . get ( "align_split" ) :
sort_opt = "-n" if data . get ( "align_split" ) and _check_dedup ( data ) else ""
... |
def get_client ( self , client_id ) :
'''Gets a single client by id .''' | client_response = self . get_request ( 'clients/%s' % client_id )
return Client ( self , client_response [ 'client' ] ) |
def create_from_previous_version ( cls , previous_shadow , payload ) :
"""set None to payload when you want to delete shadow""" | version , previous_payload = ( previous_shadow . version + 1 , previous_shadow . to_dict ( include_delta = False ) ) if previous_shadow else ( 1 , { } )
if payload is None : # if given payload is None , delete existing payload
# this means the request was delete _ thing _ shadow
shadow = FakeShadow ( None , None , ... |
def as_view ( cls , * args , ** kwargs ) :
"""This method is used within urls . py to create unique formwizard
instances for every request . We need to override this method because
we add some kwargs which are needed to make the formwizard usable .""" | initkwargs = cls . get_initkwargs ( * args , ** kwargs )
return super ( WizardView , cls ) . as_view ( ** initkwargs ) |
def call ( self , args = None , kwargs = None , node = None , send_timeout = 1000 , recv_timeout = 5000 , zmq_ctx = None ) :
"""Calls a service on a node with req as arguments . if node is None , a node is chosen by zmq .
if zmq _ ctx is passed , it will use the existing context
Uses a REQ socket . Ref : http :... | context = zmq_ctx or zmq . Context ( )
assert isinstance ( context , zmq . Context )
args = args or ( )
assert isinstance ( args , tuple )
kwargs = kwargs or { }
assert isinstance ( kwargs , dict )
socket = context . socket ( zmq . REQ )
# connect to all addresses ( optionally matching node name )
for n , a in [ ( n , ... |
def get_vm_size_completion_list ( cmd , prefix , namespace , ** kwargs ) : # pylint : disable = unused - argument
"""Return the intersection of the VM sizes allowed by the ACS SDK with those returned by the Compute Service .""" | location = _get_location ( cmd . cli_ctx , namespace )
result = get_vm_sizes ( cmd . cli_ctx , location )
return set ( r . name for r in result ) & set ( c . value for c in ContainerServiceVMSizeTypes ) |
def find_py_files ( srctree , ignore = None ) :
"""Return all the python files in a source tree
Ignores any path that contains the ignore string
This is not used by other class methods , but is
designed to be used in code that uses this class .""" | if not os . path . isdir ( srctree ) :
yield os . path . split ( srctree )
for srcpath , _ , fnames in os . walk ( srctree ) : # Avoid infinite recursion for silly users
if ignore is not None and ignore in srcpath :
continue
for fname in ( x for x in fnames if x . endswith ( '.py' ) ) :
yiel... |
def clusterStatus ( self ) :
"""Returns a dict of cluster nodes and their status information""" | servers = yield self . getClusterServers ( )
d = { 'workers' : { } , 'crons' : { } , 'queues' : { } }
now = time . time ( )
reverse_map = { }
for sname in servers :
last = yield self . _get_key ( '/server/%s/heartbeat' % sname )
status = yield self . _get_key ( '/server/%s/status' % sname )
uuid = yield sel... |
def get_current_goal_temperature ( self , refresh = False ) :
"""Get current goal temperature / setpoint""" | if refresh :
self . refresh ( )
try :
return float ( self . get_value ( 'setpoint' ) )
except ( TypeError , ValueError ) :
return None |
def _get_switchports ( profile ) :
"""Return list of ( switch _ ip , interface ) tuples from local _ link _ info""" | switchports = [ ]
if profile . get ( 'local_link_information' ) :
for link in profile [ 'local_link_information' ] :
if 'switch_info' in link and 'port_id' in link :
switch = link [ 'switch_info' ]
interface = link [ 'port_id' ]
switchports . append ( ( switch , interface... |
def to_dict ( self ) :
"""Return a dictionary of the worker stats .
Returns :
dict : Dictionary of the stats .""" | return { 'name' : self . name , 'broker' : self . broker . to_dict ( ) , 'pid' : self . pid , 'process_pids' : self . process_pids , 'concurrency' : self . concurrency , 'job_count' : self . job_count , 'queues' : [ q . to_dict ( ) for q in self . queues ] } |
def CreateCounterMetadata ( metric_name , fields = None , docstring = None , units = None ) :
"""Helper function for creating MetricMetadata for counter metrics .""" | return rdf_stats . MetricMetadata ( varname = metric_name , metric_type = rdf_stats . MetricMetadata . MetricType . COUNTER , value_type = rdf_stats . MetricMetadata . ValueType . INT , fields_defs = FieldDefinitionProtosFromTuples ( fields or [ ] ) , docstring = docstring , units = units ) |
def find_introns ( fa , seqs , sequences , threads ) :
"""find introns by searching Rfam intron databse using cmscan
# seqs [ id ] = [ gene , model , [ [ i - gene _ pos , i - model _ pos , i - length , iseq , [ orfs ] , [ introns ] ] , . . . ] ]""" | db = '%s/rfam/Rfam.cm.1_1.introns' % ( os . environ [ 'databases' ] )
out = '%s.rfam-introns.cmscan' % ( fa )
tblout = '%s.rfam-introns.cmscan-tblout' % ( fa )
if os . path . exists ( tblout ) is False :
p = subprocess . Popen ( 'cmscan --cpu %s --tblout %s %s %s > %s' % ( threads , tblout , db , fa , out ) , shell... |
def median ( data , channels = None ) :
"""Calculate the median of the events in an FCSData object .
Parameters
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters ( aka channels ) .
channels : int or str or list of int or list of str , o... | # Slice data to take statistics from
if channels is None :
data_stats = data
else :
data_stats = data [ : , channels ]
# Calculate and return statistic
return np . median ( data_stats , axis = 0 ) |
def create ( self , data = { } , store = None ) :
"""Initiazes an OPR
First step in the OPR process is to create the OPR request .
Returns the OPR token""" | _store = store or self . store
_data = self . _build_opr_data ( data , _store ) if data else self . _opr_data
return self . _process ( 'opr/create' , _data ) |
def _authenticate ( self ) :
"""Authenticate .""" | # to obtain csrftoken , remove Referer from headers
headers = HEADERS . copy ( )
headers . pop ( 'Referer' )
# initial GET request
self . client = requests . Session ( )
self . client . proxies = self . _proxies
self . client . verify = self . _ssl_verify
self . client . stream = True
self . client . get ( LOGIN_ENDPOI... |
def _memory_data ( self , log_prefix ) :
"""Returns a dict with information for current memory utilization .
Uses log _ prefix in log statements .""" | machine_data = psutil . virtual_memory ( )
process = psutil . Process ( )
process_data = { 'memory_info' : process . get_memory_info ( ) , 'ext_memory_info' : process . get_ext_memory_info ( ) , 'memory_percent' : process . get_memory_percent ( ) , 'cpu_percent' : process . get_cpu_percent ( ) , }
log . info ( u"%s Mac... |
def nxm_field_name_to_ryu ( field ) :
"""Convert an ovs - ofctl style NXM _ / OXM _ field name to
a ryu match field name .""" | if field . endswith ( "_W" ) :
field = field [ : - 2 ]
prefix = field [ : 7 ]
field = field [ 7 : ] . lower ( )
mapped_result = None
if prefix == 'NXM_NX_' :
mapped_result = _NXM_FIELD_MAP . get ( field )
elif prefix == "NXM_OF_" :
mapped_result = _NXM_OF_FIELD_MAP . get ( field )
elif prefix == "OXM_OF_" :... |
def fill_n ( self , values , weights = None , ** kwargs ) :
"""Add more values at once .
This ( default ) implementation uses a simple loop to add values using ` fill ` method .
Actually , it is not used in neither Histogram1D , nor HistogramND .
Parameters
values : Iterable
Values to add
weights : Opti... | if weights is not None :
if weights . shape != values . shape [ 0 ] :
raise RuntimeError ( "Wrong shape of weights" )
for i , value in enumerate ( values ) :
if weights is not None :
self . fill ( value , weights [ i ] , ** kwargs )
else :
self . fill ( value , ** kwargs ) |
def _generate_issue ( self , run , entry , callablesCount ) :
"""Insert the issue instance into a run . This includes creating ( for
new issues ) or finding ( for existing issues ) Issue objects to associate
with the instances .
Also create sink entries and associate related issues""" | trace_frames = [ ]
for p in entry [ "preconditions" ] :
tf = self . _generate_issue_precondition ( run , entry , p )
trace_frames . append ( tf )
for p in entry [ "postconditions" ] :
tf = self . _generate_issue_postcondition ( run , entry , p )
trace_frames . append ( tf )
features = set ( )
for f in e... |
def search_for_subject ( self , subject , timeout = None , content_type = None ) :
"""Get content of emails , sent to a specific email address .
@ Params
email - the recipient email address to search for
timeout - seconds to try beore timing out
content _ type - type of email string to return
@ Returns
... | return self . search ( timeout = timeout , content_type = content_type , SUBJECT = subject ) |
def send ( self , soapenv ) :
"""Send soap message .
@ param soapenv : A soap envelope to send .
@ type soapenv : L { Document }
@ return : The reply to the sent message .
@ rtype : I { builtin } or I { subclass of } L { Object }""" | result = None
location = self . location ( )
binding = self . method . binding . input
transport = self . options . transport
retxml = self . options . retxml
prettyxml = self . options . prettyxml
log . debug ( 'sending to (%s)\nmessage:\n%s' , location , soapenv )
try :
self . last_sent ( soapenv )
plugins = ... |
def get_gpubsub_publisher ( config , metrics , changes_channel , ** kw ) :
"""Get a GPubsubPublisher client .
A factory function that validates configuration , creates an auth
and pubsub API client , and returns a Google Pub / Sub Publisher
provider .
Args :
config ( dict ) : Google Cloud Pub / Sub - rela... | builder = gpubsub_publisher . GPubsubPublisherBuilder ( config , metrics , changes_channel , ** kw )
return builder . build_publisher ( ) |
def _make_xml ( self , endpoints ) : # type : ( List [ EndpointDescription ] ) - > ElementTree . Element
"""Converts the given endpoint description beans into an XML Element
: param endpoints : A list of EndpointDescription beans
: return : A string containing an XML document""" | root = ElementTree . Element ( TAG_ENDPOINT_DESCRIPTIONS )
for endpoint in endpoints :
self . _make_endpoint ( root , endpoint )
# Prepare pretty - printing
self . _indent ( root )
return root |
def subscribe ( self , _func = None , needs = ( ) , returns = ( ) , modifies = ( ) , ** conditions ) :
"""Add a hook to a pangler .
This method can either be used as a decorator for a function or method ,
or standalone on a callable .
* ` needs ` is an iterable of parameters that this hook operates on .
* `... | modifies = set ( modifies )
parameters = set ( needs ) | modifies
needs = parameters | set ( conditions )
if not needs :
raise ValueError ( "tried to hook nothing" )
returns = set ( returns ) | modifies
def deco ( func ) :
self . hooks . append ( _Hook ( func , needs , parameters , returns , conditions ) )
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.