signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def update ( self , lease_time = None ) :
'''Refresh this task ' s expiration time .
This tries to set the task ' s expiration time to the current
time , plus ` lease _ time ` seconds . It requires the job to not
already be complete . If ` lease _ time ` is negative , makes the
job immediately be available ... | if lease_time is None :
lease_time = self . default_lifetime
with self . registry . lock ( identifier = self . worker_id ) as session :
self . _refresh ( session )
try :
self . expires = time . time ( ) + lease_time
session . update ( WORK_UNITS_ + self . work_spec_name , { self . key : self... |
def refs ( self ) :
"""Iterate over downloadable sources - - references and templates""" | def set_bundle ( s ) :
s . _bundle = self
return s
return list ( set_bundle ( s ) for s in self . dataset . sources if not s . is_downloadable ) |
def ftpparse ( line ) :
"""Parse a FTP list line into a dictionary with attributes :
name - name of file ( string )
trycwd - False if cwd is definitely pointless , True otherwise
tryretr - False if retr is definitely pointless , True otherwise
If the line has no file information , None is returned""" | if len ( line ) < 2 : # an empty name in EPLF , with no info , could be 2 chars
return None
info = dict ( name = None , trycwd = False , tryretr = False )
# EPLF format
# http : / / pobox . com / ~ djb / proto / eplf . html
# " + i8388621.29609 , m824255902 , / , \ tdev "
# " + i8388621.44468 , m839956783 , r , s10... |
def _get_rules_from_aws ( self ) :
"""Load the EC2 security rules off AWS into a list of dict .
Returns :
list""" | list_of_rules = list ( )
if self . profile :
boto3 . setup_default_session ( profile_name = self . profile )
if self . region :
ec2 = boto3 . client ( 'ec2' , region_name = self . region )
else :
ec2 = boto3 . client ( 'ec2' )
security_groups = ec2 . describe_security_groups ( Filters = self . filters )
for... |
def get ( ) :
"""Get all nagios status information from a local nagios instance""" | livestatus = mk_livestatus ( )
hosts = livestatus . get_hosts ( )
services = livestatus . get_services ( )
result = { }
result [ 'hosts' ] = hosts
result [ 'services' ] = services
return result |
def import_keys ( self , key_data ) :
"""Import the key _ data into our keyring .
> > > import shutil
> > > shutil . rmtree ( " doctests " )
> > > gpg = gnupg . GPG ( homedir = " doctests " )
> > > inpt = gpg . gen _ key _ input ( )
> > > key1 = gpg . gen _ key ( inpt )
> > > print1 = str ( key1 . finge... | # # xxx need way to validate that key _ data is actually a valid GPG key
# # it might be possible to use - - list - packets and parse the output
result = self . _result_map [ 'import' ] ( self )
log . info ( 'Importing: %r' , key_data [ : 256 ] )
data = _make_binary_stream ( key_data , self . _encoding )
self . _handle... |
def addMibSource ( self , * mibSources ) :
"""Adds path to repository to search PySNMP MIB files .
Parameters
* mibSources :
one or more paths to search or Python package names to import
and search for PySNMP MIB modules .
Returns
: : py : class : ` ~ pysnmp . smi . rfc1902 . ObjectIdentity `
referenc... | if self . _mibSourcesToAdd is None :
self . _mibSourcesToAdd = mibSources
else :
self . _mibSourcesToAdd += mibSources
return self |
def change_view ( self , change_in_depth ) :
"""Change the view depth by expand or collapsing all same - level nodes""" | self . current_view_depth += change_in_depth
if self . current_view_depth < 0 :
self . current_view_depth = 0
self . collapseAll ( )
if self . current_view_depth > 0 :
for item in self . get_items ( maxlevel = self . current_view_depth - 1 ) :
item . setExpanded ( True ) |
def bootstrap ( force = False ) :
'''Download and install the latest version of the Chocolatey package manager
via the official bootstrap .
Chocolatey requires Windows PowerShell and the . NET v4.0 runtime . Depending
on the host ' s version of Windows , chocolatey . bootstrap will attempt to
ensure these p... | # Check if Chocolatey is already present in the path
try :
choc_path = _find_chocolatey ( __context__ , __salt__ )
except CommandExecutionError :
choc_path = None
if choc_path and not force :
return 'Chocolatey found at {0}' . format ( choc_path )
# The following lookup tables are required to determine the ... |
def ampliconfile ( self , sample , contig , amplicon_range , forward_primer , reverse_primer ) :
"""Extracts amplicon sequence from contig file
: param sample : sample metadata object
: param contig : name of the contig hit by primers
: param amplicon _ range : range of the amplicon within the contig
: para... | # Open the file
with open ( sample [ self . analysistype ] . ampliconfile , 'a' ) as ampliconfile :
try : # Load the records from the assembly into the dictionary
for record in SeqIO . parse ( sample [ self . analysistype ] . assemblyfile , 'fasta' ) :
if record . id == contig :
... |
def get_key_delivery_url ( access_token , ck_id , key_type ) :
'''Get Media Services Key Delivery URL .
Args :
access _ token ( str ) : A valid Azure authentication token .
ck _ id ( str ) : A Media Service Content Key ID .
key _ type ( str ) : A Media Service key Type .
Returns :
HTTP response . JSON b... | path = '/ContentKeys'
full_path = '' . join ( [ path , "('" , ck_id , "')" , "/GetKeyDeliveryUrl" ] )
endpoint = '' . join ( [ ams_rest_endpoint , full_path ] )
body = '{"keyDeliveryType": "' + key_type + '"}'
return do_ams_post ( endpoint , full_path , body , access_token ) |
def factorial ( n ) :
"""Factorial function that works with really big numbers .""" | if isinstance ( n , float ) :
if n . is_integer ( ) :
n = int ( n )
if not isinstance ( n , INT_TYPES ) :
raise TypeError ( "Non-integer input (perhaps you need Euler Gamma " "function or Gauss Pi function)" )
if n < 0 :
raise ValueError ( "Input shouldn't be negative" )
return reduce ( operator . m... |
def run_miner_if_free ( self ) :
"""TODO : docstring""" | ( address , username , password , device , tstart , tend ) = read_config ( )
if self . dtype == 0 :
self . run_miner_cmd = [ cpu_miner_path , '-o' , address , '-O' , '{}:{}' . format ( username , password ) ]
elif self . dtype == 1 : # parse address - > scheme + netloc
r = urlparse ( address )
# scheme : / ... |
def __check_response_for_fedex_error ( self ) :
"""This checks the response for general Fedex errors that aren ' t related
to any one WSDL .""" | if self . response . HighestSeverity == "FAILURE" :
for notification in self . response . Notifications :
if notification . Severity == "FAILURE" :
raise FedexFailure ( notification . Code , notification . Message ) |
def __global_logging_exception_handler ( exc_type , exc_value , exc_traceback ) :
'''This function will log all un - handled python exceptions .''' | if exc_type . __name__ == "KeyboardInterrupt" : # Do not log the exception or display the traceback on Keyboard Interrupt
# Stop the logging queue listener thread
if is_mp_logging_listener_configured ( ) :
shutdown_multiprocessing_logging_listener ( )
else : # Log the exception
logging . getLogger ( __n... |
def set_seed ( self , seed ) :
"""Override default values for random initial topic assignment ,
set to " seed " instead .
seed is 2 - d array ( number of samples in LDA model x number
of tokens in LDA model )""" | assert seed . dtype == np . int and seed . shape == ( self . samples , self . N )
self . topic_seed = seed |
def after_initial_csrf ( self , response ) :
"""This method is called * only * if the crawler is started with an
email and password combination .
In order to log in , we need a CSRF token from a GET request . This
method takes the result of a GET request , extracts the CSRF token ,
and uses it to make a log... | login_url = ( URLObject ( "http://" ) . with_hostname ( self . domain ) . with_port ( self . port ) . with_path ( LOGIN_API_PATH ) )
credentials = { "email" : self . login_email , "password" : self . login_password , }
headers = { b"X-CSRFToken" : get_csrf_token ( response ) , }
yield scrapy . FormRequest ( login_url ,... |
def ExamineEvent ( self , mediator , event ) :
"""Analyzes an event .
Args :
mediator ( AnalysisMediator ) : mediates interactions between analysis
plugins and other components , such as storage and dfvfs .
event ( EventObject ) : event to examine .""" | # Only interested in filesystem events .
if event . data_type != 'fs:stat' :
return
filename = getattr ( event , 'filename' , None )
if not filename :
return
# Determine if we have a Chrome extension ID .
if 'chrome' not in filename . lower ( ) :
return
if not self . _sep :
self . _sep = self . _GetPath... |
def get_corpus ( self ) :
"""获取语料库
Return :
corpus - - 语料库 , str类型""" | # 正向判定
corpus = [ ]
cd = 0
tag = None
for i in range ( 0 , self . init_corpus [ 0 ] [ 0 ] ) :
init_unit = self . unit_raw [ self . init_corpus [ 0 ] [ 0 ] - i ]
cdm = CDM ( init_unit )
alpha = cdm . get_alpha ( )
if cd <= self . cd_min and cdm . NC is not 0 :
tag = True
if cd > self . cd_max... |
def gen_txt_repr ( self , hdrs , register = True ) : # type : ( Union [ H2Frame , List [ HPackHeaders ] ] , Optional [ bool ] ) - > str
"""gen _ txt _ repr returns a " textual " representation of the provided
headers .
The output of this function is compatible with the input of
parse _ txt _ hdrs .
@ param ... | lst = [ ]
if isinstance ( hdrs , H2Frame ) :
hdrs = hdrs . payload . hdrs
for hdr in hdrs :
try :
if isinstance ( hdr , HPackIndexedHdr ) :
lst . append ( '{}' . format ( self [ hdr . index ] ) )
elif isinstance ( hdr , ( HPackLitHdrFldWithIncrIndexing , HPackLitHdrFldWithoutIndexing... |
def time_segments_average ( X , interval , time_column ) :
"""Compute average of values over fixed length time segments .""" | warnings . warn ( _TIME_SEGMENTS_AVERAGE_DEPRECATION_WARNING , DeprecationWarning )
if isinstance ( X , np . ndarray ) :
X = pd . DataFrame ( X )
X = X . sort_values ( time_column ) . set_index ( time_column )
start_ts = X . index . values [ 0 ]
max_ts = X . index . values [ - 1 ]
values = list ( )
index = list ( )... |
def _load_file ( self , f ) :
"""Get values from config file""" | try :
with open ( f , 'r' ) as _fo :
_seria_in = seria . load ( _fo )
_y = _seria_in . dump ( 'yaml' )
except IOError :
raise FiggypyError ( "could not open configuration file" )
self . values . update ( yaml . load ( _y ) ) |
def as_es2_command ( command ) :
"""Modify a desktop command so it works on es2.""" | if command [ 0 ] == 'FUNC' :
return ( command [ 0 ] , re . sub ( r'^gl([A-Z])' , lambda m : m . group ( 1 ) . lower ( ) , command [ 1 ] ) ) + command [ 2 : ]
if command [ 0 ] == 'SHADERS' :
return command [ : 2 ] + convert_shaders ( 'es2' , command [ 2 : ] )
if command [ 0 ] == 'UNIFORM' :
return command [ ... |
def reverse_media_url ( target_type , url_string , * args , ** kwargs ) :
'''Given a target type and an resource URL , generates a valid URL to this via''' | args_str = '<%s>' % '><' . join ( args )
kwargs_str = '<%s>' % '><' . join ( '%s:%s' % pair for pair in kwargs . items ( ) )
url_str = '' . join ( [ url_string , args_str , kwargs_str ] )
normalized_url = str ( ResourceURL ( url_str ) )
query_tuples = [ ]
if singletons . settings . SECURITY and 'Sha1' in singletons . s... |
def _resolve ( self ) :
"""resolve the type symbol from name by doing a lookup""" | self . __is_resolved = True
if self . is_complex :
type = self . nested if self . nested else self
type . __reference = self . module . lookup ( type . name ) |
def karbasa ( self , result ) :
"""Finding if class probabilities are close to eachother
Ratio of the distance between 1st and 2nd class ,
to the distance between 1st and last class .
: param result : The dict returned by LM . calculate ( )""" | probs = result [ 'all_probs' ]
probs . sort ( )
return float ( probs [ 1 ] - probs [ 0 ] ) / float ( probs [ - 1 ] - probs [ 0 ] ) |
def from_fortran_file ( cls , fortran_file : str , tmpdir : str = "." ) :
"""Builds GrFN object from a Fortran program .""" | stem = Path ( fortran_file ) . stem
if tmpdir == "." and "/" in fortran_file :
tmpdir = Path ( fortran_file ) . parent
preprocessed_fortran_file = f"{tmpdir}/{stem}_preprocessed.f"
lambdas_path = f"{tmpdir}/{stem}_lambdas.py"
json_filename = stem + ".json"
with open ( fortran_file , "r" ) as f :
inputLines = f ... |
def to_xml ( self ) : # pylint : disable = R0912
"""Converts object into an XML string .""" | xml = ''
for asset in self . assets :
xml += '<asset filename="%s" ' % os . path . basename ( asset [ 'filename' ] )
xml += ' refid="%(refid)s"' % asset
xml += ' size="%(size)s"' % asset
xml += ' hash-code="%s"' % asset [ 'hash-code' ]
xml += ' type="%(type)s"' % asset
if asset . get ( 'encoding... |
def _delegate ( self , path ) : # type : ( Text ) - > Tuple [ FS , Text ]
"""Get the delegate FS for a given path .
Arguments :
path ( str ) : A path .
Returns :
( FS , str ) : a tuple of ` ` ( < fs > , < path > ) ` ` for a mounted filesystem ,
or ` ` ( None , None ) ` ` if no filesystem is mounted on the... | _path = forcedir ( abspath ( normpath ( path ) ) )
is_mounted = _path . startswith
for mount_path , fs in self . mounts :
if is_mounted ( mount_path ) :
return fs , _path [ len ( mount_path ) : ] . rstrip ( "/" )
return self . default_fs , path |
async def retract ( self , mount : top_types . Mount , margin : float ) :
"""Pull the specified mount up to its home position .
Works regardless of critical point or home status .""" | smoothie_ax = Axis . by_mount ( mount ) . name . upper ( )
async with self . _motion_lock :
smoothie_pos = self . _backend . fast_home ( smoothie_ax , margin )
self . _current_position = self . _deck_from_smoothie ( smoothie_pos ) |
def _add_transaction_to_canonical_chain ( db : BaseDB , transaction_hash : Hash32 , block_header : BlockHeader , index : int ) -> None :
""": param bytes transaction _ hash : the hash of the transaction to add the lookup for
: param block _ header : The header of the block with the txn that is in the canonical ch... | transaction_key = TransactionKey ( block_header . block_number , index )
db . set ( SchemaV1 . make_transaction_hash_to_block_lookup_key ( transaction_hash ) , rlp . encode ( transaction_key ) , ) |
def _CreateLineString ( self , parent , coordinate_list ) :
"""Create a KML LineString element .
The points of the string are given in coordinate _ list . Every element of
coordinate _ list should be one of a tuple ( longitude , latitude ) or a tuple
( longitude , latitude , altitude ) .
Args :
parent : T... | if not coordinate_list :
return None
linestring = ET . SubElement ( parent , 'LineString' )
tessellate = ET . SubElement ( linestring , 'tessellate' )
tessellate . text = '1'
if len ( coordinate_list [ 0 ] ) == 3 :
altitude_mode = ET . SubElement ( linestring , 'altitudeMode' )
altitude_mode . text = 'absol... |
def send_to_contact ( self , obj_id , contact_id ) :
"""Send email to a specific contact
: param obj _ id : int
: param contact _ id : int
: return : dict | str""" | response = self . _client . session . post ( '{url}/{id}/send/contact/{contact_id}' . format ( url = self . endpoint_url , id = obj_id , contact_id = contact_id ) )
return self . process_response ( response ) |
def query ( self , query , inplace = True ) :
"""State what you want to keep""" | # TODO : add to queue
result = self . data . query ( query , inplace = inplace )
return result |
def get_local_part ( value ) :
"""local - part = dot - atom / quoted - string / obs - local - part""" | local_part = LocalPart ( )
leader = None
if value [ 0 ] in CFWS_LEADER :
leader , value = get_cfws ( value )
if not value :
raise errors . HeaderParseError ( "expected local-part but found '{}'" . format ( value ) )
try :
token , value = get_dot_atom ( value )
except errors . HeaderParseError :
try :
... |
async def answer_shipping_query ( self , shipping_query_id : base . String , ok : base . Boolean , shipping_options : typing . Union [ typing . List [ types . ShippingOption ] , None ] = None , error_message : typing . Union [ base . String , None ] = None ) -> base . Boolean :
"""If you sent an invoice requesting ... | if shipping_options :
shipping_options = prepare_arg ( [ shipping_option . to_python ( ) if hasattr ( shipping_option , 'to_python' ) else shipping_option for shipping_option in shipping_options ] )
payload = generate_payload ( ** locals ( ) )
result = await self . request ( api . Methods . ANSWER_SHIPPING_QUERY , ... |
def enforce_duration ( self , duration_thresh ) :
"""This method takes a quantized pitch contour and filters out
those time sections where the contour is not long enough , as specified
by duration threshold ( given in milliseconds ) .
All transactions assume data in cent scale .""" | i = 1
while i < len ( self . pitch ) - 1 :
if self . pitch [ i ] == - 10000 :
i += 1
continue
if self . pitch [ i ] - self . pitch [ i - 1 ] != 0 and self . pitch [ i + 1 ] - self . pitch [ i ] == 0 :
start = i
while i < len ( self . pitch ) and self . pitch [ i + 1 ] - self . pi... |
def show_non_search_results ( log_rec , code_view = True , json_view = False , show_message_details = False ) :
"""show _ non _ search _ results
Show non - search results for search jobs like :
` ` index = " antinex " | stats count ` `
: param log _ rec : log record from splunk
: param code _ view : show as... | log_dict = None
try :
log_dict = json . loads ( log_rec )
except Exception as e :
log_dict = None
# end of try / ex
if not log_dict :
log . info ( ( '{}' ) . format ( ppj ( log_rec ) ) )
else :
log . info ( ( '{}' ) . format ( ppj ( log_dict ) ) ) |
def check_critical_load ( self ) :
"""Check for critical load and log an error if necessary .""" | if self . load_avg . intervals [ '1m' ] . value > 1 :
if self . last_load_level == 1 and time . time ( ) - self . last_load_log < 30 :
return
self . last_load_log = time . time ( )
self . last_load_level = 1
logger . error ( "Listener load limit exceeded, the system can't handle this!" , extra =... |
def min_width ( self ) -> int :
"""Minimum width necessary to render the block ' s contents .""" | return max ( max ( len ( e ) for e in self . content . split ( '\n' ) ) , # Only horizontal lines can cross 0 width blocks .
int ( any ( [ self . top , self . bottom ] ) ) ) |
def derivative ( self , x ) :
"""Return the operator derivative .
The derivative of the operator composition follows the chain
rule :
` ` OperatorComp ( left , right ) . derivative ( y ) = =
OperatorComp ( left . derivative ( right ( y ) ) , right . derivative ( y ) ) ` `
Parameters
x : ` domain ` ` ele... | if self . is_linear :
return self
else :
if self . left . is_linear :
left_deriv = self . left
else :
left_deriv = self . left . derivative ( self . right ( x ) )
right_deriv = self . right . derivative ( x )
return OperatorComp ( left_deriv , right_deriv , self . __tmp ) |
def get_attribute ( self , app = None , key = None ) :
"""Returns an application attribute
: param app : application id
: param key : attribute key or None to retrieve all values for the
given application
: returns : attribute value if key was specified , or an array of tuples
( key , value ) for each att... | path = 'getattribute'
if app is not None :
path += '/' + parse . quote ( app , '' )
if key is not None :
path += '/' + parse . quote ( self . _encode_string ( key ) , '' )
res = self . _make_ocs_request ( 'GET' , self . OCS_SERVICE_PRIVATEDATA , path )
if res . status_code == 200 :
tree = ET . froms... |
def update ( self , data ) :
"""update the state with new data , storing excess data
as necessary . may be called multiple times and if a
call sends less than a full block in size , the leftover
is cached and will be consumed in the next call
data : data to be hashed ( bytestring )""" | self . state = 2
BLKBYTES = self . BLKBYTES
# de - referenced for improved readability
BLKBITS = self . BLKBITS
datalen = len ( data )
if not datalen :
return
if type ( data ) == type ( u'' ) : # use either of the next two lines for a proper
# response under both Python2 and Python3
data = data . encode ( 'UTF-... |
def netconf_state_sessions_session_session_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
netconf_state = ET . SubElement ( config , "netconf-state" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring" )
sessions = ET . SubElement ( netconf_state , "sessions" )
session = ET . SubElement ( sessions , "session" )
session_id = ET . SubElement ( session , "session-i... |
def static_transition ( timestamp , contract_dates , transition , holidays = None , validate_inputs = True ) :
"""An implementation of * get _ weights * parameter in roller ( ) .
Return weights to tradeable instruments for a given date based on a
transition DataFrame which indicates how to roll through the roll... | if validate_inputs : # required for MultiIndex slicing
_check_static ( transition . sort_index ( axis = 1 ) )
# the algorithm below will return invalid results if contract _ dates is
# not as expected so better to fail explicitly
_check_contract_dates ( contract_dates )
if not holidays :
holidays = ... |
async def decrypt ( self , ciphertext : bytes , sender : str = None ) -> ( bytes , str ) :
"""Decrypt ciphertext and optionally authenticate sender .
Raise BadKey if authentication operation reveals sender key distinct from current
verification key of owner of input DID . Raise WalletState if wallet is closed .... | LOGGER . debug ( 'BaseAnchor.decrypt >>> ciphertext: %s, sender: %s' , ciphertext , sender )
if not self . wallet . handle :
LOGGER . debug ( 'BaseAnchor.decrypt <!< Wallet %s is closed' , self . name )
raise WalletState ( 'Wallet {} is closed' . format ( self . name ) )
from_verkey = None
if sender :
from_... |
def _force_close ( self ) :
"""Close connection without QUIT message""" | if self . _sock :
try :
self . _sock . close ( )
except : # noqa
pass
self . _sock = None
self . _rfile = None |
def set_consistent ( self , consistent_config ) :
"""Indicates that the stream is the start of a consistent region .
Args :
consistent _ config ( consistent . ConsistentRegionConfig ) : the configuration of the consistent region .
Returns :
Stream : Returns this stream .
. . versionadded : : 1.11""" | # add job control plane if needed
self . topology . _add_job_control_plane ( )
self . oport . operator . consistent ( consistent_config )
return self . _make_placeable ( ) |
def plotter ( molecules , ensemble_lookup , options ) :
"""plot ROC curves for ensembles in ensemble _ lookup
: param molecules :
: param ensemble _ lookup :
: param options :
: return :""" | try :
import matplotlib
matplotlib . use ( 'Agg' )
import matplotlib . pyplot as plt
except ImportError :
print ( "\n Plotting requires matplotlib to be installed\n" )
sys . exit ( 1 )
for ensemble in ensemble_lookup . keys ( ) : # create figure
fig = plt . figure ( )
# create the queries su... |
def get_id ( self ) :
"""Returns the id of the resource .""" | if self . _id_attr is None or not hasattr ( self , self . _id_attr ) :
return None
return getattr ( self , self . _id_attr ) |
def pretty_bytes ( num ) :
"""pretty print the given number of bytes""" | for unit in [ '' , 'KB' , 'MB' , 'GB' ] :
if num < 1024.0 :
if unit == '' :
return "%d" % ( num )
else :
return "%3.1f%s" % ( num , unit )
num /= 1024.0
return "%3.1f%s" % ( num , 'TB' ) |
def from_simplex ( x ) :
r"""Inteprets the last index of x as unit simplices and returns a
real array of the sampe shape in logit space .
Inverse to : func : ` to _ simplex ` ; see that function for more details .
: param np . ndarray : Array of unit simplices along the last index .
: rtype : ` ` np . ndarr... | n = x . shape [ - 1 ]
# z are the stick breaking fractions in [ 0,1]
# the last one is always 1 , so don ' t worry about it
z = np . empty ( shape = x . shape )
z [ ... , 0 ] = x [ ... , 0 ]
z [ ... , 1 : - 1 ] = x [ ... , 1 : - 1 ] / ( 1 - x [ ... , : - 2 ] . cumsum ( axis = - 1 ) )
# now z are the logit - transformed... |
def folderitems ( self ) :
"""Returns an array of dictionaries , each dictionary represents an
analysis row to be rendered in the list . The array returned is sorted
in accordance with the layout positions set for the analyses this
worksheet contains when the analyses were added in the worksheet .
: returns... | items = BaseView . folderitems ( self )
# Fill empty positions from the layout with fake rows . The worksheet
# can be generated by making use of a WorksheetTemplate , so there is
# the chance that some slots of this worksheet being empty . We need to
# render a row still , at lest to display the slot number ( Pos )
se... |
def flatten ( * sequence ) :
"""Flatten nested sequences into one .""" | result = [ ]
for entry in sequence :
if isinstance ( entry , list ) :
result += Select . flatten ( * entry )
elif isinstance ( entry , tuple ) :
result += Select . flatten ( * entry )
else :
result . append ( entry )
return result |
def update ( self ) :
"""Updates the currently running animation .
This method should be called in every frame where you want an animation to run .
Its job is to figure out if it is time to move onto the next image in the animation .""" | returnValue = False
# typical return value
if self . state != PygAnimation . PLAYING :
return returnValue
# The job here is to figure out the index of the image to show
# and the matching elapsed time threshold for the current image
self . elapsed = ( time . time ( ) - self . playingStartTime )
if self . elapsed > ... |
def add_permalink_methods ( content_inst ) :
'''Add permalink methods to object''' | for permalink_method in PERMALINK_METHODS :
setattr ( content_inst , permalink_method . __name__ , permalink_method . __get__ ( content_inst , content_inst . __class__ ) ) |
def parse_messages_by_stream ( messages_by_stream ) :
"""Parse messages returned by stream
Messages returned by XREAD arrive in the form :
[ stream _ name ,
[ message _ id , [ key1 , value1 , key2 , value2 , . . . ] ] ,
Here we parse this into ( with the help of the above parse _ messages ( )
function ) :... | if messages_by_stream is None :
return [ ]
parsed = [ ]
for stream , messages in messages_by_stream :
for message_id , fields in parse_messages ( messages ) :
parsed . append ( ( stream , message_id , fields ) )
return parsed |
def swo_supported_speeds ( self , cpu_speed , num_speeds = 3 ) :
"""Retrives a list of SWO speeds supported by both the target and the
connected J - Link .
The supported speeds are returned in order from highest to lowest .
Args :
self ( JLink ) : the ` ` JLink ` ` instance
cpu _ speed ( int ) : the targe... | buf_size = num_speeds
buf = ( ctypes . c_uint32 * buf_size ) ( )
res = self . _dll . JLINKARM_SWO_GetCompatibleSpeeds ( cpu_speed , 0 , buf , buf_size )
if res < 0 :
raise errors . JLinkException ( res )
return list ( buf ) [ : res ] |
def _validate_auth_scheme ( self , req ) :
"""Check if the request has auth & the proper scheme
Remember NOT to include the error related info in
the WWW - Authenticate header for these conditions .
: raise :
AuthRequired""" | if not req . auth :
raise AuthRequired ( ** { 'detail' : 'You must first login to access the requested ' 'resource(s). Please retry your request using ' 'OAuth 2.0 Bearer Token Authentication as ' 'documented in RFC 6750. If you do not have an ' 'access_token then request one at the token ' 'endpdoint of: %s' % sel... |
def read ( self , n = 4096 ) :
"""Return ` n ` bytes of data from the Stream , or None at end of stream .""" | while True :
try :
if hasattr ( self . fd , 'recv' ) :
return self . fd . recv ( n )
return os . read ( self . fd . fileno ( ) , n )
except EnvironmentError as e :
if e . errno not in Stream . ERRNO_RECOVERABLE :
raise e |
def _get_roots ( self ) :
"""Return URL roots for this storage .
Returns :
tuple of str or re . Pattern : URL roots""" | region = self . _get_session ( ) . region_name or r'[\w-]+'
return ( # S3 scheme
# - s3 : / / < bucket > / < key >
's3://' , # Virtual - hosted – style URL
# - http : / / < bucket > . s3 . amazonaws . com / < key >
# - https : / / < bucket > . s3 . amazonaws . com / < key >
# - http : / / < bucket > . s3 - < region > .... |
def put ( self , path = None , url_kwargs = None , ** kwargs ) :
"""Sends a PUT request .
: param path :
The HTTP path ( either absolute or relative ) .
: param url _ kwargs :
Parameters to override in the generated URL . See ` ~ hyperlink . URL ` .
: param * * kwargs :
Optional arguments that ` ` reque... | return self . _session . put ( self . _url ( path , url_kwargs ) , ** kwargs ) |
def return_env ( self , exists = True ) :
"""Return environment dict .
Parameters
exists : bool
It True , only return existing paths .""" | env = dict ( include = self . _build_paths ( 'include' , [ self . VCIncludes , self . OSIncludes , self . UCRTIncludes , self . NetFxSDKIncludes ] , exists ) , lib = self . _build_paths ( 'lib' , [ self . VCLibraries , self . OSLibraries , self . FxTools , self . UCRTLibraries , self . NetFxSDKLibraries ] , exists ) , ... |
def _get_csrf_disabled_param ( ) :
"""Return the right param to disable CSRF depending on WTF - Form version .
From Flask - WTF 0.14.0 , ` csrf _ enabled ` param has been deprecated in favor of
` meta = { csrf : True / False } ` .""" | import flask_wtf
from pkg_resources import parse_version
supports_meta = parse_version ( flask_wtf . __version__ ) >= parse_version ( "0.14.0" )
return dict ( meta = { 'csrf' : False } ) if supports_meta else dict ( csrf_enabled = False ) |
def at ( self , step ) :
"""Return a TimeMachine for the same object at a different time .
Takes an integer argument representing the id field of an Action .
Returns the TimeMachine at the time of that Action . ( Less ambiguously :
at the time right after the Action .""" | return TimeMachine ( self . uid , step = step , info = copy . deepcopy ( self . info ) ) |
def detect_function_shadowing ( contracts , direct_shadowing = True , indirect_shadowing = True ) :
"""Detects all overshadowing and overshadowed functions in the provided contracts .
: param contracts : The contracts to detect shadowing within .
: param direct _ shadowing : Include results from direct inherita... | results = set ( )
for contract in contracts : # Detect immediate inheritance shadowing .
if direct_shadowing :
shadows = detect_direct_function_shadowing ( contract )
for ( overshadowing_function , overshadowed_base_contract , overshadowed_function ) in shadows :
results . add ( ( contra... |
def exists ( self ) :
"""A convenience method that returns True if a record
satisfying the query exists""" | return self . rpc_model . search_count ( self . domain , context = self . context ) > 0 |
def just_log ( * texts , sep = "" ) :
"""Log a text without adding the current time .""" | if config . silent :
return
text = _color_sep + "default" + _color_sep2 + sep . join ( texts )
array = text . split ( _color_sep )
for part in array :
parts = part . split ( _color_sep2 , 1 )
if len ( parts ) != 2 or not parts [ 1 ] :
continue
if not config . color :
print ( parts [ 1 ] ... |
def rnd_date_array ( self , size , start = date ( 1970 , 1 , 1 ) , end = date . today ( ) ) :
"""Array or Matrix of random date generator .""" | if isinstance ( start , string_types ) :
start = self . str2date ( start )
if isinstance ( end , string_types ) :
end = self . str2date ( end )
if start > end :
raise ValueError ( "start time has to be earlier than end time" )
return self . randn ( size , self . _rnd_date , start , end ) |
def disapproveproposal ( ctx , proposal , account ) :
"""Disapprove a proposal""" | print_tx ( ctx . bitshares . disapproveproposal ( proposal , account = account ) ) |
def from_short_lines_text ( self , text : str ) :
"""Famous example from Hávamál 77
> > > text = " Deyr fé , \\ ndeyja frændr , \\ ndeyr sjalfr it sama , \\ nek veit einn , \\ nat aldrei deyr : \\ ndómr um dauðan hvern . "
> > > lj = Ljoodhhaattr ( )
> > > lj . from _ short _ lines _ text ( text )
> > >... | Metre . from_short_lines_text ( self , text )
lines = [ line for line in text . split ( "\n" ) if line ]
self . short_lines = [ ShortLine ( lines [ 0 ] ) , ShortLine ( lines [ 1 ] ) , LongLine ( lines [ 2 ] ) , ShortLine ( lines [ 3 ] ) , ShortLine ( lines [ 4 ] ) , LongLine ( lines [ 5 ] ) ]
self . long_lines = [ self... |
def _write_wrapped ( self , line , sep = " " , indent = "" , width = 78 ) :
"""Word - wrap a line of RiveScript code for being written to a file .
: param str line : The original line of text to word - wrap .
: param str sep : The word separator .
: param str indent : The indentation to use ( as a set of spac... | words = line . split ( sep )
lines = [ ]
line = ""
buf = [ ]
while len ( words ) :
buf . append ( words . pop ( 0 ) )
line = sep . join ( buf )
if len ( line ) > width : # Need to word wrap !
words . insert ( 0 , buf . pop ( ) )
# Undo
lines . append ( sep . join ( buf ) )
bu... |
def cli ( env ) :
"""Get Event Log Types""" | mgr = SoftLayer . EventLogManager ( env . client )
event_log_types = mgr . get_event_log_types ( )
table = formatting . Table ( COLUMNS )
for event_log_type in event_log_types :
table . add_row ( [ event_log_type ] )
env . fout ( table ) |
def count_table ( * keys ) :
"""count the number of times each key occurs in the input set
Arguments
keys : tuple of indexable objects , each having the same number of items
Returns
unique : tuple of ndarray , [ groups , . . . ]
unique keys for each input item
they form the axes labels of the table
ta... | indices = [ as_index ( k , axis = 0 ) for k in keys ]
uniques = [ i . unique for i in indices ]
inverses = [ i . inverse for i in indices ]
shape = [ i . groups for i in indices ]
table = np . zeros ( shape , np . int )
np . add . at ( table , inverses , 1 )
return tuple ( uniques ) , table |
def add ( user_id , resource_policy , admin , inactive , rate_limit ) :
'''Add a new keypair .
USER _ ID : User ID of a new key pair .
RESOURCE _ POLICY : resource policy for new key pair .''' | try :
user_id = int ( user_id )
except ValueError :
pass
# string - based user ID for Backend . AI v1.4 +
with Session ( ) as session :
try :
data = session . KeyPair . create ( user_id , is_active = not inactive , is_admin = admin , resource_policy = resource_policy , rate_limit = rate_limit )
... |
def _update_dict ( self , initial : JSON , other : Mapping ) -> JSON :
"""Recursively update a dictionary .
: param initial : Dict to update .
: param other : Dict to update from .
: return : Updated dict .""" | for key , value in other . items ( ) :
if isinstance ( value , collections . Mapping ) :
r = self . _update_dict ( initial . get ( key , { } ) , value )
initial [ key ] = r
else :
initial [ key ] = other [ key ]
return initial |
def preloop ( self ) :
'''Executed before the command loop starts .''' | script_dir = os . path . dirname ( os . path . realpath ( __file__ ) )
help_dir = os . path . join ( script_dir , HELP_DIR_NAME )
self . load_forth_commands ( help_dir )
self . load_shell_commands ( help_dir ) |
def get_endpoint_w_server_list ( endpoint_id ) :
"""A helper for handling endpoint server list lookups correctly accounting
for various endpoint types .
- Raises click . UsageError when used on Shares
- Returns ( < get _ endpoint _ response > , " S3 " ) for S3 endpoints
- Returns ( < get _ endpoint _ respon... | client = get_client ( )
endpoint = client . get_endpoint ( endpoint_id )
if endpoint [ "host_endpoint_id" ] : # not GCS - - this is a share endpoint
raise click . UsageError ( dedent ( u"""\
{id} ({0}) is a share and does not have servers.
To see details of the share, use
gl... |
def contains ( bank , key , cachedir ) :
'''Checks if the specified bank contains the specified key .''' | if key is None :
base = os . path . join ( cachedir , os . path . normpath ( bank ) )
return os . path . isdir ( base )
else :
keyfile = os . path . join ( cachedir , os . path . normpath ( bank ) , '{0}.p' . format ( key ) )
return os . path . isfile ( keyfile ) |
def print_error_to_io_stream ( err : Exception , io : TextIOBase , print_big_traceback : bool = True ) :
"""Utility method to print an exception ' s content to a stream
: param err :
: param io :
: param print _ big _ traceback :
: return :""" | if print_big_traceback :
traceback . print_tb ( err . __traceback__ , file = io , limit = - GLOBAL_CONFIG . multiple_errors_tb_limit )
else :
traceback . print_tb ( err . __traceback__ , file = io , limit = - 1 )
io . writelines ( ' ' + str ( err . __class__ . __name__ ) + ' : ' + str ( err ) ) |
def hashkey ( * args , ** kwargs ) :
"""Return a cache key for the specified hashable arguments .""" | if kwargs :
return _HashedTuple ( args + sum ( sorted ( kwargs . items ( ) ) , _kwmark ) )
else :
return _HashedTuple ( args ) |
def render ( self , namespace ) :
'''Render template lines .
Note : we only need to parse the namespace if we used variables in
this part of the template .''' | return self . _text . format_map ( namespace . dictionary ) if self . _need_format else self . _text |
def populate ( self , priority , address , rtr , data ) :
""": return : None""" | assert isinstance ( data , bytes )
self . needs_low_priority ( priority )
self . needs_no_rtr ( rtr )
self . needs_data ( data , 4 )
self . set_attributes ( priority , address , rtr )
self . closed = self . byte_to_channels ( data [ 0 ] )
self . led_on = self . byte_to_channels ( data [ 1 ] )
self . led_slow_blinking =... |
def Column ( self , column_name ) :
"""Iterates over values of a given column .
Args :
column _ name : A nome of the column to retrieve the values for .
Yields :
Values of the specified column .
Raises :
KeyError : If given column is not present in the table .""" | column_idx = None
for idx , column in enumerate ( self . header . columns ) :
if column . name == column_name :
column_idx = idx
break
if column_idx is None :
raise KeyError ( "Column '{}' not found" . format ( column_name ) )
for row in self . rows :
yield row . values [ column_idx ] |
def connect ( self , successor ) :
"""Connect this node to its successor node by
setting its outgoing and the successors ingoing .""" | if isinstance ( self , ConnectToExitNode ) and not isinstance ( successor , EntryOrExitNode ) :
return
self . outgoing . append ( successor )
successor . ingoing . append ( self ) |
def add_constraint ( self , func , variables , default_values = None ) :
"""Adds a constraint that applies to one or more variables .
The function must return true or false to indicate which combinations
of variable values are valid .""" | self . _constraints . append ( ( func , variables , default_values or ( ) ) ) |
async def deploy ( self , charm , series , application , options , constraints , storage , endpoint_bindings , * args ) :
""": param charm string :
Charm holds the URL of the charm to be used to deploy this
application .
: param series string :
Series holds the series of the application to be deployed
if ... | # resolve indirect references
charm = self . resolve ( charm )
if len ( args ) == 1 : # Juju 2.4 and below only sends the resources
resources = args [ 0 ]
devices , num_units = None , None
else : # Juju 2.5 + sends devices before resources , as well as num _ units
# There might be placement but we need to ignor... |
def _send_locked ( self , cmd ) :
"""Sends the specified command to the lutron controller .
Assumes self . _ lock is held .""" | _LOGGER . debug ( "Sending: %s" % cmd )
try :
self . _telnet . write ( cmd . encode ( 'ascii' ) + b'\r\n' )
except BrokenPipeError :
self . _disconnect_locked ( ) |
def validate_email ( self , email_address ) :
'''a method to validate an email address
: param email _ address : string with email address to validate
: return : dictionary with validation fields in response _ details [ ' json ' ]''' | title = '%s.validate_email' % __class__ . __name__
# validate inputs
object_title = '%s(email_address="")' % title
email_address = self . fields . validate ( email_address , '.email_address' , object_title )
# construct request _ kwargs
request_kwargs = { 'url' : '%s/address/validate' % self . api_endpoint , 'params' :... |
def updateFile ( cls , file_ , url ) :
"""Check and update file compares with remote _ url
Args :
file _ : str . Local filename . Normally it ' s _ _ file _ _
url : str . Remote url of raw file content . Normally it ' s https : / / raw . github . com / . . .
Returns :
bool : file updated or not""" | def compare ( s1 , s2 ) :
return s1 == s2 , len ( s2 ) - len ( s1 )
if not url or not file_ :
return False
try :
req = urllib . request . urlopen ( url )
raw_codes = req . read ( )
with open ( file_ , 'rb' ) as f :
current_codes = f . read ( ) . replace ( b'\r' , b'' )
is_same , diff = c... |
def named_function ( name ) :
"""Gets a fully named module - global object .""" | name_parts = name . split ( '.' )
module = named_object ( '.' . join ( name_parts [ : - 1 ] ) )
func = getattr ( module , name_parts [ - 1 ] )
if hasattr ( func , 'original_func' ) :
func = func . original_func
return func |
def _add_ssh_key ( ret ) :
'''Setups the salt - ssh minion to be accessed with salt - ssh default key''' | priv = None
if __opts__ . get ( 'ssh_use_home_key' ) and os . path . isfile ( os . path . expanduser ( '~/.ssh/id_rsa' ) ) :
priv = os . path . expanduser ( '~/.ssh/id_rsa' )
else :
priv = __opts__ . get ( 'ssh_priv' , os . path . abspath ( os . path . join ( __opts__ [ 'pki_dir' ] , 'ssh' , 'salt-ssh.rsa' ) ) ... |
def _list_request ( self ) :
"""Returns a dictionary with JMX domain names as keys""" | try : # https : / / jolokia . org / reference / html / protocol . html
# A maxDepth of 1 restricts the return value to a map with the JMX
# domains as keys . The values of the maps don ' t have any meaning
# and are dummy values .
# maxCollectionSize = 0 means " unlimited " . This works around an issue
# prior to Jolok... |
def create ( self , unique_name , default_ttl = values . unset , callback_url = values . unset , geo_match_level = values . unset , number_selection_behavior = values . unset , intercept_callback_url = values . unset , out_of_session_callback_url = values . unset , chat_instance_sid = values . unset ) :
"""Create a... | data = values . of ( { 'UniqueName' : unique_name , 'DefaultTtl' : default_ttl , 'CallbackUrl' : callback_url , 'GeoMatchLevel' : geo_match_level , 'NumberSelectionBehavior' : number_selection_behavior , 'InterceptCallbackUrl' : intercept_callback_url , 'OutOfSessionCallbackUrl' : out_of_session_callback_url , 'ChatIns... |
def connect ( self , forceReconnect = False ) :
"""Check current conditions and initiate connection if possible .
This is called to check preconditions for starting a new connection ,
and initating the connection itself .
If the service is not running , this will do nothing .
@ param forceReconnect : Drop a... | if self . _state == 'stopped' :
raise Error ( "This service is not running. Not connecting." )
if self . _state == 'connected' :
if forceReconnect :
self . _toState ( 'disconnecting' )
return True
else :
raise ConnectError ( "Already connected." )
elif self . _state == 'aborting' :
... |
def _safe_string ( self , source , encoding = 'utf-8' ) :
"""Convert unicode to string as gnomekeyring barfs on unicode""" | if not isinstance ( source , str ) :
return source . encode ( encoding )
return str ( source ) |
def view_fields ( self , * attributes , ** options ) :
"""Returns an : class : ` ordered dictionary < collections . OrderedDict > ` which
contains the ` ` { ' member name ' : field attribute } ` ` or the
` ` { ' member name ' : dict ( field attributes ) } ` ` pairs for each : class : ` Field `
* nested * in t... | members = OrderedDict ( )
for name , item in self . items ( ) : # Container
if is_container ( item ) :
members [ name ] = item . view_fields ( * attributes , ** options )
# Pointer
elif is_pointer ( item ) and get_nested ( options ) :
members [ name ] = item . view_fields ( * attributes , **... |
def target_data ( self ) :
"""The TargetData for this execution engine .""" | if self . _td is not None :
return self . _td
ptr = ffi . lib . LLVMPY_GetExecutionEngineTargetData ( self )
self . _td = targets . TargetData ( ptr )
self . _td . _owned = True
return self . _td |
def packet_read ( self ) :
"""Read packet from network .""" | bytes_received = 0
if self . sock == NC . INVALID_SOCKET :
return NC . ERR_NO_CONN
if self . in_packet . command == 0 :
ba_data , errnum , errmsg = nyamuk_net . read ( self . sock , 1 )
if errnum == 0 and len ( ba_data ) == 1 :
bytes_received += 1
byte = ba_data [ 0 ]
self . in_packe... |
def send_image ( self , number , path , caption = None ) :
"""Send image message
: param str number : phone number with cc ( country code )
: param str path : image file path""" | return self . _send_media_path ( number , path , RequestUploadIqProtocolEntity . MEDIA_TYPE_IMAGE , caption ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.