signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _validate_signal ( self , sig ) :
"""Internal helper to validate a signal .
Raise ValueError if the signal number is invalid or uncatchable .
Raise RuntimeError if there is a problem setting up the handler .""" | if not isinstance ( sig , int ) :
raise TypeError ( 'sig must be an int, not {!r}' . format ( sig ) )
if signal is None :
raise RuntimeError ( 'Signals are not supported' )
if not ( 1 <= sig < signal . NSIG ) :
raise ValueError ( 'sig {} out of range(1, {})' . format ( sig , signal . NSIG ) )
if sys . platf... |
def status ( name = None , user = None , conf_file = None , bin_env = None ) :
'''List programs and its state
user
user to run supervisorctl as
conf _ file
path to supervisord config file
bin _ env
path to supervisorctl bin or path to virtualenv with supervisor
installed
CLI Example :
. . code - b... | all_process = { }
for line in status_raw ( name , user , conf_file , bin_env ) . splitlines ( ) :
if len ( line . split ( ) ) > 2 :
process , state , reason = line . split ( None , 2 )
else :
process , state , reason = line . split ( ) + [ '' ]
all_process [ process ] = { 'state' : state , '... |
def process_import ( self , request , * args , ** kwargs ) :
"""Perform the actual import action ( after the user has confirmed the import )""" | if not self . has_import_permission ( request ) :
raise PermissionDenied
form_type = self . get_confirm_import_form ( )
confirm_form = form_type ( request . POST )
if confirm_form . is_valid ( ) :
import_formats = self . get_import_formats ( )
input_format = import_formats [ int ( confirm_form . cleaned_dat... |
def get_stp_mst_detail_output_cist_port_designated_port_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_stp_mst_detail = ET . Element ( "get_stp_mst_detail" )
config = get_stp_mst_detail
output = ET . SubElement ( get_stp_mst_detail , "output" )
cist = ET . SubElement ( output , "cist" )
port = ET . SubElement ( cist , "port" )
designated_port_id = ET . SubElement ( port , "designat... |
def get_osd_config ( self , osd_version ) :
"""Select appropriate portion of config .
If the version requested is not supported the raise an exception with
a helpful error message listing the versions supported .""" | if ( osd_version in self . osd_config ) :
return ( self . osd_config [ osd_version ] )
else :
raise IIIFStaticError ( "OpenSeadragon version %s not supported, available versions are %s" % ( osd_version , ', ' . join ( sorted ( self . osd_config . keys ( ) ) ) ) ) |
def mtime ( path ) :
"""Get the modification time of a file , or - 1 if the file does not exist .""" | if not os . path . exists ( path ) :
return - 1
stat = os . stat ( path )
return stat . st_mtime |
def build_iters ( data_dir , max_records , q , horizon , splits , batch_size ) :
"""Load & generate training examples from multivariate time series data
: return : data iters & variables required to define network architecture""" | # Read in data as numpy array
df = pd . read_csv ( os . path . join ( data_dir , "electricity.txt" ) , sep = "," , header = None )
feature_df = df . iloc [ : , : ] . astype ( float )
x = feature_df . as_matrix ( )
x = x [ : max_records ] if max_records else x
# Construct training examples based on horizon and window
x_... |
def oldest_frame ( self , raw = False ) :
"""Get the oldest frame in the panel .""" | if raw :
return self . buffer . values [ : , self . _start_index , : ]
return self . buffer . iloc [ : , self . _start_index , : ] |
def set_hparams_from_args ( args ) :
"""Set hparams overrides from unparsed args list .""" | if not args :
return
hp_prefix = "--hp_"
tf . logging . info ( "Found unparsed command-line arguments. Checking if any " "start with %s and interpreting those as hparams " "settings." , hp_prefix )
pairs = [ ]
i = 0
while i < len ( args ) :
arg = args [ i ]
if arg . startswith ( hp_prefix ) :
pairs ... |
def main ( ) :
"""parse commandline arguments and print result""" | # setup command line parsing a la argpase
parser = argparse . ArgumentParser ( )
# positional args
parser . add_argument ( 'uri' , metavar = 'URI' , nargs = '?' , default = '/' , help = '[owserver:]//server:port/entity' )
# optional args for temperature scale
parser . set_defaults ( t_flags = protocol . FLG_TEMP_C )
te... |
def focus_parent ( self ) :
"""move focus to parent node of currently focussed one""" | w , focuspos = self . get_focus ( )
parent = self . _tree . parent_position ( focuspos )
if parent is not None :
self . set_focus ( parent ) |
def take_action ( self , alert , action , text , ** kwargs ) :
"""should return internal id of external system""" | BASE_URL = '{}/projects/{}' . format ( GITLAB_URL , quote ( GITLAB_PROJECT_ID , safe = '' ) )
if action == 'createIssue' :
if 'issue_iid' not in alert . attributes :
url = BASE_URL + '/issues?title=' + alert . text
r = requests . post ( url , headers = self . headers )
alert . attributes [ '... |
def split_long_sentence ( sentence , words_per_line ) :
"""Takes a sentence and adds a newline every " words _ per _ line " words .
Parameters
sentence : str
Sentene to split
words _ per _ line : double
Add a newline every this many words""" | words = sentence . split ( ' ' )
split_sentence = ''
for i in range ( len ( words ) ) :
split_sentence = split_sentence + words [ i ]
if ( i + 1 ) % words_per_line == 0 :
split_sentence = split_sentence + '\n'
elif i != len ( words ) - 1 :
split_sentence = split_sentence + " "
return split_s... |
def reserve ( ctx , amount , symbol , account ) :
"""Reserve / Burn tokens""" | print_tx ( ctx . bitshares . reserve ( Amount ( amount , symbol , bitshares_instance = ctx . bitshares ) , account = account ) ) |
def getTarget ( self , iid ) :
'''Returns a dictionary containing information about a certain target''' | sql = 'select name, path from {} where _id=?' . format ( self . TABLE_ITEMS )
data = self . db . execute ( sql , ( iid , ) ) . fetchone ( )
if data :
return { 'name' : data [ 0 ] , 'path' : data [ 1 ] }
return None |
def _load_meta_cache ( self ) :
"""Try to load metadata from file .""" | try :
if self . _should_invalidate_cache ( ) :
os . remove ( self . _cache_filename )
else :
with open ( self . _cache_filename , 'rb' ) as f :
self . _document_meta = compat . pickle . load ( f )
except ( OSError , IOError , compat . pickle . PickleError , ImportError , AttributeErr... |
def image_data ( verbose = False ) :
"""Get the raw encoded image data , downloading it if necessary .""" | # This is a principled use of the ` global ` statement ; don ' t lint me .
global _IMAGE_DATA
# pylint : disable = global - statement
if _IMAGE_DATA is None :
if verbose :
logger . info ( "--- Downloading image." )
with contextlib . closing ( urllib . request . urlopen ( IMAGE_URL ) ) as infile :
... |
def structure_lines ( self , structure , cell_flg = True , frac_flg = True , anion_shell_flg = True , cation_shell_flg = False , symm_flg = True ) :
"""Generates GULP input string corresponding to pymatgen structure .
Args :
structure : pymatgen Structure object
cell _ flg ( default = True ) : Option to use l... | gin = ""
if cell_flg :
gin += "cell\n"
l = structure . lattice
lat_str = [ str ( i ) for i in [ l . a , l . b , l . c , l . alpha , l . beta , l . gamma ] ]
gin += " " . join ( lat_str ) + "\n"
if frac_flg :
gin += "frac\n"
coord_attr = "frac_coords"
else :
gin += "cart\n"
coord_attr = "... |
def flatten ( nested , containers = ( list , tuple ) ) :
"""Flatten a nested list in - place and return it .""" | flat = list ( nested )
# handle iterators / generators
i = 0
while i < len ( flat ) :
while isinstance ( flat [ i ] , containers ) :
if not flat [ i ] : # kill empty list
flat . pop ( i )
# inspect new ' i ' th element in outer loop
i -= 1
break
else :... |
def resize ( image , shape , kind = 'linear' ) :
"""Resize an image
Parameters
image : ndarray
Array of shape ( N , M , . . . ) .
shape : tuple
2 - element shape .
kind : str
Interpolation , either " linear " or " nearest " .
Returns
scaled _ image : ndarray
New image , will have dtype np . floa... | image = np . array ( image , float )
shape = np . array ( shape , int )
if shape . ndim != 1 or shape . size != 2 :
raise ValueError ( 'shape must have two elements' )
if image . ndim < 2 :
raise ValueError ( 'image must have two dimensions' )
if not isinstance ( kind , string_types ) or kind not in ( 'nearest'... |
def new_program ( self , _id , series , title , subtitle , description , mpaaRating , starRating , runTime , year , showType , colorCode , originalAirDate , syndicatedEpisodeNumber , advisories ) :
"""Callback run for each new program entry""" | raise NotImplementedError ( ) |
def collect_data ( parent_module ) :
"""Find Picard VariantCallingMetrics reports and parse their data""" | data = dict ( )
for file_meta in parent_module . find_log_files ( 'picard/variant_calling_metrics' , filehandles = True ) :
s_name = None
for header , value in table_in ( file_meta [ 'f' ] , pre_header_string = '## METRICS CLASS' ) :
if header == 'SAMPLE_ALIAS' :
s_name = value
i... |
def unique_prefix ( self , area_uuid ) :
"""Find the minimum prefix required to address this Upload Area UUID uniquely .
: param ( str ) area _ uuid : UUID of Upload Area
: return : a string with the minimum prefix required to be unique
: rtype : str""" | for prefix_len in range ( 1 , len ( area_uuid ) ) :
prefix = area_uuid [ 0 : prefix_len ]
matching_areas = [ uuid for uuid in self . areas if re . match ( prefix , uuid ) ]
if len ( matching_areas ) == 1 :
return prefix |
def get_nac_eigendisplacements_along_dir ( self , direction ) :
"""Returns the nac _ eigendisplacements for the given direction ( not necessarily a versor ) .
None if the direction is not present or nac _ eigendisplacements has not been calculated .
Args :
direction : the direction as a list of 3 elements
R... | versor = [ i / np . linalg . norm ( direction ) for i in direction ]
for d , e in self . nac_eigendisplacements :
if np . allclose ( versor , d ) :
return e
return None |
def sample ( self , ctrs , rstate = None , return_q = False , kdtree = None ) :
"""Sample a point uniformly distributed within the * union * of cubes .
Uses a K - D Tree to perform the search if provided .
Returns
x : ` ~ numpy . ndarray ` with shape ( ndim , )
A coordinate within the set of cubes .
q : i... | if rstate is None :
rstate = np . random
nctrs = len ( ctrs )
# number of cubes
# If there is only one cube , sample from it .
if nctrs == 1 :
dx = self . hside * ( 2. * rstate . rand ( self . n ) - 1. )
x = ctrs [ 0 ] + dx
if return_q :
return x , 1
else :
return x
# Select a cube a... |
def get_nodes ( self , node_id = None , ** kwargs ) :
"""Alias for get _ elements ( ) but filter the result by Node ( )
: param node _ id : The Id of the node
: type node _ id : Integer
: return : List of elements""" | return self . get_elements ( Node , elem_id = node_id , ** kwargs ) |
def done_evaluating ( self , n : Node , s : ShExJ . shapeExpr , result : bool ) -> Tuple [ bool , bool ] :
"""Indicate that we have completed an actual evaluation of ( n , s ) . This is only called when start _ evaluating
has returned None as the assumed result
: param n : Node that was evaluated
: param s : ... | key = ( n , s . id )
# If we didn ' t have to assume anything or our assumption was correct , we ' re done
if key not in self . assumptions or self . assumptions [ key ] == result :
if key in self . assumptions :
del self . assumptions [ key ]
# good housekeeping , not strictly necessary
self . ... |
def fitcircle ( n , x , y ) : # n points , x points , y points
"""c Fit circle to arbitrary number of x , y pairs , based on the
c modified least squares method of Umback and Jones ( 2000 ) ,
c IEEE Transactions on Instrumentation and Measurement .""" | # adding in normalize vectors step
# x = numpy . array ( x ) / max ( x )
# y = numpy . array ( y ) / max ( y )
sx , sx2 , sx3 , sy , sy2 , sy3 , sxy , sxy2 , syx2 = ( 0 , ) * 9
print ( type ( sx ) , sx )
for i in range ( n ) :
sx = sx + x [ i ]
sx2 = sx2 + x [ i ] ** 2
sx3 = sx3 + x [ i ] ** 3
sy = sy +... |
def nvmlDeviceGetDriverModel ( handle ) :
r"""* Retrieves the current and pending driver model for the device .
* For Fermi & tm ; or newer fully supported devices .
* For windows only .
* On Windows platforms the device driver can run in either WDDM or WDM ( TCC ) mode . If a display is attached
* to the d... | c_currModel = _nvmlDriverModel_t ( )
c_pendingModel = _nvmlDriverModel_t ( )
fn = _nvmlGetFunctionPointer ( "nvmlDeviceGetDriverModel" )
ret = fn ( handle , byref ( c_currModel ) , byref ( c_pendingModel ) )
_nvmlCheckReturn ( ret )
return [ c_currModel . value , c_pendingModel . value ] |
def from_file ( cls , filename ) :
"""Initialize datasource from file ( . tds ot . tdsx )""" | dsxml = xml_open ( filename , 'datasource' ) . getroot ( )
return cls ( dsxml , filename ) |
def _parse_log_entry ( entry_pb ) :
"""Special helper to parse ` ` LogEntry ` ` protobuf into a dictionary .
The ` ` proto _ payload ` ` field in ` ` LogEntry ` ` is of type ` ` Any ` ` . This
can be problematic if the type URL in the payload isn ' t in the
` ` google . protobuf ` ` registry . To help with pa... | try :
return MessageToDict ( entry_pb )
except TypeError :
if entry_pb . HasField ( "proto_payload" ) :
proto_payload = entry_pb . proto_payload
entry_pb . ClearField ( "proto_payload" )
entry_mapping = MessageToDict ( entry_pb )
entry_mapping [ "protoPayload" ] = proto_payload
... |
def explore_show_summary ( self , list , index = False , expected = None , context = None ) :
"""Show summary of one capability document .
Given a capability document or index ( in list , index True if it is an
index ) , write out a simply textual summary of the document with all
related documents shown as nu... | num_entries = len ( list . resources )
capability = '(unknown capability)'
if ( 'capability' in list . md ) :
capability = list . md [ 'capability' ]
if ( index ) :
capability += 'index'
print ( "Parsed %s document with %d entries:" % ( capability , num_entries ) )
if ( expected is not None and capability not i... |
def parse_references ( reference_lines , recid = None , override_kbs_files = None , reference_format = u"{title} {volume} ({year}) {page}" , linker_callback = None ) :
"""Parse a list of references
Given a list of raw reference lines ( list of strings ) ,
output a list of dictionaries containing the parsed refe... | # RefExtract knowledge bases
kbs = get_kbs ( custom_kbs_files = override_kbs_files )
# Identify journal titles , report numbers , URLs , DOIs , and authors . . .
processed_references , counts , dummy_bad_titles_count = parse_references_elements ( reference_lines , kbs , linker_callback )
return ( build_references ( pro... |
def crc16 ( data ) :
"""Calculate an ISO13239 CRC checksum of the input buffer .""" | m_crc = 0xffff
for this in data :
m_crc ^= ord ( this )
for _ in range ( 8 ) :
j = m_crc & 1
m_crc >>= 1
if j :
m_crc ^= 0x8408
return m_crc |
def engineering ( value , precision = 3 , prefix = False , prefixes = SI ) :
"""Convert a number to engineering notation .""" | display = decimal . Context ( prec = precision )
value = decimal . Decimal ( value ) . normalize ( context = display )
string = value . to_eng_string ( )
if prefix :
prefixes = { e ( exponent ) : prefix for exponent , prefix in prefixes . items ( ) }
return replace ( string , prefixes )
else :
return string |
def tracking_event_post ( node_id ) :
"""Enqueue a TrackingEvent worker for the specified Node .""" | details = request_parameter ( parameter = "details" , optional = True )
if details :
details = loads ( details )
# check the node exists
node = models . Node . query . get ( node_id )
if node is None :
return error_response ( error_type = "/info POST, node does not exist" )
db . logger . debug ( "rq: Queueing %... |
def enumerate_version_changelog ( self , url , versions_estimated , timeout = 15 , headers = { } ) :
"""If we have a changelog in store for this CMS , this function will be
called , and a changelog will be used for narrowing down which version is
installed . If the changelog ' s version is outside our estimated... | changelogs = self . vf . changelogs_get ( )
ch_hash = None
for ch_url in changelogs :
try :
ch_hash = self . enumerate_file_hash ( url , file_url = ch_url , timeout = timeout , headers = headers )
except RuntimeError :
pass
ch_version = self . vf . changelog_identify ( ch_hash )
if ch_version in... |
def notify_observers ( self , joinpoint , post = False ) :
"""Notify observers with parameter calls and information about
pre / post call .""" | _observers = tuple ( self . observers )
for observer in _observers :
observer . notify ( joinpoint = joinpoint , post = post ) |
async def crawl ( self , urls , sem ) :
""": param urls :
: type urls : list / dict
: param sem :
: type sem :
: return :
: rtype :""" | tasks = [ self . _sem_crawl ( sem , x ) for x in urls ]
tasks_iter = asyncio . as_completed ( tasks )
fk_task_iter = tqdm . tqdm ( tasks_iter , total = len ( tasks ) , desc = ' ✈' , # desc = ' ✈ { } / { } ' . format ( self . result [ ' ok ' ] , self . result [ ' fail ' ] )
)
for co_ in fk_task_iter :
await co_ |
def render ( self , surf ) :
"""Render the button""" | if self . clicked :
icon = self . icon_pressed
else :
icon = self . icon
surf . blit ( icon , self ) |
def endStep ( self , key ) :
"""Record the end time for the step .
If key = = None , simply record ptime as end time for class to represent
the overall runtime since the initialization of the class .""" | ptime = _ptime ( )
if key is not None :
self . steps [ key ] [ 'end' ] = ptime
self . steps [ key ] [ 'elapsed' ] = ptime [ 1 ] - self . steps [ key ] [ 'start' ] [ 1 ]
self . end = ptime
print ( '==== Processing Step ' , key , ' finished at ' , ptime [ 0 ] )
print ( '' ) |
def get_dataset ( self , dsid , dsinfo ) :
"""Get dataset function
Args :
dsid : Dataset ID
param2 : Dataset Information
Returns :
Dask DataArray : Data""" | data = self [ dsinfo . get ( 'file_key' , dsid . name ) ]
data . attrs . update ( dsinfo )
data . attrs [ "platform_name" ] = self [ '/attr/satellite_name' ]
data . attrs [ "sensor" ] = self [ '/attr/instrument_name' ]
return data |
def decrypt ( self , esp , key , icv_size = None ) :
"""Decrypt an ESP packet
@ param esp : an encrypted ESP packet
@ param key : the secret key used for encryption
@ param icv _ size : the length of the icv used for integrity check
@ return : a valid ESP packet encrypted with this algorithm
@ raise IPSec... | if icv_size is None :
icv_size = self . icv_size if self . is_aead else 0
iv = esp . data [ : self . iv_size ]
data = esp . data [ self . iv_size : len ( esp . data ) - icv_size ]
icv = esp . data [ len ( esp . data ) - icv_size : ]
if self . cipher :
cipher = self . new_cipher ( key , iv , icv )
decryptor ... |
def _get_image_information ( self ) :
""": returns : Dictionary information about the container image""" | result = yield from self . manager . query ( "GET" , "images/{}/json" . format ( self . _image ) )
return result |
def clear_cache_root ( ) :
"""Clears everything in the song cache""" | logger . debug ( "Clearing root cache" )
if os . path . isdir ( _root_songcache_dir ) :
for filename in os . listdir ( _root_songcache_dir ) :
file_path = os . path . join ( _root_songcache_dir , filename )
try :
if os . path . isfile ( file_path ) :
os . unlink ( file_pa... |
def set ( self , value : Optional [ bool ] ) :
"""Sets current status of a check
: param value : ` ` True ` ` ( healthy ) , ` ` False ` ` ( unhealthy ) , or ` ` None ` `
( unknown )""" | prev_value = self . _value
self . _value = value
if self . _value != prev_value : # notify all watchers that this check was changed
for event in self . _events :
event . set ( ) |
def get_bios ( self ) :
"""Gets the list of BIOS / UEFI values currently set on the physical server .
Returns :
dict : Dictionary of BIOS / UEFI values .""" | uri = "{}/bios" . format ( self . data [ "uri" ] )
return self . _helper . do_get ( uri ) |
def get_last_date ( self , field , filters_ = [ ] ) :
''': field : field with the data
: filters _ : additional filters to find the date''' | last_date = self . get_last_item_field ( field , filters_ = filters_ )
return last_date |
def x_position ( self , filter_order = None , window_size = None , tol = 0.05 , Lx = None ) :
'''Calculate $ x $ - position according to :
_ _ | C |
╲ ╱ a ⋅ | - - c _ f |
c _ d - c _ f
where :
- $ C $ is the measured capacitance .
- $ c _ f $ is the capacitance of the filler medium per unit area
_ ( e... | if self . calibration . _c_drop :
c_drop = self . calibration . c_drop ( self . frequency )
else :
c_drop = self . capacitance ( ) [ - 1 ] / self . area
if self . calibration . _c_filler :
c_filler = self . calibration . c_filler ( self . frequency )
else :
c_filler = 0
if Lx is None :
Lx = np . sqr... |
def _create_nodes ( self , env , target = None , source = None ) :
"""Create and return lists of target and source nodes .""" | src_suf = self . get_src_suffix ( env )
target_factory = env . get_factory ( self . target_factory )
source_factory = env . get_factory ( self . source_factory )
source = self . _adjustixes ( source , None , src_suf )
slist = env . arg2nodes ( source , source_factory )
pre = self . get_prefix ( env , slist )
suf = self... |
def remove ( self , bw ) :
"""Removes a buffer watch identifier .
@ type bw : L { BufferWatch }
@ param bw :
Buffer watch identifier .
@ raise KeyError : The buffer watch identifier was already removed .""" | try :
self . __ranges . remove ( bw )
except KeyError :
if not bw . oneshot :
raise |
def unzip ( source_file , destination_dir ) :
"""Unzips < source _ file > into < destination _ dir > .
: param str | unicode source _ file : The name of the file to read
: param str | unicode destination _ dir : The name of the directory to write the unzipped files""" | with zipfile . ZipFile ( source_file ) as zf :
zf . extractall ( destination_dir ) |
def download ( url , tries = DEFAULT_TRIES , retry_delay = RETRY_DELAY , try_timeout = None , proxies = None , verify = True ) :
"""Descarga un archivo a través del protocolo HTTP , en uno o más intentos .
Args :
url ( str ) : URL ( schema HTTP ) del archivo a descargar .
tries ( int ) : Intentos a realizar... | for i in range ( tries ) :
try :
return requests . get ( url , timeout = try_timeout , proxies = proxies , verify = verify ) . content
except Exception as e :
download_exception = e
if i < tries - 1 :
time . sleep ( retry_delay )
raise download_exception |
def getRequiredAttrs ( self ) :
"""Get the type URIs for all attributes that have been marked
as required .
@ returns : A list of the type URIs for attributes that have
been marked as required .
@ rtype : [ str ]""" | required = [ ]
for type_uri , attribute in self . requested_attributes . items ( ) :
if attribute . required :
required . append ( type_uri )
return required |
def get_queryset ( self ) :
"""Get queryset based on url params ( < app > , < mode > ) if model is not set on class""" | if self . queryset is None and not self . model :
try :
return self . get_model_class ( ) . _default_manager . all ( )
except LookupError :
raise Http404 ( )
return super ( ) . get_queryset ( ) |
def commit ( self ) :
"""Commit mutations to the database .
: rtype : datetime
: returns : timestamp of the committed changes .""" | self . _check_state ( )
database = self . _session . _database
api = database . spanner_api
metadata = _metadata_with_prefix ( database . name )
txn_options = TransactionOptions ( read_write = TransactionOptions . ReadWrite ( ) )
response = api . commit ( self . _session . name , self . _mutations , single_use_transact... |
def local_runtime_values ( self ) :
"""Tries to find all runtime values of this function which do not come from inputs .
These values are generated by starting from a blank state and reanalyzing the basic blocks once each .
Function calls are skipped , and back edges are never taken so these values are often un... | constants = set ( )
if not self . _project . loader . main_object . contains_addr ( self . addr ) :
return constants
# FIXME the old way was better for architectures like mips , but we need the initial irsb
# reanalyze function with a new initial state ( use persistent registers )
# initial _ state = self . _ funct... |
def untrust ( self , scope , vk ) :
"""Stop trusting a particular key for given scope .""" | self . data [ 'verifiers' ] . remove ( { 'scope' : scope , 'vk' : vk } )
return self |
def gantry_axes ( cls ) -> Tuple [ 'Axis' , 'Axis' , 'Axis' , 'Axis' ] :
"""The axes which are tied to the gantry and require the deck
calibration transform""" | return ( cls . X , cls . Y , cls . Z , cls . A ) |
def draw_shapes_svg_layer ( df_shapes , shape_i_columns , layer_name , layer_number = 1 , use_svg_path = True ) :
'''Draw shapes as a layer in a SVG file .
Args :
df _ shapes ( pandas . DataFrame ) : Table of shape vertices ( one row per
vertex ) .
shape _ i _ columns ( str or list ) : Either a single colum... | # Note that ` svgwrite . Drawing ` requires a filepath to be specified during
# construction , * but * nothing is actually written to the path unless one of
# the ` save * ` methods is called .
# In this function , we do * not * call any of the ` save * ` methods . Instead ,
# we use the ` write ` method to write to an... |
def _draw_cursor ( self , dc , grid , row , col , pen = None , brush = None ) :
"""Draws cursor as Rectangle in lower right corner""" | # If in full screen mode draw no cursor
if grid . main_window . IsFullScreen ( ) :
return
key = row , col , grid . current_table
rect = grid . CellToRect ( row , col )
rect = self . get_merged_rect ( grid , key , rect )
# Check if cell is invisible
if rect is None :
return
size = self . get_zoomed_size ( 1.0 )
... |
def templates ( self ) :
"""Property for accessing : class : ` TemplateManager ` instance , which is used to manage templates .
: rtype : yagocd . resources . template . TemplateManager""" | if self . _template_manager is None :
self . _template_manager = TemplateManager ( session = self . _session )
return self . _template_manager |
def load_config ( config , expand_env = False , force = False ) :
"""Return repos from a directory and fnmatch . Not recursive .
: param config : paths to config file
: type config : str
: param expand _ env : True to expand environment varialbes in the config .
: type expand _ env : bool
: param bool for... | if not os . path . exists ( config ) :
raise ConfigException ( 'Unable to find configuration file: %s' % config )
file_extension = os . path . splitext ( config ) [ 1 ] [ 1 : ]
conf = kaptan . Kaptan ( handler = kaptan . HANDLER_EXT . get ( file_extension ) )
if expand_env :
with open ( config , 'r' ) as file_h... |
def setPalette ( self , palette ) :
"""Sets the palette for this node to the inputed palette . If None is
provided , then the scene ' s palette will be used for this node .
: param palette | < XNodePalette > | | None""" | self . _palette = XNodePalette ( palette ) if palette is not None else None
self . setDirty ( ) |
def get_args ( self ) :
"""Gets the args for the query which will be escaped when being executed by the
db . All inner queries are inspected and their args are combined with this
query ' s args .
: return : all args for this query as a dict
: rtype : dict""" | for table in self . tables + self . with_tables :
if type ( table ) is QueryTable :
self . _where . args . update ( table . query . get_args ( ) )
return self . _where . args |
def get_fcps_emerg ( request ) :
"""Return FCPS emergency information .""" | try :
emerg = get_emerg ( )
except Exception :
logger . info ( "Unable to fetch FCPS emergency info" )
emerg = { "status" : False }
if emerg [ "status" ] or ( "show_emerg" in request . GET ) :
msg = emerg [ "message" ]
return "{} <span style='display: block;text-align: right'>— FCPS</span>" . ... |
def write_corrected ( self , output , clobber = False ) :
"""Write out the destriped data .""" | # un - apply the flatfield if necessary
if self . flatcorr != 'COMPLETE' :
self . science = self . science / self . invflat
self . err = self . err / self . invflat
# un - apply the post - flash if necessary
if self . flshcorr != 'COMPLETE' :
self . science = self . science + self . flash
# un - apply the d... |
def debug_string ( self ) :
"""This provides a progress notification for the algorithm .
For each bracket , the algorithm will output a string as follows :
Bracket ( Max Size ( n ) = 5 , Milestone ( r ) = 33 , completed = 14.6 % ) :
{ PENDING : 2 , RUNNING : 3 , TERMINATED : 2}
" Max Size " indicates the ma... | out = "Using HyperBand: "
out += "num_stopped={} total_brackets={}" . format ( self . _num_stopped , sum ( len ( band ) for band in self . _hyperbands ) )
for i , band in enumerate ( self . _hyperbands ) :
out += "\nRound #{}:" . format ( i )
for bracket in band :
out += "\n {}" . format ( bracket )
re... |
def args_options ( ) :
"""Generates an arugment parser .
: returns :
Parser object""" | parser = argparse . ArgumentParser ( prog = 'landsat' , formatter_class = argparse . RawDescriptionHelpFormatter , description = textwrap . dedent ( DESCRIPTION ) )
subparsers = parser . add_subparsers ( help = 'Landsat Utility' , dest = 'subs' )
parser . add_argument ( '--version' , action = 'version' , version = '%(p... |
def main ( mode ) :
"""Tags the current repository
and commits changes to news files
: param mode : ReleaseTarget mode ( i . e . beta or prod )
: type mode : ReleaseTarget""" | # see :
# https : / / packaging . python . org / tutorials / distributing - packages / # uploading - your - project - to - pypi
version = subprocess . check_output ( [ 'python' , 'setup.py' , '--version' ] ) . decode ( ) . strip ( )
twine_repo = os . getenv ( 'TWINE_REPOSITORY_URL' ) or os . getenv ( 'TWINE_REPOSITORY'... |
def get_image_id ( self , namespace , respository , tag ) :
"""GET / v1 / repositories / ( namespace ) / ( repository ) / tags / ( tag * )""" | return self . _http_call ( self . TAGS + '/' + tag , get , namespace = namespace , repository = respository ) |
def validate_template_syntax ( source ) :
"""Basic Django Template syntax validation . This allows for robuster template
authoring .""" | try :
Template ( source )
except ( TemplateSyntaxError , TemplateDoesNotExist ) as err :
raise ValidationError ( text_type ( err ) ) |
def echo_class2 ( self , catstr = '' ) :
'''弹出的二级发布菜单''' | fatherid = catstr [ 1 : ]
self . write ( self . format_class2 ( fatherid ) ) |
def min_depth_img ( self , num_img = 1 ) :
"""Collect a series of depth images and return the min of the set .
Parameters
num _ img : int
The number of consecutive frames to process .
Returns
: obj : ` DepthImage `
The min DepthImage collected from the frames .""" | depths = self . _read_depth_images ( num_img )
return Image . min_images ( depths ) |
def getPose3d ( self ) :
'''Returns last Pose3d .
@ return last JdeRobotTypes Pose3d saved''' | self . lock . acquire ( )
pose = self . pose
self . lock . release ( )
return pose |
def update ( collection_name , upsert , multi , spec , doc , safe , last_error_args , check_keys , opts , ctx = None ) :
"""Get an * * update * * message .""" | if ctx :
return _update_compressed ( collection_name , upsert , multi , spec , doc , check_keys , opts , ctx )
return _update_uncompressed ( collection_name , upsert , multi , spec , doc , safe , last_error_args , check_keys , opts ) |
def cli_parse ( parser ) :
"""Add method specific options to CLI parser .
Parameters
parser : argparse object
Returns
Updated argparse object""" | parser . add_argument ( '-n' , '--samples' , type = int , required = True , help = 'Number of Samples' )
return parser |
def walk_dir_progress ( path , maxdircnt = 5000 , file = sys . stdout ) :
"""Walk a directory , printing status updates along the way .""" | p = ProgressBar ( 'Walking {}' . format ( C ( path , 'cyan' ) ) , bars = Bars . numbers_blue . with_wrapper ( ( '(' , ')' ) ) , show_time = True , file = file , )
rootcnt = 0
print ( '\nStarting progress bar...' )
p . start ( )
for root , dirs , files in os . walk ( path ) :
rootcnt += 1
if rootcnt % 100 == 0 :... |
def losing_name ( self ) :
"""Returns a ` ` string ` ` of the losing team ' s name , such as ' Los Angeles
Dodgers ' .""" | if self . winner == HOME :
return self . _away_name . text ( )
return self . _home_name . text ( ) |
def compute_master_secret ( self , pre_master_secret , client_random , server_random ) :
"""Return the 48 - byte master _ secret , computed from pre _ master _ secret ,
client _ random and server _ random . See RFC 5246 , section 6.3.""" | seed = client_random + server_random
if self . tls_version < 0x0300 :
return None
elif self . tls_version == 0x0300 :
return self . prf ( pre_master_secret , seed , 48 )
else :
return self . prf ( pre_master_secret , b"master secret" , seed , 48 ) |
def send_file ( self , path , contents , shutit_pexpect_child = None , truncate = False , note = None , user = None , echo = False , group = None , loglevel = logging . INFO , encoding = None ) :
"""Sends the passed - in string as a file to the passed - in path on the
target .
@ param path : Target location of ... | shutit_global . shutit_global_object . yield_to_draw ( )
shutit_pexpect_child = shutit_pexpect_child or self . get_current_shutit_pexpect_session ( ) . pexpect_child
shutit_pexpect_session = self . get_shutit_pexpect_session_from_child ( shutit_pexpect_child )
return shutit_pexpect_session . send_file ( path , contents... |
def effective_value ( self ) :
"""Read / write | float | representing normalized adjustment value for this
adjustment . Actual values are a large - ish integer expressed in shape
coordinates , nominally between 0 and 100,000 . The effective value is
normalized to a corresponding value nominally between 0.0 an... | raw_value = self . actual
if raw_value is None :
raw_value = self . def_val
return self . _normalize ( raw_value ) |
def _ows_check_if_paused ( services = None , ports = None ) :
"""Check if the unit is supposed to be paused , and if so check that the
services / ports ( if passed ) are actually stopped / not being listened to .
If the unit isn ' t supposed to be paused , just return None , None
If the unit is performing a s... | if is_unit_upgrading_set ( ) :
state , message = check_actually_paused ( services = services , ports = ports )
if state is None : # we ' re paused okay , so set maintenance and return
state = "blocked"
message = ( "Ready for do-release-upgrade and reboot. " "Set complete when finished." )
re... |
def create_from_hdu ( cls , hdu , ebins ) :
"""Creates and returns an HpxMap object from a FITS HDU .
hdu : The FITS
ebins : Energy bin edges [ optional ]""" | hpx = HPX . create_from_hdu ( hdu , ebins )
colnames = hdu . columns . names
cnames = [ ]
if hpx . conv . convname == 'FGST_SRCMAP_SPARSE' :
pixs = hdu . data . field ( 'PIX' )
chans = hdu . data . field ( 'CHANNEL' )
keys = chans * hpx . npix + pixs
vals = hdu . data . field ( 'VALUE' )
nebin = len... |
def _highlight_caret_scope ( self ) :
"""Highlight the scope of the current caret position .
This get called only if : attr : `
spyder . widgets . panels . FoldingPanel . highlight _ care _ scope ` is True .""" | cursor = self . editor . textCursor ( )
block_nbr = cursor . blockNumber ( )
if self . _block_nbr != block_nbr :
block = FoldScope . find_parent_scope ( self . editor . textCursor ( ) . block ( ) )
try :
s = FoldScope ( block )
except ValueError :
self . _clear_scope_decos ( )
else :
... |
def add_categories ( self , new_categories , inplace = False ) :
"""Add new categories .
` new _ categories ` will be included at the last / highest place in the
categories and will be unused directly after this call .
Parameters
new _ categories : category or list - like of category
The new categories to... | inplace = validate_bool_kwarg ( inplace , 'inplace' )
if not is_list_like ( new_categories ) :
new_categories = [ new_categories ]
already_included = set ( new_categories ) & set ( self . dtype . categories )
if len ( already_included ) != 0 :
msg = ( "new categories must not include old categories: " "{already... |
def remove_all_logger_handlers ( logger : logging . Logger ) -> None :
"""Remove all handlers from a logger .
Args :
logger : logger to modify""" | while logger . handlers :
h = logger . handlers [ 0 ]
logger . removeHandler ( h ) |
def item_count ( self , request , variant_id = None ) :
"""Get quantity of a single item in the basket""" | bid = utils . basket_id ( request )
item = ProductVariant . objects . get ( id = variant_id )
try :
count = BasketItem . objects . get ( basket_id = bid , variant = item ) . quantity
except BasketItem . DoesNotExist :
count = 0
return Response ( data = { "quantity" : count } , status = status . HTTP_200_OK ) |
def login ( self ) :
"""Login to verisure app api
Login before calling any read or write commands""" | if os . path . exists ( self . _cookieFileName ) :
with open ( self . _cookieFileName , 'r' ) as cookieFile :
self . _vid = cookieFile . read ( ) . strip ( )
try :
self . _get_installations ( )
except ResponseError :
self . _vid = None
os . remove ( self . _cookieFileName )
i... |
def ReadRemoteFile ( remote_file_path , hostname , ssh_key ) :
"""Reads a remote file into a string .""" | cmd = 'sudo cat %s' % remote_file_path
exit_code , output = RunCommandOnHost ( cmd , hostname , ssh_key )
if exit_code :
raise IOError ( 'Can not read remote path: %s' % ( remote_file_path ) )
return output |
def _push_condition ( predicate ) :
"""As we enter new conditions , this pushes them on the predicate stack .""" | global _depth
_check_under_condition ( )
_depth += 1
if predicate is not otherwise and len ( predicate ) > 1 :
raise PyrtlError ( 'all predicates for conditional assignments must wirevectors of len 1' )
_conditions_list_stack [ - 1 ] . append ( predicate )
_conditions_list_stack . append ( [ ] ) |
def disable_dataset ( self , dataset = None , ** kwargs ) :
"""Disable a ' dataset ' . Datasets that are enabled will be computed
during : meth : ` run _ compute ` and included in the cost function
during : meth : ` run _ fitting ` .
If compute is not provided , the dataset will be disabled across all
compu... | kwargs [ 'context' ] = 'compute'
kwargs [ 'dataset' ] = dataset
kwargs [ 'qualifier' ] = 'enabled'
self . set_value_all ( value = False , ** kwargs )
self . _add_history ( redo_func = 'disable_dataset' , redo_kwargs = { 'dataset' : dataset } , undo_func = 'enable_dataset' , undo_kwargs = { 'dataset' : dataset } )
retur... |
def wngram2idngram ( input_file , vocab_file , output_file , buffersize = 100 , hashtablesize = 2000000 , files = 20 , compress = False , verbosity = 2 , n = 3 , write_ascii = False , fof_size = 10 ) :
"""Takes a word N - gram file and a vocabulary file and lists every id n - gram which occurred in the text , along... | cmd = [ 'wngram2idngram' , '-vocab' , os . path . abspath ( vocab_file ) , '-idngram' , os . path . abspath ( output_file ) ]
if buffersize :
cmd . extend ( [ '-buffer' , buffersize ] )
if hashtablesize :
cmd . extend ( [ '-hash' , hashtablesize ] )
if files :
cmd . extend ( [ '-files' , files ] )
if verbos... |
def is_not_in ( self , iterable ) :
"""Ensures : attr : ` subject ` is not contained in * iterable * .""" | self . _run ( unittest_case . assertNotIn , ( self . _subject , iterable ) )
return ChainInspector ( self . _subject ) |
def bind ( self , func : Callable [ [ Any ] , IO ] ) -> IO :
"""IO a - > ( a - > IO b ) - > IO b""" | filename , g = self . _get_value ( )
return ReadFile ( filename , lambda s : g ( s ) . bind ( func ) ) |
def exists ( self ) :
""": type : bool
True when the object actually exists ( and can be accessed by
the current user ) in Fedora""" | # If we made the object under the pretext that it doesn ' t exist in
# fedora yet , then assume it doesn ' t exist in fedora yet .
if self . _create :
return False
# If we can get a valid object profile , regardless of its contents ,
# then this object exists . If not , then it doesn ' t .
try :
self . getProfi... |
def should_include_node ( ctx , directives ) : # type : ( ExecutionContext , Optional [ List [ Directive ] ] ) - > bool
"""Determines if a field should be included based on the @ include and
@ skip directives , where @ skip has higher precidence than @ include .""" | # TODO : Refactor based on latest code
if directives :
skip_ast = None
for directive in directives :
if directive . name . value == GraphQLSkipDirective . name :
skip_ast = directive
break
if skip_ast :
args = get_argument_values ( GraphQLSkipDirective . args , skip_a... |
def check_hankel ( ht , htarg , verb ) :
r"""Check Hankel transform parameters .
This check - function is called from one of the modelling routines in
: mod : ` model ` . Consult these modelling routines for a detailed description
of the input parameters .
Parameters
ht : { ' fht ' , ' qwe ' , ' quad ' } ... | # Ensure ht is all lowercase
ht = ht . lower ( )
if ht == 'fht' : # If FHT , check filter settings
# Get and check input or set defaults
htarg = _check_targ ( htarg , [ 'fhtfilt' , 'pts_per_dec' ] )
# Check filter ; defaults to key _ 201_2009
try :
fhtfilt = htarg [ 'fhtfilt' ]
if not hasatt... |
def fix_pdb ( self ) :
'''A function to fix fatal errors in PDB files when they can be automatically fixed . At present , this only runs if
self . strict is False . We may want a separate property for this since we may want to keep strict mode but still
allow PDBs to be fixed .
The only fixes at the moment ar... | if self . strict :
return
# Get the list of chains
chains = set ( )
for l in self . lines :
if l . startswith ( 'ATOM ' ) or l . startswith ( 'HETATM' ) :
chains . add ( l [ 21 ] )
# If there is a chain with a blank ID , change that ID to a valid unused ID
if ' ' in chains :
fresh_id = None
all... |
def get_appliances ( self , start = 0 , count = - 1 , filter = '' , fields = '' , query = '' , sort = '' , view = '' ) :
"""Gets a list of all the Image Streamer resources based on optional sorting and filtering , and constrained
by start and count parameters .
Args :
start :
The first item to return , usin... | uri = self . URI + '/image-streamer-appliances'
return self . _client . get_all ( start , count , filter = filter , sort = sort , query = query , fields = fields , view = view , uri = uri ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.