signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def install_package ( self , client , package ) :
"""Install package using distro specific install method .""" | try :
out = self . distro . install_package ( client , package )
except Exception as error :
raise IpaCloudException ( 'Failed installing package, "{0}"; {1}.' . format ( package , error ) )
else :
self . _write_to_log ( out ) |
def wrap ( self , value ) :
'''Validate and then wrap ` ` value ` ` for insertion .
: param value : the tuple ( or list ) to wrap''' | self . validate_wrap ( value )
ret = [ ]
for field , value in izip ( self . types , value ) :
ret . append ( field . wrap ( value ) )
return ret |
def listed ( self ) :
"""Print blacklist packages""" | print ( "\nPackages in the blacklist:\n" )
for black in self . get_black ( ) :
if black :
print ( "{0}{1}{2}" . format ( self . meta . color [ "GREEN" ] , black , self . meta . color [ "ENDC" ] ) )
self . quit = True
if self . quit :
print ( "" ) |
def create_layer ( self , lipid_indices = None , flip_orientation = False ) :
"""Create a monolayer of lipids .
Parameters
lipid _ indices : list , optional , default = None
A list of indices associated with each lipid in the layer .
flip _ orientation : bool , optional , default = False
Flip the orientat... | layer = mb . Compound ( )
if not lipid_indices :
lipid_indices = list ( range ( self . n_lipids_per_layer ) )
shuffle ( lipid_indices )
for n_type , n_of_lipid_type in enumerate ( self . number_of_each_lipid_per_layer ) :
current_type = self . lipids [ n_type ] [ 0 ]
for n_this_type , n_this_lipid_type ... |
def _add_meta_info ( self , eopatch , request_params , service_type ) :
"""Adds any missing metadata info to EOPatch""" | for param , eoparam in zip ( [ 'time' , 'time_difference' , 'maxcc' ] , [ 'time_interval' , 'time_difference' , 'maxcc' ] ) :
if eoparam not in eopatch . meta_info :
eopatch . meta_info [ eoparam ] = request_params [ param ]
if 'service_type' not in eopatch . meta_info :
eopatch . meta_info [ 'service_t... |
def get_message ( self , msglevels = None , joiner = None ) :
"""the final message for mult - checks
arguments :
msglevels : an array of all desired levels ( ex : [ CRITICAL , WARNING ] )
joiner : string used to join all messages ( default : ' , ' )
returns :
one - line message created with input results ... | messages = [ ]
if joiner is None :
joiner = ', '
if msglevels is None :
msglevels = [ OK , WARNING , CRITICAL ]
for result in self . _results :
if result . code in msglevels :
messages . append ( result . message )
return joiner . join ( [ msg for msg in messages if msg ] ) |
def get_server_capabilities ( self ) :
"""Gets server properties which can be used for scheduling
: returns : a dictionary of hardware properties like firmware
versions , server model .
: raises : IloError , if iLO returns an error in command execution .""" | capabilities = { }
system = self . _get_host_details ( )
capabilities [ 'server_model' ] = system [ 'Model' ]
rom_firmware_version = ( system [ 'Oem' ] [ 'Hp' ] [ 'Bios' ] [ 'Current' ] [ 'VersionString' ] )
capabilities [ 'rom_firmware_version' ] = rom_firmware_version
capabilities . update ( self . _get_ilo_firmware_... |
def encrypt ( self , data , pad = True ) :
"""DES encrypts the data based on the key it was initialised with .
: param data : The bytes string to encrypt
: param pad : Whether to right pad data with \x00 to a multiple of 8
: return : The encrypted bytes string""" | encrypted_data = b""
for i in range ( 0 , len ( data ) , 8 ) :
block = data [ i : i + 8 ]
block_length = len ( block )
if block_length != 8 and pad :
block += b"\x00" * ( 8 - block_length )
elif block_length != 8 :
raise ValueError ( "DES encryption must be a multiple of 8 " "bytes" )
... |
def _createConnectivity ( self , linkList , connectList ) :
"""Create GSSHAPY Connect Object Method""" | # Create StreamLink - Connectivity Pairs
for idx , link in enumerate ( linkList ) :
connectivity = connectList [ idx ]
# Initialize GSSHAPY UpstreamLink objects
for upLink in connectivity [ 'upLinks' ] :
upstreamLink = UpstreamLink ( upstreamLinkID = int ( upLink ) )
upstreamLink . streamLin... |
def describe_vpc_peering_connection ( name , region = None , key = None , keyid = None , profile = None ) :
'''Returns any VPC peering connection id ( s ) for the given VPC
peering connection name .
VPC peering connection ids are only returned for connections that
are in the ` ` active ` ` , ` ` pending - acc... | conn = _get_conn3 ( region = region , key = key , keyid = keyid , profile = profile )
return { 'VPC-Peerings' : _get_peering_connection_ids ( name , conn ) } |
def validate_regex ( ctx , param , value ) :
"""Validate that a provided regex compiles .""" | if not value :
return None
try :
re . compile ( value )
except re . error :
raise click . BadParameter ( 'Invalid regex "{0}" provided' . format ( value ) )
return value |
def get_ids_in_region ( self , resource , resolution , x_range , y_range , z_range , time_range , url_prefix , auth , session , send_opts ) :
"""Get all ids in the region defined by x _ range , y _ range , z _ range .
Args :
resource ( intern . resource . Resource ) : An annotation channel .
resolution ( int ... | if not isinstance ( resource , ChannelResource ) :
raise TypeError ( 'resource must be ChannelResource' )
if resource . type != 'annotation' :
raise TypeError ( 'Channel is not an annotation channel' )
req = self . get_ids_request ( resource , 'GET' , 'application/json' , url_prefix , auth , resolution , x_rang... |
def compile_change ( self , blueprint , command , connection ) :
"""Compile a change column command into a series of SQL statement .
: param blueprint : The blueprint
: type blueprint : Blueprint
: param command : The command
: type command : Fluent
: param connection : The connection
: type connection ... | schema = connection . get_schema_manager ( )
table_diff = self . _get_changed_diff ( blueprint , schema )
if table_diff :
sql = schema . get_database_platform ( ) . get_alter_table_sql ( table_diff )
if isinstance ( sql , list ) :
return sql
return [ sql ]
return [ ] |
def methodcaller ( name , * args ) :
"""Upstream bug in python :
https : / / bugs . python . org / issue26822""" | func = operator . methodcaller ( name , * args )
return lambda obj , ** kwargs : func ( obj ) |
def start_child_span ( parent_span , operation_name , tags = None , start_time = None ) :
"""A shorthand method that starts a ` child _ of ` : class : ` Span ` for a given
parent : class : ` Span ` .
Equivalent to calling : :
parent _ span . tracer ( ) . start _ span (
operation _ name ,
references = open... | return parent_span . tracer . start_span ( operation_name = operation_name , child_of = parent_span , tags = tags , start_time = start_time ) |
def to_row ( advice ) :
'''Serialize an advice into a CSV row''' | return [ advice . id , advice . administration , advice . type , advice . session . year , advice . session . strftime ( '%d/%m/%Y' ) , advice . subject , ', ' . join ( advice . topics ) , ', ' . join ( advice . tags ) , ', ' . join ( advice . meanings ) , ROMAN_NUMS . get ( advice . part , '' ) , advice . content , ] |
def artifact_cache_dir ( self ) :
"""Note that this is unrelated to the general pants artifact cache .""" | return ( self . get_options ( ) . artifact_cache_dir or os . path . join ( self . scratch_dir , 'artifacts' ) ) |
def check_login ( func ) :
"""检查用户登录状态
: param func : 需要被检查的函数""" | @ wraps ( func )
def wrapper ( * args , ** kwargs ) :
ret = func ( * args , ** kwargs )
if type ( ret ) == requests . Response : # 检测结果是否为JSON
if ret . content [ 0 ] != b'{' and ret . content [ 0 ] != b'[' :
return ret
try :
foo = json . loads ( ret . content . decode ( '... |
def stop ( self ) :
"""Stop tracing""" | # Stop tracing
sys . settrace ( None )
# Build group structure if group filter is defined
if self . grpflt is not None : # Iterate over graph nodes ( functions )
for k in self . fncts : # Construct group identity string
m = self . grpflt . search ( k )
# If group identity string found , append curre... |
def _ContinueReportCompilation ( self ) :
"""Determines if the plugin should continue trying to compile the report .
Returns :
bool : True if the plugin should continue , False otherwise .""" | analyzer_alive = self . _analyzer . is_alive ( )
hash_queue_has_tasks = self . hash_queue . unfinished_tasks > 0
analysis_queue = not self . hash_analysis_queue . empty ( )
# pylint : disable = consider - using - ternary
return ( analyzer_alive and hash_queue_has_tasks ) or analysis_queue |
def filter_somaticsniper ( job , tumor_bam , somaticsniper_output , tumor_pileup , univ_options , somaticsniper_options ) :
"""Filter SomaticSniper calls .
: param dict tumor _ bam : Dict of bam and bai for tumor DNA - Seq
: param toil . fileStore . FileID somaticsniper _ output : SomaticSniper output vcf
: p... | work_dir = os . getcwd ( )
input_files = { 'tumor.bam' : tumor_bam [ 'tumor_dna_fix_pg_sorted.bam' ] , 'tumor.bam.bai' : tumor_bam [ 'tumor_dna_fix_pg_sorted.bam.bai' ] , 'input.vcf' : somaticsniper_output , 'pileup.txt' : tumor_pileup , 'genome.fa.tar.gz' : somaticsniper_options [ 'genome_fasta' ] , 'genome.fa.fai.tar... |
def create ( self , to , channel , custom_message = values . unset , send_digits = values . unset , locale = values . unset , custom_code = values . unset , amount = values . unset , payee = values . unset ) :
"""Create a new VerificationInstance
: param unicode to : The phone number to verify
: param unicode c... | data = values . of ( { 'To' : to , 'Channel' : channel , 'CustomMessage' : custom_message , 'SendDigits' : send_digits , 'Locale' : locale , 'CustomCode' : custom_code , 'Amount' : amount , 'Payee' : payee , } )
payload = self . _version . create ( 'POST' , self . _uri , data = data , )
return VerificationInstance ( se... |
def _etextno_to_uri_subdirectory ( etextno ) :
"""Returns the subdirectory that an etextno will be found in a gutenberg
mirror . Generally , one finds the subdirectory by separating out each digit
of the etext number , and uses it for a directory . The exception here is for
etext numbers less than 10 , which ... | str_etextno = str ( etextno ) . zfill ( 2 )
all_but_last_digit = list ( str_etextno [ : - 1 ] )
subdir_part = "/" . join ( all_but_last_digit )
subdir = "{}/{}" . format ( subdir_part , etextno )
# etextno not zfilled
return subdir |
def matches_pattern ( self , other ) :
"""Test if the current instance matches a template instance .""" | ismatch = False
if isinstance ( other , Userdata ) :
for key in self . _userdata :
if self . _userdata [ key ] is None or other [ key ] is None :
ismatch = True
elif self . _userdata [ key ] == other [ key ] :
ismatch = True
else :
ismatch = False
... |
def mean_harmonic ( self ) :
'返回DataStruct . price的调和平均数' | res = self . price . groupby ( level = 1 ) . apply ( lambda x : statistics . harmonic_mean ( x ) )
res . name = 'mean_harmonic'
return res |
def visitMembersDef ( self , ctx : jsgParser . MembersDefContext ) :
"""membersDef : COMMA | member + ( BAR altMemberDef ) * ( BAR lastComma ) ? ;
altMemberDef : member * ;
member : pairDef COMMA ?
lastComma : COMMA ;""" | if not self . _name :
self . _name = self . _context . anon_id ( )
if ctx . COMMA ( ) : # lone comma - wild card
self . _strict = False
if not ctx . BAR ( ) : # member +
self . visitChildren ( ctx )
else :
entry = 1
self . _add_choice ( entry , ctx . member ( ) )
# add first brance ( member + )
... |
def log ( self , level , message , exc_info = None , reference = None ) : # pylint : disable = W0212
"""Logs a message , possibly with an exception
: param level : Severity of the message ( Python logging level )
: param message : Human readable message
: param exc _ info : The exception context ( sys . exc _... | if not isinstance ( reference , pelix . framework . ServiceReference ) : # Ensure we have a clean Service Reference
reference = None
if exc_info is not None : # Format the exception to avoid memory leaks
try :
exception_str = "\n" . join ( traceback . format_exception ( * exc_info ) )
except ( TypeE... |
def ISBNValidator ( raw_isbn ) :
"""Check string is a valid ISBN number""" | isbn_to_check = raw_isbn . replace ( '-' , '' ) . replace ( ' ' , '' )
if not isinstance ( isbn_to_check , string_types ) :
raise ValidationError ( _ ( u'Invalid ISBN: Not a string' ) )
if len ( isbn_to_check ) != 10 and len ( isbn_to_check ) != 13 :
raise ValidationError ( _ ( u'Invalid ISBN: Wrong length' ) )... |
def request ( self , identifier , version = None , format = None ) :
"""Retrieve a named schema , with optional revision and type .
* identifier * name of the schema to be retrieved
* version * version of schema to get
* format * format of the schema to be retrieved , yang is the default
: seealso : : ref :... | node = etree . Element ( qualify ( "get-schema" , NETCONF_MONITORING_NS ) )
if identifier is not None :
elem = etree . Element ( qualify ( "identifier" , NETCONF_MONITORING_NS ) )
elem . text = identifier
node . append ( elem )
if version is not None :
elem = etree . Element ( qualify ( "version" , NETC... |
def _create_eni_if_necessary ( interface , vm_ ) :
'''Create an Elastic Interface if necessary and return a Network Interface Specification''' | if 'NetworkInterfaceId' in interface and interface [ 'NetworkInterfaceId' ] is not None :
return { 'DeviceIndex' : interface [ 'DeviceIndex' ] , 'NetworkInterfaceId' : interface [ 'NetworkInterfaceId' ] }
params = { 'Action' : 'DescribeSubnets' }
subnet_query = aws . query ( params , return_root = True , location =... |
def find ( self , resource_format , ids = None ) :
"""Find Resource object for any addressable resource on the server .
This method is a universal resource locator for any REST - ful resource in JIRA . The
argument ` ` resource _ format ` ` is a string of the form ` ` resource ` ` , ` ` resource / { 0 } ` ` ,
... | resource = Resource ( resource_format , self . _options , self . _session )
resource . find ( ids )
return resource |
def create ( provider , instances , opts = None , ** kwargs ) :
'''Create an instance using Salt Cloud
CLI Example :
. . code - block : : bash
salt - run cloud . create my - ec2 - config myinstance image = ami - 1624987f size = ' t1 . micro ' ssh _ username = ec2 - user securitygroup = default delvol _ on _ d... | client = _get_client ( )
if isinstance ( opts , dict ) :
client . opts . update ( opts )
info = client . create ( provider , instances , ** salt . utils . args . clean_kwargs ( ** kwargs ) )
return info |
def GetHashType ( self , hash_str ) :
"""Identify the type of hash in a hash string .
Args :
hash _ str : A string value that may be a hash .
Returns :
A string description of the type of hash .""" | # Return the type of the first matching hash .
for hash_type , hash_re in self . hashes :
if hash_re . match ( hash_str ) :
return hash_type
# No hash matched .
return "EMPTY" |
def _run_train_step ( self , train_X ) :
"""Run a training step .
A training step is made by randomly corrupting the training set ,
randomly shuffling it , divide it into batches and run the optimizer
for each batch .
Parameters
train _ X : array _ like
Training data , shape ( num _ samples , num _ feat... | x_corrupted = utilities . corrupt_input ( train_X , self . tf_session , self . corr_type , self . corr_frac )
shuff = list ( zip ( train_X , x_corrupted ) )
np . random . shuffle ( shuff )
batches = [ _ for _ in utilities . gen_batches ( shuff , self . batch_size ) ]
for batch in batches :
x_batch , x_corr_batch = ... |
def _do_download ( version , download_base , to_dir , download_delay ) :
"""Download Setuptools .""" | py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}' . format ( sys = sys )
tp = 'setuptools-{version}-{py_desig}.egg'
egg = os . path . join ( to_dir , tp . format ( ** locals ( ) ) )
if not os . path . exists ( egg ) :
archive = download_setuptools ( version , download_base , to_dir , download_delay )
_... |
def handle_request ( self ) :
"""Handle one request , possibly blocking .
Respects self . timeout .""" | # Support people who used socket . settimeout ( ) to escape
# handle _ request before self . timeout was available .
timeout = self . socket . gettimeout ( )
if timeout is None :
timeout = self . timeout
elif self . timeout is not None :
timeout = min ( timeout , self . timeout )
fd_sets = select . select ( [ s... |
def create_action ( parent , text , shortcut = None , icon = None , tip = None , toggled = None , triggered = None , data = None , menurole = None , context = Qt . WindowShortcut ) :
"""Create a QAction""" | action = QAction ( text , parent )
if triggered is not None :
action . triggered . connect ( triggered )
if toggled is not None :
action . toggled . connect ( toggled )
action . setCheckable ( True )
if icon is not None :
action . setIcon ( icon )
if shortcut is not None :
action . setShortcut ( sho... |
def strip_prefix_from_items ( prefix , items ) :
"""Strips out the prefix from each of the items if it is present .
Args :
prefix : the string for that you wish to strip from the beginning of each
of the items .
items : a list of strings that may or may not contain the prefix you want
to strip out .
Ret... | items_no_prefix = [ ]
for item in items :
if item . startswith ( prefix ) :
items_no_prefix . append ( item [ len ( prefix ) : ] )
else :
items_no_prefix . append ( item )
return items_no_prefix |
def manhattan_distant ( vector1 , vector2 ) :
"""曼哈顿距离""" | vector1 = np . mat ( vector1 )
vector2 = np . mat ( vector2 )
return np . sum ( np . abs ( vector1 - vector2 ) ) |
def _set_loopback ( self , v , load = False ) :
"""Setter method for loopback , mapped from YANG variable / interface / ethernet / loopback ( enumeration )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ loopback is considered as a private
method . Backends looking to... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'phy' : { 'value' : 1 } } , ) , is_leaf = True , yang_name = "loopback" , rest_name = "loopback" , parent = self , path_helper =... |
def c ( self ) :
"""continue""" | i , node = self . _get_next_eval ( )
if node . name in self . _bpset :
if self . state == RUNNING :
return self . _break ( )
self . state = RUNNING
self . _eval ( node )
# increment to next node
self . step = i + 1
if self . step < len ( self . _exe_order ) :
return self . c ( )
else :
return self .... |
def download_threads ( self , url ) :
"""Download the allele files""" | # Set the name of the allele file - split the gene name from the URL
output_file = os . path . join ( self . output_path , '{}.tfa' . format ( os . path . split ( url ) [ - 1 ] ) )
# Check to see whether the file already exists , and if it is unusually small
size = 0
try :
stats = os . stat ( output_file )
size... |
def on_epoch_end ( self , epoch , logs = { } ) :
'''Run on end of each epoch''' | LOG . debug ( logs )
nni . report_intermediate_result ( logs [ "val_acc" ] ) |
def strip_headers ( text ) :
"""Remove lines that are part of the Project Gutenberg header or footer .
Note : this function is a port of the C + + utility by Johannes Krugel . The
original version of the code can be found at :
http : / / www14 . in . tum . de / spp1307 / src / strip _ headers . cpp
Args :
... | lines = text . splitlines ( )
sep = str ( os . linesep )
out = [ ]
i = 0
footer_found = False
ignore_section = False
for line in lines :
reset = False
if i <= 600 : # Check if the header ends here
if any ( line . startswith ( token ) for token in TEXT_START_MARKERS ) :
reset = True
#... |
def get ( self , data_type , options = None ) :
"""Get a single item
: param data _ type : str
: param options : dict
: return : dict | str""" | if options is None :
options = { }
response = self . _client . session . get ( '{url}/{type}' . format ( url = self . endpoint_url , type = data_type ) , params = options )
return self . process_response ( response ) |
def fix_include ( model_code ) :
"""Reformat ` model _ code ` ( remove whitespace ) around the # include statements .
Note
A modified ` model _ code ` is returned .
Parameters
model _ code : str
Model code
Returns
str
Reformatted model code
Example
> > > from pystan . experimental import fix _ i... | pattern = r"(?<=\n)\s*(#include)\s*(\S+)\s*(?=\n)"
model_code , n = re . subn ( pattern , r"\1 \2" , model_code )
if n == 1 :
msg = "Made {} substitution for the model_code"
else :
msg = "Made {} substitutions for the model_code"
logger . info ( msg . format ( n ) )
return model_code |
def getAsWmsDatasetString ( self , session ) :
"""Retrieve the WMS Raster as a string in the WMS Dataset format""" | # Magic numbers
FIRST_VALUE_INDEX = 12
# Write value raster
if type ( self . raster ) != type ( None ) : # Convert to GRASS ASCII Raster
valueGrassRasterString = self . getAsGrassAsciiGrid ( session )
# Split by lines
values = valueGrassRasterString . split ( )
# Assemble into string
wmsDatasetStrin... |
def eccentricity ( self , ** kw ) :
r"""Returns the eccentricity computed from the mean apocenter and
mean pericenter .
. . math : :
e = \ frac { r _ { \ rm apo } - r _ { \ rm per } } { r _ { \ rm apo } + r _ { \ rm per } }
Parameters
* * kw
Any keyword arguments passed to ` ` apocenter ( ) ` ` and
` ... | ra = self . apocenter ( ** kw )
rp = self . pericenter ( ** kw )
return ( ra - rp ) / ( ra + rp ) |
def set_target_from_config ( self , cp , section ) :
"""Sets the target using the given config file .
This looks for ` ` niterations ` ` to set the ` ` target _ niterations ` ` , and
` ` effective - nsamples ` ` to set the ` ` target _ eff _ nsamples ` ` .
Parameters
cp : ConfigParser
Open config parser t... | if cp . has_option ( section , "niterations" ) :
niterations = int ( cp . get ( section , "niterations" ) )
else :
niterations = None
if cp . has_option ( section , "effective-nsamples" ) :
nsamples = int ( cp . get ( section , "effective-nsamples" ) )
else :
nsamples = None
self . set_target ( niterati... |
async def fire ( self , evtname , ** info ) :
'''Fire the given event name on the Base .
Returns a list of the return values of each callback .
Example :
for ret in d . fire ( ' woot ' , foo = ' asdf ' ) :
print ( ' got : % r ' % ( ret , ) )''' | event = ( evtname , info )
if self . isfini :
return event
await self . dist ( event )
return event |
def until_state_in ( self , * states , ** kwargs ) :
"""Return a tornado Future , resolves when any of the requested states is set""" | timeout = kwargs . get ( 'timeout' , None )
state_futures = ( self . until_state ( s , timeout = timeout ) for s in states )
return until_any ( * state_futures ) |
def __set_recent_files_actions ( self ) :
"""Sets the recent files actions .""" | recentFiles = [ foundations . strings . to_string ( file ) for file in self . __settings . get_key ( self . __settings_section , "recentFiles" ) . toStringList ( ) if foundations . common . path_exists ( file ) ]
if not recentFiles :
return
numberRecentFiles = min ( len ( recentFiles ) , self . __maximum_recent_fil... |
def _save_function_initial_state ( self , function_key , function_address , state ) :
"""Save the initial state of a function , and merge it with existing ones if there are any .
: param FunctionKey function _ key : The key to this function .
: param int function _ address : Address of the function .
: param ... | l . debug ( 'Saving the initial state for function %#08x with function key %s' , function_address , function_key )
if function_key in self . _function_initial_states [ function_address ] :
existing_state = self . _function_initial_states [ function_address ] [ function_key ]
merged_state , _ , _ = existing_stat... |
def coupling_matrix ( self , lmax , nwin = None , weights = None , mode = 'full' ) :
"""Return the coupling matrix of the first nwin tapers . This matrix
relates the global power spectrum to the expectation of the localized
multitaper spectrum .
Usage
Mmt = x . coupling _ matrix ( lmax , [ nwin , weights , ... | if weights is not None :
if nwin is not None :
if len ( weights ) != nwin :
raise ValueError ( 'Length of weights must be equal to nwin. ' + 'len(weights) = {:d}, nwin = {:d}' . format ( len ( weights ) , nwin ) )
else :
if len ( weights ) != self . nwin :
raise ValueErro... |
def _ll_pre_transform ( self , train_tfm : List [ Callable ] , valid_tfm : List [ Callable ] ) :
"Call ` train _ tfm ` and ` valid _ tfm ` after opening image , before converting from ` PIL . Image `" | self . train . x . after_open = compose ( train_tfm )
self . valid . x . after_open = compose ( valid_tfm )
return self |
def plot_prh_filtered ( p , r , h , p_lf , r_lf , h_lf ) :
'''Plot original and low - pass filtered PRH data
Args
p : ndarray
Derived pitch data
r : ndarray
Derived roll data
h : ndarray
Derived heading data
p _ lf : ndarray
Low - pass filtered pitch data
r _ lf : ndarray
Low - pass filtered r... | import numpy
fig , ( ax1 , ax2 , ax3 ) = plt . subplots ( 3 , 1 , sharex = 'col' )
# rad2deg = lambda x : x * 180 / numpy . pi
ax1 . title . set_text ( 'Pitch' )
ax1 . plot ( range ( len ( p ) ) , p , color = _colors [ 0 ] , linewidth = _linewidth , label = 'original' )
ax1 . plot ( range ( len ( p_lf ) ) , p_lf , colo... |
def post ( self , path , payload = None , headers = None ) :
"""HTTP POST operation .
: param path : URI Path
: param payload : HTTP Body
: param headers : HTTP Headers
: raises ApiError : Raises if the remote server encountered an error .
: raises ApiConnectionError : Raises if there was a connectivity i... | return self . _request ( 'post' , path , payload , headers ) |
def get_cursor_pos ( window ) :
"""Retrieves the last reported cursor position , relative to the client
area of the window .
Wrapper for :
void glfwGetCursorPos ( GLFWwindow * window , double * xpos , double * ypos ) ;""" | xpos_value = ctypes . c_double ( 0.0 )
xpos = ctypes . pointer ( xpos_value )
ypos_value = ctypes . c_double ( 0.0 )
ypos = ctypes . pointer ( ypos_value )
_glfw . glfwGetCursorPos ( window , xpos , ypos )
return xpos_value . value , ypos_value . value |
def join_session ( self , sid ) :
"""Attach to an existing session .""" | self . _rest . add_header ( 'X-STC-API-Session' , sid )
self . _sid = sid
try :
status , data = self . _rest . get_request ( 'objects' , 'system1' , [ 'version' , 'name' ] )
except resthttp . RestHttpError as e :
self . _rest . del_header ( 'X-STC-API-Session' )
self . _sid = None
raise RuntimeError ( '... |
def do_releases ( self , subcmd , opts , component ) :
"""$ { cmd _ name } : print all releases for the given component
$ { cmd _ usage }
$ { cmd _ option _ list }""" | releases = get_released_versions ( component )
for x in releases :
print ( "{} - {}" . format ( * x ) ) |
def total_statements ( self , filename = None ) :
"""Return the total number of statements for the file
` filename ` . If ` filename ` is not given , return the total
number of statements for all files .""" | if filename is not None :
statements = self . _get_lines_by_filename ( filename )
return len ( statements )
total = 0
for filename in self . files ( ) :
statements = self . _get_lines_by_filename ( filename )
total += len ( statements )
return total |
def launch_debugger ( frame , stream = None ) :
"""Interrupt running process , and provide a python prompt for
interactive debugging .""" | d = { '_frame' : frame }
# Allow access to frame object .
d . update ( frame . f_globals )
# Unless shadowed by global
d . update ( frame . f_locals )
import code , traceback
i = code . InteractiveConsole ( d )
message = "Signal received : entering python shell.\nTraceback:\n"
message += '' . join ( traceback . format_... |
def force_single_imports ( self ) :
"""force a single import per statement""" | for import_stmt in self . imports [ : ] :
import_info = import_stmt . import_info
if import_info . is_empty ( ) or import_stmt . readonly :
continue
if len ( import_info . names_and_aliases ) > 1 :
for name_and_alias in import_info . names_and_aliases :
if hasattr ( import_info ,... |
def bounds ( self ) :
"""Return the overall bounding box of the scene .
Returns
bounds : ( 2,3 ) float points for min , max corner""" | corners = self . bounds_corners
bounds = np . array ( [ corners . min ( axis = 0 ) , corners . max ( axis = 0 ) ] )
return bounds |
def distribute_covar_matrix_to_match_covariance_type ( tied_cv , covariance_type , n_components ) :
"""Create all the covariance matrices from a given template .""" | if covariance_type == 'spherical' :
cv = np . tile ( tied_cv . mean ( ) * np . ones ( tied_cv . shape [ 1 ] ) , ( n_components , 1 ) )
elif covariance_type == 'tied' :
cv = tied_cv
elif covariance_type == 'diag' :
cv = np . tile ( np . diag ( tied_cv ) , ( n_components , 1 ) )
elif covariance_type == 'full'... |
def cookie ( url , name , value , expires = None ) :
'''Return a new Cookie using a slightly more
friendly API than that provided by six . moves . http _ cookiejar
@ param name The cookie name { str }
@ param value The cookie value { str }
@ param url The URL path of the cookie { str }
@ param expires The... | u = urlparse ( url )
domain = u . hostname
if '.' not in domain and not _is_ip_addr ( domain ) :
domain += ".local"
port = str ( u . port ) if u . port is not None else None
secure = u . scheme == 'https'
if expires is not None :
if expires . tzinfo is not None :
raise ValueError ( 'Cookie expiration mu... |
def get_corpus ( self , corpus_id ) :
"""Return a corpus given an ID .
If the corpus ID cannot be found , an InvalidCorpusError is raised .
Parameters
corpus _ id : str
The ID of the corpus to return .
Returns
Corpus
The corpus with the given ID .""" | try :
corpus = self . corpora [ corpus_id ]
return corpus
except KeyError :
raise InvalidCorpusError |
def parse_url ( url ) :
"""Return a dictionary of parsed url
Including scheme , netloc , path , params , query , fragment , uri , username ,
password , host , port and http _ host""" | try :
url = unicode ( url )
except UnicodeDecodeError :
pass
if py3k :
make_utf8 = lambda x : x
else :
make_utf8 = lambda x : isinstance ( x , unicode ) and x . encode ( 'utf-8' ) or x
if '://' in url :
scheme , url = url . split ( '://' , 1 )
else :
scheme = 'http'
url = 'http://' + url
parsed ... |
def read ( filename , binary = True ) :
"""Open and read a file
: param filename : filename to open and read
: param binary : True if the file should be read as binary
: return : bytes if binary is True , str otherwise""" | with open ( filename , 'rb' if binary else 'r' ) as f :
return f . read ( ) |
def p_arguments ( self , p ) :
"""arguments : LPAREN RPAREN
| LPAREN argument _ list RPAREN""" | if len ( p ) == 4 :
p [ 0 ] = self . asttypes . Arguments ( p [ 2 ] )
else :
p [ 0 ] = self . asttypes . Arguments ( [ ] )
p [ 0 ] . setpos ( p ) |
def is_outbound_presence_filter ( cb ) :
"""Return true if ` cb ` has been decorated with
: func : ` outbound _ presence _ filter ` .""" | try :
handlers = get_magic_attr ( cb )
except AttributeError :
return False
hs = HandlerSpec ( ( _apply_outbound_presence_filter , ( ) ) )
return hs in handlers |
def setup ( db_class , simple_object_cls , primary_keys ) :
"""A simple API to configure the metadata""" | table_name = simple_object_cls . __name__
column_names = simple_object_cls . FIELDS
metadata = MetaData ( )
table = Table ( table_name , metadata , * [ Column ( cname , _get_best_column_type ( cname ) , primary_key = cname in primary_keys ) for cname in column_names ] )
db_class . metadata = metadata
db_class . mapper_... |
def get ( cls , id ) :
'''Retrieves an object by id . Returns None in case of failure''' | if not id :
return None
redis = cls . get_redis ( )
key = '{}:{}:obj' . format ( cls . cls_key ( ) , id )
if not redis . exists ( key ) :
return None
obj = cls ( id = id )
obj . _persisted = True
data = debyte_hash ( redis . hgetall ( key ) )
for fieldname , field in obj . proxy :
value = field . recover ( ... |
def clean_proc_dir ( opts ) :
'''Loop through jid files in the minion proc directory ( default / var / cache / salt / minion / proc )
and remove any that refer to processes that no longer exist''' | for basefilename in os . listdir ( salt . minion . get_proc_dir ( opts [ 'cachedir' ] ) ) :
fn_ = os . path . join ( salt . minion . get_proc_dir ( opts [ 'cachedir' ] ) , basefilename )
with salt . utils . files . fopen ( fn_ , 'rb' ) as fp_ :
job = None
try :
job = salt . payload .... |
def _process_publics ( self , contents ) :
"""Extracts a list of public members , types and executables that were declared using
the public keyword instead of a decoration .""" | matches = self . RE_PUBLIC . finditer ( contents )
result = { }
start = 0
for public in matches :
methods = public . group ( "methods" )
# We need to keep track of where the public declarations start so that the unit
# testing framework can insert public statements for those procedures being tested
# wh... |
def _highlight_line_udiff ( self , line , next ) :
"""Highlight inline changes in both lines .""" | start = 0
limit = min ( len ( line [ 'line' ] ) , len ( next [ 'line' ] ) )
while start < limit and line [ 'line' ] [ start ] == next [ 'line' ] [ start ] :
start += 1
end = - 1
limit -= start
while - end <= limit and line [ 'line' ] [ end ] == next [ 'line' ] [ end ] :
end -= 1
end += 1
if start or end :
d... |
def p_Case ( p ) :
'''Case : CASE ArgList COLON Terminator Block
| DEFAULT COLON Terminator Block''' | if p [ 1 ] == 'case' :
p [ 0 ] = Case ( p [ 1 ] , p [ 2 ] , p [ 4 ] , p [ 5 ] )
else :
p [ 0 ] = Case ( p [ 1 ] , None , p [ 3 ] , p [ 4 ] ) |
def first_paragraph ( multiline_str , without_trailing_dot = True , maxlength = None ) :
'''Return first paragraph of multiline _ str as a oneliner .
When without _ trailing _ dot is True , the last char of the first paragraph
will be removed , if it is a dot ( ' . ' ) .
Examples :
> > > multiline _ str = '... | stripped = '\n' . join ( [ line . strip ( ) for line in multiline_str . splitlines ( ) ] )
paragraph = stripped . split ( '\n\n' ) [ 0 ]
res = paragraph . replace ( '\n' , ' ' )
if without_trailing_dot :
res = res . rsplit ( '.' , 1 ) [ 0 ]
if maxlength :
res = res [ 0 : maxlength ]
return res |
def global_config ( cls , key , * args ) :
'''This reads or sets the global settings stored in class . settings .''' | if args :
cls . settings [ key ] = args [ 0 ]
else :
return cls . settings [ key ] |
def est_entropy ( self ) :
r"""Estimates the entropy of the current particle distribution
as : math : ` - \ sum _ i w _ i \ log w _ i ` where : math : ` \ { w _ i \ } `
is the set of particles with nonzero weight .""" | nz_weights = self . particle_weights [ self . particle_weights > 0 ]
return - np . sum ( np . log ( nz_weights ) * nz_weights ) |
def _getScalesRand ( self ) :
"""Internal function for parameter initialization
Return a vector of random scales""" | if self . P > 1 :
scales = [ ]
for term_i in range ( self . n_randEffs ) :
_scales = sp . randn ( self . diag [ term_i ] . shape [ 0 ] )
if self . jitter [ term_i ] > 0 :
_scales = sp . concatenate ( ( _scales , sp . array ( [ sp . sqrt ( self . jitter [ term_i ] ) ] ) ) )
sc... |
def add_cmd_method ( self , name , method , argc = None , complete = None ) :
"""Adds a command to the command line interface loop .
Parameters
name : string
The command .
method : function ( args )
The function to execute when this command is issued . The argument
of the function is a list of space sep... | if ' ' in name :
raise ValueError ( "' ' cannot be in command name {0}" . format ( name ) )
self . _cmd_methods [ name ] = method
self . _cmd_argc [ name ] = argc
self . _cmd_complete [ name ] = complete |
def get_default_config ( self ) :
"""Returns the default collector settings""" | default_config = super ( FlumeCollector , self ) . get_default_config ( )
default_config [ 'path' ] = 'flume'
default_config [ 'req_host' ] = 'localhost'
default_config [ 'req_port' ] = 41414
default_config [ 'req_path' ] = '/metrics'
return default_config |
def draw_text ( self , ax , text , force_trans = None , text_type = None ) :
"""Process a matplotlib text object and call renderer . draw _ text""" | content = text . get_text ( )
if content :
transform = text . get_transform ( )
position = text . get_position ( )
coords , position = self . process_transform ( transform , ax , position , force_trans = force_trans )
style = utils . get_text_style ( text )
self . renderer . draw_text ( text = conte... |
def require_mapping ( self ) -> None :
"""Require the node to be a mapping .""" | if not isinstance ( self . yaml_node , yaml . MappingNode ) :
raise RecognitionError ( ( '{}{}A mapping is required here' ) . format ( self . yaml_node . start_mark , os . linesep ) ) |
def translate_to ( compound , pos ) :
"""Translate a compound to a coordinate .
Parameters
compound : mb . Compound
The compound being translated .
pos : np . ndarray , shape = ( 3 , ) , dtype = float
The coordinate to translate the compound to .""" | atom_positions = compound . xyz_with_ports
atom_positions -= compound . center
atom_positions = Translation ( pos ) . apply_to ( atom_positions )
compound . xyz_with_ports = atom_positions |
def transform ( self , func ) :
"""Return a new DStream in which each RDD is generated by applying a function
on each RDD of this DStream .
` func ` can have one argument of ` rdd ` , or have two arguments of
( ` time ` , ` rdd ` )""" | if func . __code__ . co_argcount == 1 :
oldfunc = func
func = lambda t , rdd : oldfunc ( rdd )
assert func . __code__ . co_argcount == 2 , "func should take one or two arguments"
return TransformedDStream ( self , func ) |
def profile ( self ) :
"""Buffered result of : meth : ` build _ profile `""" | if self . _profile is None :
self . _profile = self . build_profile ( )
return self . _profile |
def itake_column ( list_ , colx ) :
"""iterator version of get _ list _ column""" | if isinstance ( colx , list ) : # multi select
return ( [ row [ colx_ ] for colx_ in colx ] for row in list_ )
else :
return ( row [ colx ] for row in list_ ) |
def send ( self , message , * args , ** kwargs ) :
'''Sends provided message to all listeners . Message is only added to
queue and will be processed on next tick .
: param Message message :
Message to send .''' | self . _messages . put ( ( message , args , kwargs ) , False ) |
def _raise_bulk_write_error ( full_result ) :
"""Raise a BulkWriteError from the full bulk api result .""" | if full_result [ "writeErrors" ] :
full_result [ "writeErrors" ] . sort ( key = lambda error : error [ "index" ] )
raise BulkWriteError ( full_result ) |
def find_plugins ( self , path ) :
"""Return a list with all plugins found in path
: param path : the directory with plugins
: type path : str
: returns : list of JB _ Plugin subclasses
: rtype : list
: raises : None""" | ext = os . extsep + 'py'
files = [ ]
for ( dirpath , dirnames , filenames ) in os . walk ( path ) :
files . extend ( [ os . path . join ( dirpath , x ) for x in filenames if x . endswith ( ext ) ] )
plugins = [ ]
for f in files :
try :
mod = self . __import_file ( f )
except Exception :
tb =... |
def _make_elastic_range ( begin , end ) :
"""Generate an S - curved range of pages .
Start from both left and right , adding exponentially growing indexes ,
until the two trends collide .""" | # Limit growth for huge numbers of pages .
starting_factor = max ( 1 , ( end - begin ) // 100 )
factor = _iter_factors ( starting_factor )
left_half , right_half = [ ] , [ ]
left_val , right_val = begin , end
right_val = end
while left_val < right_val :
left_half . append ( left_val )
right_half . append ( righ... |
def update ( self , * data , ** kwargs ) -> 'Entity' :
"""Update a Record in the repository .
Also performs unique validations before creating the entity .
Supports both dictionary and keyword argument updates to the entity : :
dog . update ( { ' age ' : 10 } )
dog . update ( age = 10)
: param data : Dict... | logger . debug ( f'Updating existing `{self.__class__.__name__}` object with id {self.id}' )
# Fetch Model class and connected repository from Repository Factory
model_cls = repo_factory . get_model ( self . __class__ )
repository = repo_factory . get_repository ( self . __class__ )
try : # Update entity ' s data attri... |
def CELERY_RESULT_BACKEND ( self ) :
"""Redis result backend config""" | # allow specify directly
configured = get ( 'CELERY_RESULT_BACKEND' , None )
if configured :
return configured
if not self . _redis_available ( ) :
return None
host , port = self . REDIS_HOST , self . REDIS_PORT
if host and port :
default = "redis://{host}:{port}/{db}" . format ( host = host , port = port ,... |
def add_native_name ( self , name ) :
"""Add native name .
Args :
: param name : native name for the current author .
: type name : string""" | self . _ensure_field ( 'name' , { } )
self . obj [ 'name' ] . setdefault ( 'native_names' , [ ] ) . append ( name ) |
def _add_childTnLst ( self ) :
"""Add ` . / p : timing / p : tnLst / p : par / p : cTn / p : childTnLst ` descendant .
Any existing ` p : timing ` child element is ruthlessly removed and
replaced .""" | self . remove ( self . get_or_add_timing ( ) )
timing = parse_xml ( self . _childTnLst_timing_xml ( ) )
self . _insert_timing ( timing )
return timing . xpath ( './p:tnLst/p:par/p:cTn/p:childTnLst' ) [ 0 ] |
def _getScalesDiag ( self , termx = 0 ) :
"""Uses 2 term single trait model to get covar params for initialization
Args :
termx : non - noise term terms that is used for initialization""" | assert self . P > 1 , 'CVarianceDecomposition:: diagonal init_method allowed only for multi trait models'
assert self . noisPos != None , 'CVarianceDecomposition:: noise term has to be set'
assert termx < self . n_terms - 1 , 'CVarianceDecomposition:: termx>=n_terms-1'
assert self . covar_type [ self . noisPos ] not in... |
def log_file_name ( ext = False ) :
"""Function : Creates a logfile name , named after this script and includes the number of seconds since the Epoch .
An optional extension can be specified to make the logfile name more meaningful regarding its purpose .
Args : ext - The extension to add to the log file name t... | script_name = os . path . splitext ( os . path . basename ( sys . argv [ 0 ] ) ) [ 0 ]
val = script_name + "_" + str ( int ( time . time ( ) ) ) + "_LOG"
if ext :
val += "_" + ext
val += ".txt"
return val |
def verify ( self , msg , signature , key ) :
"""Verify a message signature
: param msg : The message
: param sig : A signature
: param key : A ec . EllipticCurvePublicKey to use for the verification .
: raises : BadSignature if the signature can ' t be verified .
: return : True""" | try :
key . verify ( signature , msg , padding . PSS ( mgf = padding . MGF1 ( self . hash_algorithm ( ) ) , salt_length = padding . PSS . MAX_LENGTH ) , self . hash_algorithm ( ) )
except InvalidSignature as err :
raise BadSignature ( err )
else :
return True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.