signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def FileEntryExistsByPathSpec ( self , path_spec ) :
"""Determines if a file entry for a path specification exists .
Args :
path _ spec ( PathSpec ) : path specification .
Returns :
bool : True if the file entry exists .""" | # Opening a file by inode number is faster than opening a file by location .
tsk_file = None
inode = getattr ( path_spec , 'inode' , None )
location = getattr ( path_spec , 'location' , None )
try :
if inode is not None :
tsk_file = self . _tsk_file_system . open_meta ( inode = inode )
elif location is ... |
def make_qadapter ( ** kwargs ) :
"""Return the concrete : class : ` QueueAdapter ` class from a string .
Note that one can register a customized version with :
. . example : :
from qadapters import SlurmAdapter
class MyAdapter ( SlurmAdapter ) :
QTYPE = " myslurm "
# Add your customized code here
# R... | # Get all known subclasses of QueueAdapter .
d = { c . QTYPE : c for c in all_subclasses ( QueueAdapter ) }
# Preventive copy before pop
kwargs = copy . deepcopy ( kwargs )
qtype = kwargs [ "queue" ] . pop ( "qtype" )
return d [ qtype ] ( ** kwargs ) |
def pipeline_filepath ( pm , filename = None , suffix = None ) :
"""Derive path to file for managed pipeline .
: param pypiper . PipelineManager | pypiper . Pipeline pm : Manager of a
particular pipeline instance .
: param str filename : Name of file for which to create full path based
on pipeline ' s outpu... | if filename is None and suffix is None :
raise TypeError ( "Provide filename and/or suffix to create " "path to a pipeline file." )
filename = ( filename or pm . name ) + ( suffix or "" )
# Note that Pipeline and PipelineManager define the same outfolder .
# In fact , a Pipeline just references its manager ' s outf... |
def add_reaction_constraints ( model , reactions , Constraint ) :
"""Add the stoichiometric coefficients as constraints .
Parameters
model : optlang . Model
The transposed stoichiometric matrix representation .
reactions : iterable
Container of ` cobra . Reaction ` instances .
Constraint : optlang . Con... | constraints = [ ]
for rxn in reactions :
expression = add ( [ c * model . variables [ m . id ] for m , c in rxn . metabolites . items ( ) ] )
constraints . append ( Constraint ( expression , lb = 0 , ub = 0 , name = rxn . id ) )
model . add ( constraints ) |
def call_api ( self , request_data , service , action , idempotency = False , ** kwargs ) :
"""This will call the adyen api . username , password , merchant _ account ,
and platform are pulled from root module level and or self object .
AdyenResult will be returned on 200 response . Otherwise , an exception
i... | if not self . http_init :
self . http_client = HTTPClient ( self . app_name , self . USER_AGENT_SUFFIX , self . LIB_VERSION , self . http_force )
self . http_init = True
# username at self object has highest priority . fallback to root module
# and ensure that it is set .
if self . xapikey :
xapikey = self ... |
def find_value_type ( global_ns , value_type_str ) :
"""implementation details""" | if not value_type_str . startswith ( '::' ) :
value_type_str = '::' + value_type_str
found = global_ns . decls ( name = value_type_str , function = lambda decl : not isinstance ( decl , calldef . calldef_t ) , allow_empty = True )
if not found :
no_global_ns_value_type_str = value_type_str [ 2 : ]
if no_glo... |
def lambda_handler ( event , context ) :
"""Main handler .""" | email = event . get ( 'email' , None )
api_key = event . get ( 'api_key' , None )
if not ( api_key or email ) :
msg = "Missing authentication parameters in your request"
return { 'success' : False , 'message' : msg }
indicators = list ( set ( event . get ( 'indicators' , list ( ) ) ) )
if len ( indicators ) == ... |
def extract_rows ( self , result = { } , selector = '' , table_headers = [ ] , attr = '' , connector = '' , default = '' , verbosity = 0 , * args , ** kwargs ) :
"""Row data extraction for extract _ tabular""" | result_list = [ ]
try :
values = self . get_tree_tag ( selector )
if len ( table_headers ) >= len ( values ) :
from itertools import izip_longest
pairs = izip_longest ( table_headers , values , fillvalue = default )
else :
from itertools import izip
pairs = izip ( table_heade... |
def fetch ( self ) :
"""Fetch a ReservationInstance
: returns : Fetched ReservationInstance
: rtype : twilio . rest . taskrouter . v1 . workspace . task . reservation . ReservationInstance""" | params = values . of ( { } )
payload = self . _version . fetch ( 'GET' , self . _uri , params = params , )
return ReservationInstance ( self . _version , payload , workspace_sid = self . _solution [ 'workspace_sid' ] , task_sid = self . _solution [ 'task_sid' ] , sid = self . _solution [ 'sid' ] , ) |
def kill ( self ) :
"""Remove the socket as it is no longer needed .""" | try :
os . unlink ( self . server_address )
except OSError :
if os . path . exists ( self . server_address ) :
raise |
def _Function ( self , t ) :
"""Handle function definitions""" | if t . decorators is not None :
self . _fill ( "@" )
self . _dispatch ( t . decorators )
self . _fill ( "def " + t . name + "(" )
defaults = [ None ] * ( len ( t . argnames ) - len ( t . defaults ) ) + list ( t . defaults )
for i , arg in enumerate ( zip ( t . argnames , defaults ) ) :
self . _write ( arg [... |
def error ( self , msg = 'Program error: {err}' , exit = None ) :
"""Error handler factory
This function takes a message with optional ` ` { err } ` ` placeholder and
returns a function that takes an exception object , prints the error
message to STDERR and optionally quits .
If no message is supplied ( e .... | def handler ( exc ) :
if msg :
self . perr ( msg . format ( err = exc ) )
if exit is not None :
self . quit ( exit )
return handler |
def recordData ( self , measurementId , deviceId , data ) :
"""Passes the data to the handler .
: param deviceId : the device the data comes from .
: param measurementId : the measurement id .
: param data : the data .
: return : true if the data was handled .""" | am , handler = self . getDataHandler ( measurementId , deviceId )
if handler is not None :
am . stillRecording ( deviceId , len ( data ) )
handler . handle ( data )
return True
else :
logger . error ( 'Received data for unknown handler ' + deviceId + '/' + measurementId )
return False |
def __authenticate ( self ) :
"""Sends a json payload with the email and password in order to get the
authentication api _ token to be used with the rest of the requests""" | if self . api_token : # verify current API token
check_auth_uri = self . uri . split ( '/api/v1' ) [ 0 ] + '/check_token'
req = self . request ( check_auth_uri )
try :
ping = req . get ( ) . json ( )
except Exception as exc :
if str ( exc ) . startswith ( 'User not authenticated' ) :
... |
def filter ( self , chamber , congress = CURRENT_CONGRESS , ** kwargs ) :
"""Takes a chamber and Congress ,
OR state and district , returning a list of members""" | check_chamber ( chamber )
kwargs . update ( chamber = chamber , congress = congress )
if 'state' in kwargs and 'district' in kwargs :
path = ( "members/{chamber}/{state}/{district}/" "current.json" ) . format ( ** kwargs )
elif 'state' in kwargs :
path = ( "members/{chamber}/{state}/" "current.json" ) . format ... |
def troll ( roll , dec , v2 , v3 ) :
"""Computes the roll angle at the target position based on : :
the roll angle at the V1 axis ( roll ) ,
the dec of the target ( dec ) , and
the V2 / V3 position of the aperture ( v2 , v3 ) in arcseconds .
Based on the algorithm provided by Colin Cox that is used in
Gen... | # Convert all angles to radians
_roll = DEGTORAD ( roll )
_dec = DEGTORAD ( dec )
_v2 = DEGTORAD ( v2 / 3600. )
_v3 = DEGTORAD ( v3 / 3600. )
# compute components
sin_rho = sqrt ( ( pow ( sin ( _v2 ) , 2 ) + pow ( sin ( _v3 ) , 2 ) ) - ( pow ( sin ( _v2 ) , 2 ) * pow ( sin ( _v3 ) , 2 ) ) )
rho = asin ( sin_rho )
beta ... |
def mean ( self ) :
"""Mean of the distribution .""" | _self = self . _discard_value ( None )
if not _self . total ( ) :
return None
weighted_sum = sum ( key * value for key , value in iteritems ( _self ) )
return weighted_sum / float ( _self . total ( ) ) |
def switch_positions ( elems ) :
"""This function switches the position of every nth value with ( n + 1 ) th value in a given list .
Examples :
switch _ positions ( [ 0 , 1 , 2 , 3 , 4 , 5 ] ) - > [ 1 , 0 , 3 , 2 , 5 , 4]
switch _ positions ( [ 5 , 6 , 7 , 8 , 9 , 10 ] ) - > [ 6 , 5 , 8 , 7 , 10 , 9]
switch... | from itertools import tee , chain , zip_longest
( elems1 , elems2 ) = tee ( iter ( elems ) , 2 )
return list ( chain . from_iterable ( zip_longest ( elems [ 1 : : 2 ] , elems [ : : 2 ] ) ) ) |
def _dim_attribute ( self , attr , * args , ** kwargs ) :
"""Returns a list of dimension attribute attr , for the
dimensions specified as strings in args .
. . code - block : : python
ntime , nbl , nchan = cube . _ dim _ attribute ( ' global _ size ' , ' ntime ' , ' nbl ' , ' nchan ' )
or
. . code - block... | import re
# If we got a single string argument , try splitting it by separators
if len ( args ) == 1 and isinstance ( args [ 0 ] , str ) :
args = ( s . strip ( ) for s in re . split ( ',|:|;| ' , args [ 0 ] ) )
# Now get the specific attribute for each string dimension
# Integers are returned as is
result = [ d if ... |
def _init ( self , trcback ) :
"""format a traceback from sys . exc _ info ( ) into 7 - item tuples ,
containing the regular four traceback tuple items , plus the original
template filename , the line number adjusted relative to the template
source , and code line from that line number of the template .""" | import mako . template
mods = { }
rawrecords = traceback . extract_tb ( trcback )
new_trcback = [ ]
for filename , lineno , function , line in rawrecords :
if not line :
line = ''
try :
( line_map , template_lines ) = mods [ filename ]
except KeyError :
try :
info = mako ... |
def convert_reshape ( node , ** kwargs ) :
"""Map MXNet ' s Reshape operator attributes to onnx ' s Reshape operator .
Converts output shape attribute to output shape tensor
and return multiple created nodes .""" | name , input_nodes , attrs = get_inputs ( node , kwargs )
output_shape_list = convert_string_to_list ( attrs [ "shape" ] )
initializer = kwargs [ "initializer" ]
output_shape_np = np . array ( output_shape_list , dtype = 'int64' )
data_type = onnx . mapping . NP_TYPE_TO_TENSOR_TYPE [ output_shape_np . dtype ]
dims = np... |
def _DownloadTS05Data ( Overwrite = False ) :
'''This function will try to download all existing TS05 archives and
extract them in $ GEOPACK _ PATH / tab .''' | Year = 1995
Cont = True
OutPath = Globals . DataPath + 'tab/'
cmd0 = 'wget -nv --show-progress '
cmd0 += 'http://geo.phys.spbu.ru/~tsyganenko/TS05_data_and_stuff/{:4d}_OMNI_5m_with_TS05_variables.zip'
cmd0 += ' -O ' + OutPath + '{:04d}.zip'
cmd1 = 'unzip ' + OutPath + '{:04d}.zip -d ' + OutPath
cmd2 = 'rm -v ' + OutPat... |
def add_distances ( self , indices , periodic = True , indices2 = None ) :
r"""Adds the distances between atoms to the feature list .
Parameters
indices : can be of two types :
ndarray ( ( n , 2 ) , dtype = int ) :
n x 2 array with the pairs of atoms between which the distances shall be computed
iterable ... | from . distances import DistanceFeature
atom_pairs = _parse_pairwise_input ( indices , indices2 , self . logger , fname = 'add_distances()' )
atom_pairs = self . _check_indices ( atom_pairs )
f = DistanceFeature ( self . topology , atom_pairs , periodic = periodic )
self . __add_feature ( f ) |
def Ctrl_V ( self , delay = 0 ) :
"""Ctrl + V shortcut .""" | self . _delay ( delay )
self . add ( Command ( "KeyDown" , 'KeyDown "%s", %s' % ( BoardKey . Ctrl , 1 ) ) )
self . add ( Command ( "KeyPress" , 'KeyPress "%s", %s' % ( BoardKey . V , 1 ) ) )
self . add ( Command ( "KeyUp" , 'KeyUp "%s", %s' % ( BoardKey . Ctrl , 1 ) ) ) |
def image_single_point_source ( self , image_model_class , kwargs_lens , kwargs_source , kwargs_lens_light , kwargs_ps ) :
"""return model without including the point source contributions as a list ( for each point source individually )
: param image _ model _ class : ImageModel class instance
: param kwargs _ ... | # reconstructed model with given psf
model , error_map , cov_param , param = image_model_class . image_linear_solve ( kwargs_lens , kwargs_source , kwargs_lens_light , kwargs_ps )
# model = image _ model _ class . image ( kwargs _ lens , kwargs _ source , kwargs _ lens _ light , kwargs _ ps )
data = image_model_class .... |
def version_is_valid ( version_str ) :
"""Check to see if the version specified is a valid as far as pkg _ resources is concerned
> > > version _ is _ valid ( ' blah ' )
False
> > > version _ is _ valid ( ' 1.2.3 ' )
True""" | try :
packaging . version . Version ( version_str )
except packaging . version . InvalidVersion :
return False
return True |
def start_session ( self ) :
"""Start the session . Invoke in your @ gen . coroutine wrapped prepare
method like : :
result = yield gen . Task ( self . start _ session )
: rtype : bool""" | self . session = self . _session_start ( )
result = yield gen . Task ( self . session . fetch )
self . _set_session_cookie ( )
if not self . session . get ( 'ip_address' ) :
self . session . ip_address = self . request . remote_ip
self . _last_values ( )
raise gen . Return ( result ) |
def get_find_all_query ( self , table_name , constraints = None , * , columns = None , order_by = None , limiting = ( None , None ) ) :
"""Builds a find query .
: limiting : if present must be a 2 - tuple of ( limit , offset ) either of which can be None .""" | where , params = self . parse_constraints ( constraints )
if columns :
if isinstance ( columns , str ) :
pass
else :
columns = ", " . join ( columns )
else :
columns = "*"
if order_by :
order = " order by {0}" . format ( order_by )
else :
order = ""
paging = ""
if limiting is not Non... |
def one_point_crossover ( parents ) :
"""Perform one point crossover on two parent chromosomes .
Select a random position in the chromosome .
Take genes to the left from one parent and the rest from the other parent .
Ex . p1 = xxxxx , p2 = yyyyy , position = 2 ( starting at 0 ) , child = xxyyy""" | # The point that the chromosomes will be crossed at ( see Ex . above )
crossover_point = random . randint ( 1 , len ( parents [ 0 ] ) - 1 )
return ( _one_parent_crossover ( parents [ 0 ] , parents [ 1 ] , crossover_point ) , _one_parent_crossover ( parents [ 1 ] , parents [ 0 ] , crossover_point ) ) |
def build_tree_from_alignment ( aln , moltype = DNA , best_tree = False , params = { } , working_dir = '/tmp' ) :
"""Returns a tree from Alignment object aln .
aln : an cogent . core . alignment . Alignment object , or data that can be used
to build one .
- Clearcut only accepts aligned sequences . Alignment ... | params [ '--out' ] = get_tmp_filename ( working_dir )
# Create instance of app controller , enable tree , disable alignment
app = Clearcut ( InputHandler = '_input_as_multiline_string' , params = params , WorkingDir = working_dir , SuppressStdout = True , SuppressStderr = True )
# Input is an alignment
app . Parameters... |
def platedir ( self , filetype , ** kwargs ) :
"""Returns plate subdirectory in : envvar : ` PLATELIST _ DIR ` of the form : ` ` NNNNXX / NNNNN ` ` .
Parameters
filetype : str
File type parameter .
plateid : int or str
Plate ID number . Will be converted to int internally .
Returns
platedir : str
Pl... | plateid = int ( kwargs [ 'plateid' ] )
plateid100 = plateid // 100
subdir = "{:0>4d}" . format ( plateid100 ) + "XX"
return os . path . join ( subdir , "{:0>6d}" . format ( plateid ) ) |
def complete_contexts ( self ) :
'''Return a list of interfaces that have satisfied contexts .''' | if self . _complete_contexts :
return self . _complete_contexts
self . context ( )
return self . _complete_contexts |
def get_gene_names ( self ) :
"""Gather gene names of all nodes and node members""" | # Collect all gene names in network
gene_names = [ ]
for node in self . _nodes :
members = node [ 'data' ] . get ( 'members' )
if members :
gene_names += list ( members . keys ( ) )
else :
if node [ 'data' ] [ 'name' ] . startswith ( 'Group' ) :
continue
gene_names . appe... |
def pexpire ( self , name , time ) :
"""Set an expire flag on key ` ` name ` ` for ` ` time ` ` milliseconds .
` ` time ` ` can be represented by an integer or a Python timedelta
object .""" | if isinstance ( time , datetime . timedelta ) :
time = int ( time . total_seconds ( ) * 1000 )
return self . execute_command ( 'PEXPIRE' , name , time ) |
def df2plotshape ( dlen , xlabel_unit , ylabel_unit , suptitle = '' , fix = 'h' , xlabel_skip = [ ] , test = False ) :
"""_ xlen :
_ ylen :
title :""" | dlen [ 'xlabel' ] = dlen . apply ( lambda x : f"{x['_xlen']}" if not x [ 'title' ] in xlabel_skip else '' , axis = 1 )
dlen [ 'ylabel' ] = dlen . apply ( lambda x : "" , axis = 1 )
ylen = dlen [ '_ylen' ] . unique ( ) [ 0 ]
if test :
print ( dlen . columns )
if fix == 'h' :
dlen [ 'xlen' ] = dlen [ '_xlen' ] / ... |
async def get_home_data ( self ) :
"""Get Tautulli home stats .""" | cmd = 'get_home_stats'
url = self . base_url + cmd
data = { }
try :
async with async_timeout . timeout ( 8 , loop = self . _loop ) :
request = await self . _session . get ( url )
response = await request . json ( )
for stat in response . get ( 'response' , { } ) . get ( 'data' , { } ) :
... |
def escape ( self , text , quote = True ) :
"""Escape special characters in HTML""" | if isinstance ( text , bytes ) :
return escape_b ( text , quote )
else :
return escape ( text , quote ) |
def returnList ( self , limit = False ) :
'''Return a list of dictionaries ( and * not * a PLOD class ) .
The list returned maintains the ' types ' of the original entries unless
another operation has explicity changed them . For example , an ' upsert '
replacement of an entry .
Example of use :
> > > tes... | if limit == False :
return self . table
result = [ ]
for i in range ( limit ) :
if len ( self . table ) > i :
result . append ( self . table [ i ] )
return result |
def polygon_to_mask ( coords , dims , z = None ) :
"""Given a list of pairs of points which define a polygon , return a binary
mask covering the interior of the polygon with dimensions dim""" | bounds = array ( coords ) . astype ( 'int' )
path = Path ( bounds )
grid = meshgrid ( range ( dims [ 1 ] ) , range ( dims [ 0 ] ) )
grid_flat = zip ( grid [ 0 ] . ravel ( ) , grid [ 1 ] . ravel ( ) )
mask = path . contains_points ( grid_flat ) . reshape ( dims [ 0 : 2 ] ) . astype ( 'int' )
if z is not None :
if le... |
def expand ( self , line , do_expand , force = False , vislevels = 0 , level = - 1 ) :
"""Multi - purpose expand method from original STC class""" | lastchild = self . GetLastChild ( line , level )
line += 1
while line <= lastchild :
if force :
if vislevels > 0 :
self . ShowLines ( line , line )
else :
self . HideLines ( line , line )
elif do_expand :
self . ShowLines ( line , line )
if level == - 1 :
... |
def _device_expiry_callback ( self ) :
"""Periodic callback to remove expired devices from visible _ devices .""" | expired = 0
for adapters in self . _devices . values ( ) :
to_remove = [ ]
now = monotonic ( )
for adapter_id , dev in adapters . items ( ) :
if 'expires' not in dev :
continue
if now > dev [ 'expires' ] :
to_remove . append ( adapter_id )
local_conn = "ad... |
def pi ( nsteps ) :
sum , step = 0. , 1. / nsteps
"omp parallel for reduction ( + : sum ) private ( x )" | for i in range ( nsteps ) :
x = ( i - 0.5 ) * step
sum += 4. / ( 1. + x ** 2 )
return step * sum |
def order_stop ( backend , order_id ) :
"""Stop an order - Turn off the serving generation ability of an order . Stop any running jobs . Keep all state around .""" | if order_id is None :
raise click . ClickException ( 'invalid order id %s' % order_id )
click . secho ( '%s - Stop order id %s' % ( get_datetime ( ) , order_id ) , fg = 'green' )
check_and_print ( DKCloudCommandRunner . stop_order ( backend . dki , order_id ) ) |
def enable_cpu ( self , rg ) :
'''Enable cpus
rg : range or list of threads to enable''' | if type ( rg ) == int :
rg = [ rg ]
to_disable = set ( rg ) & set ( self . __get_ranges ( "offline" ) )
for cpu in to_disable :
fpath = path . join ( "cpu%i" % cpu , "online" )
self . __write_cpu_file ( fpath , b"1" ) |
def idle_task ( self ) :
'''called rapidly by mavproxy''' | now = time . time ( )
time_delta = now - self . last_calc
if time_delta > 1 :
self . last_calc = now
self . buckets . append ( self . counts )
self . counts = { }
if len ( self . buckets ) > self . max_buckets :
self . buckets = self . buckets [ - self . max_buckets : ] |
def from_string ( string , output_path , options = None , toc = None , cover = None , css = None , config = None , cover_first = None ) :
"""Convert given string / strings to IMG file
: param string :
: param output _ path : path to output PDF file / files . False means file will be returned as string
: param... | rtn = IMGKit ( string , 'string' , options = options , toc = toc , cover = cover , css = css , config = config , cover_first = cover_first )
return rtn . to_img ( output_path ) |
def log_status ( plugin , filename , status ) :
'''Properly display a migration status line''' | display = ':' . join ( ( plugin , filename ) ) + ' '
log . info ( '%s [%s]' , '{:.<70}' . format ( display ) , status ) |
def add_size_info ( self ) :
"""Set size of URL content ( if any ) . .
Should be overridden in subclasses .""" | maxbytes = self . aggregate . config [ "maxfilesizedownload" ]
if self . size > maxbytes :
self . add_warning ( _ ( "Content size %(size)s is larger than %(maxbytes)s." ) % dict ( size = strformat . strsize ( self . size ) , maxbytes = strformat . strsize ( maxbytes ) ) , tag = WARN_URL_CONTENT_SIZE_TOO_LARGE ) |
def delete_request ( self , container , resource = None , query_items = None , accept = None ) :
"""Send a DELETE request .""" | url = self . make_url ( container , resource )
headers = self . _make_headers ( accept )
if query_items and isinstance ( query_items , ( list , tuple , set ) ) :
url += RestHttp . _list_query_str ( query_items )
query_items = None
try :
rsp = requests . delete ( url , params = query_items , headers = header... |
def currency ( s = '' ) :
'dirty float ( strip non - numeric characters )' | if isinstance ( s , str ) :
s = '' . join ( ch for ch in s if ch in floatchars )
return float ( s ) if s else TypedWrapper ( float , None ) |
def umount ( name , device = None , user = None , util = 'mount' ) :
'''Attempt to unmount a device by specifying the directory it is mounted on
CLI Example :
. . code - block : : bash
salt ' * ' mount . umount / mnt / foo
. . versionadded : : 2015.5.0
. . code - block : : bash
salt ' * ' mount . umount... | if util != 'mount' : # This functionality used to live in img . umount _ image
if 'qemu_nbd.clear' in __salt__ :
if 'img.mnt_{0}' . format ( name ) in __context__ :
__salt__ [ 'qemu_nbd.clear' ] ( __context__ [ 'img.mnt_{0}' . format ( name ) ] )
return
mnts = active ( )
if name not ... |
def sign ( allocate_quota_request ) :
"""Obtains a signature for an operation in a ` AllocateQuotaRequest `
Args :
op ( : class : ` endpoints _ management . gen . servicecontrol _ v1 _ messages . Operation ` ) : an
operation used in a ` AllocateQuotaRequest `
Returns :
string : a secure hash generated fro... | if not isinstance ( allocate_quota_request , sc_messages . AllocateQuotaRequest ) :
raise ValueError ( u'Invalid request' )
op = allocate_quota_request . allocateOperation
if op is None or op . methodName is None or op . consumerId is None :
logging . error ( u'Bad %s: not initialized => not signed' , allocate_... |
def volume_show ( self , name ) :
'''Show one volume''' | if self . volume_conn is None :
raise SaltCloudSystemExit ( 'No cinder endpoint available' )
nt_ks = self . volume_conn
volumes = self . volume_list ( search_opts = { 'display_name' : name } , )
volume = volumes [ name ]
# except Exception as esc :
# # volume doesn ' t exist
# log . error ( esc . strerror )
# retur... |
def rolling_window ( arr , window_size , stride = 1 , return_idx = False ) :
"""There is an example of an iterator for pure - Python objects in :
http : / / stackoverflow . com / questions / 6822725 / rolling - or - sliding - window - iterator - in - python
This is a rolling - window iterator Numpy arrays , wit... | window_size = int ( window_size )
stride = int ( stride )
if window_size < 0 or stride < 1 :
raise ValueError
arr_len = len ( arr )
if arr_len < window_size :
if return_idx :
yield ( 0 , arr_len ) , arr
else :
yield arr
ix1 = 0
while ix1 < arr_len :
ix2 = ix1 + window_size
result = a... |
def after_batch ( self , stream_name : str , batch_data : Batch ) -> None :
"""If ` ` stream _ name ` ` equals to : py : attr : ` cxflow . constants . TRAIN _ STREAM ` ,
increase the iterations counter and possibly stop the training ; additionally , call : py : meth : ` _ check _ train _ time ` .
: param stream... | self . _check_train_time ( )
if self . _iters is not None and stream_name == self . _train_stream_name :
self . _iters_done += 1
if self . _iters_done >= self . _iters :
raise TrainingTerminated ( 'Training terminated after iteration {}' . format ( self . _iters_done ) ) |
def to_grey ( self , on : bool = False ) :
"""Change the LED to grey .
: param on : Unused , here for API consistency with the other states
: return : None""" | self . _on = False
self . _load_new ( led_grey ) |
def update ( self , ptime ) :
"""Update tween with the time since the last frame""" | delta = self . delta + ptime
total_duration = self . delay + self . duration
if delta > total_duration :
delta = total_duration
if delta < self . delay :
pass
elif delta == total_duration :
for key , tweenable in self . tweenables :
setattr ( self . target , key , tweenable . target_value )
else :
... |
def local ( self ) :
"""Access the local
: returns : twilio . rest . api . v2010 . account . available _ phone _ number . local . LocalList
: rtype : twilio . rest . api . v2010 . account . available _ phone _ number . local . LocalList""" | if self . _local is None :
self . _local = LocalList ( self . _version , account_sid = self . _solution [ 'account_sid' ] , country_code = self . _solution [ 'country_code' ] , )
return self . _local |
def mv_grid_topology ( pypsa_network , configs , timestep = None , line_color = None , node_color = None , line_load = None , grid_expansion_costs = None , filename = None , arrows = False , grid_district_geom = True , background_map = True , voltage = None , limits_cb_lines = None , limits_cb_nodes = None , xlim = Non... | def get_color_and_size ( name , colors_dict , sizes_dict ) :
if 'BranchTee' in name :
return colors_dict [ 'BranchTee' ] , sizes_dict [ 'BranchTee' ]
elif 'LVStation' in name :
return colors_dict [ 'LVStation' ] , sizes_dict [ 'LVStation' ]
elif 'GeneratorFluctuating' in name :
retur... |
def read_creds_from_aws_credentials_file ( profile_name , credentials_file = aws_credentials_file ) :
"""Read credentials from AWS config file
: param profile _ name :
: param credentials _ file :
: return :""" | credentials = init_creds ( )
profile_found = False
try : # Make sure the ~ . aws folder exists
if not os . path . exists ( aws_config_dir ) :
os . makedirs ( aws_config_dir )
with open ( credentials_file , 'rt' ) as cf :
for line in cf :
profile_line = re_profile_name . match ( line ... |
def post_build ( self , pkt , pay ) :
"""add padding to the frame if required .
note that padding is only added if pay is None / empty . this allows us to add # noqa : E501
any payload after the MACControl * PDU if needed ( piggybacking ) .""" | if not pay :
under_layers_size = self . _get_underlayers_size ( )
frame_size = ( len ( pkt ) + under_layers_size )
if frame_size < 64 :
return pkt + b'\x00' * ( 64 - frame_size )
return pkt + pay |
def set_time ( self , time ) :
"""Set the time marker to a specific time
: param time : Time to set for the time marker on the TimeLine
: type time : float""" | x = self . get_time_position ( time )
_ , y = self . _canvas_ticks . coords ( self . _time_marker_image )
self . _canvas_ticks . coords ( self . _time_marker_image , x , y )
self . _timeline . coords ( self . _time_marker_line , x , 0 , x , self . _timeline . winfo_height ( ) ) |
async def send_all_reactions ( self ) :
"""Sends all reactions for this paginator , if any are missing .
This method is generally for internal use only .""" | for emoji in filter ( None , self . emojis ) :
await self . message . add_reaction ( emoji )
self . sent_page_reactions = True |
def layers ( self , annotationtype = None , set = None ) :
"""Returns a list of annotation layers found * directly * under this element , does not include alternative layers""" | if inspect . isclass ( annotationtype ) :
annotationtype = annotationtype . ANNOTATIONTYPE
return [ x for x in self . select ( AbstractAnnotationLayer , set , False , True ) if annotationtype is None or x . ANNOTATIONTYPE == annotationtype ] |
def get_file_history ( self , path , limit = None ) :
"""Returns history of file as reversed list of ` ` Changeset ` ` objects for
which file at given ` ` path ` ` has been modified .""" | fctx = self . _get_filectx ( path )
hist = [ ]
cnt = 0
for cs in reversed ( [ x for x in fctx . filelog ( ) ] ) :
cnt += 1
hist . append ( hex ( fctx . filectx ( cs ) . node ( ) ) )
if limit and cnt == limit :
break
return [ self . repository . get_changeset ( node ) for node in hist ] |
def serial_packet ( self , event ) :
"""Handles incoming raw sensor data
: param data : raw incoming data""" | self . log ( 'Incoming serial packet:' , event . __dict__ , lvl = verbose )
if self . scanning :
pass
else : # self . log ( " Incoming data : " , ' % . 50s . . . ' % event . data , lvl = debug )
sanitized_data = self . _parse ( event . bus , event . data )
self . log ( 'Sanitized data:' , sanitized_data , l... |
def gtd7 ( Input , flags , output ) :
'''The standard model subroutine ( GTD7 ) always computes the
‘ ‘ thermospheric ’ ’ mass density by explicitly summing the masses of
the species in equilibrium at the thermospheric temperature T ( z ) .''' | mn3 = 5
zn3 = [ 32.5 , 20.0 , 15.0 , 10.0 , 0.0 ]
mn2 = 4
zn2 = [ 72.5 , 55.0 , 45.0 , 32.5 ]
zmix = 62.5
soutput = nrlmsise_output ( )
tselec ( flags ) ;
# / * Latitude variation of gravity ( none for sw [ 2 ] = 0 ) * /
xlat = Input . g_lat ;
if ( flags . sw [ 2 ] == 0 ) : # pragma : no cover
xlat = 45.0 ;
glatf (... |
def configure ( self ) :
"""Configure the device .
Send the device configuration saved inside the MCP342x object to the target device .""" | logger . debug ( 'Configuring ' + hex ( self . get_address ( ) ) + ' ch: ' + str ( self . get_channel ( ) ) + ' res: ' + str ( self . get_resolution ( ) ) + ' gain: ' + str ( self . get_gain ( ) ) )
self . bus . write_byte ( self . address , self . config ) |
def _retrieve ( self , * criterion ) :
"""Retrieve a model by some criteria .
: raises ` ModelNotFoundError ` if the row cannot be deleted .""" | try :
return self . _query ( * criterion ) . one ( )
except NoResultFound as error :
raise ModelNotFoundError ( "{} not found" . format ( self . model_class . __name__ , ) , error , ) |
def get_tunnel_info_output_tunnel_admin_state ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_tunnel_info = ET . Element ( "get_tunnel_info" )
config = get_tunnel_info
output = ET . SubElement ( get_tunnel_info , "output" )
tunnel = ET . SubElement ( output , "tunnel" )
admin_state = ET . SubElement ( tunnel , "admin-state" )
admin_state . text = kwargs . pop ( 'admin_stat... |
def updateComponentStartVals ( self ) :
"""Go through selected components for each auto parameter and set the start value""" | for param in self . _parameters :
for component in param [ 'selection' ] :
if param [ 'parameter' ] == 'filename' :
component . set ( param [ 'parameter' ] , param [ 'names' ] [ 0 ] )
else :
component . set ( param [ 'parameter' ] , param [ 'start' ] ) |
def solve ( self ) :
"""Runs the Dancing Links / Algorithm X solver on the Sudoku .
This code has been adapted from http : / / www . cs . mcgill . ca / ~ aassaf9 / python / algorithm _ x . html
: return : List of lists with the same size as the input Sudoku , representing solutions .
: rtype : list""" | R , C = int ( math . sqrt ( len ( self . sudoku ) ) ) , int ( math . sqrt ( len ( self . sudoku [ 0 ] ) ) )
N = R * C
X = ( [ ( "rc" , rc ) for rc in product ( range ( N ) , range ( N ) ) ] + [ ( "rn" , rn ) for rn in product ( range ( N ) , range ( 1 , N + 1 ) ) ] + [ ( "cn" , cn ) for cn in product ( range ( N ) , ra... |
def GetAllPackages ( classification ) :
"""Gets a list of all Blueprint Packages with a given classification .
https : / / t3n . zendesk . com / entries / 20411357 - Get - Packages
: param classification : package type filter ( System , Script , Software )""" | packages = [ ]
for visibility in Blueprint . visibility_stoi . keys ( ) :
try :
for r in Blueprint . GetPackages ( classification , visibility ) :
packages . append ( dict ( r . items ( ) + { 'Visibility' : visibility } . items ( ) ) )
except :
pass
if len ( packages ) :
return (... |
def _pre_train ( self , stop_param_updates , num_epochs , updates_epoch ) :
"""Set parameters and constants before training .""" | # Calculate the total number of updates given early stopping .
updates = { k : stop_param_updates . get ( k , num_epochs ) * updates_epoch for k , v in self . params . items ( ) }
# Calculate the value of a single step given the number of allowed
# updates .
single_steps = { k : np . exp ( - ( ( 1.0 - ( 1.0 / v ) ) ) *... |
def parse_denovo_params ( user_params = None ) :
"""Return default GimmeMotifs parameters .
Defaults will be replaced with parameters defined in user _ params .
Parameters
user _ params : dict , optional
User - defined parameters .
Returns
params : dict""" | config = MotifConfig ( )
if user_params is None :
user_params = { }
params = config . get_default_params ( )
params . update ( user_params )
if params . get ( "torque" ) :
logger . debug ( "Using torque" )
else :
logger . debug ( "Using multiprocessing" )
params [ "background" ] = [ x . strip ( ) for x in p... |
def img2wav ( path , min_x , max_x , min_y , max_y , window_size = 3 ) :
"""Generate 1 - D data ` ` y = f ( x ) ` ` from a black / white image .
Suppose we have an image like that :
. . image : : images / waveform . png
: align : center
Put some codes : :
> > > from weatherlab . math . img2waveform import... | image = Image . open ( path ) . convert ( "L" )
matrix = np . array ( image ) [ : : - 1 ]
# you can customize the gray scale fix behavior to fit color image
matrix [ np . where ( matrix >= 128 ) ] = 255
matrix [ np . where ( matrix < 128 ) ] = 0
tick_x = ( max_x - min_x ) / matrix . shape [ 1 ]
tick_y = ( max_y - min_y... |
def deregister_image ( self , ami_id , region = 'us-east-1' ) :
"""Deregister an AMI by id
: param ami _ id :
: param region : region to deregister from
: return :""" | deregister_cmd = "aws ec2 --profile {} --region {} deregister-image --image-id {}" . format ( self . aws_project , region , ami_id )
print "De-registering old image, now that the new one exists."
print "De-registering cmd: {}" . format ( deregister_cmd )
res = subprocess . check_output ( shlex . split ( deregister_cmd ... |
def get_my_learning_path_session ( self , proxy ) :
"""Gets the ` ` OsidSession ` ` associated with the my learning path service .
: param proxy : a proxy
: type proxy : ` ` osid . proxy . Proxy ` `
: return : a ` ` MyLearningPathSession ` `
: rtype : ` ` osid . learning . MyLearningPathSession ` `
: rais... | if not self . supports_my_learning_path ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( )
proxy = self . _convert_proxy ( proxy )
try :
session = sessions . MyLearningPathSession ( proxy = proxy , runtime = self . _runtime )
except AttributeError :... |
def is_insertion ( self ) :
"""Does this variant represent the insertion of nucleotides into the
reference genome ?""" | # An insertion would appear in a VCF like C > CT , so that the
# alternate allele starts with the reference nucleotides .
# Since the nucleotide strings may be normalized in the constructor ,
# it ' s worth noting that the normalized form of this variant would be
# ' ' > ' T ' , so that ' T ' . startswith ( ' ' ) still... |
def bind ( self , instance_id : str , binding_id : str , details : BindDetails ) -> Binding :
"""Binding the instance
see openbrokerapi documentation""" | # Find the instance
instance = self . _backend . find ( instance_id )
# Find or create the binding
binding = self . _backend . find ( binding_id , instance )
# Create the binding if needed
return self . _backend . bind ( binding , details . parameters ) |
def check_workers ( self ) :
'''Kill workers that have been pending for a while and check if all workers
are alive .''' | if time . time ( ) - self . _worker_alive_time > 5 :
self . _worker_alive_time = time . time ( )
# join processes if they are now gone , it should not do anything bad
# if the process is still running
[ worker . join ( ) for worker in self . _workers if not worker . is_alive ( ) ]
self . _workers = ... |
def to_frame ( self , slot = SLOT . DEVICE_CONFIG ) :
"""Return the current configuration as a YubiKeyFrame object .""" | data = self . to_string ( )
payload = data . ljust ( 64 , b'\0' )
return yubikey_frame . YubiKeyFrame ( command = slot , payload = payload ) |
def from_config ( cls , cp , data = None , delta_f = None , delta_t = None , gates = None , recalibration = None , ** kwargs ) :
"""Initializes an instance of this class from the given config file .
Parameters
cp : WorkflowConfigParser
Config file parser to read .
data : dict
A dictionary of data , in whi... | prior_section = "marginalized_prior"
args = cls . _init_args_from_config ( cp )
marg_prior = read_distributions_from_config ( cp , prior_section )
if len ( marg_prior ) == 0 :
raise AttributeError ( "No priors are specified for the " "marginalization. Please specify this in a " "section in the config file with head... |
def get_plaintext ( self , id ) : # pylint : disable = invalid - name , redefined - builtin
"""Get a config as plaintext .
: param id : Config ID as an int .
: rtype : string""" | return self . service . get_id ( self . base , id , params = { 'format' : 'text' } ) . text |
async def list ( self , * , filters : Mapping = None ) -> List [ Mapping ] :
"""Return a list of services
Args :
filters : a dict with a list of filters
Available filters :
id = < service id >
label = < service label >
mode = [ " replicated " | " global " ]
name = < service name >""" | params = { "filters" : clean_filters ( filters ) }
response = await self . docker . _query_json ( "services" , method = "GET" , params = params )
return response |
def _construct_rest_api ( self ) :
"""Constructs and returns the ApiGateway RestApi .
: returns : the RestApi to which this SAM Api corresponds
: rtype : model . apigateway . ApiGatewayRestApi""" | rest_api = ApiGatewayRestApi ( self . logical_id , depends_on = self . depends_on , attributes = self . resource_attributes )
rest_api . BinaryMediaTypes = self . binary_media
rest_api . MinimumCompressionSize = self . minimum_compression_size
if self . endpoint_configuration :
self . _set_endpoint_configuration ( ... |
def _expandDH ( self , sampling , lmax , lmax_calc ) :
"""Evaluate the coefficients on a Driscoll and Healy ( 1994 ) grid .""" | if self . normalization == '4pi' :
norm = 1
elif self . normalization == 'schmidt' :
norm = 2
elif self . normalization == 'unnorm' :
norm = 3
elif self . normalization == 'ortho' :
norm = 4
else :
raise ValueError ( "Normalization must be '4pi', 'ortho', 'schmidt', or " + "'unnorm'. Input value was... |
def wrap_line ( line , limit = None , chars = 80 ) :
"""Wraps the specified line of text on whitespace to make sure that none of the
lines ' lengths exceeds ' chars ' characters .""" | result = [ ]
builder = [ ]
length = 0
if limit is not None :
sline = line [ 0 : limit ]
else :
sline = line
for word in sline . split ( ) :
if length <= chars :
builder . append ( word )
length += len ( word ) + 1
else :
result . append ( ' ' . join ( builder ) )
builder ... |
def wiki_versions_list ( self , page_id , updater_id ) :
"""Return a list of wiki page version .
Parameters :
page _ id ( int ) :
updater _ id ( int ) :""" | params = { 'earch[updater_id]' : updater_id , 'search[wiki_page_id]' : page_id }
return self . _get ( 'wiki_page_versions.json' , params ) |
def bmp_server_add ( self , address , port ) :
"""This method registers a new BMP ( BGP monitoring Protocol )
server . The BGP speaker starts to send BMP messages to the
server . Currently , only one BMP server can be registered .
` ` address ` ` specifies the IP address of a BMP server .
` ` port ` ` speci... | func_name = 'bmp.start'
param = { 'host' : address , 'port' : port , }
call ( func_name , ** param ) |
def add_exception_handler ( self , exception_handler ) : # type : ( AbstractExceptionHandler ) - > None
"""Register input to the exception handlers list .
: param exception _ handler : Exception Handler instance to be
registered .
: type exception _ handler : AbstractExceptionHandler
: return : None""" | if exception_handler is None :
raise RuntimeConfigException ( "Valid Exception Handler instance to be provided" )
if not isinstance ( exception_handler , AbstractExceptionHandler ) :
raise RuntimeConfigException ( "Input should be an ExceptionHandler instance" )
self . exception_handlers . append ( exception_ha... |
def _set_cfm_state ( self , v , load = False ) :
"""Setter method for cfm _ state , mapped from YANG variable / cfm _ state ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ cfm _ state is considered as a private
method . Backends looking to populate this ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = cfm_state . cfm_state , is_container = 'container' , presence = False , yang_name = "cfm-state" , rest_name = "cfm-state" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths ... |
def on ( self , event , handler = None ) :
"""Register an event handler .
: param event : The event name . Can be ` ` ' connect ' ` ` , ` ` ' message ' ` ` or
` ` ' disconnect ' ` ` .
: param handler : The function that should be invoked to handle the
event . When this parameter is not given , the method
... | if event not in self . event_names :
raise ValueError ( 'Invalid event' )
def set_handler ( handler ) :
self . handlers [ event ] = handler
return handler
if handler is None :
return set_handler
set_handler ( handler ) |
def _merge_two ( res1 , res2 , compute_aux = False ) :
"""Internal method used to merges two runs with differing ( possibly variable )
numbers of live points into one run .
Parameters
res1 : : class : ` ~ dynesty . results . Results ` instance
The " base " nested sampling run .
res2 : : class : ` ~ dynest... | # Initialize the first ( " base " ) run .
base_id = res1 . samples_id
base_u = res1 . samples_u
base_v = res1 . samples
base_logl = res1 . logl
base_nc = res1 . ncall
base_it = res1 . samples_it
nbase = len ( base_id )
# Number of live points throughout the run .
try :
base_n = res1 . samples_n
except :
niter ,... |
def override_ssh_auth_env ( ) :
"""Override the ` $ SSH _ AUTH _ SOCK ` env variable to mock the absence of an SSH agent .""" | ssh_auth_sock = "SSH_AUTH_SOCK"
old_ssh_auth_sock = os . environ . get ( ssh_auth_sock )
del os . environ [ ssh_auth_sock ]
yield
if old_ssh_auth_sock :
os . environ [ ssh_auth_sock ] = old_ssh_auth_sock |
def prepare_model_data ( self , packages , linked , pip = None , private_packages = None ) :
"""Prepare downloaded package info along with pip pacakges info .""" | logger . debug ( '' )
return self . _prepare_model_data ( packages , linked , pip = pip , private_packages = private_packages ) |
def fileRefDiscovery ( self ) :
'''Finds the missing components for file nodes by parsing the Doxygen xml ( which is
just the ` ` doxygen _ output _ dir / node . refid ` ` ) . Additional items parsed include
adding items whose ` ` refid ` ` tag are used in this file , the < programlisting > for
the file , wha... | if not os . path . isdir ( configs . _doxygen_xml_output_directory ) :
utils . fancyError ( "The doxygen xml output directory [{0}] is not valid!" . format ( configs . _doxygen_xml_output_directory ) )
# parse the doxygen xml file and extract all refid ' s put in it
# keys : file object , values : list of refid ' s... |
def shards ( self ) :
"""Retrieves information about the shards in the current remote database .
: returns : Shard information retrieval status in JSON format""" | url = '/' . join ( ( self . database_url , '_shards' ) )
resp = self . r_session . get ( url )
resp . raise_for_status ( )
return response_to_json_dict ( resp ) |
def cancel_job ( self , job_id , project = None , location = None , retry = DEFAULT_RETRY ) :
"""Attempt to cancel a job from a job ID .
See
https : / / cloud . google . com / bigquery / docs / reference / rest / v2 / jobs / cancel
Arguments :
job _ id ( str ) : Unique job identifier .
Keyword Arguments :... | extra_params = { "projection" : "full" }
if project is None :
project = self . project
if location is None :
location = self . location
if location is not None :
extra_params [ "location" ] = location
path = "/projects/{}/jobs/{}/cancel" . format ( project , job_id )
resource = self . _call_api ( retry , me... |
def iter ( self , offs ) :
'''Iterate over items in a sequence from a given offset .
Args :
offs ( int ) : The offset to begin iterating from .
Yields :
( indx , valu ) : The index and valu of the item .''' | startkey = s_common . int64en ( offs )
for lkey , lval in self . slab . scanByRange ( startkey , db = self . db ) :
indx = s_common . int64un ( lkey )
valu = s_msgpack . un ( lval )
yield indx , valu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.