signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
async def list ( self ) :
'''Get a list of ( name , info ) tuples for the CryoTanks .
Returns :
list : A list of tufos .''' | return [ ( name , await tank . info ( ) ) for ( name , tank ) in self . tanks . items ( ) ] |
def get_class ( self ) :
"""Return a Code class based on current ErrorType value .
Returns :
enum . IntEnum : class referenced by current error type .""" | classes = { 'OFPET_HELLO_FAILED' : HelloFailedCode , 'OFPET_BAD_REQUEST' : BadRequestCode , 'OFPET_BAD_ACTION' : BadActionCode , 'OFPET_BAD_INSTRUCTION' : BadInstructionCode , 'OFPET_BAD_MATCH' : BadMatchCode , 'OFPET_FLOW_MOD_FAILED' : FlowModFailedCode , 'OFPET_GROUP_MOD_FAILED' : GroupModFailedCode , 'OFPET_PORT_MOD... |
def _set_route_table ( self , v , load = False ) :
"""Setter method for route _ table , mapped from YANG variable / hardware / profile / route _ table ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ route _ table is considered as a private
method . Backe... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = route_table . route_table , is_container = 'container' , presence = False , yang_name = "route-table" , rest_name = "route-table" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , registe... |
def commit ( self ) -> None :
"""Commit the transaction with a fixed transaction id .
A read transaction can call commit ( ) any number of times , while a write transaction can only use the
same tx _ id for 10 minutes from the first call .""" | now = datetime . now ( timezone . utc )
if self . first_commit_at is None :
self . first_commit_at = now
if self . mode == "r" :
response = self . engine . session . transaction_read ( self . _request )
elif self . mode == "w" :
if now - self . first_commit_at > MAX_TOKEN_LIFETIME :
raise Transactio... |
def get_field_type ( f ) :
"""Obtain the type name of a GRPC Message field .""" | types = ( t [ 5 : ] for t in dir ( f ) if t [ : 4 ] == 'TYPE' and getattr ( f , t ) == f . type )
return next ( types ) |
async def xrange ( self , name : str , start = '-' , end = '+' , count = None ) -> list :
"""Read stream values within an interval .
Available since 5.0.0.
Time complexity : O ( log ( N ) + M ) with N being the number of elements in the stream and M the number
of elements being returned . If M is constant ( e... | pieces = [ start , end ]
if count is not None :
if not isinstance ( count , int ) or count < 1 :
raise RedisError ( "XRANGE count must be a positive integer" )
pieces . append ( "COUNT" )
pieces . append ( str ( count ) )
return await self . execute_command ( 'XRANGE' , name , * pieces ) |
def temperature_series ( self , unit = 'kelvin' ) :
"""Returns the temperature time series relative to the meteostation , in
the form of a list of tuples , each one containing the couple
timestamp - value
: param unit : the unit of measure for the temperature values . May be
among : ' * kelvin * ' ( default... | if unit not in ( 'kelvin' , 'celsius' , 'fahrenheit' ) :
raise ValueError ( "Invalid value for parameter 'unit'" )
result = [ ]
for tstamp in self . _station_history . get_measurements ( ) :
t = self . _station_history . get_measurements ( ) [ tstamp ] [ 'temperature' ]
if unit == 'kelvin' :
temp = ... |
def _reserved_symbols ( self ) :
"""Helper property for the build _ remap _ symbols method . This
property first resolves _ all _ local references from parents ,
skipping all locally declared symbols as the goal is to generate
a local mapping for them , but in a way not to shadow over any
already declared s... | # In practice , and as a possible optimisation , the parent ' s
# remapped symbols table can be merged into this instance , but
# this bloats memory use and cause unspecified reservations that
# may not be applicable this or any child scope . So for clarity
# and purity of references made , this somewhat more involved ... |
def valuefrompostdata ( self , postdata ) :
"""This parameter method searches the POST data and retrieves the values it needs . It does not set the value yet though , but simply returns it . Needs to be explicitly passed to parameter . set ( )""" | if self . id in postdata and postdata [ self . id ] != '' :
return float ( postdata [ self . id ] )
else :
return None |
def get_all_subscriptions ( self , next_token = None ) :
"""Get list of all subscriptions .
: type next _ token : string
: param next _ token : Token returned by the previous call to
this method .""" | params = { 'ContentType' : 'JSON' }
if next_token :
params [ 'NextToken' ] = next_token
response = self . make_request ( 'ListSubscriptions' , params , '/' , 'GET' )
body = response . read ( )
if response . status == 200 :
return json . loads ( body )
else :
boto . log . error ( '%s %s' % ( response . statu... |
def notifications ( self ) :
"""Access the notifications
: returns : twilio . rest . notify . v1 . service . notification . NotificationList
: rtype : twilio . rest . notify . v1 . service . notification . NotificationList""" | if self . _notifications is None :
self . _notifications = NotificationList ( self . _version , service_sid = self . _solution [ 'sid' ] , )
return self . _notifications |
def K_separator_Watkins ( x , rhol , rhog , horizontal = False , method = 'spline' ) :
r'''Calculates the Sounders - Brown ` K ` factor as used in determining maximum
allowable gas velocity in a two - phase separator in either a horizontal or
vertical orientation . This function approximates a graph published i... | factor = ( 1. - x ) / x * ( rhog / rhol ) ** 0.5
if method == 'spline' :
K = exp ( float ( splev ( log ( factor ) , tck_Watkins ) ) )
elif method == 'blackwell' :
X = log ( factor )
A = - 1.877478097
B = - 0.81145804597
C = - 0.1870744085
D = - 0.0145228667
E = - 0.00101148518
K = exp ( ... |
async def delete_entries ( self , entry ) :
"""DELETE / api / entries / { entry } . { _ format }
Delete permanently an entry
: param entry : \ w + an integer The Entry ID
: return result""" | params = { 'Authorization' : 'Bearer {}' . format ( self . token ) }
path = '/api/entries/{entry}.{ext}' . format ( entry = entry , ext = self . format )
return await self . query ( path , "delete" , ** params ) |
def next_population ( self , population , fitnesses ) :
"""Make a new population after each optimization iteration .
Args :
population : The population current population of solutions .
fitnesses : The fitness associated with each solution in the population
Returns :
list ; a list of solutions .""" | return common . make_population ( self . _population_size , self . _generate_solution ) |
def resample ( grid , wl , flux ) :
"""Resample spectrum onto desired grid""" | flux_rs = ( interpolate . interp1d ( wl , flux ) ) ( grid )
return flux_rs |
def search_aikif ( txt , formatHTML = True ) :
"""search for text - currently this looks in all folders in the
root of AIKIF but that also contains binaries so will need to
use the agent _ filelist . py to specify the list of folders .
NOTE - this needs to use indexes rather than full search each time""" | results = [ ]
num_found = 0
import aikif . lib . cls_filelist as mod_fl
my_files = mod_fl . FileList ( [ aikif_folder ] , [ '*.*' ] , [ '*.pyc' ] )
files = my_files . get_list ( )
for f in files :
try :
num_found = 0
with open ( f , 'r' ) as cur :
line_num = 0
for line in cur... |
def get_int ( self , key , optional = False ) :
"""Tries to fetch a variable from the config and expects it to be strictly an int
: param key : Variable to look for
: param optional : Whether to raise ConfigKeyNotFoundError if key was not found .
: return : int""" | return self . _get_typed_value ( key , int , lambda x : int ( x ) , optional ) |
def truncate_table ( self , tablename ) :
"""SQLite3 doesn ' t support direct truncate , so we just use delete here""" | self . get ( tablename ) . remove ( )
self . db . commit ( ) |
def archive_if_exists ( filename ) :
"""Move ` filename ` out of the way , archiving it by appending the current datetime
Can be a file or a directory""" | if os . path . exists ( filename ) :
current_time = datetime . datetime . now ( )
dt_format = '%Y-%m-%dT%H:%M:%S%z'
timestamp = current_time . strftime ( dt_format )
dst = filename + '_' + timestamp
shutil . move ( filename , dst ) |
def prepare_arg ( value ) :
"""Stringify dicts / lists and convert datetime / timedelta to unix - time
: param value :
: return :""" | if value is None :
return value
elif isinstance ( value , ( list , dict ) ) or hasattr ( value , 'to_python' ) :
return json . dumps ( _normalize ( value ) )
elif isinstance ( value , datetime . timedelta ) :
now = datetime . datetime . now ( )
return int ( ( now + value ) . timestamp ( ) )
elif isinsta... |
def get_attribute ( file , element ) :
'''Return the attributes of the matched xpath element .
CLI Example :
. . code - block : : bash
salt ' * ' xml . get _ attribute / tmp / test . xml " . / / element [ @ id = ' 3 ' ] "''' | try :
root = ET . parse ( file )
element = root . find ( element )
return element . attrib
except AttributeError :
log . error ( "Unable to find element matching %s" , element )
return False |
def _move_dragged_row ( self , item ) :
"""Insert dragged row at item ' s position .""" | self . move ( self . _dragged_row , '' , self . index ( item ) )
self . see ( self . _dragged_row )
bbox = self . bbox ( self . _dragged_row )
self . _dragged_row_y = bbox [ 1 ]
self . _dragged_row_height = bbox [ 3 ]
self . _visual_drag . see ( self . _dragged_row ) |
def _quadratic_sum_cost ( self , state : _STATE ) -> float :
"""Cost function that sums squares of lengths of sequences .
Args :
state : Search state , not mutated .
Returns :
Cost which is minus the normalized quadratic sum of each linear
sequence section in the state . This promotes single , long linear... | cost = 0.0
total_len = float ( len ( self . _c ) )
seqs , _ = state
for seq in seqs :
cost += ( len ( seq ) / total_len ) ** 2
return - cost |
def get_many ( self , uris ) :
"""Return request uri map of found nodes as dicts :
{ requested _ uri : { uri : x , content : y } }""" | cache_keys = dict ( ( self . _build_cache_key ( uri ) , uri ) for uri in uris )
result = self . _get_many ( cache_keys )
nodes = { }
for cache_key in result :
uri = cache_keys [ cache_key ]
value = result [ cache_key ]
node = self . _decode_node ( uri , value )
if node :
nodes [ uri ] = node
ret... |
def get_network_settings ( ) :
'''Return the contents of the global network script .
CLI Example :
. . code - block : : bash
salt ' * ' ip . get _ network _ settings''' | if __grains__ [ 'lsb_distrib_id' ] == 'nilrt' :
raise salt . exceptions . CommandExecutionError ( 'Not supported in this version.' )
settings = [ ]
networking = 'no' if _get_state ( ) == 'offline' else 'yes'
settings . append ( 'networking={0}' . format ( networking ) )
hostname = __salt__ [ 'network.get_hostname' ... |
def _compute_magnitude ( self , rup , C ) :
"""Compute the first term of the equation described on p . 1144:
` ` c1 + c2 * ( M - 6 ) + c3 * log ( M / 6 ) ` `""" | return C [ 'c1' ] + C [ 'c2' ] * ( rup . mag - 6.0 ) + ( C [ 'c3' ] * np . log ( rup . mag / 6.0 ) ) |
def get_codoc_frequencies ( dtm , min_val = 1 , proportions = False ) :
"""For each unique pair of words ` w1 , w2 ` in the vocab of ` dtm ` ( i . e . its columns ) , return how often both occur
together at least ` min _ val ` times . If ` proportions ` is True , return proportions scaled to the number of documen... | if dtm . ndim != 2 :
raise ValueError ( '`dtm` must be a 2D array/matrix' )
n_docs , n_vocab = dtm . shape
if n_vocab < 2 :
raise ValueError ( '`dtm` must have at least two columns (i.e. 2 unique words)' )
word_in_doc = dtm >= min_val
codoc_freq = { }
for w1 , w2 in itertools . combinations ( range ( n_vocab ) ... |
def token_middleware ( ctx , get_response ) :
"""Reinject token and consistency into requests .""" | async def middleware ( request ) :
params = request . setdefault ( 'params' , { } )
if params . get ( "token" ) is None :
params [ 'token' ] = ctx . token
return await get_response ( request )
return middleware |
def hash ( self ) :
''': rtype : int
: return : hash of the field''' | hashed = super ( Calculated , self ) . hash ( )
return khash ( hashed , self . _field_name ) |
def set_bounds ( self , new_bounds ) :
"""A method that allows changing the lower and upper searching bounds
Parameters
new _ bounds : dict
A dictionary with the parameter name and its new bounds""" | for row , key in enumerate ( self . keys ) :
if key in new_bounds :
self . _bounds [ row ] = new_bounds [ key ] |
def import_cert ( name , cert_format = _DEFAULT_FORMAT , context = _DEFAULT_CONTEXT , store = _DEFAULT_STORE , exportable = True , password = '' , saltenv = 'base' ) :
'''Import the certificate file into the given certificate store .
: param str name : The path of the certificate file to import .
: param str ce... | cmd = list ( )
thumbprint = None
store_path = r'Cert:\{0}\{1}' . format ( context , store )
cert_format = cert_format . lower ( )
_validate_cert_format ( name = cert_format )
cached_source_path = __salt__ [ 'cp.cache_file' ] ( name , saltenv )
if not cached_source_path :
_LOG . error ( 'Unable to get cached copy of... |
def _hash_html_blocks ( self , text , raw = False ) :
"""Hashify HTML blocks
We only want to do this for block - level HTML tags , such as headers ,
lists , and tables . That ' s because we still want to wrap < p > s around
" paragraphs " that are wrapped in non - block - level tags , such as anchors ,
phra... | if '<' not in text :
return text
# Pass ` raw ` value into our calls to self . _ hash _ html _ block _ sub .
hash_html_block_sub = _curry ( self . _hash_html_block_sub , raw = raw )
# First , look for nested blocks , e . g . :
# < div >
# < div >
# tags for inner block must be indented .
# < / div >
# < / div >
# T... |
def index ( self , fields , name = None , table = None , ** kwargs ) :
'''Build a new index on a cube .
Examples :
+ index ( ' field _ name ' )
: param fields : A single field or a list of ( key , direction ) pairs
: param name : ( optional ) Custom name to use for this index
: param collection : cube nam... | table = self . get_table ( table )
name = self . _index_default_name ( fields , name )
fields = parse . parse_fields ( fields )
fields = self . columns ( table , fields , reflect = True )
session = self . session_new ( )
index = Index ( name , * fields )
logger . info ( 'Writing new index %s: %s' % ( name , fields ) )
... |
def cartesian ( self , subsets = None , step_pixels = 100 , max_distance_pixels = 150 , * args , ** kwargs ) :
"""Return a class that can be used to create honeycomb plots
Args :
subsets ( list ) : list of SubsetLogic objects
step _ pixels ( int ) : distance between hexagons
max _ distance _ pixels ( int ) ... | n = Cartesian . read_cellframe ( self , subsets = subsets , step_pixels = step_pixels , max_distance_pixels = max_distance_pixels , prune_neighbors = False , * args , ** kwargs )
if 'measured_regions' in kwargs :
n . measured_regions = kwargs [ 'measured_regions' ]
else :
n . measured_regions = self . get_measu... |
def extract_direction ( self ) :
'''Extract image direction ( i . e . compass , heading , bearing )''' | fields = [ 'GPS GPSImgDirection' , 'EXIF GPS GPSImgDirection' , 'GPS GPSTrack' , 'EXIF GPS GPSTrack' ]
direction , _ = self . _extract_alternative_fields ( fields )
if direction is not None :
direction = normalize_bearing ( direction , check_hex = True )
return direction |
def runOnExecutor ( self , * commands , oper = ACCEPT , defer_shell_expansion = False ) :
"""This runs in the executor of the current scope .
You cannot magically back out since there are no
gurantees that ssh keys will be in place ( they shouldn ' t be ) .""" | return self . makeOutput ( EXE , commands , oper = oper , defer_shell_expansion = defer_shell_expansion ) |
def _begin_validation ( session : UpdateSession , config : config . Config , loop : asyncio . AbstractEventLoop , downloaded_update_path : str ) -> asyncio . futures . Future :
"""Start the validation process .""" | session . set_stage ( Stages . VALIDATING )
cert_path = config . update_cert_path if config . signature_required else None
validation_future = asyncio . ensure_future ( loop . run_in_executor ( None , file_actions . validate_update , downloaded_update_path , session . set_progress , cert_path ) )
def validation_done ( ... |
def _read_frame ( self ) :
"""Headquarters for frame reader .""" | if self . _exeng == 'scapy' :
return self . _scapy_read_frame ( )
elif self . _exeng == 'dpkt' :
return self . _dpkt_read_frame ( )
elif self . _exeng == 'pyshark' :
return self . _pyshark_read_frame ( )
else :
return self . _default_read_frame ( ) |
def items ( self ) :
"""Returns an iterator over the named bitfields in the structure as
2 - tuples of ( key , value ) . Uses a clone so as to only read from
the underlying data once .""" | temp = self . clone ( )
return [ ( f , getattr ( temp , f ) ) for f in iter ( self ) ] |
def set_creation_date ( self , p_date = date . today ( ) ) :
"""Sets the creation date of a todo . Should be passed a date object .""" | self . fields [ 'creationDate' ] = p_date
# not particularly pretty , but inspired by
# http : / / bugs . python . org / issue1519638 non - existent matches trigger
# exceptions , hence the lambda
self . src = re . sub ( r'^(x \d{4}-\d{2}-\d{2} |\([A-Z]\) )?(\d{4}-\d{2}-\d{2} )?(.*)$' , lambda m : u"{}{} {}" . format (... |
def tag ( self , querystring , tags , afterwards = None , remove_rest = False ) :
"""add tags to messages matching ` querystring ` .
This appends a tag operation to the write queue and raises
: exc : ` ~ errors . DatabaseROError ` if in read only mode .
: param querystring : notmuch search string
: type que... | if self . ro :
raise DatabaseROError ( )
if remove_rest :
self . writequeue . append ( ( 'set' , afterwards , querystring , tags ) )
else :
self . writequeue . append ( ( 'tag' , afterwards , querystring , tags ) ) |
def continued_indentation ( logical_line , tokens , indent_level , hang_closing , indent_char , noqa ) :
"""Override pycodestyle ' s function to provide indentation information .""" | first_row = tokens [ 0 ] [ 2 ] [ 0 ]
nrows = 1 + tokens [ - 1 ] [ 2 ] [ 0 ] - first_row
if noqa or nrows == 1 :
return
# indent _ next tells us whether the next block is indented . Assuming
# that it is indented by 4 spaces , then we should not allow 4 - space
# indents on the final continuation line . In turn , so... |
def is_relevant ( self , action , subject ) :
"""Matches both the subject and action , not necessarily the conditions .""" | return self . matches_action ( action ) and self . matches_subject ( subject ) |
def keep_alive ( self , conn ) :
'''Maintains auth sessions''' | while self . __up :
msg = conn . recv ( len ( AUTH_KEEP_ALIVE ) )
if msg != AUTH_KEEP_ALIVE :
log . error ( 'Received something other than %s' , AUTH_KEEP_ALIVE )
conn . close ( )
return
try :
conn . send ( AUTH_KEEP_ALIVE_ACK )
except ( IOError , socket . error ) as err ... |
def _prune_node ( self , node ) :
"""Prune the given node if context exits cleanly .""" | if self . is_pruning : # node is mutable , so capture the key for later pruning now
prune_key , node_body = self . _node_to_db_mapping ( node )
should_prune = ( node_body is not None )
else :
should_prune = False
yield
# Prune only if no exception is raised
if should_prune :
del self . db [ prune_key ] |
def speaker ( self ) :
"""Lazy - loads the speaker for this word
: getter : Returns the plain string value of the speaker tag for the word
: type : str""" | if self . _speaker is None :
speakers = self . _element . xpath ( 'Speaker/text()' )
if len ( speakers ) > 0 :
self . _speaker = speakers [ 0 ]
return self . _speaker |
def load_pem ( cls , private_key , password = None ) :
"""Return a PrivateKey instance .
: param private _ key : Private key string ( PEM format ) or the path
to a local private key file .""" | # TODO ( sam ) : try to break this in tests
maybe_path = normpath ( private_key )
if os . path . isfile ( maybe_path ) :
with open ( maybe_path , 'rb' ) as pkf :
private_key = pkf . read ( )
if not isinstance ( private_key , six . binary_type ) :
private_key = private_key . encode ( 'utf-8' )
pkey = ser... |
def top_matches ( self , top ) :
'''Search through the top high data for matches and return the states
that this minion needs to execute .
Returns :
{ ' saltenv ' : [ ' state1 ' , ' state2 ' , . . . ] }''' | matches = DefaultOrderedDict ( OrderedDict )
# pylint : disable = cell - var - from - loop
for saltenv , body in six . iteritems ( top ) :
if self . opts [ 'saltenv' ] :
if saltenv != self . opts [ 'saltenv' ] :
continue
for match , data in six . iteritems ( body ) :
def _filter_matc... |
def shape ( self ) :
"""get the implied , 2D shape of self
Returns
tuple : tuple
length 2 tuple of ints""" | if self . __x is not None :
if self . isdiagonal :
return ( max ( self . __x . shape ) , max ( self . __x . shape ) )
if len ( self . __x . shape ) == 1 :
raise Exception ( "Matrix.shape: Matrix objects must be 2D" )
return self . __x . shape
return None |
def add_variable ( self , key , value , system_wide = False ) :
"""Adds the environment variable .
: param key : the name of the variable
: type key : str
: param value : the value
: type value : str
: param system _ wide : whether to add the variable system wide
: type system _ wide : bool""" | if system_wide :
javabridge . call ( self . jobject , "addVariableSystemWide" , "(Ljava/lang/String;Ljava/lang/String;)V" , key , value )
else :
javabridge . call ( self . jobject , "addVariable" , "(Ljava/lang/String;Ljava/lang/String;)V" , key , value ) |
def contains_key ( self , key ) :
"""Determines whether this multimap contains an entry with the key .
* * Warning : This method uses _ _ hash _ _ and _ _ eq _ _ methods of binary form of the key , not the actual implementations
of _ _ hash _ _ and _ _ eq _ _ defined in key ' s class . * *
: param key : ( obj... | check_not_none ( key , "key can't be None" )
key_data = self . _to_data ( key )
return self . _encode_invoke_on_key ( multi_map_contains_key_codec , key_data , key = key_data , thread_id = thread_id ( ) ) |
def set_date ( date ) :
'''Set the current month , day , and year
: param str date : The date to set . Valid date formats are :
- % m : % d : % y
- % m : % d : % Y
- % m / % d / % y
- % m / % d / % Y
: return : True if successful , False if not
: rtype : bool
: raises : SaltInvocationError on Invali... | date_format = _get_date_time_format ( date )
dt_obj = datetime . strptime ( date , date_format )
cmd = 'systemsetup -setdate {0}' . format ( dt_obj . strftime ( '%m:%d:%Y' ) )
return salt . utils . mac_utils . execute_return_success ( cmd ) |
def _pool_one_shape ( features_2d , area_width , area_height , batch_size , width , height , depth , fn = tf . reduce_max , name = None ) :
"""Pools for an area in features _ 2d .
Args :
features _ 2d : a Tensor in a shape of [ batch _ size , height , width , depth ] .
area _ width : the max width allowed for... | with tf . name_scope ( name , default_name = "pool_one_shape" ) :
images = [ ]
for y_shift in range ( area_height ) :
image_height = tf . maximum ( height - area_height + 1 + y_shift , 0 )
for x_shift in range ( area_width ) :
image_width = tf . maximum ( width - area_width + 1 + x_s... |
def parse_wait_time ( text : str ) -> int :
"""Parse the waiting time from the exception""" | val = RATELIMIT . findall ( text )
if len ( val ) > 0 :
try :
res = val [ 0 ]
if res [ 1 ] == 'minutes' :
return int ( res [ 0 ] ) * 60
if res [ 1 ] == 'seconds' :
return int ( res [ 0 ] )
except Exception as e :
util_logger . warning ( 'Could not parse ra... |
def cmd_ac ( self , ch = None ) :
"""ac ch = chname
Calculate and set auto cut levels for the given channel .
If ` ch ` is omitted , assumes the current channel .""" | viewer = self . get_viewer ( ch )
if viewer is None :
self . log ( "No current viewer/channel." )
return
viewer . auto_levels ( )
self . cmd_cuts ( ch = ch ) |
def has_nvme_ssd ( system_obj ) :
"""Gets if the system has any drive as NVMe SSD drive
: param system _ obj : The HPESystem object .
: returns True if system has SSD drives and protocol is NVMe .""" | storage_value = False
storage_resource = _get_attribute_value_of ( system_obj , 'storages' )
if storage_resource is not None :
storage_value = _get_attribute_value_of ( storage_resource , 'has_nvme_ssd' , default = False )
return storage_value |
def _update_request_context_with_user ( self , user = None ) :
'''Store the given user as ctx . user .''' | ctx = _request_ctx_stack . top
ctx . user = self . anonymous_user ( ) if user is None else user |
def _encode_str ( self , obj , escape_quotes = True ) :
"""Return an ASCII - only JSON representation of a Python string""" | def replace ( match ) :
s = match . group ( 0 )
try :
if escape_quotes :
return ESCAPE_DCT [ s ]
else :
return BASE_ESCAPE_DCT [ s ]
except KeyError :
n = ord ( s )
if n < 0x10000 :
return '\\u{0:04x}' . format ( n )
else : # surrog... |
def native ( self ) :
"""The native Python datatype representation of this value
: return :
A byte string or None""" | if self . contents is None :
return None
if self . _parsed is not None :
return self . _parsed [ 0 ] . native
else :
return self . __bytes__ ( ) |
async def gather_coalescing_exceptions ( coros , display , * , verbose ) :
'''The tricky thing about running multiple coroutines in parallel is what
we ' re supposed to do when one of them raises an exception . The approach
we ' re using here is to catch exceptions and keep waiting for other tasks to
finish .... | exceptions = [ ]
reprs = [ ]
async def catching_wrapper ( coro ) :
try :
return ( await coro )
except Exception as e :
exceptions . append ( e )
if isinstance ( e , PrintableError ) and not verbose :
reprs . append ( e . message )
else :
reprs . append ( t... |
def version ( path ) :
"""Obtain the packge version from a python file e . g . pkg / _ _ init _ _ . py
See < https : / / packaging . python . org / en / latest / single _ source _ version . html > .""" | version_file = read ( path )
version_match = re . search ( r"""^__version__ = ['"]([^'"]*)['"]""" , version_file , re . M )
if version_match :
return version_match . group ( 1 )
raise RuntimeError ( "Unable to find version string." ) |
def wrap_search ( cls , response ) :
"""Wrap the response from a game search into instances
and return them
: param response : The response from searching a game
: type response : : class : ` requests . Response `
: returns : the new game instances
: rtype : : class : ` list ` of : class : ` Game `
: ra... | games = [ ]
json = response . json ( )
gamejsons = json [ 'games' ]
for j in gamejsons :
g = cls . wrap_json ( j )
games . append ( g )
return games |
def E ( self , * args , ** kwargs ) :
"""NAME :
PURPOSE :
calculate the energy
INPUT :
t - ( optional ) time at which to get the radius
pot = linearPotential instance or list thereof
OUTPUT :
energy
HISTORY :
2010-09-15 - Written - Bovy ( NYU )""" | if not 'pot' in kwargs or kwargs [ 'pot' ] is None :
try :
pot = self . _pot
except AttributeError :
raise AttributeError ( "Integrate orbit or specify pot=" )
if 'pot' in kwargs and kwargs [ 'pot' ] is None :
kwargs . pop ( 'pot' )
else :
pot = kwargs . pop ( 'pot' )
if len ( ar... |
def pr_curves_impl ( self , runs , tag ) :
"""Creates the JSON object for the PR curves response for a run - tag combo .
Arguments :
runs : A list of runs to fetch the curves for .
tag : The tag to fetch the curves for .
Raises :
ValueError : If no PR curves could be fetched for a run and tag .
Returns ... | if self . _db_connection_provider : # Serve data from the database .
db = self . _db_connection_provider ( )
# We select for steps greater than - 1 because the writer inserts
# placeholder rows en masse . The check for step filters out those rows .
cursor = db . execute ( '''
SELECT
Ru... |
def _connect ( contact_points = None , port = None , cql_user = None , cql_pass = None , protocol_version = None ) :
'''Connect to a Cassandra cluster .
: param contact _ points : The Cassandra cluster addresses , can either be a string or a list of IPs .
: type contact _ points : str or list of str
: param c... | # Lazy load the Cassandra cluster and session for this module by creating a
# cluster and session when cql _ query is called the first time . Get the
# Cassandra cluster and session from this module ' s _ _ context _ _ after it is
# loaded the first time cql _ query is called .
# TODO : Call cluster . shutdown ( ) when... |
def _fastfood_list ( args ) :
"""Run on ` fastfood list ` .""" | template_pack = pack . TemplatePack ( args . template_pack )
if args . stencil_set :
stencil_set = template_pack . load_stencil_set ( args . stencil_set )
print ( "Available Stencils for %s:" % args . stencil_set )
for stencil in stencil_set . stencils :
print ( " %s" % stencil )
else :
print (... |
def timesince ( when ) :
"""Returns string representing " time since " or " time until " .
Examples :
3 days ago , 5 hours ago , 3 minutes from now , 5 hours from now , now .""" | if not when :
return ''
now = datetime . datetime . utcnow ( )
if now > when :
diff = now - when
suffix = 'ago'
else :
diff = when - now
suffix = 'from now'
periods = ( ( diff . days / 365 , 'year' , 'years' ) , ( diff . days / 30 , 'month' , 'months' ) , ( diff . days / 7 , 'week' , 'weeks' ) , ( d... |
def get_tool ( name ) :
"""Returns an instance of a specific tool .
Parameters
name : str
Name of the tool ( case - insensitive ) .
Returns
tool : MotifProgram instance""" | tool = name . lower ( )
if tool not in __tools__ :
raise ValueError ( "Tool {0} not found!\n" . format ( name ) )
t = __tools__ [ tool ] ( )
if not t . is_installed ( ) :
sys . stderr . write ( "Tool {0} not installed!\n" . format ( tool ) )
if not t . is_configured ( ) :
sys . stderr . write ( "Tool {0} no... |
def belongs_to_module ( t , module_name ) :
"Check if ` t ` belongs to ` module _ name ` ." | if hasattr ( t , '__func__' ) :
return belongs_to_module ( t . __func__ , module_name )
if not inspect . getmodule ( t ) :
return False
return inspect . getmodule ( t ) . __name__ . startswith ( module_name ) |
def is_remote_video_enabled ( self , remote_node ) :
"""Check if the remote node has the video recorder enabled
: param remote _ node : remote node name
: returns : true if it has the video recorder enabled""" | enabled = False
if remote_node :
url = '{}/config' . format ( self . _get_remote_node_url ( remote_node ) )
try :
response = requests . get ( url , timeout = 5 ) . json ( )
record_videos = response [ 'config_runtime' ] [ 'theConfigMap' ] [ 'video_recording_options' ] [ 'record_test_videos' ]
... |
def TransformerLM ( vocab_size , feature_depth = 512 , feedforward_depth = 2048 , num_layers = 6 , num_heads = 8 , dropout = 0.1 , max_len = 2048 , mode = 'train' ) :
"""Transformer language model ( only uses the decoder part of Transformer ) .
Args :
vocab _ size : int : vocab size
feature _ depth : int : de... | return layers . Serial ( layers . ShiftRight ( ) , layers . Embedding ( feature_depth , vocab_size ) , layers . Dropout ( rate = dropout , mode = mode ) , layers . PositionalEncoding ( max_len = max_len ) , layers . Serial ( * [ DecoderLayer ( feature_depth , feedforward_depth , num_heads , dropout , mode ) for _ in ra... |
def solve ( self , hash160_lookup , tx_in_idx , hash_type = None , ** kwargs ) :
"""Sign a standard transaction .
hash160 _ lookup :
An object with a get method that accepts a hash160 and returns the
corresponding ( secret exponent , public _ pair , is _ compressed ) tuple or
None if it ' s unknown ( in whi... | if hash_type is None :
hash_type = SIGHASH_ALL
kwargs [ "hash160_lookup" ] = hash160_lookup
if "signature_placeholder" not in kwargs :
kwargs [ "signature_placeholder" ] = generate_default_placeholder_signature ( kwargs . get ( "generator" ) )
if self . tx . txs_in [ tx_in_idx ] . witness :
kwargs [ "existi... |
def _create_structure_array ( structure_array , voxelspacing ) :
"""Convenient function to take a structure array ( single number valid for all dimensions
or a sequence with a distinct number for each dimension ) assumed to be in mm and
returns a structure array ( a sequence ) adapted to the image space using t... | try :
structure_array = [ s / float ( vs ) for s , vs in zip ( structure_array , voxelspacing ) ]
except TypeError :
structure_array = [ structure_array / float ( vs ) for vs in voxelspacing ]
return structure_array |
def similar_item_values ( self , key , replaces ) :
"""Returns a list of values for all variants of the ` ` key ` `
in this DAWG according to ` ` replaces ` ` .
` ` replaces ` ` is an object obtained from
` ` DAWG . compile _ replaces ( mapping ) ` ` where mapping is a dict
that maps single - char unicode s... | return self . _similar_item_values ( 0 , key , self . dct . ROOT , replaces ) |
def recipe_details ( recipe_id , lang = "en" ) :
"""This resource returns a details about a single recipe .
: param recipe _ id : The recipe to query for .
: param lang : The language to display the texts in .
The response is an object with the following properties :
recipe _ id ( number ) :
The recipe id... | params = { "recipe_id" : recipe_id , "lang" : lang }
cache_name = "recipe_details.%(recipe_id)s.%(lang)s.json" % params
return get_cached ( "recipe_details.json" , cache_name , params = params ) |
def get ( self , sid ) :
"""Constructs a FieldContext
: param sid : The unique string that identifies the resource
: returns : twilio . rest . autopilot . v1 . assistant . task . field . FieldContext
: rtype : twilio . rest . autopilot . v1 . assistant . task . field . FieldContext""" | return FieldContext ( self . _version , assistant_sid = self . _solution [ 'assistant_sid' ] , task_sid = self . _solution [ 'task_sid' ] , sid = sid , ) |
def read ( self ) :
"Connect to the feedback service and read all data ." | log . msg ( 'APNSService read (connecting)' )
try :
server , port = ( ( FEEDBACK_SERVER_SANDBOX_HOSTNAME if self . environment == 'sandbox' else FEEDBACK_SERVER_HOSTNAME ) , FEEDBACK_SERVER_PORT )
factory = self . feedbackProtocolFactory ( )
context = self . getContextFactory ( )
reactor . connectSSL ( ... |
def compare_graphs ( graph1 , mode , graph2 = None ) :
"""Compares graph with saved one which is loaded via networkx ' gpickle
Parameters
graph1 : networkx . graph
First Ding0 MV graph for comparison
graph2 : networkx . graph
Second Ding0 MV graph for comparison . If a second graph is not provided
it wi... | # get path
package_path = ding0 . __path__ [ 0 ]
file = path . join ( package_path , 'output' , 'debug' , 'graph1.gpickle' )
if mode == 'write' :
try :
nx . write_gpickle ( graph1 , file )
print ( '=====> DEBUG: Graph written to' , file )
except :
raise FileNotFoundError ( 'Could not wri... |
def supported_currencies ( self , project = 'moneywagon' , level = "full" ) :
"""Returns a list of all currencies that are supported by the passed in project .
and support level . Support level can be : " block " , " transaction " , " address "
or " full " .""" | ret = [ ]
if project == 'multiexplorer-wallet' :
for currency , data in self . sorted_crypto_data :
if not data . get ( "bip44_coin_type" ) :
continue
if len ( data . get ( 'services' , { } ) . get ( "push_tx" , [ ] ) ) < 1 :
continue
if len ( data . get ( 'services' ... |
def generate ( self , tool , copied = False , copy = False ) :
"""Generates a workspace""" | # copied - already done by external script , copy - do actual copy
tools = [ ]
if not tool :
logger . info ( "Workspace supports one tool for all projects within." )
return - 1
else :
tools = [ tool ]
result = 0
for export_tool in tools :
tool_export = ToolsSupported ( ) . get_tool ( export_tool )
i... |
def _validate_dtype ( self , dtype ) :
"""validate the passed dtype""" | if dtype is not None :
dtype = pandas_dtype ( dtype )
# a compound dtype
if dtype . kind == 'V' :
raise NotImplementedError ( "compound dtypes are not implemented" " in the {0} constructor" . format ( self . __class__ . __name__ ) )
return dtype |
def inspect_sensors ( self , name = None , timeout = None ) :
"""Inspect all or one sensor on the device . Update sensors index .
Parameters
name : str or None , optional
Name of the sensor or None to get all sensors .
timeout : float or None , optional
Timeout for sensors inspection , None for no timeout... | if name is None :
msg = katcp . Message . request ( 'sensor-list' )
else :
msg = katcp . Message . request ( 'sensor-list' , name )
reply , informs = yield self . katcp_client . future_request ( msg , timeout = timeout )
self . _logger . debug ( '{} received {} sensor-list informs, reply: {}' . format ( self . ... |
def verifychain ( self , anchors , untrusted = None ) :
"""Perform verification of certificate chains for that certificate . The
behavior of verifychain method is mapped ( and also based ) on openssl
verify userland tool ( man 1 verify ) .
A list of anchors is required . untrusted parameter can be provided
... | cafile = create_temporary_ca_file ( anchors )
if not cafile :
return False
untrusted_file = None
if untrusted :
untrusted_file = create_temporary_ca_file ( untrusted )
# hack
if not untrusted_file :
os . unlink ( cafile )
return False
res = self . verifychain_from_cafile ( cafile , untru... |
def on_recv_rsp ( self , rsp_pb ) :
"""receive response callback function""" | ret_code , ret_data = UpdateOrderPush . unpack_rsp ( rsp_pb )
if ret_code != RET_OK :
return ret_code , ret_data
else :
order_dict = ret_data
col_list = [ 'trd_env' , 'code' , 'stock_name' , 'dealt_avg_price' , 'dealt_qty' , 'qty' , 'order_id' , 'order_type' , 'price' , 'order_status' , 'create_time' , 'upd... |
def from_json ( cls , data ) :
"""Create a Data Collection from a dictionary .
Args :
" header " : A Ladybug Header ,
" values " : An array of values ,
" datetimes " : An array of datetimes ,
" validated _ a _ period " : Boolean for whether header analysis _ period is valid""" | assert 'header' in data , 'Required keyword "header" is missing!'
assert 'values' in data , 'Required keyword "values" is missing!'
assert 'datetimes' in data , 'Required keyword "datetimes" is missing!'
collection = cls ( Header . from_json ( data [ 'header' ] ) , data [ 'values' ] , [ DateTime . from_json ( dat ) for... |
def trim ( args ) :
"""% prog trim fastqfile
Wraps ` fastx _ trimmer ` to trim from begin or end of reads .""" | p = OptionParser ( trim . __doc__ )
p . add_option ( "-f" , dest = "first" , default = 0 , type = "int" , help = "First base to keep. Default is 1." )
p . add_option ( "-l" , dest = "last" , default = 0 , type = "int" , help = "Last base to keep. Default is entire read." )
opts , args = p . parse_args ( args )
if len (... |
def process_tls ( self , data , name ) :
"""Remote TLS processing - one address : port per line
: param data :
: param name :
: return :""" | ret = [ ]
try :
lines = [ x . strip ( ) for x in data . split ( '\n' ) ]
for idx , line in enumerate ( lines ) :
if line == '' :
continue
sub = self . process_host ( line , name , idx )
if sub is not None :
ret . append ( sub )
except Exception as e :
logger .... |
def delete ( self , id ) :
"""根据 id 删除数据 。
: param id : 要删除的数据的 id""" | self . conn . cursor ( ) . execute ( "DELETE FROM WeRoBot WHERE id=%s" , ( id , ) )
self . conn . commit ( ) |
def iterkeys ( self , match = None , count = 1 ) :
"""Return an iterator over the db ' s keys .
` ` match ` ` allows for filtering the keys by pattern .
` ` count ` ` allows for hint the minimum number of returns .
> > > dc = Dictator ( )
> > > dc [ ' 1 ' ] = ' abc '
> > > dc [ ' 2 ' ] = ' def '
> > > d... | logger . debug ( 'call iterkeys %s' , match )
if match is None :
match = '*'
for key in self . _redis . scan_iter ( match = match , count = count ) :
yield key |
def transition ( self , duration , is_on = None , ** kwargs ) :
"""Transition to the specified state of the led .
If another transition is already running , it is aborted .
: param duration : The duration of the transition .
: param is _ on : The on - off state to transition to .
: param kwargs : The state ... | self . _cancel_active_transition ( )
dest_state = self . _prepare_transition ( is_on , ** kwargs )
total_steps = self . _transition_steps ( ** dest_state )
state_stages = [ self . _transition_stage ( step , total_steps , ** dest_state ) for step in range ( total_steps ) ]
pwm_stages = [ self . _get_pwm_values ( ** stag... |
def _body ( self ) :
"""The | _ Body | instance containing the content for this document .""" | if self . __body is None :
self . __body = _Body ( self . _element . body , self )
return self . __body |
def satisfied ( self , lab ) :
"""Check whether the labeling satisfies all constraints""" | for const in self . constraints :
if not const . satisfied ( lab ) :
return False
return True |
def query ( self , session = None ) :
'''Returns a new : class : ` Query ` for : attr : ` Manager . model ` .''' | if session is None or session . router is not self . router :
session = self . session ( )
return session . query ( self . model ) |
def clear_measurements ( self ) :
"""Remove all measurements from self . measurements . Reset the
measurement counter . All ID are invalidated .""" | keys = list ( self . measurements . keys ( ) )
for key in keys :
del ( self . measurements [ key ] )
self . meas_counter = - 1 |
def _process_phenotype_cvterm ( self ) :
"""These are the qualifiers for the phenotype location itself .
But are just the qualifiers .
The actual " observable " part of the phenotype is only in
the phenotype table . These get added to a lookup variable used to
augment a phenotype association statement .
:... | line_counter = 0
raw = '/' . join ( ( self . rawdir , 'phenotype_cvterm' ) )
LOG . info ( "processing phenotype cvterm mappings" )
with open ( raw , 'r' ) as f :
f . readline ( )
# read the header row ; skip
filereader = csv . reader ( f , delimiter = '\t' , quotechar = '\"' )
for line in filereader :
... |
def create_multiple_bar_chart ( self , x_labels , mul_y_values , mul_y_labels , normalize = False ) :
"""Creates bar chart with multiple lines
: param x _ labels : Names for each variable
: param mul _ y _ values : list of values of x labels
: param mul _ y _ labels : list of labels for each y value
: param... | self . setup ( 0.25 )
ax1 = self . get_ax ( )
ax1 . set_xticks ( list ( range ( len ( x_labels ) ) ) )
ax1 . set_xticklabels ( [ x_labels [ i ] for i in range ( len ( x_labels ) ) ] , rotation = 90 )
y_counts = len ( mul_y_values )
colors = cm . rainbow ( np . linspace ( 0 , 1 , y_counts ) )
# different colors
max_bar_... |
def get_D_square_min ( atoms_now , atoms_old , i_now , j_now , delta_plus_epsilon = None ) :
"""Calculate the D ^ 2 _ min norm of Falk and Langer""" | nat = len ( atoms_now )
assert len ( atoms_now ) == len ( atoms_old )
pos_now = atoms_now . positions
pos_old = atoms_old . positions
# Compute current and old distance vectors . Note that current distance
# vectors cannot be taken from the neighbor calculation , because neighbors
# are calculated from the sheared cell... |
def _file_to_abs ( x , dnames , makedir = False ) :
"""Make a file absolute using the supplied base directory choices .""" | if x is None or os . path . isabs ( x ) :
return x
elif isinstance ( x , six . string_types ) and objectstore . is_remote ( x ) :
return x
elif isinstance ( x , six . string_types ) and x . lower ( ) == "none" :
return None
else :
for dname in dnames :
if dname :
normx = os . path . ... |
def from_xdr_object ( cls , op_xdr_object ) :
"""Creates a : class : ` SetOptions ` object from an XDR Operation
object .""" | if not op_xdr_object . sourceAccount :
source = None
else :
source = encode_check ( 'account' , op_xdr_object . sourceAccount [ 0 ] . ed25519 ) . decode ( )
if not op_xdr_object . body . setOptionsOp . inflationDest :
inflation_dest = None
else :
inflation_dest = encode_check ( 'account' , op_xdr_object... |
def seek ( self , offset , whence = 0 ) :
"""Set the file ' s current position .
See ` file . seek ` for details .""" | self . flush ( )
if whence == self . SEEK_SET :
self . _realpos = self . _pos = offset
elif whence == self . SEEK_CUR :
self . _pos += offset
self . _realpos = self . _pos
else :
self . _realpos = self . _pos = self . _get_size ( ) + offset
self . _rbuffer = bytes ( ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.