signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def generate_text_files ( in_dir , out_dir , include_header = False ) :
"""Walks through the ` in _ dir ` and generates text versions of
the cables in the ` out _ dir ` .""" | for cable in cables_from_source ( in_dir ) :
out = codecs . open ( out_dir + '/' + cable . reference_id + '.txt' , 'wb' , encoding = 'utf-8' )
out . write ( cable_to_text ( cable , include_header ) )
out . close ( ) |
def form_invalid ( self , form ) :
"""Override of CreateView method , logs invalid email form submissions .""" | LOGGER . debug ( "Invalid Email Form Submitted" )
messages . add_message ( self . request , messages . ERROR , _ ( "Invalid Email Address." ) )
return super ( EmailTermsView , self ) . form_invalid ( form ) |
def match_empty ( self , el ) :
"""Check if element is empty ( if requested ) .""" | is_empty = True
for child in self . get_children ( el , tags = False ) :
if self . is_tag ( child ) :
is_empty = False
break
elif self . is_content_string ( child ) and RE_NOT_EMPTY . search ( child ) :
is_empty = False
break
return is_empty |
def bernstein ( n , t ) :
"""returns a list of the Bernstein basis polynomials b _ { i , n } evaluated at
t , for i = 0 . . . n""" | t1 = 1 - t
return [ n_choose_k ( n , k ) * t1 ** ( n - k ) * t ** k for k in range ( n + 1 ) ] |
def _start_index ( self , start = None ) :
"""Seek to the first stage to run .""" | if start is None :
return 0
start_stage = translate_stage_name ( start )
internal_names = [ translate_stage_name ( s . name ) for s in self . _stages ]
try :
return internal_names . index ( start_stage )
except ValueError :
raise UnknownPipelineStageError ( start , self ) |
def pack_command ( self , * args ) :
"Pack a series of arguments into the Redis protocol" | output = [ ]
# the client might have included 1 or more literal arguments in
# the command name , e . g . , ' CONFIG GET ' . The Redis server expects these
# arguments to be sent separately , so split the first argument
# manually . All of these arguements get wrapped in the Token class
# to prevent them from being enc... |
def get_module_name ( module : types . ModuleType ) -> str :
"""Returns the name of the specified module by looking up its name in
multiple ways to prevent incompatibility issues .
: param module :
A module object for which to retrieve the name .""" | try :
return module . __spec__ . name
except AttributeError :
return module . __name__ |
def slice_locs ( self , start = None , end = None , step = None , kind = None ) :
"""For an ordered MultiIndex , compute the slice locations for input
labels .
The input labels can be tuples representing partial levels , e . g . for a
MultiIndex with 3 levels , you can pass a single value ( corresponding to
... | # This function adds nothing to its parent implementation ( the magic
# happens in get _ slice _ bound method ) , but it adds meaningful doc .
return super ( ) . slice_locs ( start , end , step , kind = kind ) |
def start ( name , called = None ) :
"""Start a task .""" | if name not in tasks :
logger . log ( logger . red ( "Task '%s' not in your pylpfile" % name ) )
else :
task = tasks [ name ]
runner = TaskRunner ( name , task [ 0 ] , task [ 1 ] , called )
running . append ( runner )
return runner |
def ed ( s1 , s2 ) :
'''edit distance
> > > ed ( ' ' , ' ' ) , ed ( ' a ' , ' a ' ) , ed ( ' ' , ' a ' ) , ed ( ' a ' , ' ' ) , ed ( ' a ! a ' , ' a . a ' )
(0 , 0 , 1 , 1 , 1)
This implementation takes only O ( min ( | s1 | , | s2 | ) ) space .''' | m , n = len ( s1 ) , len ( s2 )
if m < n :
m , n = n , m
# ensure n < = m , to use O ( min ( n , m ) ) space
s1 , s2 = s2 , s1
d = list ( range ( n + 1 ) )
for i in range ( m ) :
p = i
d [ 0 ] = i + 1
for j in range ( n ) :
t = 0 if s1 [ i ] == s2 [ j ] else 1
p , d [ j + 1 ] = d... |
def frames ( self , * , callers : Optional [ Union [ str , List [ str ] ] ] = None , callees : Optional [ Union [ str , List [ str ] ] ] = None , kind : Optional [ TraceKind ] = None , limit : Optional [ int ] = 10 , ) :
"""Display trace frames independent of the current issue .
Parameters ( all optional ) :
ca... | with self . db . make_session ( ) as session :
query = ( session . query ( TraceFrame . id , CallerText . contents . label ( "caller" ) , TraceFrame . caller_port , CalleeText . contents . label ( "callee" ) , TraceFrame . callee_port , ) . filter ( TraceFrame . run_id == self . current_run_id ) . join ( CallerText... |
def summary ( svc_name = '' ) :
'''Display a summary from monit
CLI Example :
. . code - block : : bash
salt ' * ' monit . summary
salt ' * ' monit . summary < service name >''' | ret = { }
cmd = 'monit summary'
res = __salt__ [ 'cmd.run' ] ( cmd ) . splitlines ( )
for line in res :
if 'daemon is not running' in line :
return dict ( monit = 'daemon is not running' , result = False )
elif not line or svc_name not in line or 'The Monit daemon' in line :
continue
else :
... |
def parse_text ( self , node ) :
"""Parses < Text >
@ param node : Node containing the < Text > element
@ type node : xml . etree . Element""" | if 'name' in node . lattrib :
name = node . lattrib [ 'name' ]
else :
self . raise_error ( '<Text> must specify a name.' )
description = node . lattrib . get ( 'description' , '' )
self . current_component_type . add_text ( Text ( name , description ) ) |
def mainloop ( self ) :
"""Handle theme selection changes , or rotate through selection .""" | themes_dir = os . path . join ( self . config_dir , 'color-schemes' )
selected_file = os . path . join ( themes_dir , '.selected' )
current_file = os . path . join ( themes_dir , '.current' )
# Read persisted state
selected_themes = [ ]
if os . path . exists ( selected_file ) :
with open ( selected_file , 'rt' ) as... |
def handle ( self , object , * args , ** kw ) :
'''Calls each plugin in this PluginSet with the specified object ,
arguments , and keywords in the standard group plugin order . The
return value from each successive invoked plugin is passed as the
first parameter to the next plugin . The final return value is ... | if not bool ( self ) :
if not self . spec or self . spec == SPEC_ALL :
raise ValueError ( 'No plugins available in group %r' % ( self . group , ) )
raise ValueError ( 'No plugins in group %r matched %r' % ( self . group , self . spec ) )
for plugin in self . plugins :
object = plugin . handle ( obje... |
def read_config_file ( libname ) :
"""Extract library locations from a configuration file .
Parameters
libname : str
One of either ' openjp2 ' or ' openjpeg '
Returns
path : None or str
None if no location is specified , otherwise a path to the library""" | filename = glymurrc_fname ( )
if filename is None : # There ' s no library file path to return in this case .
return None
# Read the configuration file for the library location .
parser = ConfigParser ( )
parser . read ( filename )
try :
path = parser . get ( 'library' , libname )
except ( NoOptionError , NoSec... |
def resize ( self , size , * args , ** kwargs ) :
"""Returns a resized copy of this bounding box
: param size : The requested size in pixels , as a 2 - tuple :
( width , height ) .""" | ratios = tuple ( float ( s ) / float ( s_orig ) for s , s_orig in zip ( size , self . size ) )
if ratios [ 0 ] == ratios [ 1 ] :
ratio = ratios [ 0 ]
scaled_box = self . bbox * ratio
bbox = BoxList ( scaled_box , size , mode = self . mode )
# bbox . _ copy _ extra _ fields ( self )
for k , v in self... |
def HashBuffer ( self , buf ) :
"""Updates underlying hashers with a given buffer .
Args :
buf : A byte buffer ( string object ) that is going to be fed to the hashers .""" | for hasher in itervalues ( self . _hashers ) :
hasher . update ( buf )
if self . _progress :
self . _progress ( )
self . _bytes_read += len ( buf ) |
def add_ds_ids_from_files ( self ) :
"""Check files for more dynamically discovered datasets .""" | for file_handlers in self . file_handlers . values ( ) :
try :
fh = file_handlers [ 0 ]
avail_ids = fh . available_datasets ( )
except NotImplementedError :
continue
# dynamically discover other available datasets
for ds_id , ds_info in avail_ids : # don ' t overwrite an existing... |
def fetch_sel ( self , ipmicmd , clear = False ) :
"""Fetch SEL entries
Return an iterable of SEL entries . If clearing is requested ,
the fetch and clear will be done as an atomic operation , assuring
no entries are dropped .
: param ipmicmd : The Command object to use to interrogate
: param clear : Whet... | records = [ ]
# First we do a fetch all without reservation , reducing the risk
# of having a long lived reservation that gets canceled in the middle
endat = self . _fetch_entries ( ipmicmd , 0 , records )
if clear and records : # don ' t bother clearing if there were no records
# To do clear , we make a reservation fi... |
def index_discovered_zonefiles ( self , lastblock ) :
"""Go through the list of zone files we discovered via Atlas , grouped by name and ordered by block height .
Find all subsequent zone files for this name , and process all subdomain operations contained within them .""" | all_queued_zfinfos = [ ]
# contents of the queue
subdomain_zonefile_infos = { }
# map subdomain fqn to list of zonefile info bundles , for process _ subdomains
name_blocks = { }
# map domain name to the block at which we should reprocess its subsequent zone files
offset = 0
while True :
queued_zfinfos = queuedb_fin... |
def serialise_to_nrml ( self , filename , use_defaults = False ) :
'''Writes the source model to a nrml source model file given by the
filename
: param str filename :
Path to output file
: param bool use _ defaults :
Boolean to indicate whether to use default values ( True ) or not .
If set to False , V... | source_model = self . convert_to_oqhazardlib ( PoissonTOM ( 1.0 ) , 2.0 , 2.0 , 10.0 , use_defaults = use_defaults )
write_source_model ( filename , source_model , name = self . name ) |
def getFrameTimings ( self , nFrames ) :
"""Interface for copying a range of timing data . Frames are returned in ascending order ( oldest to newest ) with the last being the most recent frame .
Only the first entry ' s m _ nSize needs to be set , as the rest will be inferred from that . Returns total number of e... | fn = self . function_table . getFrameTimings
pTiming = Compositor_FrameTiming ( )
result = fn ( byref ( pTiming ) , nFrames )
return result , pTiming |
def parse_text ( self , formatted_text ) :
"""Retursn a list of operations ( draw , cup , ed , . . . ) .
Each operation consist of a command and its associated data .
: param formatted _ text : text to parse with the default char format to apply .
: return : list of Operation""" | assert isinstance ( formatted_text , FormattedText )
ret_val = [ ]
fmt = formatted_text . fmt if self . _prev_fmt_closed else self . _prev_fmt
fmt = QtGui . QTextCharFormat ( fmt )
if not self . _pending_text :
stripped_text = formatted_text . txt
else :
stripped_text = self . _pending_text + formatted_text . t... |
def create_tar ( archive , compression , cmd , verbosity , interactive , filenames ) :
"""Create a TAR archive with the tarfile Python module .""" | mode = get_tar_mode ( compression )
try :
with tarfile . open ( archive , mode ) as tfile :
for filename in filenames :
tfile . add ( filename )
except Exception as err :
msg = "error creating %s: %s" % ( archive , err )
raise util . PatoolError ( msg )
return None |
def get_header_anim ( self , im ) :
"""get _ header _ anim ( im )
Get animation header . To replace PILs getheader ( ) [ 0]""" | bb = "GIF89a"
bb += int_to_bin ( im . size [ 0 ] )
bb += int_to_bin ( im . size [ 1 ] )
bb += "\x87\x00\x00"
return bb |
def add_accounts_to_project ( accounts_query , project ) :
"""Add accounts to project .""" | query = accounts_query . filter ( date_deleted__isnull = True )
for account in query :
add_account_to_project ( account , project ) |
def cmd_output_remove ( self , args ) :
'''remove an output''' | device = args [ 0 ]
for i in range ( len ( self . mpstate . mav_outputs ) ) :
conn = self . mpstate . mav_outputs [ i ]
if str ( i ) == device or conn . address == device :
print ( "Removing output %s" % conn . address )
try :
mp_util . child_fd_list_add ( conn . port . fileno ( ) )
... |
def network_info ( ) :
"""Returns hostname , ipv4 and ipv6.""" | def extract ( host , family ) :
return socket . getaddrinfo ( host , None , family ) [ 0 ] [ 4 ] [ 0 ]
host = socket . gethostname ( )
response = { 'hostname' : host , 'ipv4' : None , 'ipv6' : None }
with suppress ( IndexError , socket . gaierror ) :
response [ 'ipv4' ] = extract ( host , socket . AF_INET )
wit... |
def connection ( self , shareable = True ) :
"""Get a steady , cached DB - API 2 connection from the pool .
If shareable is set and the underlying DB - API 2 allows it ,
then the connection may be shared with other threads .""" | if shareable and self . _maxshared :
self . _lock . acquire ( )
try :
while ( not self . _shared_cache and self . _maxconnections and self . _connections >= self . _maxconnections ) :
self . _wait_lock ( )
if len ( self . _shared_cache ) < self . _maxshared : # shared cache is not fu... |
def install_vexts ( vext_files , verify = True ) :
"""copy vext _ file to sys . prefix + ' / share / vext / specs '
( PIP7 seems to remove data _ files so we recreate something similar here )""" | if verify and not check_sysdeps ( vext_files ) :
return
spec_dir = join ( prefix , 'share/vext/specs' )
try :
makedirs ( spec_dir )
except OSError as e :
if not isdir ( spec_dir ) :
logger . error ( "Error making spec directory [%s]: %r" % ( spec_dir , e ) )
for vext_file in vext_files :
dest = ... |
def _parse_input_data ( self , node ) :
"""Parses inputOutput part camunda modeller extensions .
Args :
node : SpiffWorkflow Node object .
Returns :
Data dict .""" | data = DotDict ( )
try :
for nod in self . _get_input_nodes ( node ) :
data . update ( self . _parse_input_node ( nod ) )
except Exception as e :
log . exception ( "Error while processing node: %s" % node )
return data |
def _checkstatus ( status , line ) :
"""Returns state / status after reading the next line .
The status codes are : :
LE07 _ clip _ L1TP _ 039027_20150529_20160902_01 _ T1 _ B1 . TIF - BEGIN parsing ; 1 - ENTER METADATA GROUP , 2 - READ METADATA LINE ,
3 - END METDADATA GROUP , 4 - END PARSING
Permitted Tra... | newstatus = 0
if status == 0 : # begin - - > enter metadata group OR end
if _islinetype ( line , GRPSTART ) :
newstatus = 1
elif _isfinal ( line ) :
newstatus = 4
elif status == 1 : # enter metadata group - - > enter metadata group
# OR add metadata item OR leave metadata group
if _islinetyp... |
def _checkTimeValue ( timevalue , maxvalue ) :
"""Check that the given timevalue is valid .
Args :
* timevalue ( numerical ) : The time value to be checked . Must be positive .
* maxvalue ( numerical ) : Upper limit for time value . Must be positive .
Raises :
TypeError , ValueError""" | if maxvalue is None :
raise TypeError ( 'The maxvalue (for the time value) must not be None!' )
minimalmodbus . _checkNumerical ( timevalue , minvalue = 0 , maxvalue = maxvalue , description = 'time value' ) |
def translate ( self , val1 , val2 = None ) :
"""Move to new ( x + dx , y + dy ) .
accepts Point , ( x , y ) , [ x , y ] , int , float""" | error = "Point.translate only accepts a Point, a tuple, a list, ints or floats."
if val1 and val2 :
if isinstance ( val1 , ( int , float ) ) and isinstance ( val2 , ( int , float ) ) :
self . x += val1
self . y += val2
else :
raise ValueError ( error )
elif val1 and val2 is None :
if... |
def marketPrice ( self ) -> float :
"""Return the first available one of
* last price if within current bid / ask ;
* average of bid and ask ( midpoint ) ;
* close price .""" | price = self . last if ( self . hasBidAsk ( ) and self . bid <= self . last <= self . ask ) else self . midpoint ( )
if isNan ( price ) :
price = self . close
return price |
def get_max_events_in_both_arrays ( events_one , events_two ) :
"""Calculates the maximum count of events that exist in both arrays .""" | events_one = np . ascontiguousarray ( events_one )
# change memory alignement for c + + library
events_two = np . ascontiguousarray ( events_two )
# change memory alignement for c + + library
event_result = np . empty ( shape = ( events_one . shape [ 0 ] + events_two . shape [ 0 ] , ) , dtype = events_one . dtype )
cou... |
def save ( self ) :
"""Save the manual clustering back to disk .""" | spike_clusters = self . clustering . spike_clusters
groups = { c : self . cluster_meta . get ( 'group' , c ) or 'unsorted' for c in self . clustering . cluster_ids }
# List of tuples ( field _ name , dictionary ) .
labels = [ ( field , self . get_labels ( field ) ) for field in self . cluster_meta . fields if field not... |
def trace_format ( self ) :
"""Retrieves the current format the trace buffer is using .
Args :
self ( JLink ) : the ` ` JLink ` ` instance .
Returns :
The current format the trace buffer is using . This is one of the
attributes of ` ` JLinkTraceFormat ` ` .""" | cmd = enums . JLinkTraceCommand . GET_FORMAT
data = ctypes . c_uint32 ( 0 )
res = self . _dll . JLINKARM_TRACE_Control ( cmd , ctypes . byref ( data ) )
if ( res == 1 ) :
raise errors . JLinkException ( 'Failed to get trace format.' )
return data . value |
def window_boundaries ( self , current_round ) :
""": param current _ round :
: return : the low and high boundaries of the estimators window to consider .""" | lo = max ( 0 , current_round - self . window_length + 1 )
hi = current_round + 1
return lo , hi |
def get_logger ( ) :
"""Instantiate a logger .""" | root = logging . getLogger ( )
root . setLevel ( logging . WARNING )
ch = logging . StreamHandler ( sys . stderr )
ch . setLevel ( logging . DEBUG )
formatter = logging . Formatter ( '%(message)s' )
ch . setFormatter ( formatter )
root . addHandler ( ch )
return root |
def noaa ( D = "" , path = "" , wds_url = "" , lpd_url = "" , version = "" ) :
"""Convert between NOAA and LiPD files
| Example : LiPD to NOAA converter
| 1 : L = lipd . readLipd ( )
| 2 : lipd . noaa ( L , " / Users / someuser / Desktop " , " https : / / www1 . ncdc . noaa . gov / pub / data / paleo / pages2... | global files , cwd
# When going from NOAA to LPD , use the global " files " variable .
# When going from LPD to NOAA , use the data from the LiPD Library .
# Choose the mode
_mode = noaa_prompt ( )
start = clock ( )
# LiPD mode : Convert LiPD files to NOAA files
if _mode == "1" : # _ project , _ version = noaa _ prompt... |
def _populate_text_file ( self ) :
"""Create the ` ` self . text _ file ` ` object by reading
the text file at ` ` self . text _ file _ path _ absolute ` ` .""" | self . log ( u"Populate text file..." )
if ( ( self . text_file_path_absolute is not None ) and ( self . configuration [ "language" ] is not None ) ) : # the following values might be None
parameters = { gc . PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX : self . configuration [ "i_t_ignore_regex" ] , gc . PPN_TASK_IS_TEXT_FI... |
def children ( self , ** kwargs ) :
"""Retrieve the direct activities of this subprocess .
It returns a combination of Tasks ( a . o . UserTasks ) and Subprocesses on the direct descending level .
Only when the activity is a Subprocess , otherwise it raises a NotFoundError
: param kwargs : Additional search a... | if self . activity_type != ActivityType . SUBPROCESS :
raise NotFoundError ( "Only subprocesses can have children, please choose a subprocess instead of a '{}' " "(activity '{}')" . format ( self . activity_type , self . name ) )
return self . _client . activities ( container = self . id , scope = self . scope_id ,... |
def _get_label ( placeholder , label_mapping , label_i ) :
"""Helper function to either get the appropriate label for a given placeholder or generate
a new label and update the mapping .
See : py : func : ` instantiate _ labels ` for usage .""" | if placeholder in label_mapping :
return label_mapping [ placeholder ] , label_mapping , label_i
new_target = Label ( "{}{}" . format ( placeholder . prefix , label_i ) )
label_i += 1
label_mapping [ placeholder ] = new_target
return new_target , label_mapping , label_i |
def set_el ( cls , el , value ) :
"""Set given ` el ` tag element to ` value ` .
Automatically choose proper method to set the ` value ` based on the type
of the ` el ` .
Args :
el ( obj ) : Element reference to the input you want to convert to
typeahead .
value ( list ) : List of dicts with two keys : ... | if not el :
return
tag_name = el . elt . tagName . lower ( )
if tag_name == "textarea" :
cls . _set_textarea ( el , value )
elif tag_name == "input" :
if "typeahead" in el . class_name . lower ( ) :
cls . _set_typeahead ( el , value )
else :
cls . _set_input ( el , value )
elif tag_name ... |
def has_scope ( self , scope ) :
"""Return True if OAuth2 authorized for the passed in scope ( s ) .""" | if not self . is_oauth_session ( ) :
return False
if '*' in self . _authentication :
return True
if isinstance ( scope , six . string_types ) :
scope = [ scope ]
return all ( s in self . _authentication for s in scope ) |
def lowercase ( text_string ) :
'''Converts text _ string into lowercase and returns the converted string as type str .
Keyword argument :
- text _ string : string instance
Exceptions raised :
- InputError : occurs should a non - string argument be passed''' | if text_string is None or text_string == "" :
return ""
elif isinstance ( text_string , str ) :
return text_string . lower ( )
else :
raise InputError ( "string not passed as argument for text_string" ) |
def ximplotxy_jupyter ( x , y , fmt = None , ** args ) :
"""Auxiliary function to call ximplotxy from a jupyter notebook .""" | using_jupyter = True
if fmt is None :
return ximplotxy ( x , y , using_jupyter = using_jupyter , ** args )
else :
return ximplotxy ( x , y , fmt , using_jupyter = using_jupyter , ** args ) |
def replace_termcodes ( self , string , from_part = False , do_lt = True , special = True ) :
r"""Replace any terminal code strings by byte sequences .
The returned sequences are Nvim ' s internal representation of keys ,
for example :
< esc > - > ' \ x1b '
< cr > - > ' \ r '
< c - l > - > ' \ x0c '
< u... | return self . request ( 'nvim_replace_termcodes' , string , from_part , do_lt , special ) |
def default ( ) :
"""Get default shaman instance by " data / trained . json " """ | if Shaman . _default_instance is not None :
return Shaman . _default_instance
with open ( ( os . path . dirname ( __file__ ) or '.' ) + '/data/trained.json' ) as file :
tset = json . loads ( file . read ( ) )
Shaman . _default_instance = Shaman ( tset )
return Shaman . _default_instance |
def save ( potential , f ) :
"""Write a : class : ` ~ gala . potential . PotentialBase ` object out to a text ( YAML )
file .
Parameters
potential : : class : ` ~ gala . potential . PotentialBase `
The instantiated : class : ` ~ gala . potential . PotentialBase ` object .
f : str , file _ like
A filenam... | d = to_dict ( potential )
if hasattr ( f , 'write' ) :
yaml . dump ( d , f , default_flow_style = False )
else :
with open ( f , 'w' ) as f2 :
yaml . dump ( d , f2 , default_flow_style = False ) |
def extract_response ( raw_response ) :
"""Extract requests response object .
only extract those status _ code in [ 200 , 300 ) .
: param raw _ response : a requests . Resposne object .
: return : content of response .""" | data = urlread ( raw_response )
if is_success_response ( raw_response ) :
return data
elif is_failure_response ( raw_response ) :
raise RemoteExecuteError ( data )
elif is_invalid_response ( raw_response ) :
raise InvalidResponseError ( data )
else :
raise UnknownStatusError ( data ) |
def spladder ( job , inputs , bam_id , bai_id ) :
"""Run SplAdder to detect and quantify alternative splicing events
: param JobFunctionWrappingJob job : passed by Toil automatically
: param Namespace inputs : Stores input arguments ( see main )
: param str bam _ id : FileStore ID of bam
: param str bai _ i... | job . fileStore . logToMaster ( 'SplAdder: {}' . format ( inputs . uuid ) )
work_dir = job . fileStore . getLocalTempDir ( )
# Pull in alignment . bam from fileStore
job . fileStore . readGlobalFile ( bam_id , os . path . join ( work_dir , 'alignment.bam' ) )
job . fileStore . readGlobalFile ( bai_id , os . path . join... |
def _write_bytes ( stream : Union [ StdSim , TextIO ] , to_write : bytes ) -> None :
"""Write bytes to a stream
: param stream : the stream being written to
: param to _ write : the bytes being written""" | try :
stream . buffer . write ( to_write )
except BrokenPipeError : # This occurs if output is being piped to a process that closed
pass |
def init ( self , name , subject , expires = None , algorithm = None , parent = None , pathlen = None , issuer_url = None , issuer_alt_name = '' , crl_url = None , ocsp_url = None , ca_issuer_url = None , ca_crl_url = None , ca_ocsp_url = None , name_constraints = None , password = None , parent_password = None , ecc_c... | # NOTE : Already verified by KeySizeAction , so these checks are only for when the Python API is used
# directly .
if key_type != 'ECC' :
if key_size is None :
key_size = ca_settings . CA_DEFAULT_KEY_SIZE
if not is_power2 ( key_size ) :
raise ValueError ( "%s: Key size must be a power of two" % ... |
def _set_axis ( self , traces , on = None , side = 'right' , title = '' ) :
"""Sets the axis in which each trace should appear
If the axis doesn ' t exist then a new axis is created
Parameters :
traces : list ( str )
List of trace names
on : string
The axis in which the traces should be placed .
If th... | fig = { }
fig_cpy = fig_to_dict ( self ) . copy ( )
fig [ 'data' ] = fig_cpy [ 'data' ]
fig [ 'layout' ] = fig_cpy [ 'layout' ]
fig = Figure ( fig )
traces = make_list ( traces )
def update_data ( trace , y ) :
anchor = fig . axis [ 'def' ] [ y ] [ 'anchor' ] if 'anchor' in fig . axis [ 'def' ] [ y ] else 'x1'
... |
def sms_recipients ( self ) :
"""Returns a list of recipients subscribed to receive SMS ' s
for this " notifications " class .
See also : edc _ auth . UserProfile .""" | sms_recipients = [ ]
UserProfile = django_apps . get_model ( "edc_auth.UserProfile" )
for user_profile in UserProfile . objects . filter ( user__is_active = True , user__is_staff = True ) :
try :
user_profile . sms_notifications . get ( name = self . name )
except ObjectDoesNotExist :
pass
e... |
def _write_iodir ( self , iodir = None ) :
"""Write the specified byte value to the IODIR registor . If no value
specified the current buffered value will be written .""" | if iodir is not None :
self . iodir = iodir
self . i2c . write_list ( self . IODIR , self . iodir ) |
def process_response_params ( self , params : Sequence [ ExtensionParameter ] , accepted_extensions : Sequence [ "Extension" ] , ) -> PerMessageDeflate :
"""Process response parameters .
Return an extension instance .""" | if any ( other . name == self . name for other in accepted_extensions ) :
raise NegotiationError ( f"Received duplicate {self.name}" )
# Request parameters are available in instance variables .
# Load response parameters in local variables .
( server_no_context_takeover , client_no_context_takeover , server_max_win... |
def use_comparative_authorization_view ( self ) :
"""Pass through to provider AuthorizationLookupSession . use _ comparative _ authorization _ view""" | self . _object_views [ 'authorization' ] = COMPARATIVE
# self . _ get _ provider _ session ( ' authorization _ lookup _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_comparative_authorization_view ( )
except AttributeError :
... |
def _descendants ( self ) :
"""Scans full list of node descendants .
: return : Generator of nodes .""" | children = self . _children
if children is not None :
for child in children . values ( ) :
yield from child . _descendants
yield child |
def feedback ( self ) :
"""Access the feedback
: returns : twilio . rest . api . v2010 . account . call . feedback . FeedbackList
: rtype : twilio . rest . api . v2010 . account . call . feedback . FeedbackList""" | if self . _feedback is None :
self . _feedback = FeedbackList ( self . _version , account_sid = self . _solution [ 'account_sid' ] , call_sid = self . _solution [ 'sid' ] , )
return self . _feedback |
def on_timer ( self ) :
"""Executes flush ( ) . Ignores any errors to make sure one exception
doesn ' t halt the whole flushing process .""" | try :
self . flush ( )
except Exception as e :
log . exception ( 'Error while flushing: %s' , e )
self . _set_timer ( ) |
def insert_tree ( self , items , node , headers ) :
"""Recursively grow FP tree .""" | first = items [ 0 ]
child = node . get_child ( first )
if child is not None :
child . count += 1
else : # Add new child .
child = node . add_child ( first )
# Link it to header structure .
if headers [ first ] is None :
headers [ first ] = child
else :
current = headers [ first ]
... |
def _sanity_check_query_root_block ( ir_blocks ) :
"""Assert that QueryRoot is always the first block , and only the first block .""" | if not isinstance ( ir_blocks [ 0 ] , QueryRoot ) :
raise AssertionError ( u'The first block was not QueryRoot: {}' . format ( ir_blocks ) )
for block in ir_blocks [ 1 : ] :
if isinstance ( block , QueryRoot ) :
raise AssertionError ( u'Found QueryRoot after the first block: {}' . format ( ir_blocks ) ) |
def get_port_channel_detail_output_lacp_oper_key ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_port_channel_detail = ET . Element ( "get_port_channel_detail" )
config = get_port_channel_detail
output = ET . SubElement ( get_port_channel_detail , "output" )
lacp = ET . SubElement ( output , "lacp" )
oper_key = ET . SubElement ( lacp , "oper-key" )
oper_key . text = kwargs . ... |
def upload_data ( job , master_ip , inputs , hdfs_name , upload_name , spark_on_toil ) :
"""Upload file hdfsName from hdfs to s3""" | if mock_mode ( ) :
truncate_file ( master_ip , hdfs_name , spark_on_toil )
log . info ( "Uploading output BAM %s to %s." , hdfs_name , upload_name )
call_conductor ( job , master_ip , hdfs_name , upload_name , memory = inputs . memory )
remove_file ( master_ip , hdfs_name , spark_on_toil ) |
def delete_all ( self , criteria : Q = None ) :
"""Delete the dictionary object by its criteria""" | if criteria : # Delete the object from the dictionary and return the deletion count
items = self . _filter ( criteria , self . conn [ 'data' ] [ self . schema_name ] )
# Delete all the matching identifiers
with self . conn [ 'lock' ] :
for identifier in items :
self . conn [ 'data' ] [ s... |
def stats ( self ) :
""": return : Associated : class : ` stravalib . model . AthleteStats `""" | if not self . is_authenticated_athlete ( ) :
raise exc . NotAuthenticatedAthlete ( "Statistics are only available for the authenticated athlete" )
if self . _stats is None :
self . assert_bind_client ( )
self . _stats = self . bind_client . get_athlete_stats ( self . id )
return self . _stats |
def origin ( self ) :
"""Get image origin
Returns
tuple""" | libfn = utils . get_lib_fn ( 'getOrigin%s' % self . _libsuffix )
return libfn ( self . pointer ) |
def update ( self ) :
'''Update the encoder and the decoder
to minimize the reconstruction error of the inputs .
Returns :
` np . ndarray ` of the reconstruction errors .''' | observed_arr = self . noise_sampler . generate ( )
inferenced_arr = self . inference ( observed_arr )
error_arr = self . __convolutional_auto_encoder . computable_loss . compute_loss ( observed_arr , inferenced_arr )
delta_arr = self . __convolutional_auto_encoder . computable_loss . compute_delta ( observed_arr , infe... |
def check_file_path ( self , path ) :
"""Ensure file exists at the provided path
: type path : string
: param path : path to directory to check""" | if os . path . exists ( path ) is not True :
msg = "File Not Found {}" . format ( path )
raise OSError ( msg ) |
def _value_retriever ( self , value ) :
"""Get a value retrieving callback .
: type value : mixed
: rtype : callable""" | if self . _use_as_callable ( value ) :
return value
return lambda item : data_get ( item , value ) |
def validate_response ( self ) :
"""Checks that the response is valid and import succeeded .""" | if self . response is None :
logger . error ( "Failed to submit" )
return False
if not self . response :
logger . error ( "HTTP status %d: failed to submit to %s" , self . response . status_code , self . response . url , )
return False
if not self . parsed_response :
logger . error ( "Submit to %s f... |
def get ( self ) :
"""Get a new chunk if available .
Returns :
Chunk or list : If enough frames are available a chunk is returned . Otherwise None .
If ` ` self . num _ buffer > = 1 ` ` a list instead of single chunk is returned .""" | chunk_size = self . _smallest_buffer ( )
all_full = self . _all_full ( )
if all_full :
right_context = 0
num_frames = chunk_size - self . current_left_context
else :
right_context = self . right_context
num_frames = self . min_frames
chunk_size_needed = num_frames + self . current_left_context + right_c... |
def pip_ins_req ( ctx , python , req_path , venv_path = None , inputs = None , outputs = None , touch = None , check_import = False , check_import_module = None , pip_setup_file = None , pip_setup_touch = None , virtualenv_setup_touch = None , always = False , ) :
"""Create task that uses given virtual environment ... | # Ensure given context object is BuildContext object
_ensure_build_context ( ctx )
# If virtual environment directory path is not given
if venv_path is None : # Use given Python program path
venv_python = python
# If virtual environment directory path is given
else : # Get Python program path in the virtual environ... |
def next ( self ) :
'''Returns next image for same content _ object and None if image is
the last .''' | try :
return self . __class__ . objects . for_model ( self . content_object , self . content_type ) . filter ( order__lt = self . order ) . order_by ( '-order' ) [ 0 ]
except IndexError :
return None |
def label ( self , name , value , cluster_ids = None ) :
"""Assign a label to clusters .
Example : ` quality 3 `""" | if cluster_ids is None :
cluster_ids = self . cluster_view . selected
if not hasattr ( cluster_ids , '__len__' ) :
cluster_ids = [ cluster_ids ]
if len ( cluster_ids ) == 0 :
return
self . cluster_meta . set ( name , cluster_ids , value )
self . _global_history . action ( self . cluster_meta ) |
def setup_parameters ( self , centering_type = 'standard' , include_central_site_in_centroid = False , bva_distance_scale_factor = None , structure_refinement = STRUCTURE_REFINEMENT_REFINED , spg_analyzer_options = None ) :
"""Setup of the parameters for the coordination geometry finder . A reference point for the ... | self . centering_type = centering_type
self . include_central_site_in_centroid = include_central_site_in_centroid
if bva_distance_scale_factor is not None :
self . bva_distance_scale_factor = bva_distance_scale_factor
else :
self . bva_distance_scale_factor = self . DEFAULT_BVA_DISTANCE_SCALE_FACTOR
self . stru... |
def copy ( self ) :
"""Returns a copy of this channel""" | new = type ( self ) ( str ( self ) )
new . _init_from_channel ( self )
return new |
def render ( self , get_params , module , _if = None ) :
"""render the block and return the output .""" | enough = False
output = [ ]
valid = None
if self . commands . show :
valid = True
if self . parent and self . commands . soft and _if is None :
return None , self
if _if :
valid = True
elif self . commands . _if :
valid = self . check_valid ( get_params )
if valid is not False :
for item in self . c... |
def options ( self , context , module_options ) :
'''SCRIPT Script version to execute ( choices : bash , python ) ( default : bash )''' | scripts = { 'PYTHON' : get_script ( 'mimipenguin/mimipenguin.py' ) , 'BASH' : get_script ( 'mimipenguin/mimipenguin.sh' ) }
self . script_choice = 'BASH'
if 'SCRIPT' in module_options :
self . script_choice = module_options [ 'SCRIPT' ] . upper ( )
if self . script_choice not in scripts . keys ( ) :
con... |
def _parse_prefix_query ( self , query_str ) :
"""Parse a smart search query for prefixes
This is a helper function to smart _ search _ prefix for easier unit
testing of the parser .""" | sp = smart_parsing . PrefixSmartParser ( )
query = sp . parse ( query_str )
return query |
def build_url_chunks ( self ) :
"""If url is too big because of id filter is huge , break id and construct
several urls to call them in order to abstract this complexity from user .""" | CHUNK_SIZE = 500
id_filter = str ( self . api_filters . pop ( self . id_filter ) ) . split ( ',' )
chuncks = list ( self . chunks ( id_filter , CHUNK_SIZE ) )
filters = '&' . join ( "%s=%s" % ( k , v ) for ( k , v ) in self . api_filters . items ( ) )
for chunk in chuncks :
if filters :
url = "{0}?{1}&{2}={... |
def parse_varbyte_as_int ( self , fp , return_bytes_read = True ) :
"""Read a variable length byte from the file and return the
corresponding integer .""" | result = 0
bytes_read = 0
r = 0x80
while r & 0x80 :
try :
r = self . bytes_to_int ( fp . read ( 1 ) )
self . bytes_read += 1
except :
raise IOError ( "Couldn't read variable length byte from file." )
if r & 0x80 :
result = ( result << 7 ) + ( r & 0x7F )
else :
res... |
def load_user ( ) :
"""Read user config file and return it as a dict .""" | config_path = get_user_config_path ( )
config = { }
# TODO : This may be overkill and too slow just for reading a config file
with open ( config_path ) as f :
code = compile ( f . read ( ) , config_path , 'exec' )
exec ( code , config )
keys = list ( six . iterkeys ( config ) )
for k in keys :
if k . startswith... |
def observe_multi ( self , keys , master_only = False ) :
"""Multi - variant of : meth : ` observe `""" | return _Base . observe_multi ( self , keys , master_only = master_only ) |
def copyfile ( self , target ) :
"""Copies this file to the given ` target ` location .""" | shutil . copyfile ( self . path , self . _to_backend ( target ) ) |
def clear_start_timestamp ( self ) :
"""stub""" | if ( self . get_start_timestamp_metadata ( ) . is_read_only ( ) or self . get_start_timestamp_metadata ( ) . is_required ( ) ) :
raise NoAccess ( )
self . my_osid_object_form . _my_map [ 'startTimestamp' ] = self . get_start_timestamp_metadata ( ) . get_default_integer_values ( ) |
def expand_file_arguments ( ) :
"""Any argument starting with " @ " gets replaced with all values read from a text file .
Text file arguments can be split by newline or by space .
Values are added " as - is " , as if they were specified in this order on the command line .""" | new_args = [ ]
expanded = False
for arg in sys . argv :
if arg . startswith ( "@" ) :
expanded = True
with open ( arg [ 1 : ] , "r" ) as f :
for line in f . readlines ( ) :
new_args += shlex . split ( line )
else :
new_args . append ( arg )
if expanded :
p... |
def convert_tuple_into_set ( input_tuple ) :
"""This function transforms the provided tuple into a set .
Examples :
convert _ tuple _ into _ set ( ( ' x ' , ' y ' , ' z ' ) ) - > { ' x ' , ' y ' , ' z ' }
convert _ tuple _ into _ set ( ( ' a ' , ' b ' , ' c ' ) ) - > { ' a ' , ' b ' , ' c ' }
convert _ tupl... | output_set = set ( input_tuple )
return output_set |
def FormatDescriptorToPython ( i ) :
"""Format a descriptor into a form which can be used as a python attribute
example : :
> > > FormatDescriptorToPython ( ' ( Ljava / lang / Long ; Ljava / lang / Long ; Z Z ) V ' )
' Ljava _ lang _ LongLjava _ lang _ LongZZV
: param i : name to transform
: rtype : str""... | i = i . replace ( "/" , "_" )
i = i . replace ( ";" , "" )
i = i . replace ( "[" , "" )
i = i . replace ( "(" , "" )
i = i . replace ( ")" , "" )
i = i . replace ( " " , "" )
i = i . replace ( "$" , "" )
return i |
def from_stream ( cls , stream , marker_code , offset ) :
"""Extract the horizontal and vertical dots - per - inch value from the APP1
header at * offset * in * stream * .""" | # field off len type notes
# segment length 0 2 short
# Exif identifier 2 6 6 chr ' Exif \ x00 \ x00'
# TIFF byte order 8 2 2 chr ' II ' = little ' MM ' = big endian
# meaning of universe 10 2 2 chr ' * \ x00 ' or ' \ x00 * ' depending
# IFD0 off fr / II or MM 10 16 long relative to . . . ?
segment_length = stream . re... |
def transfer ( self ) :
"""Returns a MappedObject containing the account ' s transfer pool data""" | result = self . client . get ( '/account/transfer' )
if not 'used' in result :
raise UnexpectedResponseError ( 'Unexpected response when getting Transfer Pool!' )
return MappedObject ( ** result ) |
def dimensions ( self ) :
"""Iterate over the dimension columns , regardless of parent / child status""" | from ambry . valuetype . core import ROLE
for c in self . columns :
if c . role == ROLE . DIMENSION :
yield c |
def probability ( self , direction , mechanism , purview ) :
"""Probability that the purview is in it ' s current state given the
state of the mechanism .""" | repertoire = self . repertoire ( direction , mechanism , purview )
return self . state_probability ( direction , repertoire , purview ) |
def appndd ( item , cell ) :
"""Append an item to a double precision cell .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / appndd _ c . html
: param item : The item to append .
: type item : Union [ float , Iterable [ float ] ]
: param cell : The cell to append to .
: type... | assert isinstance ( cell , stypes . SpiceCell )
if hasattr ( item , "__iter__" ) :
for d in item :
libspice . appndd_c ( ctypes . c_double ( d ) , cell )
else :
item = ctypes . c_double ( item )
libspice . appndd_c ( item , cell ) |
def is_all_field_none ( self ) :
""": rtype : bool""" | if self . _id_ is not None :
return False
if self . _created is not None :
return False
if self . _updated is not None :
return False
if self . _contract_date_start is not None :
return False
if self . _contract_date_end is not None :
return False
if self . _contract_version is not None :
return... |
def install ( pkg , target = 'LocalSystem' , store = False , allow_untrusted = False ) :
'''Install a pkg file
Args :
pkg ( str ) : The package to install
target ( str ) : The target in which to install the package to
store ( bool ) : Should the package be installed as if it was from the
store ?
allow _... | if '*.' not in pkg : # If we use wildcards , we cannot use quotes
pkg = _quote ( pkg )
target = _quote ( target )
cmd = 'installer -pkg {0} -target {1}' . format ( pkg , target )
if store :
cmd += ' -store'
if allow_untrusted :
cmd += ' -allowUntrusted'
# We can only use wildcards in python _ shell which is... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.