signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_element_types ( obj , ** kwargs ) :
"""Get element types as a set .""" | max_iterable_length = kwargs . get ( 'max_iterable_length' , 10000 )
consume_generator = kwargs . get ( 'consume_generator' , False )
if not isiterable ( obj ) :
return None
if isgenerator ( obj ) and not consume_generator :
return None
t = get_types ( obj , ** kwargs )
if not t [ 'too_big' ] :
if t [ 'type... |
def profile_path ( profile_id , profile ) :
"""Create full path to given provide for the current user .""" | user = os . path . expanduser ( "~" )
return os . path . join ( user , profile_id + profile ) |
def any2utf8 ( text , errors = 'strict' , encoding = 'utf8' ) :
"""Convert a string ( unicode or bytestring in ` encoding ` ) , to bytestring in utf8.""" | if isinstance ( text , unicode ) :
return text . encode ( 'utf8' )
# do bytestring - > unicode - > utf8 full circle , to ensure valid utf8
return unicode ( text , encoding , errors = errors ) . encode ( 'utf8' ) |
def repo_url_to_project_name ( url , normalize = True ) : # type : ( str , bool ) - > str
"""Extract project title from GIT repository URL , either https or ssh .
Should work fine with github , bitbucket
: rtype : str
: param url : Url of the repository
: param normalize : Title - case the project name
: ... | if url . startswith ( 'http' ) :
http_url = urlparse ( url )
name = http_url . path . replace ( '.git' , '' ) . lstrip ( '/' ) . strip ( )
else :
name = url [ url . index ( ':' ) + 1 : ] . replace ( '.git' , '' ) . strip ( )
if normalize :
return name . replace ( '/' , ' / ' ) . title ( )
return name |
def reduce ( self , func , memo = None ) :
"""* * Reduce * * builds up a single result from a list of values ,
aka ` inject ` , or foldl""" | if memo is None :
memo = [ ]
ns = self . Namespace ( )
ns . initial = True
# arguments . length > 2
ns . memo = memo
obj = self . obj
def by ( value , index , * args ) :
if not ns . initial :
ns . memo = value
ns . initial = True
else :
ns . memo = func ( ns . memo , value , index )
... |
def _apply_color ( code , content ) :
"""Apply a color code to text""" | normal = u'\x1B[0m'
seq = u'\x1B[%sm' % code
# Replace any normal sequences with this sequence to support nested colors
return seq + ( normal + seq ) . join ( content . split ( normal ) ) + normal |
def create_gp ( self ) :
"""Create a GnuPlot file for this BAM file .""" | categories_order = [ ( "{U}" , "#ee82ee" , 'Unmapped correctly' ) , ( "{u}" , "#ff0000" , 'Unmapped incorrectly' ) , ( "{T}" , "#00ff00" , 'Thresholded correctly' ) , ( "{t}" , "#008800" , 'Thresholded incorrectly' ) , ( "{P}" , "#ffff00" , 'Multimapped' ) , ( "{w}+{x}" , "#7f7f7f" , 'Mapped, should be unmapped' ) , ( ... |
def tree ( self , path ) :
'''. . versionadded : : 2014.7.0
Recurse through etcd and return all values''' | ret = { }
try :
items = self . read ( path )
except ( etcd . EtcdKeyNotFound , ValueError ) :
return None
except etcd . EtcdConnectionFailed :
log . error ( "etcd: failed to perform 'tree' operation on path %s due to connection error" , path )
return None
for item in items . children :
comps = six .... |
def send_mail ( subject , sender , to , message , html_message = None , cc = None , bcc = None , attachments = None , host = None , port = None , auth_user = None , auth_password = None , use_tls = False , fail_silently = False , ) :
"""Send a single email to a recipient list .
All members of the recipient list w... | if message is None and html_message is None :
raise ValueError ( "Either message or html_message must be provided" )
if message is None :
message = strip_tags ( html_message )
connection = SMTPConnection ( host = host , port = port , username = auth_user , password = auth_password , use_tls = use_tls , fail_sil... |
def ClaimRecords ( self , limit = 10000 , timeout = "30m" , start_time = None , record_filter = lambda x : False , max_filtered = 1000 ) :
"""Returns and claims up to limit unclaimed records for timeout seconds .
Returns a list of records which are now " claimed " , a claimed record will
generally be unavailabl... | if not self . locked :
raise aff4 . LockError ( "Queue must be locked to claim records." )
with data_store . DB . GetMutationPool ( ) as mutation_pool :
return mutation_pool . QueueClaimRecords ( self . urn , self . rdf_type , limit = limit , timeout = timeout , start_time = start_time , record_filter = record_... |
async def import_aggregated ( self , async_client , pid ) :
"""Import the SciObj at { pid } .
If the SciObj is a Resource Map , also recursively import the aggregated objects .""" | self . _logger . info ( 'Importing: {}' . format ( pid ) )
task_set = set ( )
object_info_pyxb = d1_common . types . dataoneTypes . ObjectInfo ( )
object_info_pyxb . identifier = pid
task_set . add ( self . import_object ( async_client , object_info_pyxb ) )
result_set , task_set = await asyncio . wait ( task_set )
ass... |
def _abspath ( self , path_segment , owner = None , app = None , sharing = None ) :
"""Qualifies * path _ segment * into an absolute path for a URL .
If * path _ segment * is already absolute , returns it unchanged .
If * path _ segment * is relative , then qualifies it with either
the provided namespace argu... | skip_encode = isinstance ( path_segment , UrlEncoded )
# If path _ segment is absolute , escape all forbidden characters
# in it and return it .
if path_segment . startswith ( '/' ) :
return UrlEncoded ( path_segment , skip_encode = skip_encode )
# path _ segment is relative , so we need a namespace to build an
# a... |
def config_as_dict ( cfg ) :
"""convert raw configuration to unified dictionary""" | ret = cfg . __dict__ . copy ( )
# random cropping params
del ret [ 'rand_crop_samplers' ]
assert isinstance ( cfg . rand_crop_samplers , list )
ret = merge_dict ( ret , zip_namedtuple ( cfg . rand_crop_samplers ) )
num_crop_sampler = len ( cfg . rand_crop_samplers )
ret [ 'num_crop_sampler' ] = num_crop_sampler
# must ... |
def monkey_patch ( cls ) :
"""Monkey path zbarlight C extension on Read The Docs""" | on_read_the_docs = os . environ . get ( 'READTHEDOCS' , False )
if on_read_the_docs :
sys . modules [ 'zbarlight._zbarlight' ] = cls |
def is_resource_protected ( self , request , ** kwargs ) :
"""Returns true if and only if the resource ' s URL is * not * exempt and * is * protected .""" | exempt_urls = self . get_exempt_url_patterns ( )
protected_urls = self . get_protected_url_patterns ( )
path = request . path_info . lstrip ( '/' )
path_is_exempt = any ( m . match ( path ) for m in exempt_urls )
if path_is_exempt :
return False
path_is_protected = any ( m . match ( path ) for m in protected_urls )... |
def p_expr_int ( p ) :
"""expr : INTEGER""" | p [ 0 ] = Expr . makenode ( Container ( int ( p [ 1 ] ) , p . lineno ( 1 ) ) ) |
def text_cleanup ( data , key , last_type ) :
"""I strip extra whitespace off multi - line strings if they are ready to be stripped !""" | if key in data and last_type == STRING_TYPE :
data [ key ] = data [ key ] . strip ( )
return data |
def poll ( self , id ) :
"""Fetch information about the poll with the given id
Returns a ` poll dict ` _ .""" | id = self . __unpack_id ( id )
url = '/api/v1/polls/{0}' . format ( str ( id ) )
return self . __api_request ( 'GET' , url ) |
def db_list ( user = None , password = None , host = None , port = None , authdb = None ) :
'''List all MongoDB databases
CLI Example :
. . code - block : : bash
salt ' * ' mongodb . db _ list < user > < password > < host > < port >''' | conn = _connect ( user , password , host , port , authdb = authdb )
if not conn :
return 'Failed to connect to mongo database'
try :
log . info ( 'Listing databases' )
return conn . database_names ( )
except pymongo . errors . PyMongoError as err :
log . error ( err )
return six . text_type ( err ) |
def derive_key_block ( self , master_secret , server_random , client_random , req_len ) :
"""Perform the derivation of master _ secret into a key _ block of req _ len
requested length . See RFC 5246 , section 6.3.""" | seed = server_random + client_random
if self . tls_version <= 0x0300 :
return self . prf ( master_secret , seed , req_len )
else :
return self . prf ( master_secret , b"key expansion" , seed , req_len ) |
def _initialize_metadata_service ( cls ) :
"""Initialize metadata service once and load gcp metadata into map
This method should only be called once .""" | if cls . inited :
return
instance_id = cls . get_attribute ( 'instance/id' )
if instance_id is not None :
cls . is_running = True
_GCP_METADATA_MAP [ 'instance_id' ] = instance_id
# fetch attributes from metadata request
for attribute_key , attribute_uri in _GCE_ATTRIBUTES . items ( ) :
if a... |
def release_tcp_port ( self , port , project ) :
"""Release a specific TCP port number
: param port : TCP port number
: param project : Project instance""" | if port in self . _used_tcp_ports :
self . _used_tcp_ports . remove ( port )
project . remove_tcp_port ( port )
log . debug ( "TCP port {} has been released" . format ( port ) ) |
def ndb_delete ( self , entity_or_key ) :
"""Like delete ( ) , but for NDB entities / keys .""" | if ndb is not None and isinstance ( entity_or_key , ndb . Model ) :
key = entity_or_key . key
else :
key = entity_or_key
self . ndb_deletes . append ( key ) |
def get_last_update_time ( self ) :
'''Gets the time at which each ledger was updated .
Can be called at any time to get this information .
: return : an ordered dict of outdated ledgers sorted by last update time ( from old to new )
and then by ledger ID ( in case of equal update time )''' | last_updated = { ledger_id : freshness_state . last_updated for ledger_id , freshness_state in self . _ledger_freshness . items ( ) }
return OrderedDict ( sorted ( last_updated . items ( ) , key = lambda item : ( item [ 1 ] , item [ 0 ] ) ) ) |
def _model_params2table ( self , fit_model , star_group_size ) :
"""Place fitted parameters into an astropy table .
Parameters
fit _ model : ` astropy . modeling . Fittable2DModel ` instance
PSF or PRF model to fit the data . Could be one of the models
in this package like ` ~ photutils . psf . sandbox . Di... | param_tab = Table ( )
for param_tab_name in self . _pars_to_output . keys ( ) :
param_tab . add_column ( Column ( name = param_tab_name , data = np . empty ( star_group_size ) ) )
if star_group_size > 1 :
for i in range ( star_group_size ) :
for param_tab_name , param_name in self . _pars_to_output . it... |
def get_source ( self , source , clean = False , callback = None ) :
"""Download a file from a URL and return it wrapped in a row - generating acessor object .
: param spec : A SourceSpec that describes the source to fetch .
: param account _ accessor : A callable to return the username and password to use for ... | from fs . zipfs import ZipOpenError
import os
from ambry_sources . sources import ( GoogleSource , CsvSource , TsvSource , FixedSource , ExcelSource , PartitionSource , SourceError , DelayedOpen , DelayedDownload , ShapefileSource , SocrataSource )
from ambry_sources import extract_file_from_zip
spec = source . spec
ca... |
def write_word ( self , offset , word ) :
""". . _ write _ word :
Writes one word from a device ,
see read _ word _ .""" | self . _lock = True
if ( offset > self . current_max_offset ) :
raise BUSError ( "Offset({}) exceeds address space of BUS({})" . format ( offset , self . current_max_offset ) )
self . writes += 1
self . truncate . setvalue ( word )
for addresspace , device in self . index . items ( ) :
if ( offset in addresspac... |
def register_onchain_secret ( channel_state : NettingChannelState , secret : Secret , secrethash : SecretHash , secret_reveal_block_number : BlockNumber , delete_lock : bool = True , ) -> None :
"""This will register the onchain secret and set the lock to the unlocked stated .
Even though the lock is unlocked it ... | our_state = channel_state . our_state
partner_state = channel_state . partner_state
register_onchain_secret_endstate ( our_state , secret , secrethash , secret_reveal_block_number , delete_lock , )
register_onchain_secret_endstate ( partner_state , secret , secrethash , secret_reveal_block_number , delete_lock , ) |
def run ( self ) :
'''Overrides : meth : ` python : threading . Thread . run ` .''' | global _global_kill
for message in self . _messages : # Get the message contents from the batch file
batch_file = self . _getBatchFile ( message )
message_contents = batch_file . getMessage ( message )
self . _logger . debug ( 'Read message {:}, waiting to be put into queue' . format ( message ) )
# The... |
def init ( envVarName , enableColorOutput = False ) :
"""Initialize the logging system and parse the environment variable
of the given name .
Needs to be called before starting the actual application .""" | global _initialized
if _initialized :
return
global _ENV_VAR_NAME
_ENV_VAR_NAME = envVarName
if enableColorOutput :
_preformatLevels ( envVarName + "_NO_COLOR" )
else :
_preformatLevels ( None )
if envVarName in os . environ : # install a log handler that uses the value of the environment var
setDebug (... |
def get_queues ( * queue_names , ** kwargs ) :
"""Return queue instances from specified queue names .
All instances must use the same Redis connection .""" | from . settings import QUEUES
if len ( queue_names ) <= 1 : # Return " default " queue if no queue name is specified
# or one queue with specified name
return [ get_queue ( * queue_names , ** kwargs ) ]
# will return more than one queue
# import job class only once for all queues
kwargs [ 'job_class' ] = get_job_cl... |
def _GetEarliestYearFromFileEntry ( self ) :
"""Retrieves the year from the file entry date and time values .
This function uses the creation time if available otherwise the change
time ( metadata last modification time ) is used .
Returns :
int : year of the file entry or None .""" | file_entry = self . GetFileEntry ( )
if not file_entry :
return None
stat_object = file_entry . GetStat ( )
posix_time = getattr ( stat_object , 'crtime' , None )
if posix_time is None :
posix_time = getattr ( stat_object , 'ctime' , None )
# Gzip files don ' t store the creation or metadata modification times ... |
def sort ( self , * args , ** kwargs ) :
"""Sort this setlist in place .""" | self . _list . sort ( * args , ** kwargs )
for index , value in enumerate ( self . _list ) :
self . _dict [ value ] = index |
def save_resource ( plugin_name , resource_name , resource_data ) :
"""Save a resource in local cache
: param plugin _ name : Name of plugin this resource belongs to
: type plugin _ name : str
: param resource _ name : Name of resource
: type resource _ name : str
: param resource _ data : Resource conten... | path = os . path . join ( resource_dir_path , plugin_name )
if not os . path . exists ( path ) :
os . makedirs ( path )
path = os . path . join ( path , resource_name )
logger . debug ( "Saving {}" . format ( path ) )
with open ( path , 'wb' ) as f :
f . write ( base64 . b64decode ( resource_data ) ) |
def set_scenario_status ( scenario_id , status , ** kwargs ) :
"""Set the status of a scenario .""" | user_id = kwargs . get ( 'user_id' )
_check_can_edit_scenario ( scenario_id , kwargs [ 'user_id' ] )
scenario_i = _get_scenario ( scenario_id , user_id )
scenario_i . status = status
db . DBSession . flush ( )
return 'OK' |
def get_height_rect ( self , x : int , y : int , width : int , height : int , string : str ) -> int :
"""Return the height of this text word - wrapped into this rectangle .
Args :
x ( int ) : The x coordinate from the left .
y ( int ) : The y coordinate from the top .
width ( int ) : Maximum width to render... | string_ = string . encode ( "utf-8" )
return int ( lib . get_height_rect ( self . console_c , x , y , width , height , string_ , len ( string_ ) ) ) |
def _permission_trees ( permissions ) :
"""Get the cached permission tree , or build a new one if necessary .""" | treecache = PermissionTreeCache ( )
cached = treecache . get ( )
if not cached :
tree = PermissionTreeBuilder ( )
for permission in permissions :
tree . insert ( permission )
result = tree . serialize ( )
treecache . set ( result )
return result
return cached |
def send ( self , command , * , log = True ) :
''': param pyardrone . at . base . ATCommand command : command to send
Sends the command to the drone ,
with an internal increasing sequence number .
this method is thread - safe .''' | with self . sequence_number_mutex :
self . sequence_number += 1
packed = command . _pack ( self . sequence_number )
self . send_bytes ( packed , log = log ) |
def requires_git ( func : Callable ) -> Callable :
"""Decorator to ensure ` git ` is accessible before calling a function .
: param func : the function to wrap
: return : the wrapped function""" | def decorated ( * args , ** kwargs ) :
try :
run ( [ GIT_COMMAND , "--version" ] )
except RunException as e :
raise RuntimeError ( "`git` does not appear to be working" ) from e
return func ( * args , ** kwargs )
return decorated |
def _load_lines ( self , filename , line_generator , suite , rules ) :
"""Load a suite with lines produced by the line generator .""" | line_counter = 0
for line in line_generator :
line_counter += 1
if line . category in self . ignored_lines :
continue
if line . category == "test" :
suite . addTest ( Adapter ( filename , line ) )
rules . saw_test ( )
elif line . category == "plan" :
if line . skip :
... |
def is_non_segregating ( self , allele = None ) :
"""Find non - segregating variants ( where at most one allele is
observed ) .
Parameters
allele : int , optional
Allele index .
Returns
out : ndarray , bool , shape ( n _ variants , )
Boolean array where elements are True if variant matches the
condi... | if allele is None :
return self . allelism ( ) <= 1
else :
return ( self . allelism ( ) == 1 ) & ( self . values [ : , allele ] > 0 ) |
def fill_addressfields ( self , row , obj ) :
"""Fills the address fields for the specified object if allowed :
PhysicalAddress , PostalAddress , CountryState , BillingAddress""" | addresses = { }
for add_type in [ 'Physical' , 'Postal' , 'Billing' , 'CountryState' ] :
addresses [ add_type ] = { }
for key in [ 'Address' , 'City' , 'State' , 'District' , 'Zip' , 'Country' ] :
addresses [ add_type ] [ key . lower ( ) ] = str ( row . get ( "%s_%s" % ( add_type , key ) , '' ) )
if add... |
def get_relay_ip_list ( server = _DEFAULT_SERVER ) :
'''Get the RelayIpList list for the SMTP virtual server .
: param str server : The SMTP server name .
: return : A list of the relay IPs .
: rtype : list
. . note : :
A return value of None corresponds to the restrictive ' Only the list below ' GUI para... | ret = list ( )
setting = 'RelayIpList'
lines = _get_wmi_setting ( 'IIsSmtpServerSetting' , setting , server )
if not lines :
_LOG . debug ( '%s is empty: %s' , setting , lines )
if lines is None :
lines = [ None ]
return list ( lines )
# WMI returns the addresses as a tuple of individual octets , so... |
def block_sep1 ( self , Y ) :
r"""Separate variable into component corresponding to
: math : ` \ mathbf { y } _ 1 ` in : math : ` \ mathbf { y } \ ; \ ; ` .""" | return Y [ ( slice ( None ) , ) * self . blkaxis + ( slice ( self . blkidx , None ) , ) ] |
def _fix_slice ( self , inputs , new_attr ) :
"""onnx slice provides slicing on multiple axis . Adding multiple slice _ axis operator
for multiple axes from mxnet""" | begin = new_attr . get ( 'begin' )
end = new_attr . get ( 'end' )
axes = new_attr . get ( 'axis' , tuple ( range ( len ( begin ) ) ) )
slice_op = mx . sym . slice_axis ( inputs [ 0 ] , axis = axes [ 0 ] , begin = begin [ 0 ] , end = end [ 0 ] )
if len ( axes ) > 1 :
for i , axis in enumerate ( axes ) :
slic... |
def write ( self , fitsname = None , wcs = None , archive = True , overwrite = False , quiet = True ) :
"""Write out the values of the WCS keywords to the
specified image .
If it is a GEIS image and ' fitsname ' has been provided ,
it will automatically make a multi - extension
FITS copy of the GEIS and upd... | # # Start by making sure all derived values are in sync with CD matrix
self . update ( )
image = self . rootname
_fitsname = fitsname
if image . find ( '.fits' ) < 0 and _fitsname is not None : # A non - FITS image was provided , and openImage made a copy
# Update attributes to point to new copy instead
self . geis... |
def day_to_month ( timeperiod ) :
""": param timeperiod : as string in YYYYMMDD00 format
: return string in YYYYMM0000 format""" | t = datetime . strptime ( timeperiod , SYNERGY_DAILY_PATTERN )
return t . strftime ( SYNERGY_MONTHLY_PATTERN ) |
def filter ( self , nodes ) :
"""Returns a new DAG with only the given nodes and their
dependencies .
Args :
nodes ( list ) : The nodes you are interested in .
Returns :
: class : ` stacker . dag . DAG ` : The filtered graph .""" | filtered_dag = DAG ( )
# Add only the nodes we need .
for node in nodes :
filtered_dag . add_node_if_not_exists ( node )
for edge in self . all_downstreams ( node ) :
filtered_dag . add_node_if_not_exists ( edge )
# Now , rebuild the graph for each node that ' s present .
for node , edges in self . grap... |
def request_connect ( self , act , coro ) :
"Requests a connect for ` coro ` corutine with parameters and completion \
passed via ` act `" | result = self . try_run_act ( act , perform_connect )
if result :
return result , coro
else :
self . add_token ( act , coro , perform_connect ) |
def create_state_model_for_state ( new_state , meta , state_element_models ) :
"""Create a new state model with the defined properties
A state model is created for a state of the type of new _ state . All child models in state _ element _ models (
model list for port , connections and states ) are added to the ... | from rafcon . gui . models . abstract_state import get_state_model_class_for_state
state_m_class = get_state_model_class_for_state ( new_state )
new_state_m = state_m_class ( new_state , meta = meta , load_meta_data = False , expected_future_models = state_element_models )
error_msg = "New state has not re-used all han... |
def parse_localinstancepath ( parser , event , node ) :
"""Parse LOCALINSTANCEPATH element returning instancename
< ! ELEMENT LOCALINSTANCEPATH ( LOCALNAMESPACEPATH , INSTANCENAME ) >""" | # pylint : disable = unused - argument
( next_event , next_node ) = six . next ( parser )
if not _is_start ( next_event , next_node , 'LOCALNAMESPACEPATH' ) :
raise ParseError ( 'Expecting LOCALNAMESPACEPATH' )
namespacepath = parse_localnamespacepath ( parser , next_event , next_node )
( next_event , next_node ) =... |
def _fetch_templates ( src ) :
'''Fetch all of the templates in the src directory
: param src : The source path
: type src : ` ` str ` `
: rtype : ` ` list ` ` of ` ` tuple ` `
: returns : ` ` list ` ` of ( ' key ' , ' description ' )''' | templates = [ ]
log . debug ( 'Listing contents of %s' , src )
for item in os . listdir ( src ) :
s = os . path . join ( src , item )
if os . path . isdir ( s ) :
template_path = os . path . join ( s , TEMPLATE_FILE_NAME )
if os . path . isfile ( template_path ) :
templates . append ... |
def quick_response ( self , status_code ) :
"""Quickly construct response using a status code""" | translator = Translator ( environ = self . environ )
if status_code == 404 :
self . status ( 404 )
self . message ( translator . trans ( 'http_messages.404' ) )
elif status_code == 401 :
self . status ( 401 )
self . message ( translator . trans ( 'http_messages.401' ) )
elif status_code == 400 :
sel... |
def get_point_model ( cls ) :
"""Returns plugin point model instance . Only used from plugin classes .""" | if is_plugin_point ( cls ) :
raise Exception ( _ ( 'This method is only available to plugin ' 'classes.' ) )
else :
return PluginPointModel . objects . get ( plugin__pythonpath = cls . get_pythonpath ( ) ) |
def detail_action ( ** kwargs ) :
"""Used to mark a method on a ResourceBinding that should be routed for detail actions .""" | def decorator ( func ) :
func . action = True
func . detail = True
func . kwargs = kwargs
return func
return decorator |
def indent_func ( input_ ) :
"""Takes either no arguments or an alias label""" | if isinstance ( input_ , six . string_types ) : # A label was specified
lbl = input_
return _indent_decor ( lbl )
elif isinstance ( input_ , ( bool , tuple ) ) : # Allow individually turning of of this decorator
func = input_
return func
else : # Use the function name as the label
func = input_
... |
def floyd_warshall_get_path ( self , distance , nextn , i , j ) :
'''API :
floyd _ warshall _ get _ path ( self , distance , nextn , i , j ) :
Description :
Finds shortest path between i and j using distance and nextn
dictionaries .
Pre :
(1 ) distance and nextn are outputs of floyd _ warshall method . ... | if distance [ ( i , j ) ] == 'infinity' :
return None
k = nextn [ ( i , j ) ]
path = self . floyd_warshall_get_path
if i == k :
return [ i , j ]
else :
return path ( distance , nextn , i , k ) + [ k ] + path ( distance , nextn , k , j ) |
def submit ( self , fn , * args , ** kwargs ) :
"""Internal""" | if not self . is_shutdown :
return self . cluster . executor . submit ( fn , * args , ** kwargs ) |
def add_section ( self , section_name : str ) -> None :
"""Add a section to the : class : ` SampleSheet ` .""" | section_name = self . _whitespace_re . sub ( '_' , section_name )
self . _sections . append ( section_name )
setattr ( self , section_name , Section ( ) ) |
async def get_setting ( self , service : str , method : str , target : str ) :
"""Get a single setting for service .
: param service : Service to query .
: param method : Getter method for the setting , read from ApiMapping .
: param target : Setting to query .
: return : JSON response from the device .""" | return await self . services [ service ] [ method ] ( target = target ) |
def pull ( self , remote , branch = None ) :
'''Pull a repository
: param remote : git - remote instance
: param branch : name of the branch to pull''' | pb = ProgressBar ( )
pb . setup ( self . name )
if branch :
remote . pull ( branch , progress = pb )
else : # pragma : no cover
remote . pull ( progress = pb )
print ( ) |
def is_dict_like ( obj , attr = ( 'keys' , 'items' ) ) :
"""test if object is dict like""" | for a in attr :
if not hasattr ( obj , a ) :
return False
return True |
def otp ( scope , password , seed , seqs ) :
"""Calculates a one - time password hash using the given password , seed , and
sequence number and returns it .
Uses the md4 / sixword algorithm as supported by TACACS + servers .
: type password : string
: param password : A password .
: type seed : string
:... | return [ crypt . otp ( password [ 0 ] , seed [ 0 ] , int ( seq ) ) for seq in seqs ] |
def setDataFrame ( self , dataFrame ) :
"""setter function to _ dataFrame . Holds all data .
Note :
It ' s not implemented with python properties to keep Qt conventions .
Raises :
TypeError : if dataFrame is not of type pandas . core . frame . DataFrame .
Args :
dataFrame ( pandas . core . frame . DataF... | if not isinstance ( dataFrame , pandas . core . frame . DataFrame ) :
raise TypeError ( 'Argument is not of type pandas.core.frame.DataFrame' )
self . layoutAboutToBeChanged . emit ( )
self . _dataFrame = dataFrame
self . layoutChanged . emit ( ) |
def references_json_authors ( ref_authors , ref_content ) :
"build the authors for references json here for testability" | all_authors = references_authors ( ref_authors )
if all_authors != { } :
if ref_content . get ( "type" ) in [ "conference-proceeding" , "journal" , "other" , "periodical" , "preprint" , "report" , "web" ] :
for author_type in [ "authors" , "authorsEtAl" ] :
set_if_value ( ref_content , author_ty... |
def close ( self ) :
"""Flushes the pending events and closes the writer after it is done .""" | self . flush ( )
if self . _recordio_writer is not None :
self . _recordio_writer . close ( )
self . _recordio_writer = None |
def get_asset_id_by_label ( self , label ) :
"""stub""" | if self . has_file ( label ) :
return Id ( self . my_osid_object . _my_map [ 'fileIds' ] [ label ] [ 'assetId' ] )
raise IllegalState ( ) |
def maxwellian ( E : np . ndarray , E0 : np . ndarray , Q0 : np . ndarray ) -> Tuple [ np . ndarray , float ] :
"""input :
E : 1 - D vector of energy bins [ eV ]
E0 : characteristic energy ( scalar or vector ) [ eV ]
Q0 : flux coefficient ( scalar or vector ) ( to yield overall flux Q )
output :
Phi : dif... | E0 = np . atleast_1d ( E0 )
Q0 = np . atleast_1d ( Q0 )
assert E0 . ndim == Q0 . ndim == 1
assert ( Q0 . size == 1 or Q0 . size == E0 . size )
Phi = Q0 / ( 2 * pi * E0 ** 3 ) * E [ : , None ] * np . exp ( - E [ : , None ] / E0 )
Q = np . trapz ( Phi , E , axis = 0 )
logging . info ( 'total maxwellian flux Q: ' + ( ' ' ... |
def execute_command ( parser , config , ext_classes ) :
"""Banana banana""" | res = 0
cmd = config . get ( 'command' )
get_private_folder = config . get ( 'get_private_folder' , False )
if cmd == 'help' :
parser . print_help ( )
elif cmd == 'run' or get_private_folder : # git . mk backward compat
app = Application ( ext_classes )
try :
app . parse_config ( config )
if... |
def raw_input ( prompt = "" ) :
"""raw _ input ( [ prompt ] ) - > string
Read a string from standard input . The trailing newline is stripped .
If the user hits EOF ( Unix : Ctl - D , Windows : Ctl - Z + Return ) , raise EOFError .
On Unix , GNU readline is used if enabled . The prompt string , if given ,
i... | sys . stderr . flush ( )
tty = STDIN . is_a_TTY ( ) and STDOUT . is_a_TTY ( )
if RETURN_UNICODE :
if tty :
line_bytes = readline ( prompt )
line = stdin_decode ( line_bytes )
else :
line = stdio_readline ( prompt )
else :
if tty :
line = readline ( prompt )
else :
... |
def plot_arai_zij ( ZED , araiblock , zijdblock , s , units ) :
"""calls the four plotting programs for Thellier - Thellier experiments
Parameters
_ _ _ _ _
ZED : dictionary with plotting figure keys :
deremag : figure for de ( re ) magnezation plots
arai : figure for the Arai diagram
eqarea : equal are... | angle = zijdblock [ 0 ] [ 1 ]
norm = 1
if units == "U" :
norm = 0
plot_arai ( ZED [ 'arai' ] , araiblock , s , units )
plot_teq ( ZED [ 'eqarea' ] , araiblock , s , "" )
plot_zij ( ZED [ 'zijd' ] , zijdblock , angle , s , norm )
plot_np ( ZED [ 'deremag' ] , araiblock , s , units )
return ZED |
def unwrap_synchro ( fn ) :
"""Unwrap Synchro objects passed to a method and pass Motor objects instead .""" | @ functools . wraps ( fn )
def _unwrap_synchro ( * args , ** kwargs ) :
def _unwrap_obj ( obj ) :
if isinstance ( obj , Synchro ) :
return obj . delegate
else :
return obj
args = [ _unwrap_obj ( arg ) for arg in args ]
kwargs = dict ( [ ( key , _unwrap_obj ( value ) )... |
def close_all ( ) :
r"""Close all opened windows .""" | # Windows can be closed by releasing all references to them so they can be
# garbage collected . May not be necessary to call close ( ) .
global _qtg_windows
for window in _qtg_windows :
window . close ( )
_qtg_windows = [ ]
global _qtg_widgets
for widget in _qtg_widgets :
widget . close ( )
_qtg_widgets = [ ]
... |
def main ( ) :
"""Parse the args and call whatever function was selected""" | args = parser . parse_args ( )
try :
function = args . func
except AttributeError :
parser . print_usage ( )
parser . exit ( 1 )
function ( vars ( args ) ) |
def quil_to_program ( quil : str ) -> Program :
"""Parse a quil program and return a Program object""" | pyquil_instructions = pyquil . parser . parse ( quil )
return pyquil_to_program ( pyquil_instructions ) |
def get_item_type ( self , ttype ) :
"""Get a particular item type
: param ttype : a string which represents the desired type
: rtype : None or the item object""" | for i in self . map_item :
if TYPE_MAP_ITEM [ i . get_type ( ) ] == ttype :
return i . get_item ( )
return None |
def calibrate ( self , dataset_id , pre_launch_coeffs = False , calib_coeffs = None ) :
"""Calibrate the data""" | tic = datetime . now ( )
if calib_coeffs is None :
calib_coeffs = { }
units = { 'reflectance' : '%' , 'brightness_temperature' : 'K' , 'counts' : '' , 'radiance' : 'W*m-2*sr-1*cm ?' }
if dataset_id . name in ( "3a" , "3b" ) and self . _is3b is None : # Is it 3a or 3b :
is3b = np . expand_dims ( np . bitwise_and... |
def add_record ( self , record ) :
"""Add or update a given DNS record""" | rec = self . get_record ( record . _record_type , record . host )
if rec :
rec = record
for i , r in enumerate ( self . _entries ) :
if r . _record_type == record . _record_type and r . host == record . host :
self . _entries [ i ] = record
else :
self . _entries . append ( record )
self... |
def _simple_chinese_to_bool ( text : str ) -> Optional [ bool ] :
"""Convert a chinese text to boolean .
Examples :
是的 - > True
好的呀 - > True
不要 - > False
不用了 - > False
你好呀 - > None""" | text = text . strip ( ) . lower ( ) . replace ( ' ' , '' ) . rstrip ( ',.!?~,。!?~了的呢吧呀啊呗啦' )
if text in { '要' , '用' , '是' , '好' , '对' , '嗯' , '行' , 'ok' , 'okay' , 'yeah' , 'yep' , '当真' , '当然' , '必须' , '可以' , '肯定' , '没错' , '确定' , '确认' } :
return True
if text in { '不' , '不要' , '不用' , '不是' , '否' , '不好' , '不对' , '不行' ... |
def _flush ( self ) :
"""Flush the write buffers of the stream .""" | # Upload segment with workers
name = self . _segment_name % self . _seek
response = self . _workers . submit ( self . _client . put_object , self . _container , name , self . _get_buffer ( ) )
# Save segment information in manifest
self . _write_futures . append ( dict ( etag = response , path = '/' . join ( ( self . _... |
def scan ( node , env , libpath = ( ) ) :
"""This scanner scans program files for static - library
dependencies . It will search the LIBPATH environment variable
for libraries specified in the LIBS variable , returning any
files it finds as dependencies .""" | try :
libs = env [ 'LIBS' ]
except KeyError : # There are no LIBS in this environment , so just return a null list :
return [ ]
libs = _subst_libs ( env , libs )
try :
prefix = env [ 'LIBPREFIXES' ]
if not SCons . Util . is_List ( prefix ) :
prefix = [ prefix ]
except KeyError :
prefix = [ '... |
def draw_visual ( self , visual , event = None ) :
"""Draw a visual and its children to the canvas or currently active
framebuffer .
Parameters
visual : Visual
The visual to draw
event : None or DrawEvent
Optionally specifies the original canvas draw event that initiated
this draw .""" | prof = Profiler ( )
# make sure this canvas ' s context is active
self . set_current ( )
try :
self . _drawing = True
# get order to draw visuals
if visual not in self . _draw_order :
self . _draw_order [ visual ] = self . _generate_draw_order ( )
order = self . _draw_order [ visual ]
# draw... |
def sign_create_cancellation ( cancellation_params , key_pair ) :
"""Function to sign the parameters required to create a cancellation request from the Switcheo Exchange .
Execution of this function is as follows : :
sign _ create _ cancellation ( cancellation _ params = signable _ params , key _ pair = key _ p... | encoded_message = encode_message ( cancellation_params )
create_params = cancellation_params . copy ( )
create_params [ 'address' ] = neo_get_scripthash_from_private_key ( private_key = key_pair . PrivateKey ) . ToString ( )
create_params [ 'signature' ] = sign_message ( encoded_message = encoded_message , private_key_... |
def download_sync ( self , remote_path , local_path , callback = None ) :
"""Downloads remote resources from WebDAV server synchronously .
: param remote _ path : the path to remote resource on WebDAV server . Can be file and directory .
: param local _ path : the path to save resource locally .
: param callb... | self . download ( local_path = local_path , remote_path = remote_path )
if callback :
callback ( ) |
def _drop_axis ( self , labels , axis , level = None , errors = 'raise' ) :
"""Drop labels from specified axis . Used in the ` ` drop ` ` method
internally .
Parameters
labels : single label or list - like
axis : int or axis name
level : int or level name , default None
For MultiIndex
errors : { ' ign... | axis = self . _get_axis_number ( axis )
axis_name = self . _get_axis_name ( axis )
axis = self . _get_axis ( axis )
if axis . is_unique :
if level is not None :
if not isinstance ( axis , MultiIndex ) :
raise AssertionError ( 'axis must be a MultiIndex' )
new_axis = axis . drop ( labels ... |
def word_at_position ( self , position ) :
"""Get the word under the cursor returning the start and end positions .""" | if position [ 'line' ] >= len ( self . lines ) :
return ''
line = self . lines [ position [ 'line' ] ]
i = position [ 'character' ]
# Split word in two
start = line [ : i ]
end = line [ i : ]
# Take end of start and start of end to find word
# These are guaranteed to match , even if they match the empty string
m_st... |
def start ( self ) :
"""Starts this UdpTelemetryServer .""" | values = self . _defn . name , self . server_host , self . server_port
log . info ( 'Listening for %s telemetry on %s:%d (UDP)' % values )
super ( UdpTelemetryServer , self ) . start ( ) |
def read ( self , size ) :
"""Read the first ' size ' bytes in packet and advance cursor past them .""" | result = self . _data [ self . _position : ( self . _position + size ) ]
if len ( result ) != size :
error = ( 'Result length not requested length:\n' 'Expected=%s. Actual=%s. Position: %s. Data Length: %s' % ( size , len ( result ) , self . _position , len ( self . _data ) ) )
if DEBUG :
print ( err... |
def import_context ( cls , context ) :
"""Import context to corresponding WContextProto object ( : meth : ` WContext . export _ context ` reverse operation )
: param context : context to import
: return : WContext""" | if context is None or len ( context ) == 0 :
return
result = WContext ( context [ 0 ] [ 0 ] , context [ 0 ] [ 1 ] )
for iter_context in context [ 1 : ] :
result = WContext ( iter_context [ 0 ] , context_value = iter_context [ 1 ] , linked_context = result )
return result |
def get_event_q ( self , event_name ) :
"""Obtain the queue storing events of the specified name .
If no event of this name has been polled , wait for one to .
Returns :
A queue storing all the events of the specified name .
None if timed out .
Raises :
queue . Empty : Raised if the queue does not exist... | self . lock . acquire ( )
if not event_name in self . event_dict or self . event_dict [ event_name ] is None :
self . event_dict [ event_name ] = queue . Queue ( )
self . lock . release ( )
event_queue = self . event_dict [ event_name ]
return event_queue |
def _send_notification ( self , handle , value ) :
"""Send a notification to all connected clients on a characteristic
Args :
handle ( int ) : The handle we wish to notify on
value ( bytearray ) : The value we wish to send""" | value_len = len ( value )
value = bytes ( value )
payload = struct . pack ( "<BHB%ds" % value_len , 0xFF , handle , value_len , value )
response = self . _send_command ( 2 , 5 , payload )
result , = unpack ( "<H" , response . payload )
if result != 0 :
return False , { 'reason' : 'Error code from BLED112 notifying ... |
def main ( args = None ) :
"""Start application .""" | Config . options , Config . args = parse ( args )
logger ( )
if Config . options . aeidon or Config . options . fix :
start_aeidon ( )
else :
start_srt ( )
if Config . options . fix :
sys . exit ( 0 )
if not Config . results :
basenames = [ os . path . basename ( os . path . abspath ( x ) ) for x in Con... |
def dial ( self , target ) :
'''connects to a node
: param url : string ( optional ) - resource in which to connect .
if not provided , will use default for the stage
: returns : provider , error''' | if not target :
return None , "target network must be specified with -t or --target"
url = get_url ( self . config , target )
try :
if url . startswith ( 'ws' ) :
self . w3 = Web3 ( WebsocketProvider ( url ) )
elif url . startswith ( 'http' ) :
self . w3 = Web3 ( HTTPProvider ( url ) )
e... |
def write_file ( self , file , verbose = False ) :
"""Collect the data from get _ midi _ data and write to file .""" | dat = self . get_midi_data ( )
try :
f = open ( file , 'wb' )
except :
print "Couldn't open '%s' for writing." % file
return False
try :
f . write ( dat )
except :
print 'An error occured while writing data to %s.' % file
return False
f . close ( )
if verbose :
print 'Written %d bytes to %s.... |
def resolve_and_build ( self ) :
"""resolves the dependencies of this build target and builds it""" | pdebug ( "resolving and building task '%s'" % self . name , groups = [ "build_task" ] )
indent_text ( indent = "++2" )
toret = self . build ( ** self . resolve_dependencies ( ) )
indent_text ( indent = "--2" )
return toret |
def updateResultsView ( self , index ) :
"""Update the selection to contain only the result specified by
the index . This should be the last index of the model . Finally updade
the context menu .
The selectionChanged signal is used to trigger the update of
the Quanty dock widget and result details dialog . ... | flags = ( QItemSelectionModel . Clear | QItemSelectionModel . Rows | QItemSelectionModel . Select )
self . resultsView . selectionModel ( ) . select ( index , flags )
self . resultsView . resizeColumnsToContents ( )
self . resultsView . setFocus ( ) |
def processData ( config , stats ) :
"""Collate the stats and report""" | if 'total_time' not in stats or 'total_clock' not in stats : # toil job not finished yet
stats . total_time = [ 0.0 ]
stats . total_clock = [ 0.0 ]
stats . total_time = sum ( [ float ( number ) for number in stats . total_time ] )
stats . total_clock = sum ( [ float ( number ) for number in stats . total_clock ... |
def add ( self , func , position ) :
"""Adds all 8 cardinal directions as moves for the King if legal .
: type : function : function
: type : position : Board
: rtype : gen""" | try :
if self . loc_adjacent_to_opponent_king ( func ( self . location ) , position ) :
return
except IndexError :
return
if position . is_square_empty ( func ( self . location ) ) :
yield self . create_move ( func ( self . location ) , notation_const . MOVEMENT )
elif position . piece_at_square ( f... |
def wirevector_subset ( self , cls = None , exclude = tuple ( ) ) :
"""Return set of wirevectors , filtered by the type or tuple of types provided as cls .
If no cls is specified , the full set of wirevectors associated with the Block are
returned . If cls is a single type , or a tuple of types , only those wir... | if cls is None :
initial_set = self . wirevector_set
else :
initial_set = ( x for x in self . wirevector_set if isinstance ( x , cls ) )
if exclude == tuple ( ) :
return set ( initial_set )
else :
return set ( x for x in initial_set if not isinstance ( x , exclude ) ) |
def record_absent ( name , zone , type , data , profile ) :
'''Ensures a record is absent .
: param name : Record name without the domain name ( e . g . www ) .
Note : If you want to create a record for a base domain
name , you should specify empty string ( ' ' ) for this
argument .
: type name : ` ` str ... | zones = __salt__ [ 'libcloud_dns.list_zones' ] ( profile )
try :
matching_zone = [ z for z in zones if z [ 'domain' ] == zone ] [ 0 ]
except IndexError :
return state_result ( False , 'Zone could not be found' , name )
records = __salt__ [ 'libcloud_dns.list_records' ] ( matching_zone [ 'id' ] , profile )
match... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.