signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def expand ( self , nmax = None , grid = 'DH2' , zeros = None ) :
"""Expand the function on a grid using the first n Slepian coefficients .
Usage
f = x . expand ( [ nmax , grid , zeros ] )
Returns
f : SHGrid class instance
Parameters
nmax : int , optional , default = x . nmax
The number of expansion c... | if type ( grid ) != str :
raise ValueError ( 'grid must be a string. ' + 'Input type was {:s}' . format ( str ( type ( grid ) ) ) )
if nmax is None :
nmax = self . nmax
if self . galpha . kind == 'cap' :
shcoeffs = _shtools . SlepianCoeffsToSH ( self . falpha , self . galpha . coeffs , nmax )
else :
shc... |
def _get_peers ( self , child_self , parent_other ) :
'''_ get _ peers
Low - level api : Given a config node , find peers under a parent node .
Parameters
child _ self : ` Element `
An Element node on this side .
parent _ other : ` Element `
An Element node on the other side .
Returns
list
A list ... | peers = parent_other . findall ( child_self . tag )
s_node = self . device . get_schema_node ( child_self )
if s_node . get ( 'type' ) == 'leaf-list' :
return list ( filter ( lambda x : child_self . text == x . text , peers ) )
elif s_node . get ( 'type' ) == 'list' :
keys = self . _get_list_keys ( s_node )
... |
def run_marionette_script ( script , chrome = False , async = False , host = 'localhost' , port = 2828 ) :
"""Create a Marionette instance and run the provided script""" | m = DeviceHelper . getMarionette ( host , port )
m . start_session ( )
if chrome :
m . set_context ( marionette . Marionette . CONTEXT_CHROME )
if not async :
result = m . execute_script ( script )
else :
result = m . execute_async_script ( script )
m . delete_session ( )
return result |
def GroupsSensorsDelete ( self , group_id , sensor_id ) :
"""Stop sharing a sensor within a group
@ param group _ id ( int ) - Id of the group to stop sharing the sensor with
@ param sensor _ id ( int ) - Id of the sensor to stop sharing
@ return ( bool ) - Boolean indicating whether GroupsSensorsDelete was s... | if self . __SenseApiCall__ ( "/groups/{0}/sensors/{1}.json" . format ( group_id , sensor_id ) , "DELETE" ) :
return True
else :
self . __error__ = "api call unsuccessful"
return False |
def _executor ( self , jobGraph , stats , fileStore ) :
"""This is the core wrapping method for running the job within a worker . It sets up the stats
and logging before yielding . After completion of the body , the function will finish up the
stats and logging , and starts the async update process for the job ... | if stats is not None :
startTime = time . time ( )
startClock = getTotalCpuTime ( )
baseDir = os . getcwd ( )
yield
# If the job is not a checkpoint job , add the promise files to delete
# to the list of jobStoreFileIDs to delete
if not self . checkpoint :
for jobStoreFileID in Promise . filesToDelete :
... |
def get_client ( self , service , region , public = True , cached = True ) :
"""Returns the client object for the specified service and region .
By default the public endpoint is used . If you wish to work with a
services internal endpoints , specify ` public = False ` .
By default , if a client has already b... | client_class = None
# Cloud Networks currently uses nova - networks , so it doesn ' t appear as
# a separate entry in the service catalog . This hack will allow context
# objects to continue to work with Rackspace Cloud Networks . When the
# Neutron service is implemented , this hack will have to be removed .
if servic... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'environment_id' ) and self . environment_id is not None :
_dict [ 'environment_id' ] = self . environment_id
if hasattr ( self , 'customer_id' ) and self . customer_id is not None :
_dict [ 'customer_id' ] = self . customer_id
if hasattr ( self , 'document_type' ) and self . doc... |
def update_from ( self , source , incr = 1 , force = False ) :
"""Args :
source ( : py : class : ` SubCounter ` ) : : py : class : ` SubCounter ` or : py : class : ` Counter `
to increment from
incr ( int ) : Amount to increment ` ` count ` ` ( Default : 1)
force ( bool ) : Force refresh even if ` ` min _ d... | # Make sure source is a parent or peer
if source is self . parent or getattr ( source , 'parent' , None ) is self . parent :
if self . count + incr < 0 or source . count - incr < 0 :
raise ValueError ( 'Invalid increment: %s' % incr )
if source is self . parent :
if self . parent . count - self ... |
def add_to_queue ( self , series ) :
"""Add a series to the queue
@ param crunchyroll . models . Series series
@ return bool""" | result = self . _android_api . add_to_queue ( series_id = series . series_id )
return result |
def _make_netmask ( cls , arg ) :
"""Make a ( netmask , prefix _ len ) tuple from the given argument .
Argument can be :
- an integer ( the prefix length )
- a string representing the prefix length ( e . g . " 24 " )
- a string representing the prefix netmask ( e . g . " 255.255.255.0 " )""" | if arg not in cls . _netmask_cache :
if isinstance ( arg , _compat_int_types ) :
prefixlen = arg
else :
try : # Check for a netmask in prefix length form
prefixlen = cls . _prefix_from_prefix_string ( arg )
except NetmaskValueError : # Check for a netmask or hostmask in dotte... |
def fromJSON ( value ) :
"""loads the GP object from a JSON string""" | j = json . loads ( value )
v = GPDouble ( )
if "defaultValue" in j :
v . value = j [ 'defaultValue' ]
else :
v . value = j [ 'value' ]
if 'paramName' in j :
v . paramName = j [ 'paramName' ]
elif 'name' in j :
v . paramName = j [ 'name' ]
return v |
def search_subscriptions ( self , ** kwargs ) :
"""Search for all subscriptions by parameters""" | params = [ ( key , kwargs [ key ] ) for key in sorted ( kwargs . keys ( ) ) ]
url = "/notification/v1/subscription?{}" . format ( urlencode ( params , doseq = True ) )
response = NWS_DAO ( ) . getURL ( url , self . _read_headers )
if response . status != 200 :
raise DataFailureException ( url , response . status , ... |
def get_swagger_versions ( settings ) :
"""Validates and returns the versions of the Swagger Spec that this pyramid
application supports .
: type settings : dict
: return : list of strings . eg [ ' 1.2 ' , ' 2.0 ' ]
: raises : ValueError when an unsupported Swagger version is encountered .""" | swagger_versions = set ( aslist ( settings . get ( 'pyramid_swagger.swagger_versions' , DEFAULT_SWAGGER_VERSIONS ) ) )
if len ( swagger_versions ) == 0 :
raise ValueError ( 'pyramid_swagger.swagger_versions is empty' )
for swagger_version in swagger_versions :
if swagger_version not in SUPPORTED_SWAGGER_VERSION... |
def managed ( name , probes , defaults = None ) :
'''Ensure the networks device is configured as specified in the state SLS file .
Probes not specified will be removed , while probes not confiured as expected will trigger config updates .
: param probes : Defines the probes as expected to be configured on the
... | ret = _default_ret ( name )
result = True
comment = ''
rpm_probes_config = _retrieve_rpm_probes ( )
# retrieves the RPM config from the device
if not rpm_probes_config . get ( 'result' ) :
ret . update ( { 'result' : False , 'comment' : 'Cannot retrieve configurtion of the probes from the device: {reason}' . format... |
def html_listify ( tree , root_xl_element , extensions , list_type = 'ol' ) :
"""Convert a node tree into an xhtml nested list - of - lists .
This will create ' li ' elements under the root _ xl _ element ,
additional sublists of the type passed as list _ type . The contents
of each li depends on the extensio... | for node in tree :
li_elm = etree . SubElement ( root_xl_element , 'li' )
if node [ 'id' ] not in extensions : # no extension , no associated file
span_elm = lxml . html . fragment_fromstring ( node [ 'title' ] , create_parent = 'span' )
li_elm . append ( span_elm )
else :
a_elm = lx... |
def get_least_distinct_words ( vocab , topic_word_distrib , doc_topic_distrib , doc_lengths , n = None ) :
"""Order the words from ` vocab ` by " distinctiveness score " ( Chuang et al . 2012 ) from least to most distinctive .
Optionally only return the ` n ` least distinctive words .
J . Chuang , C . Manning ,... | return _words_by_distinctiveness_score ( vocab , topic_word_distrib , doc_topic_distrib , doc_lengths , n , least_to_most = True ) |
def format_argspec_plus ( fn , grouped = True ) :
"""Returns a dictionary of formatted , introspected function arguments .
A enhanced variant of inspect . formatargspec to support code generation .
fn
An inspectable callable or tuple of inspect getargspec ( ) results .
grouped
Defaults to True ; include (... | spec = callable ( fn ) and inspect . getargspec ( fn ) or fn
args = inspect . formatargspec ( * spec )
if spec [ 0 ] :
self_arg = spec [ 0 ] [ 0 ]
elif spec [ 1 ] :
self_arg = '%s[0]' % spec [ 1 ]
else :
self_arg = None
apply_pos = inspect . formatargspec ( spec [ 0 ] , spec [ 1 ] , spec [ 2 ] )
defaulted_v... |
def get_decoder_self_attention_bias ( length ) :
"""Calculate bias for decoder that maintains model ' s autoregressive property .
Creates a tensor that masks out locations that correspond to illegal
connections , so prediction at position i cannot draw information from future
positions .
Args :
length : i... | with tf . name_scope ( "decoder_self_attention_bias" ) :
valid_locs = tf . matrix_band_part ( tf . ones ( [ length , length ] ) , - 1 , 0 )
valid_locs = tf . reshape ( valid_locs , [ 1 , 1 , length , length ] )
decoder_bias = _NEG_INF * ( 1.0 - valid_locs )
return decoder_bias |
def restore_definition ( self , project , definition_id , deleted ) :
"""RestoreDefinition .
Restores a deleted definition
: param str project : Project ID or project name
: param int definition _ id : The identifier of the definition to restore .
: param bool deleted : When false , restores a deleted defin... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if definition_id is not None :
route_values [ 'definitionId' ] = self . _serialize . url ( 'definition_id' , definition_id , 'int' )
query_parameters = { }
if deleted is not None :
... |
def translate_x ( self , d ) :
"""Translate mesh for x - direction
: param float d : Amount to translate""" | mat = numpy . array ( [ [ 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 1 , 0 ] , [ d , 0 , 0 , 1 ] ] )
self . vectors = self . vectors . dot ( mat )
return self |
def decrypt ( ciphertext_blob , encryption_context = None , grant_tokens = None , region = None , key = None , keyid = None , profile = None ) :
'''Decrypt ciphertext .
CLI example : :
salt myminion boto _ kms . decrypt encrypted _ ciphertext''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
r = { }
try :
plaintext = conn . decrypt ( ciphertext_blob , encryption_context = encryption_context , grant_tokens = grant_tokens )
r [ 'plaintext' ] = plaintext [ 'Plaintext' ]
except boto . exception . BotoServerError as e :... |
def dividend_receivable ( self ) :
"""[ float ] 投资组合在分红现金收到账面之前的应收分红部分 。 具体细节在分红部分""" | return sum ( d [ 'quantity' ] * d [ 'dividend_per_share' ] for d in six . itervalues ( self . _dividend_receivable ) ) |
def batched_expiration_maintenance_dev ( self , elapsed_time ) :
"""Batched version of expiration _ maintenance ( )""" | num_iterations = self . num_batched_maintenance ( elapsed_time )
for i in range ( num_iterations ) :
self . expiration_maintenance ( ) |
def find_Note ( data , freq , bits ) :
"""Get the frequencies , feed them to find _ notes and the return the Note
with the highest amplitude .""" | data = find_frequencies ( data , freq , bits )
return sorted ( find_notes ( data ) , key = operator . itemgetter ( 1 ) ) [ - 1 ] [ 0 ] |
def sync ( self , group , name = None , host = None , location = None , move = False , all = False ) :
'''Sync the latest archive to the host on given location .
CLI Example :
. . code - block : : bash
salt ' * ' support . sync group = test
salt ' * ' support . sync group = test name = / tmp / myspecial - 1... | tfh , tfn = tempfile . mkstemp ( )
processed_archives = [ ]
src_uri = uri = None
last_arc = self . last_archive ( )
if name :
archives = [ name ]
elif all :
archives = self . archives ( )
elif last_arc :
archives = [ last_arc ]
else :
archives = [ ]
for name in archives :
err = None
if not name ... |
def _parse_myinfo ( client , command , actor , args ) :
"""Parse MYINFO and update the Host object .""" | _ , server , version , usermodes , channelmodes = args . split ( None , 5 ) [ : 5 ]
s = client . server
s . host = server
s . version = version
s . user_modes = set ( usermodes )
s . channel_modes = set ( channelmodes ) |
def init ( opts ) :
'''Open the connection to the Nexsu switch over the NX - API .
As the communication is HTTP based , there is no connection to maintain ,
however , in order to test the connectivity and make sure we are able to
bring up this Minion , we are executing a very simple command ( ` ` show clock `... | proxy_dict = opts . get ( 'proxy' , { } )
conn_args = copy . deepcopy ( proxy_dict )
conn_args . pop ( 'proxytype' , None )
opts [ 'multiprocessing' ] = conn_args . pop ( 'multiprocessing' , True )
# This is not a SSH - based proxy , so it should be safe to enable
# multiprocessing .
try :
rpc_reply = __utils__ [ '... |
def _detect_encoding ( self , source_file ) :
"""Detect encoding .""" | encoding = self . _guess ( source_file )
# If we didn ' t explicitly detect an encoding , assume default .
if encoding is None :
encoding = self . default_encoding
return encoding |
def wait_for ( self , condition , timeout = None , interval = 0.1 , errmsg = None ) :
'''Wait for a condition to be True .
Wait for condition , a callable , to return True . If timeout is
nonzero , raise a TimeoutError ( errmsg ) if the condition is not
True after timeout seconds . Check the condition everal ... | t0 = time . time ( )
while not condition ( ) :
t1 = time . time ( )
if timeout and ( t1 - t0 ) >= timeout :
raise TimeoutError ( errmsg )
time . sleep ( interval ) |
def set_camera_enabled ( self , camera_id , is_enabled ) :
"""Turn Arlo camera On / Off .
: param mode : True , False""" | self . publish ( action = 'set' , resource = 'privacy' , camera_id = camera_id , mode = is_enabled , publish_response = True )
self . update ( ) |
def clear ( self ) :
"""Delete Mentions of each class in the extractor from the given split .""" | # Create set of candidate _ subclasses associated with each mention _ subclass
cand_subclasses = set ( )
for mentions , tablename in [ ( _ [ 1 ] [ 0 ] , _ [ 1 ] [ 1 ] ) for _ in candidate_subclasses . values ( ) ] :
for mention in mentions :
if mention in self . mention_classes :
cand_subclasses... |
def put_function ( self , fn ) :
""": param fn : Function
: type fn : LambdaFunction""" | if fn . function_name in self . _functions :
self . _functions [ fn . function_name ] [ 'latest' ] = fn
else :
self . _functions [ fn . function_name ] = { 'latest' : fn , 'versions' : [ ] , 'alias' : weakref . WeakValueDictionary ( ) }
self . _arns [ fn . function_arn ] = fn |
def query_module_funcs ( self , module ) :
"""Query the functions in the specified module .""" | funcs = self . session . query ( Export ) . filter_by ( module = module ) . all ( )
return funcs |
async def main ( ) :
"""Get the data from a * hole instance .""" | async with aiohttp . ClientSession ( ) as session :
data = Hole ( '192.168.0.215' , loop , session )
await data . get_data ( )
# Get the raw data
print ( json . dumps ( data . data , indent = 4 , sort_keys = True ) )
print ( "Status:" , data . status )
print ( "Domains being blocked:" , data . d... |
def _extract_params_from_i0 ( only_variable_parameters , parameters_with_variability , initial_conditions_with_variability ) :
"""Used within the distance / cost function to create the current kinetic parameter and initial condition vectors
to be used during that interaction , using current values in i0.
This f... | complete_params = [ ]
counter = 0
for param , is_variable in parameters_with_variability : # If param not variable , add it from param list
if not is_variable :
complete_params . append ( param )
else : # Otherwise add it from variable parameters list
complete_params . append ( only_variable_par... |
def atlasdb_get_zonefile_bits ( zonefile_hash , con = None , path = None ) :
"""What bit ( s ) in a zonefile inventory does a zonefile hash correspond to ?
Return their indexes in the bit field .""" | with AtlasDBOpen ( con = con , path = path ) as dbcon :
sql = "SELECT inv_index FROM zonefiles WHERE zonefile_hash = ?;"
args = ( zonefile_hash , )
cur = dbcon . cursor ( )
res = atlasdb_query_execute ( cur , sql , args )
# NOTE : zero - indexed
ret = [ ]
for r in res :
ret . append ... |
def OpenServerEndpoint ( self , path , verify_cb = lambda x : True , data = None , params = None , headers = None , method = "GET" , timeout = None ) :
"""Search through all the base URLs to connect to one that works .
This is a thin wrapper around requests . request ( ) so most parameters are
documented there ... | tries = 0
last_error = HTTPObject ( code = 404 )
while tries < len ( self . base_urls ) :
base_url_index = self . last_base_url_index % len ( self . base_urls )
active_base_url = self . base_urls [ base_url_index ]
result = self . OpenURL ( self . _ConcatenateURL ( active_base_url , path ) , data = data , p... |
def read ( value , split = False ) :
'''Get the value of an option interpreting as a file implicitly or
explicitly and falling back to the value if not explicitly specified .
If the value is ' @ name ' , then a file must exist with name and the returned
value will be the contents of that file . If the value i... | v = str ( value )
retval = value
if v [ 0 ] == '@' or v == '-' :
fname = '-' if v == '-' else v [ 1 : ]
try :
with click . open_file ( fname ) as fp :
if not fp . isatty ( ) :
retval = fp . read ( )
else :
retval = None
# @ todo better to leave... |
def name ( self ) :
"""Table name used in requests .
For example :
. . literalinclude : : snippets _ table . py
: start - after : [ START bigtable _ table _ name ]
: end - before : [ END bigtable _ table _ name ]
. . note : :
This property will not change if ` ` table _ id ` ` does not , but the
retur... | project = self . _instance . _client . project
instance_id = self . _instance . instance_id
table_client = self . _instance . _client . table_data_client
return table_client . table_path ( project = project , instance = instance_id , table = self . table_id ) |
def to_data ( interval , conv = None , pinf = float ( 'inf' ) , ninf = float ( '-inf' ) ) :
"""Export given interval ( or atomic interval ) to a list of 4 - uples ( left , lower ,
upper , right ) .
: param interval : an Interval or AtomicInterval instance .
: param conv : function that convert bounds to " low... | interval = Interval ( interval ) if isinstance ( interval , AtomicInterval ) else interval
conv = ( lambda v : v ) if conv is None else conv
data = [ ]
def _convert ( bound ) :
if bound == inf :
return pinf
elif bound == - inf :
return ninf
else :
return conv ( bound )
for item in in... |
def events_for_onchain_secretreveal_if_dangerzone ( channelmap : ChannelMap , secrethash : SecretHash , transfers_pair : List [ MediationPairState ] , block_number : BlockNumber , block_hash : BlockHash , ) -> List [ Event ] :
"""Reveal the secret on - chain if the lock enters the unsafe region and the
secret is ... | events : List [ Event ] = list ( )
all_payer_channels = [ ]
for pair in transfers_pair :
channel_state = get_payer_channel ( channelmap , pair )
if channel_state :
all_payer_channels . append ( channel_state )
transaction_sent = has_secret_registration_started ( all_payer_channels , transfers_pair , sec... |
def remove ( feature , remove_payload = False , restart = False ) :
r'''Remove an installed feature
. . note : :
Some features require a reboot after installation / uninstallation . If
one of these features are modified , then other features cannot be
installed until the server is restarted . Additionally ,... | # If it is a list of features , make it a comma delimited string
if isinstance ( feature , list ) :
feature = ',' . join ( feature )
# Use Uninstall - WindowsFeature on Windows 2012 ( osversion 6.2 ) and later
# minions . Default to Remove - WindowsFeature for earlier releases of Windows .
# The newer command makes... |
def get_aoi ( self , solar_zenith , solar_azimuth ) :
"""Get the angle of incidence on the system .
Parameters
solar _ zenith : float or Series .
Solar zenith angle .
solar _ azimuth : float or Series .
Solar azimuth angle .
Returns
aoi : Series
The angle of incidence""" | aoi = irradiance . aoi ( self . surface_tilt , self . surface_azimuth , solar_zenith , solar_azimuth )
return aoi |
def build_kcorrection_array ( log , redshiftArray , snTypesArray , snLightCurves , pathToOutputDirectory , plot = True ) :
"""* Given the random redshiftArray and snTypeArray , generate a dictionary of k - correction polynomials ( one for each filter ) for every object . *
* * Key Arguments : * *
- ` ` log ` ` ... | # # # # # # > IMPORTS # # # # #
# # STANDARD LIB # #
# # THIRD PARTY # #
import yaml
import numpy as np
# # LOCAL APPLICATION # #
# # # # # # > ACTION ( S ) # # # # #
dataDir = pathToOutputDirectory + "/k_corrections/"
filters = [ 'g' , 'r' , 'i' , 'z' ]
fileName = pathToOutputDirectory + "/transient_light_curves.yaml"... |
def __filter_non_working_providers ( self ) :
'''Remove any mis - configured cloud providers from the available listing''' | for alias , drivers in six . iteritems ( self . opts [ 'providers' ] . copy ( ) ) :
for driver in drivers . copy ( ) :
fun = '{0}.get_configured_provider' . format ( driver )
if fun not in self . clouds : # Mis - configured provider that got removed ?
log . warning ( 'The cloud driver, \... |
def decrypt ( self , key ) :
"""This method checks the signature on the state and decrypts it .
: param key : the key to decrypt and sign with""" | # check signature
if ( self . get_hmac ( key ) != self . hmac ) :
raise HeartbeatError ( "Signature invalid on state." )
if ( not self . encrypted ) :
return
# decrypt
aes = AES . new ( key , AES . MODE_CFB , self . iv )
self . f_key = aes . decrypt ( self . f_key )
self . alpha_key = aes . decrypt ( self . alp... |
def regenerate_recovery_code ( self , user_id ) :
"""Removes the current recovery token , generates and returns a new one
Args :
user _ id ( str ) : The user _ id of the user identity .
See : https : / / auth0 . com / docs / api / management / v2 # ! / Users / post _ recovery _ code _ regeneration""" | url = self . _url ( '{}/recovery-code-regeneration' . format ( user_id ) )
return self . client . post ( url ) |
def connectSelection ( self , cls = None ) :
"""Creates a connection between the currently selected nodes , provided there are only 2 nodes selected . If the cls parameter is supplied then that will be the class instance used when creating the connection . Otherwise , the default connection class will be used .
:... | # collect the selected nodes
nodes = self . selectedNodes ( )
if ( len ( nodes ) != 2 ) :
return None
# create the connection
con = self . addConnection ( cls )
con . setOutputNode ( nodes [ 0 ] )
con . setInputNode ( nodes [ 1 ] )
con . rebuild ( )
return con |
def _get_points ( self ) :
"""Subclasses may override this method .""" | return tuple ( [ self . _getitem__points ( i ) for i in range ( self . _len__points ( ) ) ] ) |
def delete_snmp_template ( auth , url , template_name = None , template_id = None ) :
"""Takes template _ name as input to issue RESTUL call to HP IMC which will delete the specific
snmp template from the IMC system
: param auth : requests auth object # usually auth . creds from auth pyhpeimc . auth . class
:... | try :
if template_id is None :
snmp_templates = get_snmp_templates ( auth , url )
if template_name is None :
template_name = snmp_template [ 'name' ]
template_id = None
for template in snmp_templates :
if template [ 'name' ] == template_name :
... |
def merge_corpus ( self , corpus ) :
"""Merge the given corpus into this corpus . All assets ( tracks , utterances , issuers , . . . ) are copied into
this corpus . If any ids ( utt - idx , track - idx , issuer - idx , subview - idx , . . . ) are occurring in both corpora ,
the ids from the merging corpus are s... | # Create a copy , so objects aren ' t changed in the original merging corpus
merging_corpus = Corpus . from_corpus ( corpus )
self . import_tracks ( corpus . tracks . values ( ) )
self . import_issuers ( corpus . issuers . values ( ) )
utterance_idx_mapping = self . import_utterances ( corpus . utterances . values ( ) ... |
def state ( self ) :
"""State of this instance . One of ` ` OFFLINE ` ` , ` ` INITIALIZING ` ` ,
` ` INITIALIZED ` ` , ` ` STARTING ` ` , ` ` RUNNING ` ` , ` ` STOPPING ` ` or
` ` FAILED ` ` .""" | if self . _proto . HasField ( 'state' ) :
return yamcsManagement_pb2 . YamcsInstance . InstanceState . Name ( self . _proto . state )
return None |
def model_changed ( self , model , prop_name , info ) :
"""This method notifies the model lists and the parent state about changes
The method is called each time , the model is changed . This happens , when the state itself changes or one of
its children ( states , transitions , data flows ) changes . Changes o... | # if info . method _ name = = ' change _ state _ type ' : # Handled in method ' change _ state _ type '
# return
# If this model has been changed ( and not one of its child states ) , then we have to update all child models
# This must be done before notifying anybody else , because other may relay on the updated model... |
def get_linked_deployments ( deployments : Dict [ str , Any ] ) -> Dict [ str , Any ] :
"""Returns all deployments found in a chain URI ' s deployment data that contain link dependencies .""" | linked_deployments = { dep : data for dep , data in deployments . items ( ) if get_in ( ( "runtime_bytecode" , "link_dependencies" ) , data ) }
for deployment , data in linked_deployments . items ( ) :
if any ( link_dep [ "value" ] == deployment for link_dep in data [ "runtime_bytecode" ] [ "link_dependencies" ] ) ... |
def condensedDistance ( dupes ) :
'''Convert the pairwise list of distances in dupes to " condensed
distance matrix " required by the hierarchical clustering
algorithms . Also return a dictionary that maps the distance matrix
to the record _ ids .
The formula for an index of the condensed matrix is
index ... | candidate_set = numpy . unique ( dupes [ 'pairs' ] )
i_to_id = dict ( enumerate ( candidate_set ) )
ids = candidate_set . searchsorted ( dupes [ 'pairs' ] )
row = ids [ : , 0 ]
col = ids [ : , 1 ]
N = len ( candidate_set )
matrix_length = N * ( N - 1 ) / 2
row_step = ( N - row ) * ( N - row - 1 ) / 2
index = matrix_len... |
def get_metric_by_day ( self , unique_identifier , metric , from_date , limit = 30 , ** kwargs ) :
"""Returns the ` ` metric ` ` for ` ` unique _ identifier ` ` segmented by day
starting from ` ` from _ date ` `
: param unique _ identifier : Unique string indetifying the object this metric is for
: param metr... | conn = kwargs . get ( "connection" , None )
date_generator = ( from_date + datetime . timedelta ( days = i ) for i in itertools . count ( ) )
metric_key_date_range = self . _get_daily_date_range ( from_date , datetime . timedelta ( days = limit ) )
# generate a list of mondays in between the start date and the end date... |
def _get_context_table ( context ) :
"""Yields a formatted table to print context details .
: param dict context : The tunnel context
: return Table : Formatted for tunnel context output""" | table = formatting . KeyValueTable ( [ 'name' , 'value' ] )
table . align [ 'name' ] = 'r'
table . align [ 'value' ] = 'l'
table . add_row ( [ 'id' , context . get ( 'id' , '' ) ] )
table . add_row ( [ 'name' , context . get ( 'name' , '' ) ] )
table . add_row ( [ 'friendly name' , context . get ( 'friendlyName' , '' )... |
def distance_matrix ( self , leaf_labels = False ) :
'''Return a distance matrix ( 2D dictionary ) of the leaves of this ` ` Tree ` `
Args :
` ` leaf _ labels ` ` ( ` ` bool ` ` ) : ` ` True ` ` to have keys be labels of leaf ` ` Node ` ` objects , otherwise ` ` False ` ` to have keys be ` ` Node ` ` objects
... | M = dict ( ) ;
leaf_dists = dict ( )
for node in self . traverse_postorder ( ) :
if node . is_leaf ( ) :
leaf_dists [ node ] = [ [ node , 0 ] ]
else :
for c in node . children :
if c . edge_length is not None :
for i in range ( len ( leaf_dists [ c ] ) ) :
... |
def GetAuditLogEntries ( offset , now , token ) :
"""Return all audit log entries between now - offset and now .
Args :
offset : rdfvalue . Duration how far back to look in time
now : rdfvalue . RDFDatetime for current time
token : GRR access token
Yields :
AuditEvents created during the time range""" | start_time = now - offset - audit . AUDIT_ROLLOVER_TIME
for fd in audit . LegacyAuditLogsForTimespan ( start_time , now , token ) :
for event in fd . GenerateItems ( ) :
if now - offset < event . timestamp < now :
yield event |
def to_unicode ( string ) :
"""Ensure a passed string is unicode""" | if isinstance ( string , six . binary_type ) :
return string . decode ( 'utf8' )
if isinstance ( string , six . text_type ) :
return string
if six . PY2 :
return unicode ( string )
return str ( string ) |
def get_word_at ( self , index : int ) -> Union [ int , BitVec ] :
"""Access a word from a specified memory index .
: param index : integer representing the index to access
: return : 32 byte word at the specified index""" | try :
return symbol_factory . BitVecVal ( util . concrete_int_from_bytes ( bytes ( [ util . get_concrete_int ( b ) for b in self [ index : index + 32 ] ] ) , 0 , ) , 256 , )
except TypeError :
result = simplify ( Concat ( [ b if isinstance ( b , BitVec ) else symbol_factory . BitVecVal ( b , 8 ) for b in cast (... |
def azm ( self ) :
"""Corrected azimuth , taking into account backsight , declination , and compass corrections .""" | azm1 = self . get ( 'BEARING' , None )
azm2 = self . get ( 'AZM2' , None )
if azm1 is None and azm2 is None :
return None
if azm2 is None :
return azm1 + self . declination
if azm1 is None :
return ( azm2 + 180 ) % 360 + self . declination
return ( azm1 + ( azm2 + 180 ) % 360 ) / 2.0 + self . declination |
def _get_peering_connection_ids ( name , conn ) :
''': param name : The name of the VPC peering connection .
: type name : String
: param conn : The boto aws ec2 connection .
: return : The id associated with this peering connection
Returns the VPC peering connection ids
given the VPC peering connection n... | filters = [ { 'Name' : 'tag:Name' , 'Values' : [ name ] , } , { 'Name' : 'status-code' , 'Values' : [ ACTIVE , PENDING_ACCEPTANCE , PROVISIONING ] , } ]
peerings = conn . describe_vpc_peering_connections ( Filters = filters ) . get ( 'VpcPeeringConnections' , [ ] )
return [ x [ 'VpcPeeringConnectionId' ] for x in peeri... |
def get ( self ) :
"""Get a JSON - ready representation of this Mail object .
: returns : This Mail object , ready for use in a request body .
: rtype : dict""" | mail = { 'from' : self . _get_or_none ( self . from_email ) , 'subject' : self . _get_or_none ( self . subject ) , 'personalizations' : [ p . get ( ) for p in self . personalizations or [ ] ] , 'content' : [ c . get ( ) for c in self . contents or [ ] ] , 'attachments' : [ a . get ( ) for a in self . attachments or [ ]... |
def scan_url ( url , apikey ) :
"""If URL is found , scan it""" | logger . info ( 'Found what I believe is a URL: %s' , url )
v_api = virus_total . VirusTotal ( )
while True :
url_report = v_api . url_report ( url , apikey )
response_code = url_report [ 'response_code' ]
# report does not exist , need to scan
if response_code == - 2 :
logger . info ( 'Report j... |
def packet_synopsis ( url_encoded_ivorn = None ) :
"""Result :
Nested dict providing key details , e . g . : :
{ " coords " : [
" dec " : 10.9712,
" error " : 0.05,
" ra " : 233.7307,
" time " : " 2015-10-01T15:04:22.930000 + 00:00"
" refs " : [
" cite _ type " : u " followup " ,
" description " :... | ivorn = validate_ivorn ( url_encoded_ivorn )
voevent_row = db_session . query ( Voevent ) . filter ( Voevent . ivorn == ivorn ) . one ( )
cites = db_session . query ( Cite ) . filter ( Cite . voevent_id == voevent_row . id ) . all ( )
coords = db_session . query ( Coord ) . filter ( Coord . voevent_id == voevent_row . ... |
def get_last_content ( request , page_id ) :
"""Get the latest content for a particular type""" | content_type = request . GET . get ( 'content_type' )
language_id = request . GET . get ( 'language_id' )
page = get_object_or_404 ( Page , pk = page_id )
placeholders = get_placeholders ( page . get_template ( ) )
_template = template . loader . get_template ( page . get_template ( ) )
for placeholder in placeholders ... |
def get_input_photo ( photo ) :
"""Similar to : meth : ` get _ input _ peer ` , but for photos""" | try :
if photo . SUBCLASS_OF_ID == 0x846363e0 : # crc32 ( b ' InputPhoto ' ) :
return photo
except AttributeError :
_raise_cast_fail ( photo , 'InputPhoto' )
if isinstance ( photo , types . photos . Photo ) :
photo = photo . photo
if isinstance ( photo , types . Photo ) :
return types . InputPho... |
def unpack_value ( self , tup_tree ) :
"""Find VALUE or VALUE . ARRAY under tup _ tree and convert to a Python value .
Looks at the TYPE of the node to work out how to decode it .
Handles nodes with no value ( e . g . when representing NULL by omitting
VALUE )""" | valtype = attrs ( tup_tree ) [ 'TYPE' ]
raw_val = self . list_of_matching ( tup_tree , ( 'VALUE' , 'VALUE.ARRAY' ) )
if not raw_val :
return None
if len ( raw_val ) > 1 :
raise CIMXMLParseError ( _format ( "Element {0!A} has too many child elements {1!A} " "(allowed is one of 'VALUE' or 'VALUE.ARRAY')" , name (... |
def paginate_resources ( cls , request , resources , on_fail_status ) :
"""Truncates a list of resources based on ClientPagingControls
Args :
request ( object ) : The parsed protobuf request object
resources ( list of objects ) : The resources to be paginated
Returns :
list : The paginated list of resourc... | if not resources :
return ( resources , client_list_control_pb2 . ClientPagingResponse ( ) )
paging = request . paging
limit = min ( paging . limit , MAX_PAGE_SIZE ) or DEFAULT_PAGE_SIZE
# Find the start index from the location marker sent
try :
if paging . start :
start_index = cls . index_by_id ( pagi... |
def _services ( lancet ) :
"""List all currently configured services .""" | def get_services ( config ) :
for s in config . sections ( ) :
if config . has_option ( s , 'url' ) :
if config . has_option ( s , 'username' ) :
yield s
for s in get_services ( lancet . config ) :
click . echo ( '{}[Logout from {}]' . format ( s , lancet . config . get ( s ,... |
def find_by_typename ( self , typename ) :
"""List of all objects whose type has the given name .""" | return self . find_by ( lambda obj : type ( obj ) . __name__ == typename ) |
def get_mv_impedance ( grid ) :
"""Determine MV grid impedance ( resistance and reactance separately )
Parameters
grid : LVGridDing0
Returns
: any : ` list `
List containing resistance and reactance of MV grid""" | omega = 2 * math . pi * 50
mv_grid = grid . grid_district . lv_load_area . mv_grid_district . mv_grid
edges = mv_grid . find_path ( grid . _station , mv_grid . _station , type = 'edges' )
r_mv_grid = sum ( [ e [ 2 ] [ 'branch' ] . type [ 'R' ] * e [ 2 ] [ 'branch' ] . length / 1e3 for e in edges ] )
x_mv_grid = sum ( [... |
def tag_provinces ( tokens : List [ str ] ) -> List [ Tuple [ str , str ] ] :
"""Recognize Thailand provinces in text
Input is a list of words
Return a list of tuples
Example : :
> > > text = [ ' หนองคาย ' , ' น่าอยู่ ' ]
> > > tag _ provinces ( text )
[ ( ' หนองคาย ' , ' B - LOCATION ' ) , ( ' น่าอยู่ ... | province_list = provinces ( )
output = [ ]
for token in tokens :
if token in province_list :
output . append ( ( token , "B-LOCATION" ) )
else :
output . append ( ( token , "O" ) )
return output |
def _binary_exp ( expression , op ) : # type : ( QuilParser . ExpressionContext , Callable ) - > Number
"""Apply an operator to two expressions . Start by evaluating both sides of the operator .""" | [ arg1 , arg2 ] = expression . expression ( )
return op ( _expression ( arg1 ) , _expression ( arg2 ) ) |
def _configure_buffer_sizes ( ) :
"""Set up module globals controlling buffer sizes""" | global PIPE_BUF_BYTES
global OS_PIPE_SZ
PIPE_BUF_BYTES = 65536
OS_PIPE_SZ = None
# Teach the ' fcntl ' module about ' F _ SETPIPE _ SZ ' , which is a Linux - ism ,
# but a good one that can drastically reduce the number of syscalls
# when dealing with high - throughput pipes .
if not hasattr ( fcntl , 'F_SETPIPE_SZ' ) ... |
def _sub_hostname ( self , line ) :
'''This will replace the exact hostname and all instances of the domain name with the obfuscated alternatives .
Example :''' | try :
for od , d in self . dn_db . items ( ) : # regex = re . compile ( r ' \ w * \ . % s ' % d )
regex = re . compile ( r'(?![\W\-\:\ \.])[a-zA-Z0-9\-\_\.]*\.%s' % d )
hostnames = [ each for each in regex . findall ( line ) ]
if len ( hostnames ) > 0 :
for hn in hostnames :
... |
def sleep ( self , seconds ) :
"""Sleep in simulated time .""" | start = self . time ( )
while ( self . time ( ) - start < seconds and not self . need_to_stop . is_set ( ) ) :
self . need_to_stop . wait ( self . sim_time ) |
def since ( version ) :
"""A decorator that annotates a function to append the version of Spark the function was added .""" | import re
indent_p = re . compile ( r'\n( +)' )
def deco ( f ) :
indents = indent_p . findall ( f . __doc__ )
indent = ' ' * ( min ( len ( m ) for m in indents ) if indents else 0 )
f . __doc__ = f . __doc__ . rstrip ( ) + "\n\n%s.. versionadded:: %s" % ( indent , version )
return f
return deco |
def unfreeze ( name ) :
'''unfreezes the container''' | if not exists ( name ) :
raise ContainerNotExists ( "The container (%s) does not exist!" % name )
cmd = [ 'lxc-unfreeze' , '-n' , name ]
subprocess . check_call ( cmd ) |
def autodoc_event_handlers ( stream = sys . stdout ) :
"""Print to the given string , the documentation for the events
and the associated handlers .""" | lines = [ ]
for cls in all_subclasses ( EventHandler ) :
if cls in _ABC_EVHANDLER_CLASSES :
continue
event_class = cls . event_class
lines . extend ( cls . cls2str ( ) . split ( "\n" ) )
# Here we enforce the abstract protocol of the class
# The unit test in tests _ events will detect the pr... |
async def deregister ( self , node , * , check = None , service = None , write_token = None ) :
"""Deregisters a node , service or check
Parameters :
node ( Object or ObjectID ) : Node
check ( ObjectID ) : Check ID
service ( ObjectID ) : Service ID
write _ token ( ObjectID ) : Token ID
Returns :
bool ... | entry = { }
if isinstance ( node , str ) :
entry [ "Node" ] = node
else :
for k in ( "Datacenter" , "Node" , "CheckID" , "ServiceID" , "WriteRequest" ) :
if k in node :
entry [ k ] = node [ k ]
service_id = extract_attr ( service , keys = [ "ServiceID" , "ID" ] )
check_id = extract_attr ( ch... |
def FindDevice ( self , address ) :
'''Find a specific device by bluetooth address .''' | for obj in mockobject . objects . keys ( ) :
if obj . startswith ( '/org/bluez/' ) and 'dev_' in obj :
o = mockobject . objects [ obj ]
if o . props [ DEVICE_IFACE ] [ 'Address' ] == dbus . String ( address , variant_level = 1 ) :
return obj
raise dbus . exceptions . DBusException ( 'No ... |
async def _raise_for_status ( response ) :
"""Raise an appropriate error for a given response .
Arguments :
response ( : py : class : ` aiohttp . ClientResponse ` ) : The API response .
Raises :
: py : class : ` aiohttp . web _ exceptions . HTTPException ` : The appropriate
error for the response ' s stat... | try :
response . raise_for_status ( )
except aiohttp . ClientResponseError as exc :
reason = response . reason
spacetrack_error_msg = None
try :
json = await response . json ( )
if isinstance ( json , Mapping ) :
spacetrack_error_msg = json [ 'error' ]
except ( ValueError... |
def sma ( self , n , array = False ) :
"""简单均线""" | result = talib . SMA ( self . close , n )
if array :
return result
return result [ - 1 ] |
def getATR ( self ) :
"""Return card ATR""" | CardConnection . getATR ( self )
if None == self . hcard :
raise CardConnectionException ( 'Card not connected' )
hresult , reader , state , protocol , atr = SCardStatus ( self . hcard )
if hresult != 0 :
raise CardConnectionException ( 'Failed to get status: ' + SCardGetErrorMessage ( hresult ) )
return atr |
def enforce_git_config ( self ) :
'''For the config options which need to be maintained in the git config ,
ensure that the git config file is configured as desired .''' | git_config = os . path . join ( self . gitdir , 'config' )
conf = salt . utils . configparser . GitConfigParser ( )
if not conf . read ( git_config ) :
log . error ( 'Failed to read from git config file %s' , git_config )
else : # We are currently enforcing the following git config items :
# 1 . Fetch URL
# 2 . ref... |
def _handle_blacklisted_tag ( self ) :
"""Handle the body of an HTML tag that is parser - blacklisted .""" | strip = lambda text : text . rstrip ( ) . lower ( )
while True :
this , next = self . _read ( ) , self . _read ( 1 )
if this is self . END :
self . _fail_route ( )
elif this == "<" and next == "/" :
self . _head += 3
if self . _read ( ) != ">" or ( strip ( self . _read ( - 1 ) ) != s... |
def stop ( self ) :
"""Stop the workers ( will block until they are finished ) .""" | if self . running and self . num_workers :
for worker in self . workers :
self . queue . put ( None )
for worker in self . workers :
worker . join ( )
# Free up references held by workers
del self . workers [ : ]
self . queue . join ( )
self . running = False |
def setTitle ( self , title ) :
"""Sets the title for this page to the inputed title .
: param title | < str >""" | self . _titleLabel . setText ( title )
self . _titleLabel . adjustSize ( )
self . adjustMargins ( ) |
def _separate_header_and_content ( self , text_lines ) :
"""From a given Org text , return the header separate from the content .
The given text must be separate line by line and be a list .
The return is a list of two items : header and content .
Theses two items are text separate line by line in format of a... | no_more_header = False
expr_metadata = re . compile ( r'^#\+[a-zA-Z]+:.*' )
header = [ ]
content = [ ]
for line in text_lines :
metadata = expr_metadata . match ( line )
if metadata and not no_more_header :
header . append ( line )
else :
no_more_header = True
content . append ( line... |
def extension ( names ) :
"""Makes a function to be an extension .""" | for name in names :
if not NAME_PATTERN . match ( name ) :
raise ValueError ( 'invalid extension name: %s' % name )
def decorator ( f , names = names ) :
return Extension ( f , names = names )
return decorator |
def _transport_interceptor ( self , callback ) :
"""Takes a callback function and returns a function that takes headers and
messages and places them on the main service queue .""" | def add_item_to_queue ( header , message ) :
queue_item = ( Priority . TRANSPORT , next ( self . _transport_interceptor_counter ) , # insertion sequence to keep messages in order
( callback , header , message ) , )
self . __queue . put ( queue_item )
# Block incoming transport until insertion completes
retu... |
def loadTargetState ( targetStateConfig , existingTargetState = None ) :
"""extracts a new TargetState object from the specified configuration
: param targetStateConfig : the config dict .
: param existingTargetState : the existing state
: return :""" | from analyser . common . targetstatecontroller import TargetState
targetState = TargetState ( ) if existingTargetState is None else existingTargetState
# FIXFIX validate
if targetStateConfig is not None :
val = targetStateConfig . get ( 'fs' )
if val is not None :
targetState . fs = val
val = target... |
def tokenize_words ( string ) :
"""Tokenize input text to words .
: param string : Text to tokenize
: type string : str or unicode
: return : words
: rtype : list of strings""" | string = six . text_type ( string )
return re . findall ( WORD_TOKENIZATION_RULES , string ) |
def parse ( cls , parser , token ) :
"""Parse the node syntax :
. . code - block : : html + django
{ % page _ placeholder parentobj slotname title = " test " role = " m " % }""" | bits , as_var = parse_as_var ( parser , token )
tag_name , args , kwargs = parse_token_kwargs ( parser , bits , allowed_kwargs = cls . allowed_kwargs , compile_args = True , compile_kwargs = True )
# Play with the arguments
if len ( args ) == 2 :
parent_expr = args [ 0 ]
slot_expr = args [ 1 ]
elif len ( args )... |
def load_rdd_from_pickle ( sc , path , min_partitions = None , return_type = 'images' ) :
"""Loads an rdd that was saved as one pickle file per partition
: param sc : Spark Context
: param path : directory to load from
: param min _ partitions : minimum number of partitions . If None will be sc . defaultParal... | if min_partitions is None :
min_partitions = sc . defaultParallelism
rdd = sc . pickleFile ( path , minPartitions = min_partitions )
rdd = rdd . flatMap ( lambda x : x )
if return_type == 'images' :
result = td . images . fromrdd ( rdd ) . repartition ( min_partitions )
elif return_type == 'series' :
result... |
def find_node ( self , node_list_pyxb , base_url ) :
"""Search NodeList for Node that has { base _ url } .
Return matching Node or None""" | for node_pyxb in node_list_pyxb . node :
if node_pyxb . baseURL == base_url :
return node_pyxb |
def __get_ws_distance ( wstation , latitude , longitude ) :
"""Get the distance to the weatherstation from wstation section of xml .
wstation : weerstation section of buienradar xml ( dict )
latitude : our latitude
longitude : our longitude""" | if wstation :
try :
wslat = float ( wstation [ __BRLAT ] )
wslon = float ( wstation [ __BRLON ] )
dist = vincenty ( ( latitude , longitude ) , ( wslat , wslon ) )
log . debug ( "calc distance: %s (latitude: %s, longitude: " "%s, wslat: %s, wslon: %s)" , dist , latitude , longitude , ... |
def get_dirinfo ( self , name : str ) :
'''get a ` DirectoryInfo ` for a directory ( without create actual directory ) .''' | return DirectoryInfo ( os . path . join ( self . _path , name ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.