signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def add_device_not_active_callback ( self , callback ) :
"""Register callback to be invoked when a device is not responding .""" | _LOGGER . debug ( 'Added new callback %s ' , callback )
self . _cb_device_not_active . append ( callback ) |
def delete_collection_namespaced_role_binding ( self , namespace , ** kwargs ) : # noqa : E501
"""delete _ collection _ namespaced _ role _ binding # noqa : E501
delete collection of RoleBinding # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , plea... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . delete_collection_namespaced_role_binding_with_http_info ( namespace , ** kwargs )
# noqa : E501
else :
( data ) = self . delete_collection_namespaced_role_binding_with_http_info ( namespace , ** kwargs )
# noqa :... |
def set_export ( args ) :
'''Return a list of lines in TSV form that would suffice to reconstitute a
container ( set ) entity , if passed to entity _ import . The first line in
the list is the header , and subsequent lines are the container members .''' | r = fapi . get_entity ( args . project , args . workspace , args . entity_type , args . entity )
fapi . _check_response_code ( r , 200 )
set_type = args . entity_type
set_name = args . entity
member_type = set_type . split ( '_' ) [ 0 ]
members = r . json ( ) [ 'attributes' ] [ member_type + 's' ] [ 'items' ]
result = ... |
def _check_rule ( rule , _rule ) :
'''Check to see if two rules are the same . Needed to compare rules fetched
from boto , since they may not completely match rules defined in sls files
but may be functionally equivalent .''' | # We need to alter what Boto returns if no ports are specified
# so that we can compare rules fairly .
# Boto returns None for from _ port and to _ port where we ' re required
# to pass in " - 1 " instead .
if _rule . get ( 'from_port' ) is None :
_rule [ 'from_port' ] = - 1
if _rule . get ( 'to_port' ) is None :
... |
def get_inconsistent_fieldnames ( ) :
"""Returns a set of keys from settings . CONFIG that are not accounted for in
settings . CONFIG _ FIELDSETS .
If there are no fieldnames in settings . CONFIG _ FIELDSETS , returns an empty set .""" | field_name_list = [ ]
for fieldset_title , fields_list in settings . CONFIG_FIELDSETS . items ( ) :
for field_name in fields_list :
field_name_list . append ( field_name )
if not field_name_list :
return { }
return set ( set ( settings . CONFIG . keys ( ) ) - set ( field_name_list ) ) |
def _maintain_parent ( self , request , response ) :
"""Maintain the parent ID in the querystring for response _ add and
response _ change .""" | location = response . _headers . get ( "location" )
parent = request . GET . get ( "parent" )
if parent and location and "?" not in location [ 1 ] :
url = "%s?parent=%s" % ( location [ 1 ] , parent )
return HttpResponseRedirect ( url )
return response |
def parse ( self ) :
"""Parses configuration file items from one
or more related sections .""" | for section_name , section_options in self . sections . items ( ) :
method_postfix = ''
if section_name : # [ section . option ] variant
method_postfix = '_%s' % section_name
section_parser_method = getattr ( self , # Dots in section names are tranlsated into dunderscores .
( 'parse_section%s' %... |
def _compute_chunk_size ( self ) : # type : ( Descriptor ) - > int
"""Compute chunk size given block list
: param Descriptor self : this
: rtype : int
: return : chunk size bytes""" | if self . _src_block_list is not None :
blen = len ( self . _src_block_list )
if blen == 0 : # this is a one - shot block blob
return self . _src_ase . size
elif blen == 1 :
return self . _src_block_list [ 0 ] . size
else :
return - 1
else :
return _MAX_NONBLOCK_BLOB_CHUNKSIZ... |
def estimate ( path ) :
'''Estimate the space that an XFS filesystem will take .
For each directory estimate the space that directory would take
if it were copied to an XFS filesystem .
Estimation does not cross mount points .
CLI Example :
. . code - block : : bash
salt ' * ' xfs . estimate / path / to... | if not os . path . exists ( path ) :
raise CommandExecutionError ( "Path \"{0}\" was not found." . format ( path ) )
out = __salt__ [ 'cmd.run_all' ] ( "xfs_estimate -v {0}" . format ( path ) )
_verify_run ( out )
return _xfs_estimate_output ( out [ "stdout" ] ) |
def pin ( self , spec , pin_class = None , ** kwargs ) :
"""The pin method for : class : ` MockFactory ` additionally takes a * pin _ class *
attribute which can be used to override the class ' : attr : ` pin _ class `
attribute . Any additional keyword arguments will be passed along to the
pin constructor ( ... | if pin_class is None :
pin_class = self . pin_class
n = self . pi_info . to_gpio ( spec )
try :
pin = self . pins [ n ]
except KeyError :
pin = pin_class ( self , n , ** kwargs )
self . pins [ n ] = pin
else : # Ensure the pin class expected supports PWM ( or not )
if issubclass ( pin_class , MockPW... |
def update_group ( self , group_id , name ) :
"""Change group name
: param group _ id : Id of group
: param name : Group name""" | parameters = { 'name' : name }
url = self . TEAM_GROUPS_ID_URL % group_id
connection = Connection ( self . token )
connection . set_url ( self . production , url )
connection . add_header ( 'Content-Type' , 'application/json' )
connection . add_params ( parameters )
return connection . patch_request ( ) |
def get ( self , key , default = CACHE_MISS ) :
"""Get a value out of the cache
Returns CACHE _ DISABLED if the cache is disabled
: param key : key to search for
: param default : value to return if the key is not found ( defaults to CACHE _ MISS )""" | if not self . options . enabled :
return CACHE_DISABLED
ret = default
if self . has ( key ) :
ret = self . _dict [ key ] . value
logger . debug ( 'get({}, default={}) == {}' . format ( repr ( key ) , repr ( default ) , repr ( ret ) ) )
return ret |
def complete ( self ) :
"""Consider a transcript complete if it has start and stop codons and
a coding sequence whose length is divisible by 3""" | return ( self . contains_start_codon and self . contains_stop_codon and self . coding_sequence is not None and len ( self . coding_sequence ) % 3 == 0 ) |
def cli ( ctx , id_number , new_key , metadata = "" ) :
"""Update a canned key
Output :
an empty dictionary""" | return ctx . gi . cannedkeys . update_key ( id_number , new_key , metadata = metadata ) |
def gridPen ( self ) :
"""Returns the pen that will be used when drawing the grid lines .
: return < QtGui . QPen >""" | delegate = self . itemDelegate ( )
if isinstance ( delegate , XTreeWidgetDelegate ) :
return delegate . gridPen ( )
return QtGui . QPen ( ) |
def from_dict ( data , ctx ) :
"""Instantiate a new DynamicOrderState from a dict ( generally from loading
a JSON response ) . The data used to instantiate the DynamicOrderState is
a shallow copy of the dict passed in , with any complex child types
instantiated appropriately .""" | data = data . copy ( )
if data . get ( 'trailingStopValue' ) is not None :
data [ 'trailingStopValue' ] = ctx . convert_decimal_number ( data . get ( 'trailingStopValue' ) )
if data . get ( 'triggerDistance' ) is not None :
data [ 'triggerDistance' ] = ctx . convert_decimal_number ( data . get ( 'triggerDistanc... |
def metaclass ( * metaclasses ) : # type : ( * type ) - > Callable [ [ type ] , type ]
"""Create the class using all metaclasses .
Args :
metaclasses : A tuple of metaclasses that will be used to generate and
replace a specified class .
Returns :
A decorator that will recreate the class using the specifie... | def _inner ( cls ) : # pragma pylint : disable = unused - variable
metabases = tuple ( collections . OrderedDict ( # noqa : F841
( c , None ) for c in ( metaclasses + ( type ( cls ) , ) ) ) . keys ( ) )
# pragma pylint : enable = unused - variable
_Meta = metabases [ 0 ]
for base in metabases [ 1 : ... |
def leave_room ( self , sid , namespace , room ) :
"""Remove a client from a room .""" | try :
del self . rooms [ namespace ] [ room ] [ sid ]
if len ( self . rooms [ namespace ] [ room ] ) == 0 :
del self . rooms [ namespace ] [ room ]
if len ( self . rooms [ namespace ] ) == 0 :
del self . rooms [ namespace ]
except KeyError :
pass |
def last_archive ( self ) :
'''Get the last available archive
: return :''' | archives = { }
for archive in self . archives ( ) :
archives [ int ( archive . split ( '.' ) [ 0 ] . split ( '-' ) [ - 1 ] ) ] = archive
return archives and archives [ max ( archives ) ] or None |
def run_validators ( self , value ) :
"""Run the validators on the setting value .""" | errors = [ ]
for validator in self . validators :
try :
validator ( value )
except ValidationError as error :
errors . extend ( error . messages )
if errors :
raise ValidationError ( errors ) |
def by_pattern ( self , pattern , zipcode_type = ZipcodeType . Standard , sort_by = SimpleZipcode . zipcode . name , ascending = True , returns = DEFAULT_LIMIT ) :
"""Search zipcode by wildcard .
Returns multiple results .""" | return self . query ( pattern = pattern , sort_by = sort_by , zipcode_type = zipcode_type , ascending = ascending , returns = returns , ) |
def _find_usage_networking_sgs ( self ) :
"""calculate usage for VPC - related things""" | logger . debug ( "Getting usage for EC2 VPC resources" )
sgs_per_vpc = defaultdict ( int )
rules_per_sg = defaultdict ( int )
for sg in self . resource_conn . security_groups . all ( ) :
if sg . vpc_id is not None :
sgs_per_vpc [ sg . vpc_id ] += 1
rules_per_sg [ sg . id ] = len ( sg . ip_permission... |
def use_federated_vault_view ( self ) :
"""Pass through to provider AuthorizationLookupSession . use _ federated _ vault _ view""" | self . _vault_view = FEDERATED
# self . _ get _ provider _ session ( ' authorization _ lookup _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_federated_vault_view ( )
except AttributeError :
pass |
def _marshal ( self , obj ) :
"""Walks an object and marshals any psphere object into MORs .""" | logger . debug ( "Checking if %s needs to be marshalled" , obj )
if isinstance ( obj , ManagedObject ) :
logger . debug ( "obj is a psphere object, converting to MOR" )
return obj . _mo_ref
if isinstance ( obj , list ) :
logger . debug ( "obj is a list, recursing it" )
new_list = [ ]
for item in obj... |
def chunk ( iterable , size ) :
"""chunk ( ' ABCDEFG ' , 3 ) - - > ABC DEF G""" | # TODO : only used in gui . mainwindow ( deprecated )
iterator = iter ( iterable )
while size :
result = [ ]
try :
for i in range ( size ) :
elem = next ( iterator )
result . append ( elem )
yield tuple ( result )
except StopIteration :
if result :
... |
def is_python_inside ( self , file_path ) : # type : ( str ) - > bool
"""If . py , yes . If extensionless , open file and check shebang
TODO : support variations on this : # ! / usr / bin / env python
: param file _ path :
: return :""" | if file_path . endswith ( ".py" ) :
return True
# duh .
# not supporting surprising extensions , ege . . py2 , . python , . corn _ chowder
# extensionless
if "." not in file_path :
try :
firstline = self . open_this ( file_path , "r" ) . readline ( )
if firstline . startswith ( "#" ) and "python... |
def dbmin20years ( self , value = None ) :
"""Corresponds to IDD Field ` dbmin20years `
20 - year return period values for minimum extreme dry - bulb temperature
Args :
value ( float ) : value for IDD Field ` dbmin20years `
Unit : C
if ` value ` is None it will not be checked against the
specification a... | if value is not None :
try :
value = float ( value )
except ValueError :
raise ValueError ( 'value {} need to be of type float ' 'for field `dbmin20years`' . format ( value ) )
self . _dbmin20years = value |
def get_cache_base ( suffix = None ) :
"""Return the default base location for distlib caches . If the directory does
not exist , it is created . Use the suffix provided for the base directory ,
and default to ' . distlib ' if it isn ' t provided .
On Windows , if LOCALAPPDATA is defined in the environment , ... | if suffix is None :
suffix = '.distlib'
if os . name == 'nt' and 'LOCALAPPDATA' in os . environ :
result = os . path . expandvars ( '$localappdata' )
else : # Assume posix , or old Windows
result = os . path . expanduser ( '~' )
# we use ' isdir ' instead of ' exists ' , because we want to
# fail if there '... |
def enable_tracing ( self , thread_trace_func = None ) :
'''Enables tracing .
If in regular mode ( tracing ) , will set the tracing function to the tracing
function for this thread - - by default it ' s ` PyDB . trace _ dispatch ` , but after
` PyDB . enable _ tracing ` is called with a ` thread _ trace _ fun... | if self . frame_eval_func is not None :
self . frame_eval_func ( )
pydevd_tracing . SetTrace ( self . dummy_trace_dispatch )
return
if thread_trace_func is None :
thread_trace_func = self . get_thread_local_trace_func ( )
else :
self . _local_thread_trace_func . thread_trace_func = thread_trace_func... |
def __calculate_sigmoid ( self ) :
'''Function of temperature .
Returns :
Sigmoid .''' | sigmoid = 1 / np . log ( self . t * self . time_rate + 1.1 )
return sigmoid |
def freeze ( self ) :
"""Call this method if you want to make your response object ready for
being pickled . This buffers the generator if there is one . It will
also set the ` Content - Length ` header to the length of the body .
. . versionchanged : : 0.6
The ` Content - Length ` header is now set .""" | # we explicitly set the length to a list of the * encoded * response
# iterator . Even if the implicit sequence conversion is disabled .
self . response = list ( self . iter_encoded ( ) )
self . headers [ 'Content-Length' ] = str ( sum ( map ( len , self . response ) ) ) |
def load_graphdef ( model_url , reset_device = True ) :
"""Load GraphDef from a binary proto file .""" | graph_def = load ( model_url )
if reset_device :
for n in graph_def . node :
n . device = ""
return graph_def |
def plot ( self ) :
'''Plot the results of the run method .''' | try :
from matplotlib import pylab
except ImportError :
raise ImportError ( 'Optional dependency matplotlib not installed.' )
if self . walked :
fig = pylab . figure ( )
ax1 = fig . add_subplot ( 111 )
ax1 . plot ( self . core_starts , self . scores , 'bo-' )
pylab . xlabel ( 'Core sequence star... |
def _append ( self , target , value ) :
"""Replace PHP ' s [ ] = idiom""" | return self . __p ( target ) + '[] = ' + self . __p ( value ) + ';' |
def write_gzip ( content , abspath ) :
"""Write binary content to gzip file .
* * 中文文档 * *
将二进制内容压缩后编码写入gzip压缩文件 。""" | with gzip . open ( abspath , "wb" ) as f :
f . write ( content ) |
def ignore_exception ( exception_class ) :
"""A decorator that ignores ` exception _ class ` exceptions""" | def _decorator ( func ) :
def newfunc ( * args , ** kwds ) :
try :
return func ( * args , ** kwds )
except exception_class :
pass
return newfunc
return _decorator |
def process_tokens ( words , normalize_plurals = True ) :
"""Normalize cases and remove plurals .
Each word is represented by the most common case .
If a word appears with an " s " on the end and without an " s " on the end ,
the version with " s " is assumed to be a plural and merged with the
version witho... | # words can be either a list of unigrams or bigrams
# d is a dict of dicts .
# Keys of d are word . lower ( ) . Values are dicts
# counting frequency of each capitalization
d = defaultdict ( dict )
for word in words :
word_lower = word . lower ( )
# get dict of cases for word _ lower
case_dict = d [ word_lo... |
def _open_url ( cls , url ) :
"""Given a CFURL Python object , return an opened ExtAudioFileRef .""" | file_obj = ctypes . c_void_p ( )
check ( _coreaudio . ExtAudioFileOpenURL ( url . _obj , ctypes . byref ( file_obj ) ) )
return file_obj |
def _higher_function_scope ( node ) :
"""Search for the first function which encloses the given
scope . This can be used for looking up in that function ' s
scope , in case looking up in a lower scope for a particular
name fails .
: param node : A scope node .
: returns :
` ` None ` ` , if no parent fun... | current = node
while current . parent and not isinstance ( current . parent , nodes . FunctionDef ) :
current = current . parent
if current and current . parent :
return current . parent
return None |
def add_field ( self , name , default = None , required = False , error = None ) :
"""Add a text / non - file field to parse for a value in the request""" | if name is None :
return
self . field_arguments . append ( dict ( name = name , default = default , required = required , error = error ) ) |
def get_comments ( self , endpoint = "deviation" , deviationid = "" , commentid = "" , username = "" , statusid = "" , ext_item = False , offset = 0 , limit = 10 , maxdepth = 0 ) :
"""Fetch comments
: param endpoint : The source / endpoint you want to fetch comments from ( deviation / profile / status / siblings ... | if endpoint == "deviation" :
if deviationid :
response = self . _req ( '/comments/{}/{}' . format ( endpoint , deviationid ) , { "commentid" : commentid , 'offset' : offset , 'limit' : limit , 'maxdepth' : maxdepth } )
else :
raise DeviantartError ( "No deviationid defined." )
elif endpoint == "... |
def _pyfftw_destroys_input ( flags , direction , halfcomplex , ndim ) :
"""Return ` ` True ` ` if FFTW destroys an input array , ` ` False ` ` otherwise .""" | if any ( flag in flags or _pyfftw_to_local ( flag ) in flags for flag in ( 'FFTW_MEASURE' , 'FFTW_PATIENT' , 'FFTW_EXHAUSTIVE' , 'FFTW_DESTROY_INPUT' ) ) :
return True
elif ( direction in ( 'backward' , 'FFTW_BACKWARD' ) and halfcomplex and ndim != 1 ) :
return True
else :
return False |
def evaluate ( self , context ) :
"""Interpolates the HTML source with the context , then returns that HTML
and the text extracted from that html .""" | html = self . _source . format ( ** context )
parts = { "text/html" : html , "text/plain" : textFromHTML ( html ) }
return { } , parts |
def qteModificationChanged ( self , mod ) :
"""Update the modification status in the mode bar .
This slot is Connected to the ` ` modificationChanged ` ` signal
from the ` ` QtmacsScintilla ` ` widget .""" | if mod :
s = '*'
else :
s = '-'
self . _qteModeBar . qteChangeModeValue ( 'MODIFIED' , s ) |
def pWMRead ( fileHandle , alphabetSize = 4 ) :
"""reads in standard position weight matrix format ,
rows are different types of base , columns are individual residues""" | lines = fileHandle . readlines ( )
assert len ( lines ) == alphabetSize
l = [ [ float ( i ) ] for i in lines [ 0 ] . split ( ) ]
for line in lines [ 1 : ] :
l2 = [ float ( i ) for i in line . split ( ) ]
assert len ( l ) == len ( l2 )
for i in xrange ( 0 , len ( l ) ) :
l [ i ] . append ( l2 [ i ] )... |
def validate ( self , instance , value ) :
"""Determine if array is valid based on shape and dtype""" | if not isinstance ( value , ( tuple , list , np . ndarray ) ) :
self . error ( instance , value )
if self . coerce :
value = self . wrapper ( value )
valid_class = ( self . wrapper if isinstance ( self . wrapper , type ) else np . ndarray )
if not isinstance ( value , valid_class ) :
self . error ( instance... |
def as_msg ( self ) :
"""Convert ourself to be a message part of the appropriate
MIME type .
Return : MIMEBase
Exceptions : None""" | # Based upon http : / / docs . python . org / 2 / library / email - examples . html
# with minimal tweaking
# Guess the content type based on the file ' s extension . Encoding
# will be ignored , although we should check for simple things like
# gzip ' d or compressed files .
ctype , encoding = mimetypes . guess_type (... |
def redirect_output ( fileobj ) :
"""Redirect standard out to file .""" | old = sys . stdout
sys . stdout = fileobj
try :
yield fileobj
finally :
sys . stdout = old |
def print_result ( self , directory_result ) :
"""Print out the contents of the directory result , using ANSI color codes if
supported""" | for file_name , line_results_dict in directory_result . iter_line_results_items ( ) :
full_path = path . join ( directory_result . directory_path , file_name )
self . write ( full_path , 'green' )
self . write ( '\n' )
for line_number , line_results in sorted ( line_results_dict . items ( ) ) :
... |
def related_objects ( self , related , objs ) :
"""Gets a QuerySet of current objects related to ` ` objs ` ` via the
relation ` ` related ` ` .""" | from versions . models import Versionable
related_model = related . related_model
if issubclass ( related_model , Versionable ) :
qs = related_model . objects . current
else :
qs = related_model . _base_manager . all ( )
return qs . using ( self . using ) . filter ( ** { "%s__in" % related . field . name : objs... |
def _example_stock_quote ( quote_ctx ) :
"""获取批量报价 , 输出 股票名称 , 时间 , 当前价 , 开盘价 , 最高价 , 最低价 , 昨天收盘价 , 成交量 , 成交额 , 换手率 , 振幅 , 股票状态""" | stock_code_list = [ "US.AAPL" , "HK.00700" ]
# subscribe " QUOTE "
ret_status , ret_data = quote_ctx . subscribe ( stock_code_list , ft . SubType . QUOTE )
if ret_status != ft . RET_OK :
print ( "%s %s: %s" % ( stock_code_list , "QUOTE" , ret_data ) )
exit ( )
ret_status , ret_data = quote_ctx . query_subscript... |
def get_flattened_bsp_keys_from_schema ( schema ) :
"""Returns the flattened keys of BoundSpatialPoints in a schema
: param schema : schema
: return : list""" | keys = [ ]
for key in schema . declared_fields . keys ( ) :
field = schema . declared_fields [ key ]
if isinstance ( field , mm . fields . Nested ) and isinstance ( field . schema , BoundSpatialPoint ) :
keys . append ( "{}.{}" . format ( key , "position" ) )
return keys |
def render_html ( html_str ) :
"""makes a temporary html rendering""" | import utool as ut
from os . path import abspath
import webbrowser
try :
html_str = html_str . decode ( 'utf8' )
except Exception :
pass
html_dpath = ut . ensure_app_resource_dir ( 'utool' , 'temp_html' )
fpath = abspath ( ut . unixjoin ( html_dpath , 'temp.html' ) )
url = 'file://' + fpath
ut . writeto ( fpath... |
def relation_operation ( self ) :
"""Returns the relation operation from the last node visited on the
path , or ` None ` , if no node has been visited yet .""" | if len ( self . nodes ) > 0 :
rel_op = self . nodes [ - 1 ] . relation_operation
else :
rel_op = None
return rel_op |
def send ( self , msg , timeout = None ) :
"""Send a message to NI - CAN .
: param can . Message msg :
Message to send
: raises can . interfaces . nican . NicanError :
If writing to transmit buffer fails .
It does not wait for message to be ACKed currently .""" | arb_id = msg . arbitration_id
if msg . is_extended_id :
arb_id |= NC_FL_CAN_ARBID_XTD
raw_msg = TxMessageStruct ( arb_id , bool ( msg . is_remote_frame ) , msg . dlc , CanData ( * msg . data ) )
nican . ncWrite ( self . handle , ctypes . sizeof ( raw_msg ) , ctypes . byref ( raw_msg ) ) |
def _get_operator_class_name ( task_detail_type ) :
"""Internal helper gets the name of the Airflow operator class . We maintain
this in a map , so this method really returns the enum name , concatenated
with the string " Operator " .""" | # TODO ( rajivpb ) : Rename this var correctly .
task_type_to_operator_prefix_mapping = { 'pydatalab.bq.execute' : ( 'Execute' , 'google.datalab.contrib.bigquery.operators._bq_execute_operator' ) , 'pydatalab.bq.extract' : ( 'Extract' , 'google.datalab.contrib.bigquery.operators._bq_extract_operator' ) , 'pydatalab.bq.... |
def _build_status ( data , item ) :
'''Process a status update from a docker build , updating the data structure''' | stream = item [ 'stream' ]
if 'Running in' in stream :
data . setdefault ( 'Intermediate_Containers' , [ ] ) . append ( stream . rstrip ( ) . split ( ) [ - 1 ] )
if 'Successfully built' in stream :
data [ 'Id' ] = stream . rstrip ( ) . split ( ) [ - 1 ] |
def parse ( self , raw_content , find_message_cb ) :
"""Function parses the RAW AS2 MDN , verifies it and extracts the
processing status of the orginal AS2 message .
: param raw _ content :
A byte string of the received HTTP headers followed by the body .
: param find _ message _ cb :
A callback the must ... | status , detailed_status = None , None
self . payload = parse_mime ( raw_content )
self . orig_message_id , orig_recipient = self . detect_mdn ( )
# Call the find message callback which should return a Message instance
orig_message = find_message_cb ( self . orig_message_id , orig_recipient )
# Extract the headers and ... |
def as_dtype ( self ) :
"""represent the heading as a numpy dtype""" | return np . dtype ( dict ( names = self . names , formats = [ v . dtype for v in self . attributes . values ( ) ] ) ) |
def validate_take_with_convert ( convert , args , kwargs ) :
"""If this function is called via the ' numpy ' library , the third
parameter in its signature is ' axis ' , which takes either an
ndarray or ' None ' , so check if the ' convert ' parameter is either
an instance of ndarray or is None""" | if isinstance ( convert , ndarray ) or convert is None :
args = ( convert , ) + args
convert = True
validate_take ( args , kwargs , max_fname_arg_count = 3 , method = 'both' )
return convert |
def model ( self , ** kwargs ) :
"""Run the forward modeling for all frequencies .
Use : py : func : ` crtomo . eitManager . eitMan . measurements ` to retrieve the
resulting synthetic measurement spectra .
Parameters
* * kwargs : dict , optional
All kwargs are directly provide to the underlying
: py : ... | for key , td in self . tds . items ( ) :
td . model ( ** kwargs ) |
def slice_yx ( r , pval , ydim = 1 ) :
"""slice a correlation and p - value matrix of a ( y , X ) dataset
into a ( y , x _ i ) vector and ( x _ j , x _ k ) matrices
Parameters
r : ndarray
Correlation Matrix of a ( y , X ) dataset
pval : ndarray
p - values
ydim : int
Number of target variables y , i ... | if ydim is 1 :
return ( r [ 1 : , : 1 ] . reshape ( - 1 , ) , pval [ 1 : , : 1 ] . reshape ( - 1 , ) , r [ 1 : , 1 : ] , pval [ 1 : , 1 : ] )
else :
return ( r [ ydim : , : ydim ] , pval [ ydim : , : ydim ] , r [ ydim : , ydim : ] , pval [ ydim : , ydim : ] ) |
def fit ( self ) :
"""fit waveforms in any domain""" | # solve for estimator of B
n , p = np . shape ( self . _X )
self . _df = float ( n - p )
self . _Cx = np . linalg . pinv ( np . dot ( self . _X . T , self . _X ) )
self . _Bhat = np . dot ( np . dot ( self . _Cx , self . _X . T ) , self . _A )
self . _Y_rec = self . _compute_prediction ( self . _X ) |
def add_cushions ( table ) :
"""Add space to start and end of each string in a list of lists
Parameters
table : list of lists of str
A table of rows of strings . For example : :
[ ' dog ' , ' cat ' , ' bicycle ' ] ,
[ ' mouse ' , trumpet ' , ' ' ]
Returns
table : list of lists of str
Note
Each cel... | for row in range ( len ( table ) ) :
for column in range ( len ( table [ row ] ) ) :
lines = table [ row ] [ column ] . split ( "\n" )
for i in range ( len ( lines ) ) :
if not lines [ i ] == "" :
lines [ i ] = " " + lines [ i ] . rstrip ( ) + " "
table [ row ] [ ... |
def relative_path ( path , from_file ) :
"""Return the relative path of a file or directory , specified
as ` ` path ` ` relative to ( the parent directory of ) ` ` from _ file ` ` .
This method is intented to be called with ` ` _ _ file _ _ ` `
as second argument .
The returned path is relative to the curre... | if path is None :
return None
abs_path_target = absolute_path ( path , from_file )
abs_path_cwd = os . getcwd ( )
if is_windows ( ) : # NOTE on Windows , if the two paths are on different drives ,
# the notion of relative path is not defined :
# return the absolute path of the target instead .
t_drive , t_tail ... |
def get_as_dataframe ( worksheet , evaluate_formulas = False , ** options ) :
"""Returns the worksheet contents as a DataFrame .
: param worksheet : the worksheet .
: param evaluate _ formulas : if True , get the value of a cell after
formula evaluation ; otherwise get the formula itself if present .
Defaul... | all_values = _get_all_values ( worksheet , evaluate_formulas )
return TextParser ( all_values , ** options ) . read ( ) |
def deploy_from_linked_clone ( self , si , logger , data_holder , vcenter_data_model , reservation_id , cancellation_context ) :
"""deploy Cloned VM From VM Command , will deploy vm from a snapshot
: param cancellation _ context :
: param si :
: param logger :
: param data _ holder :
: param vcenter _ dat... | template_resource_model = data_holder . template_resource_model
return self . _deploy_a_clone ( si = si , logger = logger , app_name = data_holder . app_name , template_name = template_resource_model . vcenter_vm , other_params = template_resource_model , vcenter_data_model = vcenter_data_model , reservation_id = reser... |
def pair ( self ) :
"""Return tuple ( address , port ) , where address is a string ( empty string if self . address ( ) is None ) and
port is an integer ( zero if self . port ( ) is None ) . Mainly , this tuple is used with python socket module
( like in bind method )
: return : 2 value tuple of str and int .... | address = str ( self . __address ) if self . __address is not None else ''
port = int ( self . __port ) if self . __port is not None else 0
return address , port |
def getSimilarTermsForTerm ( self , term , contextId = None , posType = None , getFingerprint = None , startIndex = 0 , maxResults = 10 ) :
"""Get the similar terms of a given term
Args :
term , str : A term in the retina ( required )
contextId , int : The identifier of a context ( optional )
posType , str ... | return self . _terms . getSimilarTerms ( self . _retina , term , contextId , posType , getFingerprint , startIndex , maxResults ) |
def implicify_hydrogens ( self ) :
"""remove explicit hydrogen if possible
: return : number of removed hydrogens""" | explicit = defaultdict ( list )
c = 0
for n , atom in self . atoms ( ) :
if atom . element == 'H' :
for m in self . neighbors ( n ) :
if self . _node [ m ] . element != 'H' :
explicit [ m ] . append ( n )
for n , h in explicit . items ( ) :
atom = self . _node [ n ]
len_h... |
def _periodically_flush_profile_events ( self ) :
"""Drivers run this as a thread to flush profile data in the
background .""" | # Note ( rkn ) : This is run on a background thread in the driver . It uses
# the raylet client . This should be ok because it doesn ' t read
# from the raylet client and we have the GIL here . However ,
# if either of those things changes , then we could run into issues .
while True : # Sleep for 1 second . This will ... |
def file_transaction ( * data_and_files ) :
"""Wrap file generation in a transaction , moving to output if finishes .
The initial argument can be the world descriptive ` data ` dictionary , or
a ` config ` dictionary . This is used to identify global settings for
temporary directories to create transactional ... | with _flatten_plus_safe ( data_and_files ) as ( safe_names , orig_names ) : # remove any half - finished transactions
map ( utils . remove_safe , safe_names )
# no need for try except block here ,
# because exceptions and tmp dir removal
# are handled by tx _ tmpdir contextmanager
if len ( safe_name... |
def generate_private_key ( key_size = 2048 ) :
"""Generate a private key""" | return cryptography . hazmat . primitives . asymmetric . rsa . generate_private_key ( public_exponent = 65537 , key_size = key_size , backend = cryptography . hazmat . backends . default_backend ( ) , ) |
def get_local_ip_address ( target ) :
"""Get the local ip address to access one specific target .""" | ip_adr = ''
try :
s = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM )
s . connect ( ( target , 8000 ) )
ip_adr = s . getsockname ( ) [ 0 ]
s . close ( )
except :
pass
return ip_adr |
def bounds_tree ( bounds ) :
"""Given a set of axis aligned bounds , create an r - tree for broad - phase
collision detection
Parameters
bounds : ( n , dimension * 2 ) list of non - interleaved bounds
for a 2D bounds tree :
[ ( minx , miny , maxx , maxy ) , . . . ]
Returns
tree : Rtree object""" | bounds = np . asanyarray ( copy . deepcopy ( bounds ) , dtype = np . float64 )
if len ( bounds . shape ) != 2 :
raise ValueError ( 'Bounds must be (n,dimension*2)!' )
dimension = bounds . shape [ 1 ]
if ( dimension % 2 ) != 0 :
raise ValueError ( 'Bounds must be (n,dimension*2)!' )
dimension = int ( dimension /... |
def could_scope_out ( self ) :
"""could bubble up from current scope
: return :""" | return not self . waiting_for or isinstance ( self . waiting_for , callable . EndOfStory ) or self . is_breaking_a_loop ( ) |
def _listen_comments ( self ) :
"""Start listening to comments , using a separate thread .""" | # Collect comments in a queue
comments_queue = Queue ( maxsize = self . _n_jobs * 4 )
threads = [ ]
# type : List [ BotQueueWorker ]
try : # Create n _ jobs CommentsThreads
for i in range ( self . _n_jobs ) :
t = BotQueueWorker ( name = 'CommentThread-t-{}' . format ( i ) , jobs = comments_queue , target = ... |
def get_initial_status_brok ( self , extra = None ) :
"""Create an initial status brok
: param extra : some extra information to be added in the brok data
: type extra : dict
: return : Brok object
: rtype : alignak . Brok""" | data = { 'uuid' : self . uuid }
self . fill_data_brok_from ( data , 'full_status' )
if extra :
data . update ( extra )
return Brok ( { 'type' : 'initial_' + self . my_type + '_status' , 'data' : data } ) |
def get_postgres_encoding ( python_encoding : str ) -> str :
"""Python to postgres encoding map .""" | encoding = normalize_encoding ( python_encoding . lower ( ) )
encoding_ = aliases . aliases [ encoding . replace ( '_' , '' , 1 ) ] . upper ( )
pg_encoding = PG_ENCODING_MAP [ encoding_ . replace ( '_' , '' ) ]
return pg_encoding |
def from_api_repr ( cls , resource ) :
"""Factory : construct instance from resource .
: type resource : dict
: param resource : mapping as returned from API call .
: rtype : : class : ` LifecycleRuleDelete `
: returns : Instance created from resource .""" | action = resource [ "action" ]
instance = cls ( action [ "storageClass" ] , _factory = True )
instance . update ( resource )
return instance |
def reset_sma ( self , step ) :
"""Change the direction of semimajor axis growth , from outwards to
inwards .
Parameters
step : float
The current step value .
Returns
sma , new _ step : float
The new semimajor axis length and the new step value to
initiate the shrinking of the semimajor axis length ... | if self . linear_growth :
sma = self . sma - step
step = - step
else :
aux = 1. / ( 1. + step )
sma = self . sma * aux
step = aux - 1.
return sma , step |
def safe_to_file ( folder , results ) :
"""Receives a list of results ( type : class : ` Clazz ` or : class : ` Function ` ) , and put them into the right files in : var : ` folder `
: param folder : Where the files should be in .
: type folder : str
: param results : A list of : class : ` Clazz ` or : class ... | functions = [ ]
message_send_functions = [ ]
clazzes = { }
# " filepath " : [ Class , Class , . . . ]
# split results into functions and classes
for result in results :
assert isinstance ( result , ( Clazz , Function ) )
if isinstance ( result , Clazz ) :
import_path = get_type_path ( result . clazz )
... |
def get_issue_link_type ( self , issue_link_type_id ) :
"""Returns for a given issue link type id all information about this issue link type .""" | url = 'rest/api/2/issueLinkType/{issueLinkTypeId}' . format ( issueLinkTypeId = issue_link_type_id )
return self . get ( url ) |
def standings ( self , league_table , league ) :
"""Store output of league standings to a CSV file""" | headers = [ 'Position' , 'Team Name' , 'Games Played' , 'Goal For' , 'Goals Against' , 'Goal Difference' , 'Points' ]
result = [ headers ]
result . extend ( [ team [ 'position' ] , team [ 'team' ] [ 'name' ] , team [ 'playedGames' ] , team [ 'goalsFor' ] , team [ 'goalsAgainst' ] , team [ 'goalDifference' ] , team [ 'p... |
def next_basis_label_or_index ( self , label_or_index , n = 1 ) :
"""Given the label or index of a basis state , return the label / index of
the next basis state .
More generally , if ` n ` is given , return the ` n ` ' th next basis state
label / index ; ` n ` may also be negative to obtain previous basis st... | if isinstance ( label_or_index , int ) :
new_index = label_or_index + n
if new_index < 0 :
raise IndexError ( "index %d < 0" % new_index )
if self . has_basis :
if new_index >= self . dimension :
raise IndexError ( "index %d out of range for basis %s" % ( new_index , self . _basi... |
def save_conditions ( self ) -> None :
"""Save the condition files of the | Model | objects of all | Element |
objects returned by | XMLInterface . elements | :
> > > from hydpy . core . examples import prepare _ full _ example _ 1
> > > prepare _ full _ example _ 1 ( )
> > > import os
> > > from hydpy im... | hydpy . pub . conditionmanager . currentdir = strip ( self . find ( 'outputdir' ) . text )
for element in self . master . elements :
element . model . sequences . save_conditions ( )
if strip ( self . find ( 'zip' ) . text ) == 'true' :
hydpy . pub . conditionmanager . zip_currentdir ( ) |
def get_dataset ( self ) :
"""Get dataset .""" | sample = self . _header . initial . players [ 0 ] . attributes . player_stats
if 'mod' in sample and sample . mod [ 'id' ] > 0 :
return sample . mod
elif 'trickle_food' in sample and sample . trickle_food :
return { 'id' : 1 , 'name' : mgz . const . MODS . get ( 1 ) , 'version' : '<5.7.2' }
return { 'id' : 0 , ... |
def brighten ( self ) :
"""Brighten the device one step .""" | brighten_command = StandardSend ( self . _address , COMMAND_LIGHT_BRIGHTEN_ONE_STEP_0X15_0X00 )
self . _send_method ( brighten_command ) |
def parse_conpair_logs ( self , f ) :
"""Go through log file looking for conpair concordance or contamination output
One parser to rule them all .""" | conpair_regexes = { 'concordance_concordance' : r"Concordance: ([\d\.]+)%" , 'concordance_used_markers' : r"Based on (\d+)/\d+ markers" , 'concordance_total_markers' : r"Based on \d+/(\d+) markers" , 'concordance_marker_threshold' : r"\(coverage per marker threshold : (\d+) reads\)" , 'concordance_min_mapping_quality' ... |
def push_user ( self , content , access_token , content_url = None ) :
'''Push a notification to a specific pushed user .
Param : content - > content of Pushed notification message
access _ token - > OAuth access token
content _ url ( optional ) - > enrich message with URL
Returns Shipment ID as string''' | parameters = { 'app_key' : self . app_key , 'app_secret' : self . app_secret , 'access_token' : access_token }
return self . _push ( content , 'user' , parameters , content_url ) |
def _PrintStorageInformationAsText ( self , storage_reader ) :
"""Prints information about the store as human - readable text .
Args :
storage _ reader ( StorageReader ) : storage reader .""" | table_view = views . ViewsFactory . GetTableView ( self . _views_format_type , title = 'Plaso Storage Information' )
table_view . AddRow ( [ 'Filename' , os . path . basename ( self . _storage_file_path ) ] )
table_view . AddRow ( [ 'Format version' , storage_reader . format_version ] )
table_view . AddRow ( [ 'Seriali... |
def create ( self , unique_name = values . unset , ttl = values . unset , collection_ttl = values . unset ) :
"""Create a new SyncListInstance
: param unicode unique _ name : Human - readable name for this list
: param unicode ttl : Alias for collection _ ttl
: param unicode collection _ ttl : Time - to - liv... | data = values . of ( { 'UniqueName' : unique_name , 'Ttl' : ttl , 'CollectionTtl' : collection_ttl , } )
payload = self . _version . create ( 'POST' , self . _uri , data = data , )
return SyncListInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , ) |
def subnets ( self , prefixlen_diff = 1 , new_prefix = None ) :
"""The subnets which join to make the current subnet .
In the case that self contains only one IP
( self . _ prefixlen = = 32 for IPv4 or self . _ prefixlen = = 128
for IPv6 ) , yield an iterator with just ourself .
Args :
prefixlen _ diff : ... | if self . _prefixlen == self . _max_prefixlen :
yield self
return
if new_prefix is not None :
if new_prefix < self . _prefixlen :
raise ValueError ( 'new prefix must be longer' )
if prefixlen_diff != 1 :
raise ValueError ( 'cannot set prefixlen_diff and new_prefix' )
prefixlen_diff =... |
def clean_cache ( self , section = None ) :
"""Cleans the cache of this cache object .""" | self . remove_all_locks ( )
if section is not None and "/" in section :
raise ValueError ( "invalid section '{0}'" . format ( section ) )
if section is not None :
path = os . path . join ( self . _full_base , section )
else :
path = self . _full_base
if not os . path . exists ( path ) :
return
shutil . ... |
def pacl_term ( DiamTube , ConcClay , ConcAl , ConcNatOrgMat , NatOrgMat , coag , material , RatioHeightDiameter ) :
"""Return the fraction of the surface area that is covered with coagulant
that is not covered with humic acid .
: param DiamTube : Diameter of the dosing tube
: type Diamtube : float
: param ... | return ( gamma_coag ( ConcClay , ConcAl , coag , material , DiamTube , RatioHeightDiameter ) * ( 1 - gamma_humic_acid_to_coag ( ConcAl , ConcNatOrgMat , NatOrgMat , coag ) ) ) |
def _prepare_proxy ( self , conn ) :
"""Establish tunnel connection early , because otherwise httplib
would improperly set Host : header to proxy ' s IP : port .""" | conn . set_tunnel ( self . _proxy_host , self . port , self . proxy_headers )
conn . connect ( ) |
def relookup ( self , pattern ) :
"""Dictionary lookup with a regular expression . Return pairs whose key
matches pattern .""" | key = re . compile ( pattern )
return filter ( lambda x : key . match ( x [ 0 ] ) , self . data . items ( ) ) |
def register ( self , dtype ) :
"""Parameters
dtype : ExtensionDtype""" | if not issubclass ( dtype , ( PandasExtensionDtype , ExtensionDtype ) ) :
raise ValueError ( "can only register pandas extension dtypes" )
self . dtypes . append ( dtype ) |
def make_proc_name ( self , subtitle ) :
"""获取进程名称
: param subtitle :
: return :""" | proc_name = '[%s:%s %s] %s' % ( constants . NAME , subtitle , self . name , ' ' . join ( [ sys . executable ] + sys . argv ) )
return proc_name |
def get_linkage ( self , line ) :
"""Get the linkage information from a LINK entry PDB line .""" | conf1 , id1 , chain1 , pos1 = line [ 16 ] . strip ( ) , line [ 17 : 20 ] . strip ( ) , line [ 21 ] . strip ( ) , int ( line [ 22 : 26 ] )
conf2 , id2 , chain2 , pos2 = line [ 46 ] . strip ( ) , line [ 47 : 50 ] . strip ( ) , line [ 51 ] . strip ( ) , int ( line [ 52 : 56 ] )
return self . covlinkage ( id1 = id1 , chain... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.