signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def validate_rmq_ssl_enabled_units ( self , sentry_units , port = None ) :
"""Check that ssl is enabled on rmq juju sentry units .
: param sentry _ units : list of all rmq sentry units
: param port : optional ssl port override to validate
: returns : None if successful , otherwise return error message""" | for sentry_unit in sentry_units :
if not self . rmq_ssl_is_enabled_on_unit ( sentry_unit , port = port ) :
return ( 'Unexpected condition: ssl is disabled on unit ' '({})' . format ( sentry_unit . info [ 'unit_name' ] ) )
return None |
def detectPalmOS ( self ) :
"""Return detection of a PalmOS device
Detects if the current browser is on a PalmOS device .""" | # Most devices nowadays report as ' Palm ' , but some older ones reported as Blazer or Xiino .
if UAgentInfo . devicePalm in self . __userAgent or UAgentInfo . engineBlazer in self . __userAgent or UAgentInfo . engineXiino in self . __userAgent : # Make sure it ' s not WebOS
return not self . detectPalmWebOS ( )
re... |
def s2dctmat ( nfilt , ncep , freqstep ) :
"""Return the ' legacy ' not - quite - DCT matrix used by Sphinx""" | melcos = numpy . empty ( ( ncep , nfilt ) , 'double' )
for i in range ( 0 , ncep ) :
freq = numpy . pi * float ( i ) / nfilt
melcos [ i ] = numpy . cos ( freq * numpy . arange ( 0.5 , float ( nfilt ) + 0.5 , 1.0 , 'double' ) )
melcos [ : , 0 ] = melcos [ : , 0 ] * 0.5
return melcos |
def _secondary_values ( self ) :
"""Getter for secondary series values ( flattened )""" | return [ val for serie in self . secondary_series for val in serie . values if val is not None ] |
def combine ( self , merge_points = False ) :
"""Appends all blocks into a single unstructured grid .
Parameters
merge _ points : bool , optional
Merge coincidental points .""" | alg = vtk . vtkAppendFilter ( )
for block in self :
alg . AddInputData ( block )
alg . SetMergePoints ( merge_points )
alg . Update ( )
return wrap ( alg . GetOutputDataObject ( 0 ) ) |
def as_list ( x ) :
'''Ensure ` x ` is of list type .''' | if x is None :
x = [ ]
elif not isinstance ( x , Sequence ) :
x = [ x ]
return list ( x ) |
def stream_uploadfactory ( content_md5 = None , content_length = None , content_type = None ) :
"""Get default put factory .
If Content - Type is ` ` ' multipart / form - data ' ` ` then the stream is aborted .
: param content _ md5 : The content MD5 . ( Default : ` ` None ` ` )
: param content _ length : The... | if content_type . startswith ( 'multipart/form-data' ) :
abort ( 422 )
return request . stream , content_length , content_md5 , parse_header_tags ( ) |
def find_table ( self , table ) :
"""Finds a table by name or alias . The FROM tables and JOIN tables
are included in the search .
: type table : str or : class : ` ModelBase < django : django . db . models . base . ModelBase > `
: param table : string of the table name or alias or a ModelBase instance
: re... | table = TableFactory ( table )
identifier = table . get_identifier ( )
join_tables = [ join_item . right_table for join_item in self . joins ]
for table in ( self . tables + join_tables ) :
if table . get_identifier ( ) == identifier :
return table
return None |
def overlay_gateway_access_lists_mac_out_mac_acl_out_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
overlay_gateway = ET . SubElement ( config , "overlay-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" )
name_key = ET . SubElement ( overlay_gateway , "name" )
name_key . text = kwargs . pop ( 'name' )
access_lists = ET . SubElement ( overlay_gateway , "access-lists" )
mac =... |
def create_access_service ( price , service_endpoint , consume_endpoint , timeout = None ) :
"""Publish an asset with an ` Access ` service according to the supplied attributes .
: param price : Asset price , int
: param service _ endpoint : str URL for initiating service access request
: param consume _ endp... | timeout = timeout or 3600
# default to one hour timeout
service = ServiceDescriptor . access_service_descriptor ( price , service_endpoint , consume_endpoint , timeout , '' )
return service |
def file_to_list ( path ) :
"""Return the contents of a file as a list when given a path .""" | if not os . path . exists ( path ) :
ui . error ( c . MESSAGES [ "path_missing" ] , path )
sys . exit ( 1 )
with codecs . open ( path , "r" , "UTF-8" ) as contents :
lines = contents . read ( ) . splitlines ( )
return lines |
def _compute_sorted_indices ( self ) :
"""The smoothers need sorted data . This sorts it from the perspective of each column .
if self . _ x [ 0 ] [ 3 ] is the 9th - smallest value in self . _ x [ 0 ] , then _ xi _ sorted [ 3 ] = 8
We only have to sort the data once .""" | sorted_indices = [ ]
for to_sort in [ self . y ] + self . x :
data_w_indices = [ ( val , i ) for ( i , val ) in enumerate ( to_sort ) ]
data_w_indices . sort ( )
sorted_indices . append ( [ i for val , i in data_w_indices ] )
# save in meaningful variable names
self . _yi_sorted = sorted_indices [ 0 ]
# lis... |
def get_core ( self ) :
"""Get an unsatisfiable core if the formula was previously
unsatisfied .""" | if self . lingeling and self . status == False :
return pysolvers . lingeling_core ( self . lingeling , self . prev_assumps ) |
def summary ( self , * inputs ) :
"""Print the summary of the model ' s output and parameters .
The network must have been initialized , and must not have been hybridized .
Parameters
inputs : object
Any input that the model supports . For any tensor in the input , only
: class : ` mxnet . ndarray . NDArr... | summary = OrderedDict ( )
seen = set ( )
hooks = [ ]
def _get_shape_str ( args ) :
def flatten ( args ) :
if not isinstance ( args , ( list , tuple ) ) :
return [ args ] , int ( 0 )
flat = [ ]
fmts = [ ]
for i in args :
arg , fmt = flatten ( i )
fl... |
def image ( self , path_img ) :
"""Open image file""" | im_open = Image . open ( path_img )
im = im_open . convert ( "RGB" )
# Convert the RGB image in printable image
pix_line , img_size = self . _convert_image ( im )
self . _print_image ( pix_line , img_size ) |
def _count_model ( self , model ) :
"""return model count""" | try :
res = model . objects . all ( ) . count ( )
except Exception as e :
self . err ( e )
return
return res |
def _read_neuralev ( filename , read_markers = False , trigger_bits = 16 , trigger_zero = True ) :
"""Read some information from NEV
Parameters
filename : str
path to NEV file
read _ markers : bool
whether to read markers or not ( it can get really large )
trigger _ bits : int , optional
8 or 16 , rea... | hdr = { }
with open ( filename , 'rb' ) as f :
BasicHdr = f . read ( 336 )
i1 = 8
hdr [ 'FileTypeID' ] = BasicHdr [ : i1 ] . decode ( 'utf-8' )
assert hdr [ 'FileTypeID' ] == 'NEURALEV'
i0 , i1 = i1 , i1 + 2
filespec = unpack ( 'bb' , BasicHdr [ i0 : i1 ] )
hdr [ 'FileSpec' ] = str ( filespe... |
def validate_model ( self ) :
"""Validate the model""" | model : AssetAllocationModel = self . get_asset_allocation_model ( )
model . logger = self . logger
valid = model . validate ( )
if valid :
print ( f"The model is valid. Congratulations" )
else :
print ( f"The model is invalid." ) |
def process_execute ( function , * args , ** kwargs ) :
"""Runs the given function returning its results or exception .""" | try :
return function ( * args , ** kwargs )
except Exception as error :
error . traceback = format_exc ( )
return RemoteException ( error , error . traceback ) |
def upload ( self , stop_at = None ) :
"""Perform file upload .
Performs continous upload of chunks of the file . The size uploaded at each cycle is
the value of the attribute ' chunk _ size ' .
: Args :
- stop _ at ( Optional [ int ] ) :
Determines at what offset value the upload should stop . If not spe... | self . stop_at = stop_at or self . file_size
while self . offset < self . stop_at :
self . upload_chunk ( )
else :
if self . log_func :
self . log_func ( "maximum upload specified({} bytes) has been reached" . format ( self . stop_at ) ) |
def validate_cnxml ( * content_filepaths ) :
"""Validates the given CNXML file against the cnxml - jing . rng RNG .""" | content_filepaths = [ Path ( path ) . resolve ( ) for path in content_filepaths ]
return jing ( CNXML_JING_RNG , * content_filepaths ) |
def is_active ( self , instance , conditions ) :
"""value is the current value of the switch
instance is the instance of our type""" | if isinstance ( instance , User ) :
return super ( UserConditionSet , self ) . is_active ( instance , conditions )
# HACK : allow is _ authenticated to work on AnonymousUser
condition = conditions . get ( self . get_namespace ( ) , { } ) . get ( 'is_anonymous' )
if condition is not None :
return bool ( conditio... |
def _ParseSignatureIdentifiers ( self , data_location , signature_identifiers ) :
"""Parses the signature identifiers .
Args :
data _ location ( str ) : location of the format specification file , for
example , " signatures . conf " .
signature _ identifiers ( str ) : comma separated signature identifiers .... | if not signature_identifiers :
return
if not data_location :
raise ValueError ( 'Missing data location.' )
path = os . path . join ( data_location , 'signatures.conf' )
if not os . path . exists ( path ) :
raise IOError ( 'No such format specification file: {0:s}' . format ( path ) )
try :
specification... |
def getTypeInfo ( self , sql_type ) : # nopep8
"""Executes SQLGetTypeInfo a creates a result set with information
about the specified data type or all data types supported by the
ODBC driver if not specified .""" | fut = self . _run_operation ( self . _impl . getTypeInfo , sql_type )
return fut |
def qteUnbindKeyFromWidgetObject ( self , keysequence , widgetObj : QtGui . QWidget ) :
"""Disassociate the macro triggered by ` ` keysequence ` ` from
` ` widgetObj ` ` .
The ` ` keysequence ` ` can be specified either as a string ( eg
' < ctrl > + x < ctrl > + f ' ) , or a list of tuples containing the
co... | # Convert the key sequence into a QtmacsKeysequence object , or
# raise an QtmacsKeysequenceError if the conversion is
# impossible .
keysequence = QtmacsKeysequence ( keysequence )
# Check type of input arguments .
if not hasattr ( widgetObj , '_qteAdmin' ) :
msg = '<widgetObj> was probably not added with <qteAddW... |
def use ( self , tube ) :
"""Start producing jobs into the given tube .
: param tube : Name of the tube to USE
Subsequent calls to : func : ` put _ job ` insert jobs into this tube .""" | with self . _sock_ctx ( ) as socket :
if self . current_tube != tube :
self . desired_tube = tube
self . _send_message ( 'use {0}' . format ( tube ) , socket )
self . _receive_name ( socket )
self . current_tube = tube |
def reload_using_spawn_wait ( self ) :
"""Spawn a subprocess and wait until it finishes .
: return :
None .""" | # Create command parts
cmd_parts = [ sys . executable ] + sys . argv
# Get env dict copy
env_copy = os . environ . copy ( )
# Send interrupt to main thread
interrupt_main ( )
# Spawn subprocess and wait until it finishes
subprocess . call ( cmd_parts , env = env_copy , close_fds = True )
# Exit the watcher thread
sys .... |
def update_router ( self , context , router_id , router ) :
"""Update an existing router in DB , and update it in Arista HW .""" | # Read existing router record from DB
original_router = self . get_router ( context , router_id )
# Update router DB
new_router = super ( AristaL3ServicePlugin , self ) . update_router ( context , router_id , router )
# Modify router on the Arista Hw
try :
self . driver . update_router ( context , router_id , origi... |
def _getitem_iterable ( self , key , axis = None ) :
"""Index current object with an an iterable key ( which can be a boolean
indexer , or a collection of keys ) .
Parameters
key : iterable
Target labels , or boolean indexer
axis : int , default None
Dimension on which the indexing is being made
Raise... | if axis is None :
axis = self . axis or 0
self . _validate_key ( key , axis )
labels = self . obj . _get_axis ( axis )
if com . is_bool_indexer ( key ) : # A boolean indexer
key = check_bool_indexer ( labels , key )
inds , = key . nonzero ( )
return self . obj . _take ( inds , axis = axis )
else : # A c... |
def _raw_aspera_metadata ( self , bucket ) :
'''get the Aspera connection details on Aspera enabled buckets''' | response = self . _client . get_bucket_aspera ( Bucket = bucket )
# Parse metadata from response
aspera_access_key = response [ 'AccessKey' ] [ 'Id' ]
aspera_secret_key = response [ 'AccessKey' ] [ 'Secret' ]
ats_endpoint = response [ 'ATSEndpoint' ]
return aspera_access_key , aspera_secret_key , ats_endpoint |
def _random_fill ( self ) :
"""Fill the board with random tiles based on the Tile class .""" | a = self . _array
for p , tile in self . positions_with_tile ( ) :
if tile . is_blank ( ) :
a [ p ] = Tile . random_tile ( ) |
def pauli_string_half ( circuit : circuits . Circuit ) -> circuits . Circuit :
"""Return only the non - Clifford part of a circuit . See
convert _ and _ separate _ circuit ( ) .
Args :
circuit : A Circuit with the gate set { SingleQubitCliffordGate ,
PauliInteractionGate , PauliStringPhasor } .
Returns : ... | return circuits . Circuit . from_ops ( _pull_non_clifford_before ( circuit ) , strategy = circuits . InsertStrategy . EARLIEST ) |
def most_recent_among ( versions ) :
"""Compare a list of NSS versions and return the latest one .
Uses first _ older _ than _ second ( ) for comparison .
: param versions : an array of NSS version strings
: return : verbatim copy of the most recent version string""" | latest = versions [ 0 ]
for v in versions [ 1 : ] :
if nssversion . first_older_than_second ( latest , v ) :
latest = v
return latest |
def classify ( self ) :
"""* classify the transients selected from the transient selection query in the settings file or passed in via the CL or other code *
* * Return : * *
- ` ` crossmatches ` ` - - list of dictionaries of crossmatched associated sources
- ` ` classifications ` ` - - the classifications as... | global theseBatches
global crossmatchArray
self . log . debug ( 'starting the ``classify`` method' )
remaining = 1
# THE COLUMN MAPS - WHICH COLUMNS IN THE CATALOGUE TABLES = RA , DEC ,
# REDSHIFT , MAG ETC
colMaps = get_crossmatch_catalogues_column_map ( log = self . log , dbConn = self . cataloguesDbConn )
self . _cr... |
def parse_section_entry_points ( self , section_options ) :
"""Parses ` entry _ points ` configuration file section .
: param dict section _ options :""" | parsed = self . _parse_section_to_dict ( section_options , self . _parse_list )
self [ 'entry_points' ] = parsed |
def from_jwt ( self , txt , keyjar , verify = True , ** kwargs ) :
"""Given a signed and / or encrypted JWT , verify its correctness and then
create a class instance from the content .
: param txt : The JWT
: param key : keys that might be used to decrypt and / or verify the
signature of the JWT
: param v... | algarg = { }
if 'encalg' in kwargs :
algarg [ 'alg' ] = kwargs [ 'encalg' ]
if 'encenc' in kwargs :
algarg [ 'enc' ] = kwargs [ 'encenc' ]
_decryptor = jwe_factory ( txt , ** algarg )
if _decryptor :
logger . debug ( "JWE headers: {}" . format ( _decryptor . jwt . headers ) )
dkeys = keyjar . get_decryp... |
def colDelete ( self , colI = - 1 ) :
"""delete a column at a single index . Negative numbers count from the end .""" | # print ( " DELETING COLUMN : [ % d ] % s " % ( colI , self . colDesc [ colI ] ) )
self . colNames . pop ( colI )
self . colDesc . pop ( colI )
self . colUnits . pop ( colI )
self . colComments . pop ( colI )
self . colTypes . pop ( colI )
self . colData . pop ( colI )
return |
def _usage_endpoint ( self , endpoint , year = None , month = None ) :
"""Common helper for getting usage and billing reports with
optional year and month URL elements .
: param str endpoint : Cloudant usage endpoint .
: param int year : Year to query against . Optional parameter .
Defaults to None . If use... | err = False
if year is None and month is None :
resp = self . r_session . get ( endpoint )
else :
try :
if int ( year ) > 0 and int ( month ) in range ( 1 , 13 ) :
resp = self . r_session . get ( '/' . join ( ( endpoint , str ( int ( year ) ) , str ( int ( month ) ) ) ) )
else :
... |
def versions ( ) :
'''Check the version of active minions
CLI Example :
. . code - block : : bash
salt - run manage . versions''' | ret = { }
client = salt . client . get_local_client ( __opts__ [ 'conf_file' ] )
try :
minions = client . cmd ( '*' , 'test.version' , timeout = __opts__ [ 'timeout' ] )
except SaltClientError as client_error :
print ( client_error )
return ret
labels = { - 2 : 'Minion offline' , - 1 : 'Minion requires upda... |
def _blast ( bvname2vals , name_map ) :
"""Helper function to expand ( blast ) str - > int map into str - >
bool map . This is used to send word level inputs to aiger .""" | if len ( name_map ) == 0 :
return dict ( )
return fn . merge ( * ( dict ( zip ( names , bvname2vals [ bvname ] ) ) for bvname , names in name_map ) ) |
def Point2HexColor ( a , lfrac , tfrac ) :
"""Return web - safe hex triplets .""" | [ H , S , V ] = [ math . floor ( 360 * a ) , lfrac , tfrac ]
RGB = hsvToRGB ( H , S , V )
H = [ hex ( int ( math . floor ( 255 * x ) ) ) for x in RGB ]
HEX = [ a [ a . find ( 'x' ) + 1 : ] for a in H ]
HEX = [ '0' + h if len ( h ) == 1 else h for h in HEX ]
return '#' + '' . join ( HEX ) |
def group_dict_by_value ( d : dict ) -> dict :
"""Group a dictionary by values .
Parameters
d : dict
Input dictionary
Returns
dict
Output dictionary . The keys are the values of the initial dictionary
and the values ae given by a list of keys corresponding to the value .
> > > group _ dict _ by _ va... | d_out = { }
for k , v in d . items ( ) :
if v in d_out :
d_out [ v ] . append ( k )
else :
d_out [ v ] = [ k ]
return d_out |
def getReffs ( self , textId , level = 1 , subreference = None ) :
"""Retrieve the siblings of a textual node
: param textId : CtsTextMetadata Identifier
: type textId : str
: param level : Depth for retrieval
: type level : int
: param subreference : CapitainsCtsPassage Reference
: type subreference : ... | depth = level
if subreference :
textId = "{}:{}" . format ( textId , subreference )
if subreference :
if isinstance ( subreference , CtsReference ) :
depth += subreference . depth
else :
depth += ( CtsReference ( subreference ) ) . depth
if level :
level = max ( depth , level )
return se... |
def get_provider_metadata ( self ) :
"""Gets the metadata for a provider .
return : ( osid . Metadata ) - metadata for the provider
* compliance : mandatory - - This method must be implemented . *""" | metadata = dict ( self . _provider_metadata )
metadata . update ( { 'existing_id_values' : self . my_osid_object_form . _my_map [ 'providerId' ] } )
return Metadata ( ** metadata ) |
def update_selection_sm_prior ( self ) :
"""State machine prior update of tree selection""" | if self . _do_selection_update :
return
self . _do_selection_update = True
tree_selection , selected_model_list , sm_selection , sm_selected_model_list = self . get_selections ( )
if tree_selection is not None :
for path , row in enumerate ( self . list_store ) :
model = row [ self . MODEL_STORAGE_ID ]
... |
def get_partition_leaders ( cluster_config ) :
"""Return the current leaders of all partitions . Partitions are
returned as a " topic - partition " string .
: param cluster _ config : the cluster
: type cluster _ config : kafka _ utils . utils . config . ClusterConfig
: returns : leaders for partitions
: ... | client = KafkaClient ( cluster_config . broker_list )
result = { }
for topic , topic_data in six . iteritems ( client . topic_partitions ) :
for partition , p_data in six . iteritems ( topic_data ) :
topic_partition = topic + "-" + str ( partition )
result [ topic_partition ] = p_data . leader
retur... |
def info ( ctx ) :
"""Display status of PIV application .""" | controller = ctx . obj [ 'controller' ]
click . echo ( 'PIV version: %d.%d.%d' % controller . version )
# Largest possible number of PIN tries to get back is 15
tries = controller . get_pin_tries ( )
tries = '15 or more.' if tries == 15 else tries
click . echo ( 'PIN tries remaining: %s' % tries )
if controller . puk_b... |
def gpgga_to_dms ( gpgga ) :
'''Convert GPS coordinate in GPGGA format to degree / minute / second
Reference : http : / / us . cactii . net / ~ bb / gps . py''' | deg_min , dmin = gpgga . split ( '.' )
degrees = int ( deg_min [ : - 2 ] )
minutes = float ( '%s.%s' % ( deg_min [ - 2 : ] , dmin ) )
decimal = degrees + ( minutes / 60 )
return decimal |
def set_identify ( self , on = True , duration = None ) :
"""Request identify light
Request the identify light to turn off , on for a duration ,
or on indefinitely . Other than error exceptions ,
: param on : Set to True to force on or False to force off
: param duration : Set if wanting to request turn on ... | self . oem_init ( )
try :
self . _oem . set_identify ( on , duration )
return
except exc . UnsupportedFunctionality :
pass
if duration is not None :
duration = int ( duration )
if duration > 255 :
duration = 255
if duration < 0 :
duration = 0
response = self . raw_command ( n... |
def set_all_pwm ( self , on , off ) :
"""Sets all PWM channels .""" | self . i2c . write8 ( ALL_LED_ON_L , on & 0xFF )
self . i2c . write8 ( ALL_LED_ON_H , on >> 8 )
self . i2c . write8 ( ALL_LED_OFF_L , off & 0xFF )
self . i2c . write8 ( ALL_LED_OFF_H , off >> 8 ) |
def _cancel_outstanding ( self ) :
"""Cancel all of our outstanding requests""" | for d in list ( self . _outstanding ) :
d . addErrback ( lambda _ : None )
# Eat any uncaught errors
d . cancel ( ) |
def mfccInitFilterBanks ( fs , nfft ) :
"""Computes the triangular filterbank for MFCC computation
( used in the stFeatureExtraction function before the stMFCC function call )
This function is taken from the scikits . talkbox library ( MIT Licence ) :
https : / / pypi . python . org / pypi / scikits . talkbox... | # filter bank params :
lowfreq = 133.33
linsc = 200 / 3.
logsc = 1.0711703
numLinFiltTotal = 13
numLogFilt = 27
if fs < 8000 :
nlogfil = 5
# Total number of filters
nFiltTotal = numLinFiltTotal + numLogFilt
# Compute frequency points of the triangle :
freqs = numpy . zeros ( nFiltTotal + 2 )
freqs [ : numLinFiltTot... |
def tenant_absent ( name , profile = None , ** connection_args ) :
'''Ensure that the keystone tenant is absent .
name
The name of the tenant that should not exist''' | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : 'Tenant / project "{0}" is already absent' . format ( name ) }
# Check if tenant is present
tenant = __salt__ [ 'keystone.tenant_get' ] ( name = name , profile = profile , ** connection_args )
if 'Error' not in tenant :
if __opts__ . get ( 'tes... |
def supported_tags ( self , interpreter = None , force_manylinux = True ) :
"""Returns a list of supported PEP425 tags for the current platform .""" | if interpreter and not self . is_extended : # N . B . If we don ' t get an extended platform specifier , we generate
# all possible ABI permutations to mimic earlier pex version
# behavior and make cross - platform resolution more intuitive .
return _get_supported_for_any_abi ( platform = self . platform , impl = i... |
def get_task_doc ( self , path ) :
"""Get the entire task doc for a path , including any post - processing .""" | logger . info ( "Getting task doc for base dir :{}" . format ( path ) )
files = os . listdir ( path )
vasprun_files = OrderedDict ( )
if "STOPCAR" in files : # Stopped runs . Try to parse as much as possible .
logger . info ( path + " contains stopped run" )
for r in self . runs :
if r in files : # try subfolde... |
def encipher ( self , string ) :
"""Encipher string using Enigma M3 cipher according to initialised key . Punctuation and whitespace
are removed from the input .
Example : :
ciphertext = Enigma ( settings = ( ' A ' , ' A ' , ' A ' ) , rotors = ( 1,2,3 ) , reflector = ' B ' ,
ringstellung = ( ' F ' , ' V ' ,... | string = self . remove_punctuation ( string )
ret = ''
for c in string . upper ( ) :
if c . isalpha ( ) :
ret += self . encipher_char ( c )
else :
ret += c
return ret |
def raise_on_failure ( mainfunc ) :
"""raise if and only if mainfunc fails""" | try :
errors = mainfunc ( )
if errors :
exit ( errors )
except CalledProcessError as error :
exit ( error . returncode )
except SystemExit as error :
if error . code :
raise
except KeyboardInterrupt : # I don ' t plan to test - cover this . : pragma : nocover :
exit ( 1 ) |
def is_valid ( self ) :
'''Validate form .
Return True if Django validates the form , the username obeys the parameters , and passwords match .
Return False otherwise .''' | if not super ( ProfileRequestForm , self ) . is_valid ( ) :
return False
validity = True
if self . cleaned_data [ 'password' ] != self . cleaned_data [ 'confirm_password' ] :
form_add_error ( self , 'password' , "Passwords don't match." )
form_add_error ( self , 'confirm_password' , "Passwords don't match."... |
def tasks ( self , ** opts ) :
"""Convenience wrapper around listTasks ( . . . ) for this channel ID .
Tasks are sorted by priority and creation time .
: param * * opts : " opts " dict to the listTasks RPC .
For example , " state = [ task _ states . OPEN ] " will return
only the " OPEN " tasks .
: returns... | opts [ 'channel_id' ] = self . id
qopts = { 'order' : 'priority,create_time' }
return self . connection . listTasks ( opts , qopts ) |
def guess_base_branch ( ) : # type : ( str ) - > Optional [ str , None ]
"""Try to guess the base branch for the current branch .
Do not trust this guess . git makes it pretty much impossible to guess
the base branch reliably so this function implements few heuristics that
will work on most common use cases b... | my_branch = current_branch ( refresh = True ) . name
curr = latest_commit ( )
if len ( curr . branches ) > 1 : # We ' re possibly at the beginning of the new branch ( currently both
# on base and new branch ) .
other = [ x for x in curr . branches if x != my_branch ]
if len ( other ) == 1 :
return other... |
def as_crispy_errors ( form , template_pack = TEMPLATE_PACK ) :
"""Renders only form errors the same way as django - crispy - forms : :
{ % load crispy _ forms _ tags % }
{ { form | as _ crispy _ errors } }
or : :
{ { form | as _ crispy _ errors : " bootstrap " } }""" | if isinstance ( form , BaseFormSet ) :
template = get_template ( '%s/errors_formset.html' % template_pack )
c = Context ( { 'formset' : form } ) . flatten ( )
else :
template = get_template ( '%s/errors.html' % template_pack )
c = Context ( { 'form' : form } ) . flatten ( )
return template . render ( c ... |
def _shru16 ( ins ) :
'''Logical right shift 16bit unsigned integer .
The result is pushed onto the stack .
Optimizations :
* If 2nd op is 0 then
do nothing
* If 2nd op is 1
Shift Right Arithmetic''' | op1 , op2 = tuple ( ins . quad [ 2 : ] )
if is_int ( op2 ) :
op = int16 ( op2 )
if op == 0 :
return [ ]
output = _16bit_oper ( op1 )
if op == 1 :
output . append ( 'srl h' )
output . append ( 'rr l' )
output . append ( 'push hl' )
return output
output . append... |
def rank ( self , dte ) :
'''The rank of a given * dte * in the timeseries''' | timestamp = self . pickler . dumps ( dte )
return self . backend_structure ( ) . rank ( timestamp ) |
def get_repo_hooks ( self , auth , username , repo_name ) :
"""Returns all hooks of repository with name ` ` repo _ name ` ` owned by
the user with username ` ` username ` ` .
: param auth . Authentication auth : authentication object
: param str username : username of owner of repository
: param str repo _... | path = "/repos/{u}/{r}/hooks" . format ( u = username , r = repo_name )
response = self . get ( path , auth = auth )
return [ GogsRepo . Hook . from_json ( hook ) for hook in response . json ( ) ] |
def set_foreground ( self , fg , isRGBA = None ) :
"""Set the foreground color . fg can be a matlab format string , a
html hex color string , an rgb unit tuple , or a float between 0
and 1 . In the latter case , grayscale is used .""" | # Implementation note : wxPython has a separate concept of pen and
# brush - the brush fills any outline trace left by the pen .
# Here we set both to the same colour - if a figure is not to be
# filled , the renderer will set the brush to be transparent
# Same goes for text foreground . . .
DEBUG_MSG ( "set_foreground... |
def start_process ( self , program , arguments = None , working_dir = None , print_command = True , use_pseudo_terminal = True , env = None ) :
"""Starts the child process .
: param program : program to start
: param arguments : list of program arguments
: param working _ dir : working directory of the child ... | # clear previous output
self . clear ( )
self . setReadOnly ( False )
if arguments is None :
arguments = [ ]
if sys . platform != 'win32' and use_pseudo_terminal :
pgm = sys . executable
args = [ pty_wrapper . __file__ , program ] + arguments
self . flg_use_pty = use_pseudo_terminal
else :
pgm = pro... |
def update_profile_banner ( self , filename , ** kargs ) :
""": reference : https : / / dev . twitter . com / rest / reference / post / account / update _ profile _ banner
: allowed _ param : ' width ' , ' height ' , ' offset _ left ' , ' offset _ right '""" | f = kargs . pop ( 'file' , None )
headers , post_data = API . _pack_image ( filename , 700 , form_field = 'banner' , f = f )
bind_api ( api = self , path = '/account/update_profile_banner.json' , method = 'POST' , allowed_param = [ 'width' , 'height' , 'offset_left' , 'offset_right' ] , require_auth = True ) ( post_dat... |
def patch_namespaced_replica_set ( self , name , namespace , body , ** kwargs ) : # noqa : E501
"""patch _ namespaced _ replica _ set # noqa : E501
partially update the specified ReplicaSet # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pa... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . patch_namespaced_replica_set_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . patch_namespaced_replica_set_with_http_info ( name , namespace , body , ** kwargs )
# noqa... |
def request_search ( self , txt = None ) :
"""Requests a search operation .
: param txt : The text to replace . If None , the content of lineEditSearch
is used instead .""" | if self . checkBoxRegex . isChecked ( ) :
try :
re . compile ( self . lineEditSearch . text ( ) , re . DOTALL )
except sre_constants . error as e :
self . _show_error ( e )
return
else :
self . _show_error ( None )
if txt is None or isinstance ( txt , int ) :
txt = self .... |
def do_direct_payment ( self , paymentaction = "Sale" , ** kwargs ) :
"""Shortcut for the DoDirectPayment method .
` ` paymentaction ` ` could be ' Authorization ' or ' Sale '
To issue a Sale immediately : :
charge = {
' amt ' : ' 10.00 ' ,
' creditcardtype ' : ' Visa ' ,
' acct ' : ' 4812177017895760 '... | kwargs . update ( self . _sanitize_locals ( locals ( ) ) )
return self . _call ( 'DoDirectPayment' , ** kwargs ) |
def ssh_authorized_keys_lines ( application_name , user = None ) :
"""Return contents of authorized _ keys file for given application .
: param application _ name : Name of application eg nova - compute - something
: type application _ name : str
: param user : The user that the ssh asserts are for .
: type... | authorized_keys_list = [ ]
with open ( authorized_keys ( application_name , user ) ) as keys :
for authkey_line in keys :
if authkey_line . rstrip ( ) :
authorized_keys_list . append ( authkey_line . rstrip ( ) )
return ( authorized_keys_list ) |
def amalgamate ( A , blocksize ) :
"""Amalgamate matrix A .
Parameters
A : csr _ matrix
Matrix to amalgamate
blocksize : int
blocksize to use while amalgamating
Returns
A _ amal : csr _ matrix
Amalgamated matrix A , first , convert A to BSR with square blocksize
and then return a CSR matrix of one... | if blocksize == 1 :
return A
elif sp . mod ( A . shape [ 0 ] , blocksize ) != 0 :
raise ValueError ( "Incompatible blocksize" )
A = A . tobsr ( blocksize = ( blocksize , blocksize ) )
A . sort_indices ( )
subI = ( np . ones ( A . indices . shape ) , A . indices , A . indptr )
shape = ( int ( A . shape [ 0 ] / A... |
def highlight_syntax ( src , lang , linenums = False ) :
"""Pass code to the [ Pygments ] ( http : / / pygments . pocoo . org / ) highliter
with optional line numbers . The output should then be styled with CSS
to your liking . No styles are applied by default - only styling hooks
( i . e . : < span class = "... | src = src . strip ( '\n' )
if not lang :
lexer = TextLexer ( )
else :
try :
lexer = get_lexer_by_name ( lang , stripall = True )
except ValueError :
lexer = TextLexer ( )
formatter = HtmlFormatter ( linenos = linenums , tab_length = TAB_LENGTH )
html = highlight ( src , lexer , formatter )
i... |
def affine_align ( dset_from , dset_to , skull_strip = True , mask = None , suffix = '_aff' , prefix = None , cost = None , epi = False , resample = 'wsinc5' , grid_size = None , opts = [ ] ) :
'''interface to 3dAllineate to align anatomies and EPIs''' | dset_ss = lambda dset : os . path . split ( nl . suffix ( dset , '_ns' ) ) [ 1 ]
def dset_source ( dset ) :
if skull_strip == True or skull_strip == dset :
return dset_ss ( dset )
else :
return dset
dset_affine = prefix
if dset_affine == None :
dset_affine = os . path . split ( nl . suffix (... |
def run ( self , verbose = False ) :
"""Del user modules to force Python to deeply reload them
Do not del modules which are considered as system modules , i . e .
modules installed in subdirectories of Python interpreter ' s binary
Do not del C modules""" | log = [ ]
modules_copy = dict ( sys . modules )
for modname , module in modules_copy . items ( ) :
if modname == 'aaaaa' :
print ( modname , module )
print ( self . previous_modules )
if modname not in self . previous_modules :
modpath = getattr ( module , '__file__' , None )
if ... |
def row_factory ( cursor , row ) :
"""Returns a sqlite row factory that returns a dictionary""" | d = { }
for idx , col in enumerate ( cursor . description ) :
d [ col [ 0 ] ] = row [ idx ]
return d |
def get_mean_and_stddevs ( self , sctx , rctx , dctx , imt , stddev_types ) :
"""Returns the mean and standard deviations""" | # Return Distance Tables
imls = self . _return_tables ( rctx . mag , imt , "IMLs" )
# Get distance vector for the given magnitude
idx = numpy . searchsorted ( self . m_w , rctx . mag )
dists = self . distances [ : , 0 , idx - 1 ]
# Get mean and standard deviations
mean = self . _get_mean ( imls , dctx , dists )
stddevs... |
def _get_indexers_coords_and_indexes ( self , indexers ) :
"""Extract coordinates from indexers .
Returns an OrderedDict mapping from coordinate name to the
coordinate variable .
Only coordinate with a name different from any of self . variables will
be attached .""" | from . dataarray import DataArray
coord_list = [ ]
indexes = OrderedDict ( )
for k , v in indexers . items ( ) :
if isinstance ( v , DataArray ) :
v_coords = v . coords
if v . dtype . kind == 'b' :
if v . ndim != 1 : # we only support 1 - d boolean array
raise ValueError ... |
def image_update ( id = None , name = None , profile = None , ** kwargs ) : # pylint : disable = C0103
'''Update properties of given image .
Known to work for :
- min _ ram ( in MB )
- protected ( bool )
- visibility ( ' public ' or ' private ' )
CLI Example :
. . code - block : : bash
salt ' * ' glan... | if id :
image = image_show ( id = id , profile = profile )
if 'result' in image and not image [ 'result' ] :
return image
elif len ( image ) == 1 :
image = image . values ( ) [ 0 ]
elif name :
img_list = image_list ( name = name , profile = profile )
if img_list is dict and 'result' ... |
def _post_md5_skip_on_check ( self , key , md5_match ) : # type : ( Uploader , str , bool ) - > None
"""Perform post MD5 skip on check
: param Uploader self : this
: param str key : md5 map key
: param bool md5 _ match : if MD5 matches""" | with self . _md5_meta_lock :
src , rfile = self . _md5_map . pop ( key )
uid = blobxfer . operations . upload . Uploader . create_unique_id ( src , rfile )
if md5_match :
with self . _upload_lock :
self . _upload_set . remove ( uid )
self . _upload_total -= 1
if self . _general_options . dry... |
def add_fog ( img , fog_coef , alpha_coef , haze_list ) :
"""Add fog to the image .
From https : / / github . com / UjjwalSaxena / Automold - - Road - Augmentation - Library
Args :
img ( np . array ) :
fog _ coef ( float ) :
alpha _ coef ( float ) :
haze _ list ( list ) :
Returns :""" | non_rgb_warning ( img )
input_dtype = img . dtype
needs_float = False
if input_dtype == np . float32 :
img = from_float ( img , dtype = np . dtype ( 'uint8' ) )
needs_float = True
elif input_dtype not in ( np . uint8 , np . float32 ) :
raise ValueError ( 'Unexpected dtype {} for RandomFog augmentation' . fo... |
def check_lengths ( * arrays ) :
"""tool to ensure input and output data have the same number of samples
Parameters
* arrays : iterable of arrays to be checked
Returns
None""" | lengths = [ len ( array ) for array in arrays ]
if len ( np . unique ( lengths ) ) > 1 :
raise ValueError ( 'Inconsistent data lengths: {}' . format ( lengths ) ) |
def get_mask_from_raster ( rasterfile , outmaskfile , keep_nodata = False ) :
"""Generate mask data from a given raster data .
Args :
rasterfile : raster file path .
outmaskfile : output mask file path .
Returns :
Raster object of mask data .""" | raster_r = RasterUtilClass . read_raster ( rasterfile )
xsize = raster_r . nCols
ysize = raster_r . nRows
nodata_value = raster_r . noDataValue
srs = raster_r . srs
x_min = raster_r . xMin
y_max = raster_r . yMax
dx = raster_r . dx
data = raster_r . data
if not keep_nodata :
i_min = ysize - 1
i_max = 0
j_mi... |
def MakeSuiteFromDict ( d , name = '' ) :
"""Makes a suite from a map from values to probabilities .
Args :
d : dictionary that maps values to probabilities
name : string name for this suite
Returns :
Suite object""" | suite = Suite ( name = name )
suite . SetDict ( d )
suite . Normalize ( )
return suite |
def appendBlock ( self , block ) :
'''append / appendBlock - Append a block to this element . A block can be a string ( text node ) , or an AdvancedTag ( tag node )
@ param < str / AdvancedTag > - block to add
@ return - # block
NOTE : To add multiple blocks , @ see appendBlocks
If you know the type , use e... | # Determine block type and call appropriate method
if isinstance ( block , AdvancedTag ) :
self . appendNode ( block )
else :
self . appendText ( block )
return block |
def average_sharded_losses ( sharded_losses ) :
"""Average losses across datashards .
Args :
sharded _ losses : list < dict < str loss _ name , Tensor loss > > . The loss
can be a single Tensor or a 2 - tuple ( numerator and denominator ) .
Returns :
losses : dict < str loss _ name , Tensor avg _ loss >""... | losses = { }
for loss_name in sorted ( sharded_losses [ 0 ] ) :
all_shards = [ shard_losses [ loss_name ] for shard_losses in sharded_losses ]
if isinstance ( all_shards [ 0 ] , tuple ) :
sharded_num , sharded_den = zip ( * all_shards )
mean_loss = ( tf . add_n ( sharded_num ) / tf . maximum ( t... |
def create_tree_from_string ( line ) :
"""Parse and convert a string representation
of an example into a LabeledTree datastructure .
Arguments :
line : str , string version of the tree .
Returns :
LabeledTree : parsed tree .""" | depth = 0
current_word = ""
root = None
current_node = root
for char in line :
if char == '(' :
if current_node is not None and len ( current_word ) > 0 :
attribute_text_label ( current_node , current_word )
current_word = ""
depth += 1
if depth > 1 : # replace curren... |
def sort_cyclic_graph_best_effort ( graph , pick_first = 'head' ) :
"""Fallback for cases in which the graph has cycles .""" | ordered = [ ]
visited = set ( )
# Go first on the pick _ first chain then go back again on the others
# that were not visited . Given the way the graph is built both chains
# will always contain all the elements .
if pick_first == 'head' :
fst_attr , snd_attr = ( 'head_node' , 'update_node' )
else :
fst_attr , ... |
def _trim_zeros ( * char_lists ) :
"""Trim any zeros from provided character lists
Checks the beginning of any provided lists for ' 0 ' s and removes any
such leading zeros . Operates on ( and possibly ) alters the passed
list
: param list char _ lists : a list or lists of characters
: return : None
: r... | logger . debug ( '_trim_zeros(%s)' , char_lists )
for char_list in char_lists :
while len ( char_list ) != 0 and char_list [ 0 ] == '0' :
char_list . pop ( 0 )
logger . debug ( 'updated block: %s' , char_list ) |
def paste_clipboard_data ( self , data , paste_mode = PasteMode . EMACS , count = 1 ) :
"""Return a new : class : ` . Document ` instance which contains the result if
we would paste this data at the current cursor position .
: param paste _ mode : Where to paste . ( Before / after / emacs . )
: param count : ... | assert isinstance ( data , ClipboardData )
assert paste_mode in ( PasteMode . VI_BEFORE , PasteMode . VI_AFTER , PasteMode . EMACS )
before = ( paste_mode == PasteMode . VI_BEFORE )
after = ( paste_mode == PasteMode . VI_AFTER )
if data . type == SelectionType . CHARACTERS :
if after :
new_text = ( self . t... |
def add_file_to_tree ( tree , file_path , file_contents , is_executable = False ) :
"""Add a file to a tree .
Args :
tree
A list of dicts containing info about each blob in a tree .
file _ path
The path of the new file in the tree .
file _ contents
The ( UTF - 8 encoded ) contents of the new file .
... | record = { "path" : file_path , "mode" : "100755" if is_executable else "100644" , "type" : "blob" , "content" : file_contents , }
tree . append ( record )
return tree |
def ProcessHttpResponse ( self , method_config , http_response , request = None ) :
"""Convert an HTTP response to the expected message type .""" | return self . __client . ProcessResponse ( method_config , self . __ProcessHttpResponse ( method_config , http_response , request ) ) |
def leading_whitespace ( self , line ) : # type : ( str ) - > str
"""For preserving indents
: param line :
: return :""" | string = ""
for char in line :
if char in " \t" :
string += char
continue
else :
return string
return string |
def opcode ( * opcodes ) :
"""A decorator for opcodes""" | def decorator ( func ) :
setattr ( func , "_is_opcode" , True )
setattr ( func , "_opcodes" , opcodes )
return func
return decorator |
def as_dict ( df , ix = ':' ) :
"""converts df to dict and adds a datetime field if df is datetime""" | if isinstance ( df . index , pd . DatetimeIndex ) :
df [ 'datetime' ] = df . index
return df . to_dict ( orient = 'records' ) [ ix ] |
def keysym_to_string ( keysym ) :
'''Translate a keysym ( 16 bit number ) into a python string .
This will pass 0 to 0xff as well as XK _ BackSpace , XK _ Tab , XK _ Clear ,
XK _ Return , XK _ Pause , XK _ Scroll _ Lock , XK _ Escape , XK _ Delete . For other
values it returns None .''' | # ISO latin 1 , LSB is the code
if keysym & 0xff00 == 0 :
return chr ( keysym & 0xff )
if keysym in [ XK_BackSpace , XK_Tab , XK_Clear , XK_Return , XK_Pause , XK_Scroll_Lock , XK_Escape , XK_Delete ] :
return chr ( keysym & 0xff )
# We should be able to do these things quite automatically
# for latin2 , latin3... |
def succeed ( self , instance , action ) :
"""Returns if the task for the instance took place successfully""" | uid = api . get_uid ( instance )
return self . objects . get ( uid , { } ) . get ( action , { } ) . get ( 'success' , False ) |
def do_batch ( args ) :
"""Runs the batch list , batch show or batch status command , printing output
to the console
Args :
args : The parsed arguments sent to the command at runtime""" | if args . subcommand == 'list' :
do_batch_list ( args )
if args . subcommand == 'show' :
do_batch_show ( args )
if args . subcommand == 'status' :
do_batch_status ( args )
if args . subcommand == 'submit' :
do_batch_submit ( args ) |
def folderitem ( self , obj , item , index ) :
"""Service triggered each time an item is iterated in folderitems .
The use of this service prevents the extra - loops in child objects .
: obj : the instance of the class to be foldered
: item : dict containing the properties of the object to be used by
the te... | # ensure we have an object and not a brain
obj = api . get_object ( obj )
uid = api . get_uid ( obj )
# settings for this analysis
service_settings = self . context . getAnalysisServiceSettings ( uid )
hidden = service_settings . get ( "hidden" , obj . getHidden ( ) )
# get the category
category = obj . getCategoryTitl... |
def _get_scheduler ( self , net , policy , ** scheduler_kwargs ) :
"""Return scheduler , based on indicated policy , with appropriate
parameters .""" | if policy not in [ CyclicLR , ReduceLROnPlateau ] and 'last_epoch' not in scheduler_kwargs :
last_epoch = len ( net . history ) - 1
scheduler_kwargs [ 'last_epoch' ] = last_epoch
if policy is CyclicLR and 'last_batch_idx' not in scheduler_kwargs :
scheduler_kwargs [ 'last_batch_idx' ] = self . batch_idx_ - ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.