signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def eval ( self , key , default = None , loc = None , correct_key = True ) :
"""Evaluates and sets the specified option value in
environment ` loc ` . Many options need ` ` N ` ` to be defined in
` loc ` , some need ` popsize ` .
Details
Keys that contain ' filename ' are not evaluated .
For ` loc ` is No... | # TODO : try : loc [ ' dim ' ] = loc [ ' N ' ] etc
if correct_key : # in _ key = key # for debugging only
key = self . corrected_key ( key )
self [ key ] = self ( key , default , loc )
return self [ key ] |
def remove_vectored_io_slice_suffix_from_name ( name , slice ) : # type : ( str , int ) - > str
"""Remove vectored io ( stripe ) slice suffix from a given name
: param str name : entity name
: param int slice : slice num
: rtype : str
: return : name without suffix""" | suffix = '.bxslice-{}' . format ( slice )
if name . endswith ( suffix ) :
return name [ : - len ( suffix ) ]
else :
return name |
def register ( self , new_calc , * args , ** kwargs ) :
"""Register calculations and meta data .
* ` ` dependencies ` ` - list of prerequisite calculations
* ` ` always _ calc ` ` - ` ` True ` ` if calculation ignores thresholds
* ` ` frequency ` ` - frequency of calculation in intervals or units of time
: ... | kwargs . update ( zip ( self . meta_names , args ) )
# dependencies should be a list of other calculations
if isinstance ( kwargs [ 'dependencies' ] , basestring ) :
kwargs [ 'dependencies' ] = [ kwargs [ 'dependencies' ] ]
# call super method , now meta can be passed as args or kwargs .
super ( CalcRegistry , self... |
def stack_files ( files , hemi , source , target ) :
"""This function takes a list of files as input and vstacks them""" | import csv
import os
import numpy as np
fname = "sdist_%s_%s_%s.csv" % ( hemi , source , target )
filename = os . path . join ( os . getcwd ( ) , fname )
alldist = [ ]
for dfile in files :
alldist . append ( np . genfromtxt ( dfile , delimiter = ',' ) )
alldist = np . array ( alldist )
alldist . tofile ( filename ,... |
def UsersChangePassword ( self , current_password , new_password ) :
"""Change the password for the current user
@ param current _ password ( string ) - md5 hash of the current password of the user
@ param new _ password ( string ) - md5 hash of the new password of the user ( make sure to doublecheck ! )
@ re... | if self . __SenseApiCall__ ( '/change_password' , "POST" , { "current_password" : current_password , "new_password" : new_password } ) :
return True
else :
self . __error__ = "api call unsuccessful"
return False |
def point_in_tetrahedron ( tetra , pt ) :
'''point _ in _ tetrahedron ( tetrahedron , point ) yields True if the given point is in the given
tetrahedron . If either tetrahedron or point ( or both ) are lists of shapes / points , then this
calculation is automatically threaded over all the given arguments .''' | bcs = tetrahedral_barycentric_coordinates ( tetra , pt )
return np . logical_not ( np . all ( np . isclose ( bcs , 0 ) , axis = 0 ) ) |
def team_info ( ) :
"""Returns a list of team information dictionaries""" | teams = __get_league_object ( ) . find ( 'teams' ) . findall ( 'team' )
output = [ ]
for team in teams :
info = { }
for x in team . attrib :
info [ x ] = team . attrib [ x ]
output . append ( info )
return output |
def add_key ( self , key , metadata = "" ) :
"""Add a canned key
: type key : str
: param key : New canned key
: type metadata : str
: param metadata : Optional metadata
: rtype : dict
: return : A dictionnary containing canned key description""" | data = { 'key' : key , 'metadata' : metadata }
return self . post ( 'createKey' , data ) |
def get_account_db_class ( cls ) -> Type [ BaseAccountDB ] :
"""Return the : class : ` ~ eth . db . account . BaseAccountDB ` class that the
state class uses .""" | if cls . account_db_class is None :
raise AttributeError ( "No account_db_class set for {0}" . format ( cls . __name__ ) )
return cls . account_db_class |
def _add_to_tree ( tree , word , meaning ) :
'''We build word search trees , where we walk down
the letters of a word . For example :
你 Good
你好 Hello
Would build the tree
/ You 好
Hello''' | if len ( word ) == 0 :
tree [ '' ] = meaning
else :
_add_to_tree ( tree [ word [ 0 ] ] , word [ 1 : ] , meaning ) |
def encode ( self ) :
"""Returns binary string representation of this struct .
: returns : Structure encoded as binary string for keepass database .
: rtype : bytes""" | ret = bytearray ( )
for name , len , typecode in self . format :
value = getattr ( self , name )
buf = struct . pack ( '<' + typecode , value )
ret . extend ( buf )
return bytes ( ret ) |
def get_data ( city : Optional [ str ] ) -> Dict [ str , Any ] :
"""Use the Yahoo weather API to get weather information""" | req = urllib . request . Request ( get_url ( city ) )
with urllib . request . urlopen ( req ) as f :
response = f . read ( )
answer = response . decode ( 'ascii' )
data = json . loads ( answer )
r = data [ 'query' ] [ 'results' ] [ 'channel' ]
# Remove some useless nesting
return r |
def _fluent_params ( self , fluents , ordering ) -> FluentParamsList :
'''Returns the instantiated ` fluents ` for the given ` ordering ` .
For each fluent in ` fluents ` , it instantiates each parameter
type w . r . t . the contents of the object table .
Returns :
Sequence [ Tuple [ str , List [ str ] ] ] ... | variables = [ ]
for fluent_id in ordering :
fluent = fluents [ fluent_id ]
param_types = fluent . param_types
objects = ( )
names = [ ]
if param_types is None :
names = [ fluent . name ]
else :
objects = tuple ( self . object_table [ ptype ] [ 'objects' ] for ptype in param_types... |
def resources ( self ) :
'''get total resources and available ones''' | used_resources = self . _used_resources ( )
ret = collections . defaultdict ( dict )
for resource , total in six . iteritems ( self . _resources ) :
ret [ resource ] [ 'total' ] = total
if resource in used_resources :
ret [ resource ] [ 'used' ] = used_resources [ resource ]
else :
ret [ res... |
def highlightBlock ( self , string ) :
"""Highlight a block of text .""" | prev_data = self . currentBlock ( ) . previous ( ) . userData ( )
if prev_data is not None :
self . _lexer . _saved_state_stack = prev_data . syntax_stack
elif hasattr ( self . _lexer , '_saved_state_stack' ) :
del self . _lexer . _saved_state_stack
# Lex the text using Pygments
index = 0
for token , text in se... |
def SearchSeasonDirTable ( self , showID , seasonNum ) :
"""Search SeasonDir table .
Find the season directory for a given show id and season combination .
Parameters
showID : int
Show id for given show .
seasonNum : int
Season number .
Returns
string or None
If no match is found this returns None... | goodlogging . Log . Info ( "DB" , "Looking up directory for ShowID={0} Season={1} in database" . format ( showID , seasonNum ) , verbosity = self . logVerbosity )
queryString = "SELECT SeasonDir FROM SeasonDir WHERE ShowID=? AND Season=?"
queryTuple = ( showID , seasonNum )
result = self . _ActionDatabase ( queryString... |
def get_assessment_part_form_for_create_for_assessment ( self , assessment_id , assessment_part_record_types ) :
"""Gets the assessment part form for creating new assessment parts for an assessment .
A new form should be requested for each create transaction .
arg : assessment _ id ( osid . id . Id ) : an asses... | # Implemented from template for
# osid . learning . ActivityAdminSession . get _ activity _ form _ for _ create _ template
if not isinstance ( assessment_id , ABCId ) :
raise errors . InvalidArgument ( 'argument is not a valid OSID Id' )
for arg in assessment_part_record_types :
if not isinstance ( arg , ABCTyp... |
def groupByNode ( requestContext , seriesList , nodeNum , callback ) :
"""Takes a serieslist and maps a callback to subgroups within as defined by a
common node .
Example : :
& target = groupByNode ( ganglia . by - function . * . * . cpu . load5,2 , " sumSeries " )
Would return multiple series which are eac... | return groupByNodes ( requestContext , seriesList , callback , nodeNum ) |
def create_box ( width = 1 , height = 1 , depth = 1 , width_segments = 1 , height_segments = 1 , depth_segments = 1 , planes = None ) :
"""Generate vertices & indices for a filled and outlined box .
Parameters
width : float
Box width .
height : float
Box height .
depth : float
Box depth .
width _ se... | planes = ( ( '+x' , '-x' , '+y' , '-y' , '+z' , '-z' ) if planes is None else [ d . lower ( ) for d in planes ] )
w_s , h_s , d_s = width_segments , height_segments , depth_segments
planes_m = [ ]
if '-z' in planes :
planes_m . append ( create_plane ( width , depth , w_s , d_s , '-z' ) )
planes_m [ - 1 ] [ 0 ] ... |
def read_hyperparameters ( ) : # type : ( ) - > dict
"""Read the hyperparameters from / opt / ml / input / config / hyperparameters . json .
For more information about hyperparameters . json :
https : / / docs . aws . amazon . com / sagemaker / latest / dg / your - algorithms - training - algo . html # your - a... | hyperparameters = _read_json ( hyperparameters_file_dir )
deserialized_hps = { }
for k , v in hyperparameters . items ( ) :
try :
v = json . loads ( v )
except ( ValueError , TypeError ) :
logger . info ( "Failed to parse hyperparameter %s value %s to Json.\n" "Returning the value itself" , k , ... |
def _iter_grouped ( self ) :
"""Iterate over each element in this group""" | for indices in self . _group_indices :
yield self . _obj . isel ( ** { self . _group_dim : indices } ) |
def append_unreleased_entries ( app , manager , releases ) :
"""Generate new abstract ' releases ' for unreleased issues .
There ' s one for each combination of bug - vs - feature & major release line .
When only one major release line exists , that dimension is ignored .""" | for family , lines in six . iteritems ( manager ) :
for type_ in ( 'bugfix' , 'feature' ) :
bucket = 'unreleased_{}' . format ( type_ )
if bucket not in lines : # Implies unstable prehistory + 0 . x fam
continue
issues = lines [ bucket ]
fam_prefix = "{}.x " . format ( fa... |
def find_difference_contour ( self ) :
"""Find the ratio and loss / gain contours .
This method finds the ratio contour and the Loss / Gain contour values .
Its inputs are the two datasets for comparison where the second is the control
to compare against the first .
The input data sets need to be the same s... | # set contour to test and control contour
self . ratio_comp_value = ( self . comparison_value if self . ratio_comp_value is None else self . ratio_comp_value )
# indices of loss , gained .
inds_gained = np . where ( ( self . comp1 >= self . comparison_value ) & ( self . comp2 < self . comparison_value ) )
inds_lost = n... |
def upload_file ( fapi , file_name , conf ) :
"""Uploads a file to smartling""" | if not conf . has_key ( 'file-type' ) :
raise SmarterlingError ( "%s doesn't have a file-type" % file_name )
print ( "Uploading %s to smartling" % file_name )
data = UploadData ( os . path . dirname ( file_name ) + os . sep , os . path . basename ( file_name ) , conf . get ( 'file-type' ) )
data . setUri ( file_uri... |
def copy_from_local ( self , localsrc , dest , ** kwargs ) :
"""Copy a single file from the local file system to ` ` dest ` `
Takes all arguments that : py : meth : ` create ` takes .""" | with io . open ( localsrc , 'rb' ) as f :
self . create ( dest , f , ** kwargs ) |
def create ( self , order_increment_id , items_qty , comment = None , email = True , include_comment = False ) :
"""Create new shipment for order
: param order _ increment _ id : Order Increment ID
: type order _ increment _ id : str
: param items _ qty : items qty to ship
: type items _ qty : associative a... | if comment is None :
comment = ''
return self . call ( 'sales_order_shipment.create' , [ order_increment_id , items_qty , comment , email , include_comment ] ) |
def _run_bookkeeping_sql_scripts ( self ) :
"""* run bookkeeping sql scripts *""" | self . log . info ( 'starting the ``_run_bookkeeping_sql_scripts`` method' )
moduleDirectory = os . path . dirname ( __file__ )
mysqlScripts = moduleDirectory + "/mysql"
directory_script_runner ( log = self . log , pathToScriptDirectory = mysqlScripts , databaseName = self . settings [ "database settings" ] [ "atlasMov... |
def _handle_clear ( self , load ) :
'''Process a cleartext command
: param dict load : Cleartext payload
: return : The result of passing the load to a function in ClearFuncs corresponding to
the command specified in the load ' s ' cmd ' key .''' | log . trace ( 'Clear payload received with command %s' , load [ 'cmd' ] )
cmd = load [ 'cmd' ]
if cmd . startswith ( '__' ) :
return False
if self . opts [ 'master_stats' ] :
start = time . time ( )
ret = getattr ( self . clear_funcs , cmd ) ( load ) , { 'fun' : 'send_clear' }
if self . opts [ 'master_stats' ] ... |
def cli ( ctx , project_dir ) :
"""Launch the verilog simulation .""" | exit_code = SCons ( project_dir ) . sim ( )
ctx . exit ( exit_code ) |
def describe ( self ) :
"""Basic information about this entry""" | if isinstance ( self . _plugin , list ) :
pl = [ p . name for p in self . _plugin ]
elif isinstance ( self . _plugin , dict ) :
pl = { k : classname ( v ) for k , v in self . _plugin . items ( ) }
else :
pl = self . _plugin if isinstance ( self . _plugin , str ) else self . _plugin . name
return { 'name' : ... |
def set_colorization_enabled ( enabled ) :
"""Sets the enabled state of output colorization .
: param enabled : Boolean indicating whether output should be colorized .
: return : None""" | # If color is supposed to be enabled and this is windows , we have to enable console virtual terminal sequences :
if enabled and platform . system ( ) == 'Windows' :
Colors . COLORIZATION_ENABLED = enable_windows_virtual_terminal_sequences ( )
else : # This is not windows so we can enable color immediately .
Co... |
def remove_output ( clean = False , ** kwargs ) :
"""Remove the outputs generated by Andes , including power flow reports
` ` _ out . txt ` ` , time - domain list ` ` _ out . lst ` ` and data ` ` _ out . dat ` ` ,
eigenvalue analysis report ` ` _ eig . txt ` ` .
Parameters
clean : bool
If ` ` True ` ` , e... | if not clean :
return False
found = False
cwd = os . getcwd ( )
for file in os . listdir ( cwd ) :
if file . endswith ( '_eig.txt' ) or file . endswith ( '_out.txt' ) or file . endswith ( '_out.lst' ) or file . endswith ( '_out.dat' ) or file . endswith ( '_prof.txt' ) :
found = True
try :
... |
def persist_upstream_diagram ( self , filepath ) :
"""Creates upstream steps diagram and persists it to disk as png file .
Pydot graph is created and persisted to disk as png file under the filepath directory .
Args :
filepath ( str ) : filepath to which the png with steps visualization should
be persisted"... | assert isinstance ( filepath , str ) , 'Step {} error, filepath must be str. Got {} instead' . format ( self . name , type ( filepath ) )
persist_as_png ( self . upstream_structure , filepath ) |
def backup_name ( filename ) :
""": param filename : given a filename creates a backup name of the form
filename . bak . 1 . If the filename already exists
the number will be increased as much as needed so
the file does not exist in the given location .
The filename can consists a path and is expanded
wit... | location = path_expand ( filename )
n = 0
found = True
backup = None
while found :
n += 1
backup = "{0}.bak.{1}" . format ( location , n )
found = os . path . isfile ( backup )
return backup |
def stream_index ( self , bucket , index , startkey , endkey = None , return_terms = None , max_results = None , continuation = None , timeout = None , term_regex = None ) :
"""Streams a secondary index query .""" | if not self . stream_indexes ( ) :
raise NotImplementedError ( "Secondary index streaming is not " "supported on %s" % self . server_version . vstring )
if term_regex and not self . index_term_regex ( ) :
raise NotImplementedError ( "Secondary index term_regex is not " "supported on %s" % self . server_version ... |
def check_throttles ( self , request ) :
"""Check if request should be throttled .
Raises an appropriate exception if the request is throttled .""" | for throttle in self . get_throttles ( ) :
if not throttle . allow_request ( request , self ) :
self . throttled ( request , throttle . wait ( ) ) |
def account ( self , url ) :
"""Return accounts references for the given account id .
: param account _ id :
: param accounts _ password : The password for decrypting the secret
: return :""" | from sqlalchemy . orm . exc import NoResultFound
from ambry . orm . exc import NotFoundError
from ambry . util import parse_url_to_dict
from ambry . orm import Account
pd = parse_url_to_dict ( url )
# Old method of storing account information .
try :
act = self . database . session . query ( Account ) . filter ( Ac... |
def has_scope ( context = None ) :
'''Scopes were introduced in systemd 205 , this function returns a boolean
which is true when the minion is systemd - booted and running systemd > = 205.''' | if not booted ( context ) :
return False
_sd_version = version ( context )
if _sd_version is None :
return False
return _sd_version >= 205 |
def basis ( self , n ) :
"""Chebyshev basis functions T _ n .""" | if n == 0 :
return self ( np . array ( [ 1. ] ) )
vals = np . ones ( n + 1 )
vals [ 1 : : 2 ] = - 1
return self ( vals ) |
def delete_image ( self , image_id ) :
'''method for removing an image from AWS EC2
: param image _ id : string with AWS id of instance
: return : string with AWS response from snapshot delete''' | title = '%s.delete_image' % self . __class__ . __name__
# validate inputs
input_fields = { 'image_id' : image_id }
for key , value in input_fields . items ( ) :
object_title = '%s(%s=%s)' % ( title , key , str ( value ) )
self . fields . validate ( value , '.%s' % key , object_title )
# report query
self . iam ... |
def set_subprocess_arguments ( self , subprocess_arguments ) :
"""Set the list of arguments that the wrapper will pass to ` ` subprocess ` ` .
Placeholders ` ` CLI _ PARAMETER _ * ` ` can be used , and they will be replaced
by actual values in the ` ` _ synthesize _ multiple _ subprocess ( ) ` ` and
` ` _ syn... | # NOTE this is a method because we might need to access self . rconf ,
# so we cannot specify the list of arguments as a class field
self . subprocess_arguments = subprocess_arguments
self . log ( [ u"Subprocess arguments: %s" , subprocess_arguments ] ) |
def create_public_key_from_json ( values ) :
"""Create a public key object based on the values from the JSON record .""" | # currently we only support RSA public keys
_id = values . get ( 'id' )
if not _id : # Make it more forgiving for now .
_id = ''
# raise ValueError ( ' publicKey definition is missing the " id " value . ' )
if values . get ( 'type' ) == PUBLIC_KEY_TYPE_RSA :
public_key = PublicKeyRSA ( _id , owner = values ... |
def _params ( sig ) :
"""Read params , values and annotations from the signature""" | params = [ ]
for p in sig . parameters :
param = sig . parameters [ p ]
optional = param . default != inspect . Signature . empty
default = UIBuilder . _safe_default ( param . default ) if param . default != inspect . Signature . empty else ''
annotation = param . annotation if param . annotation != ins... |
def restore_state ( self ) :
"""Restore the state of the dock to the last known state .""" | if self . state is None :
return
for myCount in range ( 0 , self . exposure_layer_combo . count ( ) ) :
item_text = self . exposure_layer_combo . itemText ( myCount )
if item_text == self . state [ 'exposure' ] :
self . exposure_layer_combo . setCurrentIndex ( myCount )
break
for myCount in ... |
def insert_bytes ( fobj , size , offset , BUFFER_SIZE = 2 ** 16 ) :
"""Insert size bytes of empty space starting at offset .
fobj must be an open file object , open rb + or
equivalent . Mutagen tries to use mmap to resize the file , but
falls back to a significantly slower method if mmap fails .
Args :
fo... | if size < 0 or offset < 0 :
raise ValueError
fobj . seek ( 0 , 2 )
filesize = fobj . tell ( )
movesize = filesize - offset
if movesize < 0 :
raise ValueError
resize_file ( fobj , size , BUFFER_SIZE )
if mmap is not None :
try :
mmap_move ( fobj , offset + size , offset , movesize )
except mmap .... |
def get_connections ( self , data = False ) :
"""Get agent ' s current connections .
: param bool data :
Also return the data dictionary for each connection .
: returns : A list of agent addresses or a dictionary""" | if data :
return self . _connections
return list ( self . _connections . keys ( ) ) |
def bounds ( address ) :
"""Retrieve image bounds .
Attributes
address : str
file url .
Returns
out : dict
dictionary with image bounds .""" | with rasterio . open ( address ) as src :
wgs_bounds = transform_bounds ( * [ src . crs , "epsg:4326" ] + list ( src . bounds ) , densify_pts = 21 )
return { "url" : address , "bounds" : list ( wgs_bounds ) } |
def as_dict ( self ) :
"""Makes LibxcFunc obey the general json interface used in pymatgen for
easier serialization .""" | return { "name" : self . name , "@module" : self . __class__ . __module__ , "@class" : self . __class__ . __name__ } |
def encode_conjure_union_type ( cls , obj ) : # type : ( ConjureUnionType ) - > Any
"""Encodes a conjure union into json""" | encoded = { }
# type : Dict [ str , Any ]
encoded [ "type" ] = obj . type
for attr , field_definition in obj . _options ( ) . items ( ) :
if field_definition . identifier == obj . type :
attribute = attr
break
else :
raise ValueError ( "could not find attribute for union " + "member {0} of type ... |
def is_one_edit ( s , t ) :
""": type s : str
: type t : str
: rtype : bool""" | if len ( s ) > len ( t ) :
return is_one_edit ( t , s )
if len ( t ) - len ( s ) > 1 or t == s :
return False
for i in range ( len ( s ) ) :
if s [ i ] != t [ i ] :
return s [ i + 1 : ] == t [ i + 1 : ] or s [ i : ] == t [ i + 1 : ]
return True |
def _render_cmd ( cmd , cwd , template , saltenv = 'base' , pillarenv = None , pillar_override = None ) :
'''If template is a valid template engine , process the cmd and cwd through
that engine .''' | if not template :
return ( cmd , cwd )
# render the path as a template using path _ template _ engine as the engine
if template not in salt . utils . templates . TEMPLATE_REGISTRY :
raise CommandExecutionError ( 'Attempted to render file paths with unavailable engine ' '{0}' . format ( template ) )
kwargs = { }... |
def prepare_series ( self ) -> None : # noinspection PyUnresolvedReferences
"""Call | XMLSubseries . prepare _ series | of all | XMLSubseries |
objects with the same memory | set | object .
> > > from hydpy . auxs . xmltools import XMLInterface , XMLSubseries
> > > from hydpy import data
> > > interface = X... | memory = set ( )
for output in itertools . chain ( self . readers , self . writers ) :
output . prepare_series ( memory ) |
def main ( ) :
"""Main""" | import sys
import h5py
handler = logging . StreamHandler ( sys . stderr )
formatter = logging . Formatter ( fmt = _DEFAULT_LOG_FORMAT , datefmt = _DEFAULT_TIME_FORMAT )
handler . setFormatter ( formatter )
handler . setLevel ( logging . DEBUG )
LOG . setLevel ( logging . DEBUG )
LOG . addHandler ( handler )
platform_na... |
def cysparse_real_type_from_real_cysparse_complex_type ( cysparse_type ) :
"""Returns the * * real * * type for the real or imaginary part of a * * real * * complex type .
For instance :
COMPLEX128 _ t - > FLOAT64 _ t
Args :
cysparse :""" | r_type = None
if cysparse_type in [ 'COMPLEX64_t' ] :
r_type = 'FLOAT32_t'
elif cysparse_type in [ 'COMPLEX128_t' ] :
r_type = 'FLOAT64_t'
elif cysparse_type in [ 'COMPLEX256_t' ] :
r_type = 'FLOAT128_t'
else :
raise TypeError ( "Not a recognized complex type" )
return r_type |
def load_resfile ( directory , resfile_path = None ) :
"""Return a list of tuples indicating the start and end points of the loops
that were sampled in the given directory .""" | if resfile_path is None :
workspace = workspace_from_dir ( directory )
resfile_path = workspace . resfile_path
from klab . rosetta . input_files import Resfile
return Resfile ( resfile_path ) |
def add_sender ( self , partition = None , operation = None , send_timeout = 60 , keep_alive = 30 , auto_reconnect = True ) :
"""Add a sender to the client to EventData object to an EventHub .
: param partition : Optionally specify a particular partition to send to .
If omitted , the events will be distributed ... | target = "amqps://{}{}" . format ( self . address . hostname , self . address . path )
if operation :
target = target + operation
handler = Sender ( self , target , partition = partition , send_timeout = send_timeout , keep_alive = keep_alive , auto_reconnect = auto_reconnect )
self . clients . append ( handler )
r... |
def load_field_values ( instance , include_fields ) :
"""Load values from an AT object schema fields into a list of dictionaries""" | ret = { }
schema = instance . Schema ( )
val = None
for field in schema . fields ( ) :
fieldname = field . getName ( )
if include_fields and fieldname not in include_fields :
continue
try :
val = field . get ( instance )
except AttributeError : # If this error is raised , make a look to ... |
def handle_interlude ( self , obj , folder , index , ensemble , loop = None , ** kwargs ) :
"""Handle an interlude event .
Interlude functions permit branching . They return a folder which the
application can choose to adopt as the next supplier of dialogue .
This handler calls the interlude with the supplied... | if obj is None :
return folder . metadata
else :
return obj ( folder , index , ensemble , loop = loop , ** kwargs ) |
def add_entry ( self , ** kw ) :
"""Add an entry to an AccessList . Use the supported arguments
for the inheriting class for keyword arguments .
: raises UpdateElementFailed : failure to modify with reason
: return : None""" | self . data . setdefault ( 'entries' , [ ] ) . append ( { '{}_entry' . format ( self . typeof ) : kw } ) |
def get_parent_id ( chebi_id ) :
'''Returns parent id''' | if len ( __PARENT_IDS ) == 0 :
__parse_compounds ( )
return __PARENT_IDS [ chebi_id ] if chebi_id in __PARENT_IDS else float ( 'NaN' ) |
def from_model ( cls , document ) :
"""By default use the ` ` to _ dict ` ` method
and exclude ` ` _ id ` ` , ` ` _ cls ` ` and ` ` owner ` ` fields""" | return cls ( meta = { 'id' : document . id } , ** cls . serialize ( document ) ) |
def get_limits ( self ) :
"""Return all known limits for this service , as a dict of their names
to : py : class : ` ~ . AwsLimit ` objects .
Limits from :
docs . aws . amazon . com / Route53 / latest / DeveloperGuide / DNSLimitations . html
: returns : dict of limit names to : py : class : ` ~ . AwsLimit `... | if not self . limits :
self . limits = { }
for item in [ self . MAX_RRSETS_BY_ZONE , self . MAX_VPCS_ASSOCIATED_BY_ZONE ] :
self . limits [ item [ "name" ] ] = AwsLimit ( item [ "name" ] , self , item [ "default_limit" ] , self . warning_threshold , self . critical_threshold , limit_type = 'AWS::Route53... |
def blockshapes ( self ) :
"""Raster all bands block shape .""" | if self . _blockshapes is None :
if self . _filename :
self . _populate_from_rasterio_object ( read_image = False )
else : # if no file is attached to the raster set the shape of each band to be the data array size
self . _blockshapes = [ ( self . height , self . width ) for z in range ( self . ... |
def SaveAvatarToFile ( self , Filename , AvatarId = 1 ) :
"""Saves user avatar to a file .
: Parameters :
Filename : str
Destination path .
AvatarId : int
Avatar Id .""" | s = 'USER %s AVATAR %s %s' % ( self . Handle , AvatarId , path2unicode ( Filename ) )
self . _Owner . _DoCommand ( 'GET %s' % s , s ) |
def refresh ( self ) :
"""Resets the data for this navigator .""" | self . setUpdatesEnabled ( False )
self . blockSignals ( True )
self . clear ( )
tableType = self . tableType ( )
if not tableType :
self . setUpdatesEnabled ( True )
self . blockSignals ( False )
return
schema = tableType . schema ( )
columns = list ( sorted ( schema . columns ( ) , key = lambda x : x . na... |
def get_children ( self ) :
"""Return the children of this folder""" | try :
children = os . listdir ( self . real_path )
except OSError :
return [ ]
result = [ ]
for name in children :
try :
child = self . get_child ( name )
except exceptions . ResourceNotFoundError :
continue
if not self . project . is_ignored ( child ) :
result . append ( sel... |
def imagetransformer_b12l_4h_b256_uncond_dr03_rel_tpu ( ) :
"""works very well on 4x4.""" | hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu ( )
hparams . shared_rel = True
hparams . dec_attention_type = cia . AttentionType . RELATIVE_LOCAL_1D
return hparams |
def _update_geography ( self , countries , regions , cities , city_country_mapping ) :
"""Update database with new countries , regions and cities""" | existing = { 'cities' : list ( City . objects . values_list ( 'id' , flat = True ) ) , 'regions' : list ( Region . objects . values ( 'name' , 'country__code' ) ) , 'countries' : Country . objects . values_list ( 'code' , flat = True ) }
for country_code in countries :
if country_code not in existing [ 'countries' ... |
def load_lsdsng ( filename ) :
"""Load a Project from a ` ` . lsdsng ` ` file .
: param filename : the name of the file from which to load
: rtype : : py : class : ` pylsdj . Project `""" | # Load preamble data so that we know the name and version of the song
with open ( filename , 'rb' ) as fp :
preamble_data = bread . parse ( fp , spec . lsdsng_preamble )
with open ( filename , 'rb' ) as fp : # Skip the preamble this time around
fp . seek ( int ( len ( preamble_data ) / 8 ) )
# Load compress... |
def list ( self , * kinds , ** kwargs ) :
"""Returns a list of inputs that are in the : class : ` Inputs ` collection .
You can also filter by one or more input kinds .
This function iterates over all possible inputs , regardless of any arguments you
specify . Because the : class : ` Inputs ` collection is th... | if len ( kinds ) == 0 :
kinds = self . kinds
if len ( kinds ) == 1 :
kind = kinds [ 0 ]
logging . debug ( "Inputs.list taking short circuit branch for single kind." )
path = self . kindpath ( kind )
logging . debug ( "Path for inputs: %s" , path )
try :
path = UrlEncoded ( path , skip_en... |
def diff_config ( jaide , second_host , mode ) :
"""Perform a show | compare with some set commands .
@ param jaide : The jaide connection to the device .
@ type jaide : jaide . Jaide object
@ param second _ host : The device IP or hostname of the second host to
| compare with .
@ type second _ host : str... | try : # create a list of all the lines that differ , and merge it .
output = '\n' . join ( [ diff for diff in jaide . diff_config ( second_host , mode . lower ( ) ) ] )
except errors . SSHError :
output = color ( 'Unable to connect to port %s on device: %s\n' % ( str ( jaide . port ) , second_host ) , 'red' )
e... |
def main ( ) :
"""CLI entrypoint for scaling policy creation""" | logging . basicConfig ( format = LOGGING_FORMAT )
log = logging . getLogger ( __name__ )
parser = argparse . ArgumentParser ( )
add_debug ( parser )
add_app ( parser )
add_properties ( parser )
add_env ( parser )
add_region ( parser )
args = parser . parse_args ( )
logging . getLogger ( __package__ . split ( '.' ) [ 0 ... |
def mean_otu_pct_abundance ( ra , otuIDs ) :
"""Calculate the mean OTU abundance percentage .
: type ra : Dict
: param ra : ' ra ' refers to a dictionary keyed on SampleIDs , and the values are
dictionaries keyed on OTUID ' s and their values represent the relative
abundance of that OTUID in that SampleID .... | sids = ra . keys ( )
otumeans = defaultdict ( int )
for oid in otuIDs :
otumeans [ oid ] = sum ( [ ra [ sid ] [ oid ] for sid in sids if oid in ra [ sid ] ] ) / len ( sids ) * 100
return otumeans |
def commit ( self ) :
"""Commit current transaction .""" | if ( not self . _add_cache and not self . _remove_cache and not self . _undefined_cache ) :
return
for store_key , hash_values in self . _add_cache . items ( ) :
for hash_value in hash_values :
super ( TransactionalIndex , self ) . add_hashed_value ( hash_value , store_key )
for store_key in self . _rem... |
def tseries ( self ) :
"""Time series data .
This is a : class : ` pandas . DataFrame ` with istep as index and variable
names as columns .""" | if self . _stagdat [ 'tseries' ] is UNDETERMINED :
timefile = self . filename ( 'TimeSeries.h5' )
self . _stagdat [ 'tseries' ] = stagyyparsers . time_series_h5 ( timefile , list ( phyvars . TIME . keys ( ) ) )
if self . _stagdat [ 'tseries' ] is not None :
return self . _stagdat [ 'tseries' ]
t... |
def move_to ( self , target_datetime ) :
"""Moves frozen date to the given ` ` target _ datetime ` `""" | target_datetime = _parse_time_to_freeze ( target_datetime )
delta = target_datetime - self . time_to_freeze
self . tick ( delta = delta ) |
def mouse ( table , day = None ) :
"""Handler for showing mouse statistics for specified type and day .""" | where = ( ( "day" , day ) , ) if day else ( )
events = db . fetch ( table , where = where , order = "day" )
for e in events :
e [ "dt" ] = datetime . datetime . fromtimestamp ( e [ "stamp" ] )
stats , positions , events = stats_mouse ( events , table )
days , input = db . fetch ( "counts" , order = "day" , type = t... |
def gmove ( pattern , destination ) :
"""Move all file found by glob . glob ( pattern ) to destination directory .
Args :
pattern ( str ) : Glob pattern
destination ( str ) : Path to the destination directory .
Returns :
bool : True if the operation is successful , False otherwise .""" | for item in glob . glob ( pattern ) :
if not move ( item , destination ) :
return False
return True |
def _CalculateDigestHash ( self , file_entry , data_stream_name ) :
"""Calculates a SHA - 256 digest of the contents of the file entry .
Args :
file _ entry ( dfvfs . FileEntry ) : file entry whose content will be hashed .
data _ stream _ name ( str ) : name of the data stream whose content is to be
hashed ... | file_object = file_entry . GetFileObject ( data_stream_name = data_stream_name )
if not file_object :
return None
try :
file_object . seek ( 0 , os . SEEK_SET )
hasher_object = hashers_manager . HashersManager . GetHasher ( 'sha256' )
data = file_object . read ( self . _READ_BUFFER_SIZE )
while data... |
def get_user ( session , user_id ) :
"""Get user .""" | try :
user_id = int ( user_id )
except ValueError :
user_id = find_user ( session , user_id )
resp = _make_request ( session , USER_URL , user_id )
if not resp :
raise VooblyError ( 'user id not found' )
return resp [ 0 ] |
def build_request_body ( type , id , attributes = None , relationships = None ) :
"""Build a request body object .
A body JSON object is used for any of the ` ` update ` ` or ` ` create ` `
methods on : class : ` Resource ` subclasses . In normal library use you
should not have to use this function directly .... | result = { "data" : { "type" : type } }
data = result [ 'data' ]
if attributes is not None :
data [ 'attributes' ] = attributes
if relationships is not None :
data [ 'relationships' ] = relationships
if id is not None :
data [ 'id' ] = id
return result |
def clean ( self ) :
"""服务结束后清理服务器 .""" | # 服务结束阶段
if self . running is False :
return False
logger . info ( "Stopping worker [%s]" , self . pid )
# 关闭server
self . rpc_server . close ( )
self . loop . run_until_complete ( self . rpc_server . wait_closed ( ) )
# 关闭连接
# 完成所有空转连接的关闭工作
for connection in MPProtocolServer . CONNECTIONS :
connection . shutdo... |
def callable_validator ( instance , attribute , value ) : # pylint : disable = unused - argument
"""Validate that an attribute value is callable .
: raises TypeError : if ` ` value ` ` is not callable""" | if not callable ( value ) :
raise TypeError ( '"{name}" value "{value}" must be callable' . format ( name = attribute . name , value = value ) ) |
def prompt_file ( prompt , default = None , must_exist = True , is_dir = False , show_default = True , prompt_suffix = ': ' , color = None ) :
"""Prompt a filename using using glob for autocompetion .
If must _ exist is True ( default ) then you can be sure that the value returned
is an existing filename or dir... | if must_exist :
while True :
r = prompt_autocomplete ( prompt , path_complete ( is_dir ) , default , show_default = show_default , prompt_suffix = prompt_suffix , color = color )
if os . path . exists ( r ) :
break
print ( 'This path does not exist.' )
else :
r = prompt_autoc... |
def create_sns_event ( app_name , env , region , rules ) :
"""Create SNS lambda event from rules .
Args :
app _ name ( str ) : name of the lambda function
env ( str ) : Environment / Account for lambda function
region ( str ) : AWS region of the lambda function
rules ( str ) : Trigger rules from the setti... | session = boto3 . Session ( profile_name = env , region_name = region )
sns_client = session . client ( 'sns' )
topic_name = rules . get ( 'topic' )
lambda_alias_arn = get_lambda_alias_arn ( app = app_name , account = env , region = region )
topic_arn = get_sns_topic_arn ( topic_name = topic_name , account = env , regi... |
def get_visit_fn ( cls , kind , is_leaving = False ) -> Callable :
"""Get the visit function for the given node kind and direction .""" | method = "leave" if is_leaving else "enter"
visit_fn = getattr ( cls , f"{method}_{kind}" , None )
if not visit_fn :
visit_fn = getattr ( cls , method , None )
return visit_fn |
def add_task ( self , pid ) :
"""Add a process to the cgroups represented by this instance .""" | _register_process_with_cgrulesengd ( pid )
for cgroup in self . paths :
with open ( os . path . join ( cgroup , 'tasks' ) , 'w' ) as tasksFile :
tasksFile . write ( str ( pid ) ) |
def _logged_in_successful ( data ) :
"""Test the login status from the returned communication of the
server .
: param data : bytes received from server during login
: type data : list of bytes
: return boolean , True when you are logged in .""" | if re . match ( r'^:(testserver\.local|tmi\.twitch\.tv)' r' NOTICE \* :' r'(Login unsuccessful|Error logging in)*$' , data . strip ( ) ) :
return False
else :
return True |
def _check_sleep ( self , idx ) :
"""This ensures that the robot code called Wait ( ) at some point""" | # TODO : There are some cases where it would be ok to do this . . .
if not self . fake_time . slept [ idx ] :
errstr = ( "%s() function is not calling wpilib.Timer.delay() in its loop!" % self . mode_map [ self . mode ] )
raise RuntimeError ( errstr )
self . fake_time . slept [ idx ] = False |
def __protocolize ( base_url ) :
"""Internal add - protocol - to - url helper""" | if not base_url . startswith ( "http://" ) and not base_url . startswith ( "https://" ) :
base_url = "https://" + base_url
# Some API endpoints can ' t handle extra / ' s in path requests
base_url = base_url . rstrip ( "/" )
return base_url |
def symm_reduce ( self , coords_set , threshold = 1e-6 ) :
"""Reduces the set of adsorbate sites by finding removing
symmetrically equivalent duplicates
Args :
coords _ set : coordinate set in cartesian coordinates
threshold : tolerance for distance equivalence , used
as input to in _ coord _ list _ pbc f... | surf_sg = SpacegroupAnalyzer ( self . slab , 0.1 )
symm_ops = surf_sg . get_symmetry_operations ( )
unique_coords = [ ]
# Convert to fractional
coords_set = [ self . slab . lattice . get_fractional_coords ( coords ) for coords in coords_set ]
for coords in coords_set :
incoord = False
for op in symm_ops :
... |
def examples ( self ) :
"""Return example functions in the space .
These are created by discretizing the examples in the underlying
` fspace ` .
See Also
odl . space . fspace . FunctionSpace . examples""" | for name , elem in self . fspace . examples :
yield ( name , self . element ( elem ) ) |
def plot_basic_hist ( samples , file_type , ** plot_args ) :
"""Create line graph plot for basic histogram data for ' file _ type ' .
The ' samples ' parameter could be from the bbmap mod _ data dictionary :
samples = bbmap . MultiqcModule . mod _ data [ file _ type ]""" | sumy = sum ( [ int ( samples [ sample ] [ 'data' ] [ x ] [ 0 ] ) for sample in samples for x in samples [ sample ] [ 'data' ] ] )
cutoff = sumy * 0.999
all_x = set ( )
for item in sorted ( chain ( * [ samples [ sample ] [ 'data' ] . items ( ) for sample in samples ] ) ) :
all_x . add ( item [ 0 ] )
cutoff -= it... |
def _build_dataframes ( self ) :
"""Function called when network is created to build component pandas . DataFrames .""" | for component in self . all_components :
attrs = self . components [ component ] [ "attrs" ]
static_dtypes = attrs . loc [ attrs . static , "dtype" ] . drop ( [ "name" ] )
df = pd . DataFrame ( { k : pd . Series ( dtype = d ) for k , d in static_dtypes . iteritems ( ) } , columns = static_dtypes . index )
... |
def memoize ( f ) :
'''Caches result of a function
From : https : / / goo . gl / aXt4Qy
> > > import time
> > > @ memoize
. . . def test ( msg ) :
. . . # Processing for result that takes time
. . . time . sleep ( 1)
. . . return msg
> > > for i in range ( 5 ) :
. . . start = time . time ( )
. .... | class memodict ( dict ) :
@ wraps ( f )
def __getitem__ ( self , * args ) :
return super ( memodict , self ) . __getitem__ ( * args )
def __missing__ ( self , key ) :
self [ key ] = ret = f ( key )
return ret
return memodict ( ) . __getitem__ |
def run_thread ( self ) :
"""Run the main thread .""" | self . _run_thread = True
self . _thread . setDaemon ( True )
self . _thread . start ( ) |
def create_comment ( self , comment , repository_id , pull_request_id , thread_id , project = None ) :
"""CreateComment .
[ Preview API ] Create a comment on a specific thread in a pull request ( up to 500 comments can be created per thread ) .
: param : class : ` < Comment > < azure . devops . v5_1 . git . mod... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if repository_id is not None :
route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' )
if pull_request_id is not None :
route_values ... |
def windowed_hudson_fst ( pos , ac1 , ac2 , size = None , start = None , stop = None , step = None , windows = None , fill = np . nan ) :
"""Estimate average Fst in windows over a single chromosome / contig ,
following the method of Hudson ( 1992 ) elaborated by Bhatia et al . ( 2013 ) .
Parameters
pos : arra... | # compute values per - variants
num , den = hudson_fst ( ac1 , ac2 )
# define the statistic to compute within each window
def average_fst ( wn , wd ) :
return np . nansum ( wn ) / np . nansum ( wd )
# calculate average Fst in windows
fst , windows , counts = windowed_statistic ( pos , values = ( num , den ) , stati... |
def deserialize ( cls , cls_target , obj_raw ) :
""": type cls _ target : T | type
: type obj _ raw : int | str | bool | float | list | dict | None
: rtype : T""" | cls . _initialize ( )
deserializer = cls . _get_deserializer ( cls_target )
if deserializer == cls :
return cls . _deserialize_default ( cls_target , obj_raw )
else :
return deserializer . deserialize ( cls_target , obj_raw ) |
def stream ( self , func , * args , ** kwargs ) :
"""Watch an API resource and stream the result back via a generator .
: param func : The API function pointer . Any parameter to the function
can be passed after this parameter .
: return : Event object with these keys :
' type ' : The type of event such as ... | self . close ( )
self . _stop = False
self . return_type = self . get_return_type ( func )
kwargs [ 'watch' ] = True
kwargs [ '_preload_content' ] = False
self . func = partial ( func , * args , ** kwargs )
return self |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.