signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def filterAllOr ( self , ** kwargs ) :
'''filterAllOr - Perform a filter operation on ALL nodes in this collection and all their children .
Results must match ANY the filter criteria . for ALL , use the * And methods
For just the nodes in this collection , use " filterOr " on a TagCollection
For special filte... | if canFilterTags is False :
raise NotImplementedError ( 'filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust "find" method, or the getElement* methods.' )
allNodes = self . getAllNodes ( )
filterableNodes = FilterableTagCollection ( allNodes )
return filt... |
def put ( self , taskid , priority = 0 , exetime = 0 ) :
"""Put a task into task queue
when use heap sort , if we put tasks ( with the same priority and exetime = 0 ) into queue ,
the queue is not a strict FIFO queue , but more like a FILO stack .
It is very possible that when there are continuous big flow , ... | now = time . time ( )
task = InQueueTask ( taskid , priority , exetime )
self . mutex . acquire ( )
if taskid in self . priority_queue :
self . priority_queue . put ( task )
elif taskid in self . time_queue :
self . time_queue . put ( task )
elif taskid in self . processing and self . processing [ taskid ] . ta... |
def gte ( min_value ) :
"""Validates that a field value is greater than or equal to the
value given to this validator .""" | def validate ( value ) :
if value < min_value :
return e ( "{} is not greater than or equal to {}" , value , min_value )
return validate |
def get_fixed_long_line ( target , previous_line , original , indent_word = ' ' , max_line_length = 79 , aggressive = False , experimental = False , verbose = False ) :
"""Break up long line and return result .
Do this by generating multiple reformatted candidates and then
ranking the candidates to heuristic... | indent = _get_indentation ( target )
source = target [ len ( indent ) : ]
assert source . lstrip ( ) == source
assert not target . lstrip ( ) . startswith ( '#' )
# Check for partial multiline .
tokens = list ( generate_tokens ( source ) )
candidates = shorten_line ( tokens , source , indent , indent_word , max_line_le... |
def calc_density ( self , density_standard = None ) :
"""Calculates the density of the SpectralColor . By default , Status T
density is used , and the correct density distribution ( Red , Green ,
or Blue ) is chosen by comparing the Red , Green , and Blue components of
the spectral sample ( the values being r... | if density_standard is not None :
return density . ansi_density ( self , density_standard )
else :
return density . auto_density ( self ) |
def wait_for_browser_close ( b ) :
"""Can be used to wait until a TBrowser is closed""" | if b :
if not __ACTIVE :
wait_failover ( wait_for_browser_close )
return
wait_for_frame ( b . GetBrowserImp ( ) . GetMainFrame ( ) ) |
def tzname ( self , dt ) :
"""datetime - > string name of time zone .""" | tt = _localtime ( _mktime ( ( dt . year , dt . month , dt . day , dt . hour , dt . minute , dt . second , dt . weekday ( ) , 0 , - 1 ) ) )
return _time . tzname [ tt . tm_isdst > 0 ] |
def move ( self , lr , fb , vv , va ) :
"""Makes the drone move ( translate / rotate ) .
Parameters :
lr - - left - right tilt : float [ - 1 . . 1 ] negative : left , positive : right
fb - - front - back tilt : float [ - 1 . . 1 ] negative : forwards , positive :
backwards
vv - - vertical speed : float [ ... | self . at ( ardrone . at . pcmd , True , lr , fb , vv , va ) |
def verify_http_auth_token ( self ) -> bool :
"""Use request information to validate JWT""" | authorization_token = self . get_http_token ( )
if authorization_token is not None :
if self . verify_token ( authorization_token ) :
if self . data is not None :
self . data = self . data [ 'data' ]
return True
return False
else :
return False
return False |
def write_16S_rRNA_fasta ( self , org_list ) :
'''Writes a fasta file containing 16S rRNA sequences
for a list of Organism objects ,
The first 16S sequence found in the seq record object is used ,
since it looks like there are duplicates''' | fasta = [ ]
for org in org_list :
handle = open ( org . genome_path , "rU" )
seq_record = SeqIO . read ( handle , "genbank" )
for feat in seq_record . features :
if feat . type == 'rRNA' :
if '16S ribosomal' in feat . qualifiers [ 'product' ] [ 0 ] :
start = feat . locati... |
def increment ( self , key : Any , by : int = 1 ) -> None :
"""Increments the value set against a key . If the key is not present , 0 is assumed as the initial state""" | if key is not None :
self [ key ] = self . get ( key , 0 ) + by |
def unlock_file ( filename ) :
'''Unlock a locked file
Note that these locks are only recognized by Salt Cloud , and not other
programs or platforms .''' | log . trace ( 'Removing lock for %s' , filename )
lock = filename + '.lock'
try :
os . remove ( lock )
except OSError as exc :
log . trace ( 'Unable to remove lock for %s: %s' , filename , exc ) |
def debug ( self ) :
"""Retrieve the debug information from the identity manager .""" | url = '{}debug/status' . format ( self . url )
try :
return make_request ( url , timeout = self . timeout )
except ServerError as err :
return { "error" : str ( err ) } |
def run_show_config ( args ) :
"""Show the current configuration""" | # TODO Proposal : remove the " hidden " configuration . Only show config . If
# the system needs to be configured , then display information on how to
# configure the system .
config = copy . deepcopy ( bigchaindb . config )
del config [ 'CONFIGURED' ]
print ( json . dumps ( config , indent = 4 , sort_keys = True ) ) |
def make_linked_folder ( sym_path ) :
"""Create a folder in the ~ / . autolens directory and create a sym link to it at the provided path .
If both folders already exist then nothing is changed . If the source folder exists but the destination folder does
not then the source folder is removed and replaced so as... | source_path = path_for ( sym_path )
if os . path . exists ( source_path ) and not os . path . exists ( sym_path ) :
logger . debug ( "Source {} exists but target {} does not. Removing source." . format ( source_path , sym_path ) )
shutil . rmtree ( source_path )
try :
logger . debug ( "Making source {}" . f... |
def edit ( cls , record , parent = None , autoCommit = True , title = '' ) :
"""Prompts the user to edit the inputed record .
: param record | < orb . Table >
parent | < QWidget >
: return < bool > | accepted""" | dlg = cls . getDialog ( 'edit' , parent )
# update the title
try :
name = record . schema ( ) . displayName ( )
except AttributeError :
name = record . __class__ . __name__
if not title :
title = 'Edit {0}' . format ( name )
dlg . setWindowTitle ( title )
widget = dlg . _mainwidget
widget . setRecord ( reco... |
def sweep ( port , rate , ID , retry = 3 ) :
"""Sends a ping packet to ID ' s from 0 to maximum and prints out any returned
messages .
Actually send a broadcast and will retry ( resend ) the ping 3 times . . .""" | if port == 'dummy' :
s = ServoSerial ( port , rate , fake = True )
else :
s = ServoSerial ( port , rate )
if ID < 0 :
ID = xl320 . XL320_BROADCAST_ADDR
try :
s . open ( )
except SerialException as e : # print ( ' Error opening serial port : ' )
print ( '-' * 40 )
print ( sys . argv [ 0 ] , ':' )... |
def option ( self , key , value ) :
"""Adds an input option for the underlying data source .
You can set the following option ( s ) for reading files :
* ` ` timeZone ` ` : sets the string that indicates a timezone to be used to parse timestamps
in the JSON / CSV datasources or partition values .
If it isn ... | self . _jreader = self . _jreader . option ( key , to_str ( value ) )
return self |
def parse ( self , subscription ) :
"""Fetch the function registered for a certain subscription""" | for name in self . methods :
tag = bytes ( name . encode ( 'utf-8' ) )
if subscription . startswith ( tag ) :
fun = self . methods . get ( name )
message = subscription [ len ( tag ) : ]
return tag , message , fun
return None , None , None |
def main ( filename ) :
"""Creates a PDF by embedding the first page from the given image and
writes some text to it .
@ param [ in ] filename
The source filename of the image to embed .""" | # Prepare font .
font_family = 'arial'
font = Font ( font_family , bold = True )
if not font :
raise RuntimeError ( 'No font found for %r' % font_family )
# Initialize PDF document on a stream .
with Document ( 'output.pdf' ) as document : # Initialize a new page and begin its context .
with document . Page ( )... |
def get_structure_by_id ( self , cod_id , ** kwargs ) :
"""Queries the COD for a structure by id .
Args :
cod _ id ( int ) : COD id .
kwargs : All kwargs supported by
: func : ` pymatgen . core . structure . Structure . from _ str ` .
Returns :
A Structure .""" | r = requests . get ( "http://www.crystallography.net/cod/%s.cif" % cod_id )
return Structure . from_str ( r . text , fmt = "cif" , ** kwargs ) |
def publish_extensions ( self , handler ) :
"""Publish the Media RSS Feed elements as XML .""" | if isinstance ( self . media_content , list ) :
[ PyRSS2Gen . _opt_element ( handler , "media:content" , mc_element ) for mc_element in self . media_content ]
else :
PyRSS2Gen . _opt_element ( handler , "media:content" , self . media_content )
if hasattr ( self , 'media_title' ) :
PyRSS2Gen . _opt_element (... |
def pvremove ( devices , override = True ) :
'''Remove a physical device being used as an LVM physical volume
override
Skip devices , if they are already not used as LVM physical volumes
CLI Examples :
. . code - block : : bash
salt mymachine lvm . pvremove / dev / sdb1 , / dev / sdb2''' | if isinstance ( devices , six . string_types ) :
devices = devices . split ( ',' )
cmd = [ 'pvremove' , '-y' ]
for device in devices :
if pvdisplay ( device ) :
cmd . append ( device )
elif not override :
raise CommandExecutionError ( '{0} is not a physical volume' . format ( device ) )
if n... |
def dump_queue ( self , * names ) :
"""Debug - log some of the queues .
` ` names ` ` may include any of " worker " , " available " , " priorities " ,
" expiration " , " workers " , or " reservations _ ITEM " filling in some
specific item .""" | conn = redis . StrictRedis ( connection_pool = self . pool )
for name in names :
if name == 'worker' :
logger . debug ( 'last worker: ' + conn . get ( self . _key_worker ( ) ) )
elif name == 'available' :
logger . debug ( 'available: ' + str ( conn . zrevrange ( self . _key_available ( ) , 0 , -... |
def write_gtfsr ( feed , path , * , to_json = False ) :
"""Given a GTFSR feed ( FeedMessage instance ) , write it to the given
file path ( string or Path object ) .
If ` ` to _ json ` ` , then save the file as JSON ;
otherwise save it as Protocol Buffer .""" | path = Path ( path )
if to_json :
with path . open ( 'w' ) as tgt :
tgt . write ( json_format . MessageToJson ( feed ) )
else :
with path . open ( 'wb' ) as tgt :
tgt . write ( feed . SerializeToString ( ) ) |
def filter_params ( self , src_mod ) :
"""Remove params uneeded by source _ model""" | # point and area related params
STRIKE_PARAMS [ src_mod . num_np : ] = [ ]
DIP_PARAMS [ src_mod . num_np : ] = [ ]
RAKE_PARAMS [ src_mod . num_np : ] = [ ]
NPW_PARAMS [ src_mod . num_np : ] = [ ]
HDEPTH_PARAMS [ src_mod . num_hd : ] = [ ]
HDW_PARAMS [ src_mod . num_hd : ] = [ ]
# planar rupture related params
PLANES_ST... |
def minutes_back ( self , date ) :
'''Gives a number ( integer ) of days
since a given date''' | elapsed = ( datetime . utcnow ( ) - datetime . strptime ( date , '%Y-%m-%dT%H:%M:%S' ) )
if elapsed . days > 0 :
secondsback = ( elapsed . days * 24 * 60 * 60 ) + elapsed . seconds
else :
secondsback = elapsed . seconds
minutesback = secondsback / 60
return int ( minutesback ) |
def patch_mock_desc ( self , patch , * args , ** kwarg ) :
"""Context manager or decorator in order to patch a mock definition of service
endpoint in a test .
: param patch : Dictionary in order to update endpoint ' s mock definition
: type patch : dict
: param service _ name : Name of service where you wan... | return PatchMockDescDefinition ( patch , self , * args , ** kwarg ) |
def verify ( self , func = None , * args , ** kwargs ) :
"""Subtract the rhs from the lhs of the equation
Before the substraction , each side is expanded and any scalars are
simplified . If given , ` func ` with the positional arguments ` args ` and
keyword - arguments ` kwargs ` is applied to the result befo... | res = ( self . lhs . expand ( ) . simplify_scalar ( ) - self . rhs . expand ( ) . simplify_scalar ( ) )
if func is not None :
return func ( res , * args , ** kwargs )
else :
return res |
def read_sql_query ( sql , con , index_col = None , coerce_float = True , params = None , parse_dates = None , chunksize = None ) :
"""Read SQL query into a DataFrame .
Returns a DataFrame corresponding to the result set of the query
string . Optionally provide an ` index _ col ` parameter to use one of the
c... | pandas_sql = pandasSQL_builder ( con )
return pandas_sql . read_query ( sql , index_col = index_col , params = params , coerce_float = coerce_float , parse_dates = parse_dates , chunksize = chunksize ) |
def getv ( self , r ) :
"""Like the above , but returns the < int > value .""" | v = self . get ( r )
if not is_unknown ( v ) :
try :
v = int ( v )
except ValueError :
v = None
else :
v = None
return v |
def fmtdeglat ( radians , norm = 'raise' , precision = 2 , seps = '::' ) :
"""Format a latitudinal angle as sexagesimal degrees in a string .
Arguments are :
radians
The angle , in radians .
norm ( default " raise " )
The normalization mode , used for angles outside of the standard range
of - π / 2 to π... | if norm == 'none' :
pass
elif norm == 'raise' :
if radians > halfpi or radians < - halfpi :
raise ValueError ( 'illegal latitude of %f radians' % radians )
elif norm == 'wrap' :
radians = angcen ( radians )
if radians > halfpi :
radians = pi - radians
elif radians < - halfpi :
... |
def _export_local_images ( project , image , z ) :
"""Take a project file ( . gns3 ) and export images to the zip
: param image : Image path
: param z : Zipfile instance for the export""" | from . . compute import MODULES
for module in MODULES :
try :
img_directory = module . instance ( ) . get_images_directory ( )
except NotImplementedError : # Some modules don ' t have images
continue
directory = os . path . split ( img_directory ) [ - 1 : ] [ 0 ]
if os . path . exists ( ... |
def get_full_import_name ( import_from , name ) :
"""Get the full path of a name from a ` ` from x import y ` ` statement .
: param import _ from : The astroid node to resolve the name of .
: type import _ from : astroid . nodes . ImportFrom
: param name :
: type name : str
: returns : The full import pat... | partial_basename = resolve_import_alias ( name , import_from . names )
module_name = import_from . modname
if import_from . level :
module = import_from . root ( )
assert isinstance ( module , astroid . nodes . Module )
module_name = module . relative_to_absolute_name ( import_from . modname , level = impor... |
def remove_alert_tag ( self , id , tag_value , ** kwargs ) : # noqa : E501
"""Remove a tag from a specific alert # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . remove _ alert _ t... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . remove_alert_tag_with_http_info ( id , tag_value , ** kwargs )
# noqa : E501
else :
( data ) = self . remove_alert_tag_with_http_info ( id , tag_value , ** kwargs )
# noqa : E501
return data |
def sasdata2dataframeCSV ( self , table : str , libref : str = '' , dsopts : dict = None , tempfile : str = None , tempkeep : bool = False , ** kwargs ) -> '<Pandas Data Frame object>' :
"""This method exports the SAS Data Set to a Pandas Data Frame , returning the Data Frame object .
table - the name of the SAS ... | dsopts = dsopts if dsopts is not None else { }
port = kwargs . get ( 'port' , 0 )
if port == 0 and self . sascfg . tunnel : # we are using a tunnel ; default to that port
port = self . sascfg . tunnel
if libref :
tabname = libref + "." + table
else :
tabname = table
tmpdir = None
if tempfile is None :
t... |
def server_status ( profile = 'default' ) :
'''Get Information from the Apache server - status handler
. . note : :
The server - status handler is disabled by default .
In order for this function to work it needs to be enabled .
See http : / / httpd . apache . org / docs / 2.2 / mod / mod _ status . html
... | ret = { 'Scoreboard' : { '_' : 0 , 'S' : 0 , 'R' : 0 , 'W' : 0 , 'K' : 0 , 'D' : 0 , 'C' : 0 , 'L' : 0 , 'G' : 0 , 'I' : 0 , '.' : 0 , } , }
# Get configuration from pillar
url = __salt__ [ 'config.get' ] ( 'apache.server-status:{0}:url' . format ( profile ) , 'http://localhost/server-status' )
user = __salt__ [ 'confi... |
def detuning_combinations ( lists ) :
r"""This function recieves a list of length Nl with the number of
transitions each laser induces . It returns the cartesian product of all
these posibilities as a list of all possible combinations .""" | Nl = len ( lists )
comb = [ [ i ] for i in range ( lists [ 0 ] ) ]
for l in range ( 1 , Nl ) :
combn = [ ]
for c0 in comb :
for cl in range ( lists [ l ] ) :
combn += [ c0 [ : ] + [ cl ] ]
comb = combn [ : ]
return comb |
def total_misses ( self , filename = None ) :
"""Return the total number of uncovered statements for the file
` filename ` . If ` filename ` is not given , return the total
number of uncovered statements for all files .""" | if filename is not None :
return len ( self . missed_statements ( filename ) )
total = 0
for filename in self . files ( ) :
total += len ( self . missed_statements ( filename ) )
return total |
def spa_tmplt_engine ( htilde , kmin , phase_order , delta_f , piM , pfaN , pfa2 , pfa3 , pfa4 , pfa5 , pfl5 , pfa6 , pfl6 , pfa7 , amp_factor ) :
"""Calculate the spa tmplt phase""" | taylorf2_kernel ( htilde . data , kmin , phase_order , delta_f , piM , pfaN , pfa2 , pfa3 , pfa4 , pfa5 , pfl5 , pfa6 , pfl6 , pfa7 , amp_factor ) |
def get_conf_file ( self ) :
"""Get config from local config file , first try cache , then fallback .""" | for conf_file in [ self . collection_rules_file , self . fallback_file ] :
logger . debug ( "trying to read conf from: " + conf_file )
conf = self . try_disk ( conf_file , self . gpg )
if not conf :
continue
version = conf . get ( 'version' , None )
if version is None :
raise ValueEr... |
def map ( self , fn ) :
"""Run a map function across all y points in the series""" | return TimeSeries ( [ ( x , fn ( y ) ) for x , y in self . points ] ) |
def generate ( env ) :
"""Add Builders and construction variables for g + + to an Environment .""" | static_obj , shared_obj = SCons . Tool . createObjBuilders ( env )
if 'CXX' not in env :
env [ 'CXX' ] = env . Detect ( compilers ) or compilers [ 0 ]
cxx . generate ( env )
# platform specific settings
if env [ 'PLATFORM' ] == 'aix' :
env [ 'SHCXXFLAGS' ] = SCons . Util . CLVar ( '$CXXFLAGS -mminimal-toc' )
... |
def update_vpnservice ( self , vpnservice , body = None ) :
"""Updates a VPN service .""" | return self . put ( self . vpnservice_path % ( vpnservice ) , body = body ) |
def processFrame ( frame ) :
"""Simulate a left and right sensor output ( from 0 to 1 ) given the input image .""" | # The pixels are grey - scale values from 0-255 - white = 255 , black = 0
# We want to turn the image into two values , one for the left " sensor " and one for the right .
# There are many possible ways to do this . The very simplest way would be
# to examine the values of two pixels - one in the centre of the left hal... |
def _compare_file ( self , local , remote ) :
"""Byte compare two files ( early out on first difference ) .""" | assert isinstance ( local , FileEntry ) and isinstance ( remote , FileEntry )
if not local or not remote :
write ( " Files cannot be compared ({} != {})." . format ( local , remote ) )
return False
elif local . size != remote . size :
write ( " Files are different (size {:,d} != {:,d})." . format ( lo... |
def convert_symbol ( prototxt_fname ) :
"""Convert caffe model definition into Symbol
Parameters
prototxt _ fname : str
Filename of the prototxt file
Returns
Symbol
Converted Symbol
tuple
Input shape""" | sym , output_name , input_dim = _parse_proto ( prototxt_fname )
exec ( sym )
# pylint : disable = exec - used
_locals = locals ( )
ret = [ ]
for i in output_name :
exec ( "ret = " + i , globals ( ) , _locals )
# pylint : disable = exec - used
ret . append ( _locals [ 'ret' ] )
ret = mx . sym . Group ( ret )... |
def get_host_power_status ( self ) :
"""Request the power state of the server .
: returns : Power State of the server , ' ON ' or ' OFF '
: raises : IloError , on an error from iLO .""" | sushy_system = self . _get_sushy_system ( PROLIANT_SYSTEM_ID )
return GET_POWER_STATE_MAP . get ( sushy_system . power_state ) |
def intersection_update ( self , other ) :
"""Removes intervals from self unless they also exist in other .""" | ivs = list ( self )
for iv in ivs :
if iv not in other :
self . remove ( iv ) |
def cli ( ctx , file , quote ) :
'''This script is used to set , get or unset values from a . env file .''' | ctx . obj = { }
ctx . obj [ 'FILE' ] = file
ctx . obj [ 'QUOTE' ] = quote |
def initiate ( ) :
"""Return some relevant information about the currently running job .""" | print_debug_header ( )
workspace = pipeline . workspace_from_dir ( sys . argv [ 1 ] )
workspace . cd_to_root ( )
job_info = read_job_info ( workspace . job_info_path ( os . environ [ 'JOB_ID' ] ) )
job_info [ 'job_id' ] = int ( os . environ [ 'JOB_ID' ] )
job_info [ 'task_id' ] = int ( os . environ [ 'SGE_TASK_ID' ] ) ... |
def iter_refs ( self , subspace = '' , number = - 1 , etag = None ) :
"""Iterates over references for this repository .
: param str subspace : ( optional ) , e . g . ' tags ' , ' stashes ' , ' notes '
: param int number : ( optional ) , number of refs to return . Default : - 1
returns all available refs
: p... | if subspace :
args = ( 'git' , 'refs' , subspace )
else :
args = ( 'git' , 'refs' )
url = self . _build_url ( * args , base_url = self . _api )
return self . _iter ( int ( number ) , url , Reference , etag = etag ) |
def __get_config_table_options ( conf_file_options ) :
"""Get all table options from the config file
: type conf _ file _ options : ordereddict
: param conf _ file _ options : Dictionary with all config file options
: returns : ordereddict - - E . g . { ' table _ name ' : { } }""" | options = ordereddict ( )
if not conf_file_options :
return options
for table_name in conf_file_options [ 'tables' ] :
options [ table_name ] = { }
# Regular table options
for option in DEFAULT_OPTIONS [ 'table' ] . keys ( ) :
options [ table_name ] [ option ] = DEFAULT_OPTIONS [ 'table' ] [ opt... |
def add_field ( self , attrname , fn , default = None ) :
"""Computes a new attribute for each object in table , or replaces an
existing attribute in each record with a computed value
@ param attrname : attribute to compute for each object
@ type attrname : string
@ param fn : function used to compute new a... | # for rec in self :
def _add_field_to_rec ( rec_ , fn_ = fn , default_ = default ) :
try :
val = fn_ ( rec_ )
except Exception :
val = default_
if isinstance ( rec_ , DataObject ) :
rec_ . __dict__ [ attrname ] = val
else :
setattr ( rec_ , attrname , val )
try :
do_a... |
def broadcast ( self , channel , event , data ) :
"""Broadcasts an event to all sockets listening on a channel .""" | payload = self . _server . serialize_event ( event , data )
for socket_id in self . subscriptions . get ( channel , ( ) ) :
rv = self . _server . sockets . get ( socket_id )
if rv is not None :
rv . socket . send ( payload ) |
def _check_path ( self , src , path_type , dest = None , force = False ) :
"""Check a new destination path in the archive .
Since it is possible for multiple plugins to collect the same
paths , and since plugins can now run concurrently , it is possible
for two threads to race in archive methods : historicall... | dest = dest or self . dest_path ( src )
if path_type == P_DIR :
dest_dir = dest
else :
dest_dir = os . path . split ( dest ) [ 0 ]
if not dest_dir :
return dest
# Check containing directory presence and path type
if os . path . exists ( dest_dir ) and not os . path . isdir ( dest_dir ) :
raise ValueErro... |
def strategize ( generator ) :
"""Add strategy parameters to candidates created by a generator .
This function decorator is used to provide a means of adding strategy
parameters to candidates created by a generator . The generator function
is modifed to extend the candidate with ` ` len ( candidate ) ` ` stra... | @ functools . wraps ( generator )
def strategy_generator ( random , args ) :
candidate = generator ( random , args )
n = len ( candidate )
candidate . extend ( [ random . random ( ) for _ in range ( n ) ] )
return candidate
return strategy_generator |
def _contains_value ( self , value ) :
"""Helper function for _ _ contains _ _ to check a single value is contained within the interval""" | g = operator . gt if self . _lower is self . OPEN else operator . ge
l = operator . lt if self . _upper is self . OPEN else operator . le
return g ( value , self . lower_value ) and l ( value , self . _upper_value ) |
def generate_random_bytes ( self , n_bytes = 32 , output_format = "base64" , mount_point = DEFAULT_MOUNT_POINT ) :
"""Return high - quality random bytes of the specified length .
Supported methods :
POST : / { mount _ point } / random ( / { bytes } ) . Produces : 200 application / json
: param n _ bytes : Spe... | params = { 'bytes' : n_bytes , 'format' : output_format , }
api_path = '/v1/{mount_point}/random' . format ( mount_point = mount_point )
response = self . _adapter . post ( url = api_path , json = params , )
return response . json ( ) |
def phrases_reduce ( key , values ) :
"""Phrases demo reduce function .""" | if len ( values ) < 10 :
return
counts = { }
for filename in values :
counts [ filename ] = counts . get ( filename , 0 ) + 1
words = re . sub ( r":" , " " , key )
threshold = len ( values ) / 2
for filename , count in counts . items ( ) :
if count > threshold :
yield "%s:%s\n" % ( words , filename ... |
def build_bond ( iface , ** settings ) :
'''Create a bond script in / etc / modprobe . d with the passed settings
and load the bonding kernel module .
CLI Example :
. . code - block : : bash
salt ' * ' ip . build _ bond bond0 mode = balance - alb''' | rh_major = __grains__ [ 'osrelease' ] [ : 1 ]
opts = _parse_settings_bond ( settings , iface )
try :
template = JINJA . get_template ( 'conf.jinja' )
except jinja2 . exceptions . TemplateNotFound :
log . error ( 'Could not load template conf.jinja' )
return ''
data = template . render ( { 'name' : iface , '... |
def _processHandler ( self , securityHandler , param_dict ) :
"""proceses the handler and returns the cookiejar""" | cj = None
handler = None
if securityHandler is None :
cj = cookiejar . CookieJar ( )
elif securityHandler . method . lower ( ) == "token" :
param_dict [ 'token' ] = securityHandler . token
if hasattr ( securityHandler , 'cookiejar' ) :
cj = securityHandler . cookiejar
if hasattr ( securityHandle... |
def clean ( self ) :
"""Deletes intermediate products generated for this imageObject .""" | clean_files = [ 'blotImage' , 'crmaskImage' , 'finalMask' , 'staticMask' , 'singleDrizMask' , 'outSky' , 'outSContext' , 'outSWeight' , 'outSingle' , 'outMedian' , 'dqmask' , 'tmpmask' , 'skyMatchMask' ]
log . info ( 'Removing intermediate files for %s' % self . _filename )
# We need to remove the combined products fir... |
def get_function_name ( integration_uri ) :
"""Gets the name of the function from the Integration URI ARN . This is a best effort service which returns None
if function name could not be parsed . This can happen when the ARN is an intrinsic function which is too
complex or the ARN is not a Lambda integration . ... | arn = LambdaUri . _get_function_arn ( integration_uri )
LOG . debug ( "Extracted Function ARN: %s" , arn )
return LambdaUri . _get_function_name_from_arn ( arn ) |
def get_operations ( self , indices : Sequence [ LogicalIndex ] , qubits : Sequence [ ops . Qid ] ) -> ops . OP_TREE :
"""Gets the logical operations to apply to qubits .""" | |
def definition_to_message ( definition , message = None , table_of_contents = None , heading_level = None ) :
"""Helper function to render a definition to a message .
: param definition : A definition dictionary ( see definitions package ) .
: type definition : dict
: param message : The message that the defi... | if message is None :
message = m . Message ( )
if table_of_contents is None :
table_of_contents = m . Message ( )
if heading_level :
_create_section_header ( message , table_of_contents , definition [ 'name' ] . replace ( ' ' , '-' ) , definition [ 'name' ] , heading_level = heading_level )
else :
heade... |
def grow ( self , path ) :
"""Grow the metadata tree for the given directory path
Note : For each path , grow ( ) should be run only once . Growing the tree
from the same path multiple times with attribute adding using the " + "
sign leads to adding the value more than once !""" | if path is None :
return
path = path . rstrip ( "/" )
log . info ( "Walking through directory {0}" . format ( os . path . abspath ( path ) ) )
dirpath , dirnames , filenames = next ( os . walk ( path ) )
# Investigate main . fmf as the first file ( for correct inheritance )
filenames = sorted ( [ filename for filen... |
def create ( self , ** kwargs ) :
"""Creates a new object with the given kwargs , saving it to the database
and returning the created object .""" | obj = self . model ( ** kwargs )
meta = obj . get_meta ( )
meta . connection = get_es_connection ( self . es_url , self . es_kwargs )
meta . index = self . index
meta . type = self . type
obj . save ( force = True )
return obj |
def grouped_mappings ( self , id ) :
"""return all mappings for a node , grouped by ID prefix""" | g = self . get_xref_graph ( )
m = { }
for n in g . neighbors ( id ) :
[ prefix , local ] = n . split ( ':' )
if prefix not in m :
m [ prefix ] = [ ]
m [ prefix ] . append ( n )
return m |
def _download ( url ) :
"""Downloads an URL and returns a file - like object open for reading ,
compatible with zipping . ZipFile ( it has a seek ( ) method ) .""" | fh = StringIO ( )
for line in get ( url ) :
fh . write ( line )
fh . seek ( 0 )
return fh |
def register ( im1 , im2 , params , exact_params = False , verbose = 1 ) :
"""register ( im1 , im2 , params , exact _ params = False , verbose = 1)
Perform the registration of ` im1 ` to ` im2 ` , using the given
parameters . Returns ` ( im1 _ deformed , field ) ` , where ` field ` is a
tuple with arrays desc... | # Clear dir
tempdir = get_tempdir ( )
_clear_temp_dir ( )
# Reference image
refIm = im1
if isinstance ( im1 , ( tuple , list ) ) :
refIm = im1 [ 0 ]
# Check parameters
if not exact_params :
params = _compile_params ( params , refIm )
if isinstance ( params , Parameters ) :
params = params . as_dict ( )
# Gr... |
def get_token ( self ) :
"""Acquires a token for futher API calls , unless you already have a token this will be the first thing
you do before you use this .
: param email : string , the username for your EinsteinVision service , usually in email form
: para pem _ file : string , file containing your Secret k... | payload = { 'aud' : API_OAUTH , 'exp' : time . time ( ) + 600 , # 10 minutes
'sub' : self . email }
header = { 'Content-type' : 'application/x-www-form-urlencoded' }
assertion = jwt . encode ( payload , self . private_key , algorithm = 'RS256' )
assertion = assertion . decode ( 'utf-8' )
response = requests . post ( ur... |
def list_ ( narrow = None , all_versions = False , pre_versions = False , source = None , local_only = False , exact = False ) :
'''Instructs Chocolatey to pull a vague package list from the repository .
Args :
narrow ( str ) :
Term used to narrow down results . Searches against
name / description / tag . D... | choc_path = _find_chocolatey ( __context__ , __salt__ )
cmd = [ choc_path , 'list' ]
if narrow :
cmd . append ( narrow )
if salt . utils . data . is_true ( all_versions ) :
cmd . append ( '--allversions' )
if salt . utils . data . is_true ( pre_versions ) :
cmd . append ( '--prerelease' )
if source :
cm... |
def _download ( uri , user , password ) :
'''# FIXME DOCS''' | if user and password :
logr . debug ( 'AUTH {} at {}' . format ( user , uri ) )
cookieJar = cookielib . CookieJar ( )
opener = urllib2 . build_opener ( urllib2 . HTTPCookieProcessor ( cookieJar ) )
opener . addheaders = [ ( "User-agent" , "Mozilla/5.0 (compatible)" ) ]
urllib2 . install_opener ( ope... |
def trace ( enter = False , exit = True ) :
"""This decorator prints entry and exit message when
the decorated method is called , as well as call
arguments , result and thrown exception ( if any ) .
: param enter : indicates whether entry message should be printed .
: param exit : indicates whether exit mes... | def decorate ( fn ) :
@ inspection . wraps ( fn )
def new_fn ( * args , ** kwargs ) :
name = fn . __module__ + "." + fn . __name__
if enter :
print ( "%s(args = %s, kwargs = %s) <-" % ( name , repr ( args ) , repr ( kwargs ) ) )
try :
result = fn ( * args , ** kwa... |
def create ( self , resource_id = None , attributes = None , ** kwargs ) :
"""Creates an entry with a given ID ( optional ) and attributes .""" | if self . content_type_id is not None :
if attributes is None :
attributes = { }
attributes [ 'content_type_id' ] = self . content_type_id
return super ( EntriesProxy , self ) . create ( resource_id = resource_id , attributes = attributes ) |
def pop ( self , key = - 1 ) :
"""Removes and returns an item at a given index . Similar to list . pop ( ) .""" | value = self . _values [ key ]
self . __delitem__ ( key )
return value |
def PassphraseCallback ( verify = False , prompt1 = "Enter passphrase:" , prompt2 = "Verify passphrase:" ) :
"""A utility function to read a passphrase from stdin .""" | while 1 :
try :
p1 = getpass . getpass ( prompt1 )
if verify :
p2 = getpass . getpass ( prompt2 )
if p1 == p2 :
break
else :
break
except KeyboardInterrupt :
return None
return p1 |
def js_adaptor ( buffer ) :
"""convert javascript objects like true , none , NaN etc . to
quoted word .
Arguments :
buffer : string to be converted
Returns :
string after conversion""" | buffer = re . sub ( 'true' , 'True' , buffer )
buffer = re . sub ( 'false' , 'False' , buffer )
buffer = re . sub ( 'none' , 'None' , buffer )
buffer = re . sub ( 'NaN' , '"NaN"' , buffer )
return buffer |
def addMPCandHumanWealth ( self , solution ) :
'''Take a solution and add human wealth and the bounding MPCs to it .
Parameters
solution : ConsumerSolution
The solution to this period ' s consumption - saving problem .
Returns :
solution : ConsumerSolution
The solution to this period ' s consumption - s... | solution . hNrm = self . hNrmNow
solution . MPCmin = self . MPCminNow
solution . MPCmax = self . MPCmaxEff
return solution |
def _get_body_instance ( self ) :
"""Return the body instance .""" | pyof_class = self . _get_body_class ( )
if pyof_class is None :
return BinaryData ( b'' )
elif pyof_class is DescStats :
return pyof_class ( )
return FixedTypeList ( pyof_class = pyof_class ) |
def get_vlan_brief_output_vlan_vlan_type ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vlan_brief = ET . Element ( "get_vlan_brief" )
config = get_vlan_brief
output = ET . SubElement ( get_vlan_brief , "output" )
vlan = ET . SubElement ( output , "vlan" )
vlan_id_key = ET . SubElement ( vlan , "vlan-id" )
vlan_id_key . text = kwargs . pop ( 'vlan_id' )
vlan_type = E... |
def run ( self , steps = None , resume = False , redo = None ) :
"""Run a Stimela recipe .
steps : recipe steps to run
resume : resume recipe from last run
redo : Re - run an old recipe from a . last file""" | recipe = { "name" : self . name , "steps" : [ ] }
start_at = 0
if redo :
recipe = utils . readJson ( redo )
self . log . info ( 'Rerunning recipe {0} from {1}' . format ( recipe [ 'name' ] , redo ) )
self . log . info ( 'Recreating recipe instance..' )
self . jobs = [ ]
for step in recipe [ 'steps' ... |
def delete_request ( self , user_id , request_id ) :
"""Deletes the Request with the given ID for the given user .""" | return self . request ( "{0}_{1}" . format ( request_id , user_id ) , method = "DELETE" ) |
def parse ( text ) -> Optional [ 'Response' ] :
"""Parse response into an instance of the appropriate child class .""" | # Trim the start and end markers , and ensure only lowercase is used
if text . startswith ( MARKER_START ) and text . endswith ( MARKER_END ) :
text = text [ 1 : len ( text ) - 1 ] . lower ( )
# No - op ; can just ignore these
if not text :
return None
if text . startswith ( CMD_DATETIME ) :
return DateTime... |
def get_output_error ( cmd ) :
"""Return the exit status , stdout , stderr of a command""" | if not isinstance ( cmd , list ) :
cmd = [ cmd ]
logging . debug ( "Running: %s" , ' ' . join ( map ( quote , cmd ) ) )
try :
result = Popen ( cmd , stdout = PIPE , stderr = PIPE )
except IOError as e :
return - 1 , u ( '' ) , u ( 'Failed to run %r: %r' % ( cmd , e ) )
so , se = result . communicate ( )
# u... |
def get_generation_code ( self , ** gencode ) :
"""Generates python code that can create the gate .""" | channels , verts = self . coordinates
channels = ', ' . join ( [ "'{}'" . format ( ch ) for ch in channels ] )
verts = list ( verts )
# # Formatting the vertexes
# List level ( must be first ) , used for gates that may have multiple vertexes like a polygon
if len ( verts ) == 1 :
verts = verts [ 0 ]
# Tuple lev... |
def set_Name ( self , Name , SaveName = None , include = None , ForceUpdate = False ) :
"""Set the Name of the instance , automatically updating the SaveName
The name should be a str without spaces or underscores ( removed )
When the name is changed , if SaveName ( i . e . the name used for saving )
was not u... | self . _dall [ 'Name' ] = Name
self . set_SaveName ( SaveName = SaveName , include = include , ForceUpdate = ForceUpdate ) |
def mcast_ip_mask ( ip_addr_and_mask , return_tuple = True ) :
"""Function to check if a address is multicast and that the CIDR mask is good
Args :
ip _ addr _ and _ mask : Multicast IP address and mask in the following format 239.1.1.1/24
return _ tuple : Set to True it returns a IP and mask in a tuple , set... | regex_mcast_ip_and_mask = __re . compile ( "^(((2[2-3][4-9])|(23[0-3]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))/((3[0-2])|([1-2][0-9])|[3-9]))$" )
if return_tuple :
while not regex_mcast_ip_a... |
def debug_sync ( self , conn_id , cmd_name , cmd_args , progress_callback ) :
"""Asynchronously complete a named debug command .
The command name and arguments are passed to the underlying device adapter
and interpreted there . If the command is long running , progress _ callback
may be used to provide status... | done = threading . Event ( )
result = { }
def _debug_done ( conn_id , adapter_id , success , retval , reason ) :
result [ 'success' ] = success
result [ 'failure_reason' ] = reason
result [ 'return_value' ] = retval
done . set ( )
self . debug_async ( conn_id , cmd_name , cmd_args , progress_callback , ... |
def rm_auth_key ( user , key , config = '.ssh/authorized_keys' , fingerprint_hash_type = None ) :
'''Remove an authorized key from the specified user ' s authorized key file
CLI Example :
. . code - block : : bash
salt ' * ' ssh . rm _ auth _ key < user > < key >''' | current = auth_keys ( user , config = config , fingerprint_hash_type = fingerprint_hash_type )
linere = re . compile ( r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$' )
if key in current : # Remove the key
full = _get_config_file ( user , config )
# Return something sensible if the file doesn ' t exist
if not os . ... |
def pprint ( self , num = 10 ) :
"""Print the first ` ` num ` ` elements of each RDD .
: param int num : Set number of elements to be printed .""" | def pprint_map ( time_ , rdd ) :
print ( '>>> Time: {}' . format ( time_ ) )
data = rdd . take ( num + 1 )
for d in data [ : num ] :
py_pprint . pprint ( d )
if len ( data ) > num :
print ( '...' )
print ( '' )
self . foreachRDD ( pprint_map ) |
def now ( cls , Name = None ) :
"""Instantiate a Time element initialized to the current UTC
time in the default format ( ISO - 8601 ) . The Name attribute
will be set to the value of the Name parameter if given .""" | self = cls ( )
if Name is not None :
self . Name = Name
self . pcdata = datetime . datetime . utcnow ( )
return self |
def create ( vm_ ) :
'''Provision a single machine
CLI Example :
. . code - block : : bash
salt - cloud - p my _ profile new _ node _ 1''' | name = vm_ [ 'name' ]
machine = config . get_cloud_config_value ( 'machine' , vm_ , __opts__ , default = '' )
vm_ [ 'machine' ] = machine
host = config . get_cloud_config_value ( 'host' , vm_ , __opts__ , default = NotImplemented )
vm_ [ 'cwd' ] = config . get_cloud_config_value ( 'cwd' , vm_ , __opts__ , default = '/'... |
def get_model_ids_to_fetch ( events , context_hints_per_source ) :
"""Obtains the ids of all models that need to be fetched . Returns a dictionary of models that
point to sets of ids that need to be fetched . Return output is as follows :
model : [ id1 , id2 , . . . ] ,""" | number_types = ( complex , float ) + six . integer_types
model_ids_to_fetch = defaultdict ( set )
for event in events :
context_hints = context_hints_per_source . get ( event . source , { } )
for context_key , hints in context_hints . items ( ) :
for d , value in dict_find ( event . context , context_ke... |
def owner ( path ) :
"""Returns a tuple containing the username & groupname owning the path .
: param str path : the string path to retrieve the ownership
: return tuple ( str , str ) : A ( username , groupname ) tuple containing the
name of the user and group owning the path .
: raises OSError : if the spe... | stat = os . stat ( path )
username = pwd . getpwuid ( stat . st_uid ) [ 0 ]
groupname = grp . getgrgid ( stat . st_gid ) [ 0 ]
return username , groupname |
def dctii ( x , axes = None ) :
"""Compute a multi - dimensional DCT - II over specified array axes . This
function is implemented by calling the one - dimensional DCT - II
: func : ` scipy . fftpack . dct ` with normalization mode ' ortho ' for each
of the specified axes .
Parameters
a : array _ like
I... | if axes is None :
axes = list ( range ( x . ndim ) )
for ax in axes :
x = fftpack . dct ( x , type = 2 , axis = ax , norm = 'ortho' )
return x |
def populate ( self , blueprint , documents ) :
"""Populate the database with documents""" | # Finish the documents
documents = self . finish ( blueprint , documents )
# Convert the documents to frame instances
frames = [ ]
for document in documents : # Separate out any meta fields
meta_document = { }
for field_name in blueprint . _meta_fields :
meta_document [ field_name ] = document [ field_n... |
def generate_classified_legend ( analysis , exposure , hazard , use_rounding , debug_mode ) :
"""Generate an ordered python structure with the classified symbology .
: param analysis : The analysis layer .
: type analysis : QgsVectorLayer
: param exposure : The exposure layer .
: type exposure : QgsVectorLa... | # We need to read the analysis layer to get the number of features .
analysis_row = next ( analysis . getFeatures ( ) )
# Let ' s style the hazard class in each layers .
hazard_classification = hazard . keywords [ 'classification' ]
hazard_classification = definition ( hazard_classification )
# Let ' s check if there i... |
def custom_to_pmrapmdec ( pmphi1 , pmphi2 , phi1 , phi2 , T = None , degree = False ) :
"""NAME :
custom _ to _ pmrapmdec
PURPOSE :
rotate proper motions in a custom set of sky coordinates ( phi1 , phi2 ) to ICRS ( ra , dec )
INPUT :
pmphi1 - proper motion in custom ( multplied with cos ( phi2 ) ) [ mas /... | if T is None :
raise ValueError ( "Must set T= for custom_to_pmrapmdec" )
return pmrapmdec_to_custom ( pmphi1 , pmphi2 , phi1 , phi2 , T = nu . transpose ( T ) , # T . T = inv ( T )
degree = degree ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.