signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def MakeDeployableBinary ( self , template_path , output_path ) :
"""Repackage the template zip with the installer .""" | context = self . context + [ "Client Context" ]
zip_data = io . BytesIO ( )
output_zip = zipfile . ZipFile ( zip_data , mode = "w" , compression = zipfile . ZIP_DEFLATED )
z_template = zipfile . ZipFile ( open ( template_path , "rb" ) )
# Track which files we ' ve copied already .
completed_files = [ "grr-client.exe" ,... |
def get ( self , ** kwargs ) :
'''Returns this relation''' | redis = type ( self . obj ) . get_redis ( )
related = list ( map ( lambda id : self . model ( ) . get ( debyte_string ( id ) ) , self . get_related_ids ( redis , ** kwargs ) ) )
return related |
def load_schema ( schema_ref , # type : Union [ CommentedMap , CommentedSeq , Text ]
cache = None # type : Dict
) : # type : ( . . . ) - > Tuple [ Loader , Union [ Names , SchemaParseException ] , Dict [ Text , Any ] , Loader ]
"""Load a schema that can be used to validate documents using load _ and _ validate .
... | metaschema_names , _metaschema_doc , metaschema_loader = get_metaschema ( )
if cache is not None :
metaschema_loader . cache . update ( cache )
schema_doc , schema_metadata = metaschema_loader . resolve_ref ( schema_ref , "" )
if not isinstance ( schema_doc , MutableSequence ) :
raise ValueError ( "Schema refer... |
def install_python_module_locally ( name ) :
"""instals a python module using pip""" | with settings ( hide ( 'warnings' , 'running' , 'stdout' , 'stderr' ) , warn_only = False , capture = True ) :
local ( 'pip --quiet install %s' % name ) |
def to_argv_schema ( data , arg_names = None , arg_abbrevs = None , filters = None , defaults = None ) :
'''to _ argv _ schema ( instructions ) yields a valid tuple of CommandLineParser instructions for the
given instructions tuple ; by itself , this will only return the instructions as they are , but
optional ... | if is_plan ( data ) : # First we must convert it to a valid instruction list
( plan , data ) = ( data , { } )
# we go through the afferent parameters . . .
for aff in plan . afferents : # these are provided by the parsing mechanism and shouldn ' t be processed
if aff in [ 'argv' , 'argv_parsed' , 's... |
def _get_files ( file_patterns , top = HERE ) :
"""Expand file patterns to a list of paths .
Parameters
file _ patterns : list or str
A list of glob patterns for the data file locations .
The globs can be recursive if they include a ` * * ` .
They should be relative paths from the top directory or
absol... | if not isinstance ( file_patterns , ( list , tuple ) ) :
file_patterns = [ file_patterns ]
for i , p in enumerate ( file_patterns ) :
if os . path . isabs ( p ) :
file_patterns [ i ] = os . path . relpath ( p , top )
matchers = [ _compile_pattern ( p ) for p in file_patterns ]
files = set ( )
for root ,... |
def get_selected_submissions ( self , course , filter_type , selected_tasks , users , aggregations , stype ) :
"""Returns the submissions that have been selected by the admin
: param course : course
: param filter _ type : users or aggregations
: param selected _ tasks : selected tasks id
: param users : se... | if filter_type == "users" :
self . _validate_list ( users )
aggregations = list ( self . database . aggregations . find ( { "courseid" : course . get_id ( ) , "students" : { "$in" : users } } ) )
# Tweak if not using classrooms : classroom [ ' students ' ] may content ungrouped users
aggregations = dict... |
def _column_names ( self ) :
"""Return the column names""" | index_names = set ( _normalize_index_names ( self . _index_names ) )
column_names = [ col_name for col_name in self . _schema_rdd . columns if col_name not in index_names ]
return column_names |
def calc_qigz1_v1 ( self ) :
"""Aggregate the amount of the first interflow component released
by all HRUs .
Required control parameters :
| NHRU |
| FHRU |
Required flux sequence :
| QIB1 |
Calculated state sequence :
| QIGZ1 |
Basic equation :
: math : ` QIGZ1 = \\ Sigma ( FHRU \\ cdot QIB1 ) ... | con = self . parameters . control . fastaccess
flu = self . sequences . fluxes . fastaccess
sta = self . sequences . states . fastaccess
sta . qigz1 = 0.
for k in range ( con . nhru ) :
sta . qigz1 += con . fhru [ k ] * flu . qib1 [ k ] |
def clockIsBroken ( ) :
"""Returns whether twisted . internet . task . Clock has the bug that
returns the wrong DelayedCall or not .""" | clock = Clock ( )
dc1 = clock . callLater ( 10 , lambda : None )
dc2 = clock . callLater ( 1 , lambda : None )
if dc1 is dc2 :
return True
else :
return False |
def run ( bam_file , data , out_dir ) :
"""Run viral QC analysis :
1 . Extract the unmapped reads
2 . BWA - MEM to the viral sequences from GDC database https : / / gdc . cancer . gov / about - data / data - harmonization - and - generation / gdc - reference - files
3 . Report viruses that are in more than 50... | source_link = 'https://gdc.cancer.gov/about-data/data-harmonization-and-generation/gdc-reference-files'
viral_target = "gdc-viral"
out = { }
if vcfutils . get_paired_phenotype ( data ) :
viral_refs = [ x for x in dd . get_viral_files ( data ) if os . path . basename ( x ) == "%s.fa" % viral_target ]
if viral_re... |
def _adjust ( hsl , attribute , percent ) :
"""Internal adjust function""" | hsl = list ( hsl )
if attribute > 0 :
hsl [ attribute ] = _clamp ( hsl [ attribute ] + percent )
else :
hsl [ attribute ] += percent
return hsl |
def _set_group_type ( self , v , load = False ) :
"""Setter method for group _ type , mapped from YANG variable / openflow _ state / group / group _ info _ list / group _ type ( group - type )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ group _ type is considered as... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'dcm-group-type-select' : { 'value' : 2 } , u'dcm-group-type-invalid' : { 'value' : 0 } , u'dcm-group-type-fast-failover' : { 'v... |
def notify ( self , method_name : str , * args : Any , trim_log_values : Optional [ bool ] = None , validate_against_schema : Optional [ bool ] = None , ** kwargs : Any ) -> Response :
"""Send a JSON - RPC request , without expecting a response .
Args :
method _ name : The remote procedure ' s method name .
a... | return self . send ( Notification ( method_name , * args , ** kwargs ) , trim_log_values = trim_log_values , validate_against_schema = validate_against_schema , ) |
def send_state_event ( self , room_id , event_type , content , state_key = "" , timestamp = None ) :
"""Perform PUT / rooms / $ room _ id / state / $ event _ type
Args :
room _ id ( str ) : The room ID to send the state event in .
event _ type ( str ) : The state event type to send .
content ( dict ) : The ... | path = "/rooms/%s/state/%s" % ( quote ( room_id ) , quote ( event_type ) , )
if state_key :
path += "/%s" % ( quote ( state_key ) )
params = { }
if timestamp :
params [ "ts" ] = timestamp
return self . _send ( "PUT" , path , content , query_params = params ) |
def recur ( self , klass , data , interval , offset = 0 , priority = None , tags = None , retries = None , jid = None ) :
'''Place a recurring job in this queue''' | return self . client ( 'recur' , self . name , jid or uuid . uuid4 ( ) . hex , self . class_string ( klass ) , json . dumps ( data ) , 'interval' , interval , offset , 'priority' , priority or 0 , 'tags' , json . dumps ( tags or [ ] ) , 'retries' , retries or 5 ) |
def add_classdiff_optgroup ( parser ) :
"""option group specific to class checking""" | g = parser . add_argument_group ( "Class Checking Options" )
g . add_argument ( "--ignore-version-up" , action = "store_true" , default = False )
g . add_argument ( "--ignore-version-down" , action = "store_true" , default = False )
g . add_argument ( "--ignore-platform-up" , action = "store_true" , default = False )
g... |
def mode_collection ( ) :
"""Manage an existing collection node .""" | print globals ( ) [ 'mode_collection' ] . __doc__
collection_node_id = existing_node_input ( )
value = render_value_for_node ( collection_node_id )
if not value :
return None
print "Collection length: {0}" . format ( len ( value ) )
print safe_dump ( value , default_flow_style = False )
item_attr_list = [ ]
if len ... |
def mine_sub_trees ( self , threshold ) :
"""Generate subtrees and mine them for patterns .""" | patterns = { }
mining_order = sorted ( self . frequent . keys ( ) , key = lambda x : self . frequent [ x ] )
# Get items in tree in reverse order of occurrences .
for item in mining_order :
suffixes = [ ]
conditional_tree_input = [ ]
node = self . headers [ item ]
# Follow node links to get a list of
... |
def from_service_account_file ( cls , filename , * args , ** kwargs ) :
"""Creates an instance of this client using the provided credentials
file .
Args :
filename ( str ) : The path to the service account private key json
file .
args : Additional arguments to pass to the constructor .
kwargs : Addition... | credentials = service_account . Credentials . from_service_account_file ( filename )
kwargs [ 'credentials' ] = credentials
return cls ( * args , ** kwargs ) |
def timeFormat ( time_from , time_to = None , prefix = "" , infix = None ) :
"""Format the times time _ from and optionally time _ to , e . g . 10am""" | retval = ""
if time_from != "" and time_from is not None :
retval += prefix
retval += dateformat . time_format ( time_from , "fA" ) . lower ( )
if time_to != "" and time_to is not None :
to = format ( dateformat . time_format ( time_to , "fA" ) . lower ( ) )
if infix is not None :
retval = "{} {... |
def get_state_machine_m ( self , two_factor_check = True ) :
"""Get respective state machine model
Get a reference of the state machine model the state model belongs to . As long as the root state model
has no direct reference to its state machine model the state machine manager model is checked respective mode... | from rafcon . gui . singleton import state_machine_manager_model
state_machine = self . state . get_state_machine ( )
if state_machine :
if state_machine . state_machine_id in state_machine_manager_model . state_machines :
sm_m = state_machine_manager_model . state_machines [ state_machine . state_machine_i... |
def plot ( self , leaf_separation = 1 , cmap = 'viridis' , select_clusters = False , label_clusters = False , selection_palette = None , axis = None , colorbar = True , log_size = False , max_rectangles_per_icicle = 20 ) :
"""Use matplotlib to plot an ' icicle plot ' dendrogram of the condensed tree .
Effectively... | try :
import matplotlib . pyplot as plt
except ImportError :
raise ImportError ( 'You must install the matplotlib library to plot the condensed tree.' 'Use get_plot_data to calculate the relevant data without plotting.' )
plot_data = self . get_plot_data ( leaf_separation = leaf_separation , log_size = log_size... |
def fit ( self , X , u = None , sv = None , v = None ) :
"""Fit X into an embedded space .
Parameters
X : array , shape ( n _ samples , n _ features )
y : Ignored""" | if self . mode is 'parallel' :
Xall = X . copy ( )
X = np . reshape ( Xall . copy ( ) , ( - 1 , Xall . shape [ - 1 ] ) )
# X - = X . mean ( axis = - 1 ) [ : , np . newaxis ]
if ( u is None ) or ( sv is None ) or ( v is None ) : # compute svd and keep iPC ' s of data
nmin = min ( [ X . shape [ 0 ] , X . shap... |
def make_repo ( repodir , keyid = None , env = None , use_passphrase = False , gnupghome = '/etc/salt/gpgkeys' , runas = 'root' , timeout = 15.0 ) :
'''Make a package repository and optionally sign packages present
Given the repodir , create a ` ` yum ` ` repository out of the rpms therein
and optionally sign i... | SIGN_PROMPT_RE = re . compile ( r'Enter pass phrase: ' , re . M )
define_gpg_name = ''
local_keyid = None
local_uids = None
phrase = ''
if keyid is not None : # import _ keys
pkg_pub_key_file = '{0}/{1}' . format ( gnupghome , __salt__ [ 'pillar.get' ] ( 'gpg_pkg_pub_keyname' , None ) )
pkg_priv_key_file = '{0}... |
def _parse_keyvals ( self , line_iter ) :
"""Generate dictionary from key / value pairs .""" | out = None
line = None
for line in line_iter :
if len ( line ) == 1 and line [ 0 ] . upper ( ) == line [ 0 ] :
break
else : # setup output dictionaries , trimming off blank columns
if out is None :
while not line [ - 1 ] :
line = line [ : - 1 ]
out = [ { }... |
def fromjson ( cls , json_string : str ) -> 'Event' :
"""Create a new Event from a from a psycopg2 - pgevent event JSON .
Parameters
json _ string : str
Valid psycopg2 - pgevent event JSON .
Returns
Event
Event created from JSON deserialization .""" | obj = json . loads ( json_string )
return cls ( UUID ( obj [ 'event_id' ] ) , obj [ 'event_type' ] , obj [ 'schema_name' ] , obj [ 'table_name' ] , obj [ 'row_id' ] ) |
def partition ( lst , n ) :
"""Divide list into n equal parts""" | q , r = divmod ( len ( lst ) , n )
indices = [ q * i + min ( i , r ) for i in xrange ( n + 1 ) ]
return [ lst [ indices [ i ] : indices [ i + 1 ] ] for i in xrange ( n ) ] , [ list ( xrange ( indices [ i ] , indices [ i + 1 ] ) ) for i in xrange ( n ) ] |
def all ( self ) :
"""Synchronize all registered plugins and plugin points to database .""" | # Django > = 1.9 changed something with the migration logic causing
# plugins to be executed before the corresponding database tables
# exist . This method will only return something if the database
# tables have already been created .
# XXX : I don ' t fully understand the issue and there should be
# another way but t... |
def create_koji_session ( hub_url , auth_info = None ) :
"""Creates and returns a Koji session . If auth _ info
is provided , the session will be authenticated .
: param hub _ url : str , Koji hub URL
: param auth _ info : dict , authentication parameters used for koji _ login
: return : koji . ClientSessio... | session = KojiSessionWrapper ( koji . ClientSession ( hub_url , opts = { 'krb_rdns' : False } ) )
if auth_info is not None :
koji_login ( session , ** auth_info )
return session |
def get_config ( ) :
"""Prepare and return alembic config
These configurations used to live in alembic config initialiser , but that
just tight coupling . Ideally we should move that to userspace and find a
way to pass these into alembic commands .
@ todo : think about it""" | from boiler . migrations . config import MigrationsConfig
# used for errors
map = dict ( path = 'MIGRATIONS_PATH' , db_url = 'SQLALCHEMY_DATABASE_URI' , metadata = 'SQLAlchemy metadata' )
app = bootstrap . get_app ( )
params = dict ( )
params [ 'path' ] = app . config . get ( map [ 'path' ] , 'migrations' )
params [ 'd... |
def trim ( self ) :
"""Clear not used counters""" | for key , value in list ( iteritems ( self . counters ) ) :
if value . empty ( ) :
del self . counters [ key ] |
def create_table_from_orm_class ( engine : Engine , ormclass : DeclarativeMeta , without_constraints : bool = False ) -> None :
"""From an SQLAlchemy ORM class , creates the database table via the specified
engine , using a ` ` CREATE TABLE ` ` SQL ( DDL ) statement .
Args :
engine : SQLAlchemy : class : ` En... | table = ormclass . __table__
# type : Table
log . info ( "Creating table {} on engine {}{}" , table . name , get_safe_url_from_engine ( engine ) , " (omitting constraints)" if without_constraints else "" )
# https : / / stackoverflow . com / questions / 19175311 / how - to - create - only - one - table - with - sqlalch... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'match' ) and self . match is not None :
_dict [ 'match' ] = self . match
return _dict |
def replace ( self , key , value ) :
"""Replaces the entry for a key only if it is currently mapped to some value .
This is equivalent to :
> > > if map . contains _ key ( key ) :
> > > return map . put ( key , value )
> > > else :
> > > return None
except that the action is performed atomically .
* *... | check_not_none ( key , "key can't be None" )
check_not_none ( value , "value can't be None" )
key_data = self . _to_data ( key )
value_data = self . _to_data ( value )
return self . _replace_internal ( key_data , value_data ) |
def _get_corresponding_parsers ( self , func ) :
"""Get the parser that has been set up by the given ` function `""" | if func in self . _used_functions :
yield self
if self . _subparsers_action is not None :
for parser in self . _subparsers_action . choices . values ( ) :
for sp in parser . _get_corresponding_parsers ( func ) :
yield sp |
def method_name ( func ) :
"""Method wrapper that adds the name of the method being called to its arguments list in Pascal case""" | @ wraps ( func )
def _method_name ( * args , ** kwargs ) :
name = to_pascal_case ( func . __name__ )
return func ( name = name , * args , ** kwargs )
return _method_name |
def Move_to ( self , x , y , dl = 0 ) :
"""鼠标移动到x , y的坐标处""" | self . Delay ( dl )
self . mouse . move ( x , y ) |
def augmentation_transform ( self , data , label ) : # pylint : disable = arguments - differ
"""Override Transforms input data with specified augmentations .""" | for aug in self . auglist :
data , label = aug ( data , label )
return ( data , label ) |
def mass_3d ( self , R , Rs , rho0 , r_trunc ) :
"""mass enclosed a 3d sphere or radius r
: param r :
: param Ra :
: param Rs :
: return :""" | x = R * Rs ** - 1
func = ( r_trunc ** 2 * ( - 2 * x * ( 1 + r_trunc ** 2 ) + 4 * ( 1 + x ) * r_trunc * np . arctan ( x / r_trunc ) - 2 * ( 1 + x ) * ( - 1 + r_trunc ** 2 ) * np . log ( Rs ) + 2 * ( 1 + x ) * ( - 1 + r_trunc ** 2 ) * np . log ( Rs * ( 1 + x ) ) + 2 * ( 1 + x ) * ( - 1 + r_trunc ** 2 ) * np . log ( Rs * ... |
def hostname ( self , hostname ) :
"""hostname setter""" | if not isinstance ( hostname , six . string_types ) :
raise TypeError ( "hostname must be a string. {0} was passed." . format ( type ( hostname ) ) )
# if a host name is passed and its not valid raise else set hostname empty strings are the docker default .
if hostname and not is_valid_hostname ( hostname ) :
... |
def switch_inline ( text , query = '' , same_peer = False ) :
"""Creates a new button to switch to inline query .
If ` query ` is given , it will be the default text to be used
when making the inline query .
If ` ` same _ peer is True ` ` the inline query will directly be
set under the currently opened chat... | return types . KeyboardButtonSwitchInline ( text , query , same_peer ) |
def load_network_from_checkpoint ( checkpoint , model_json , input_shape = None ) :
"""Function to read the weights from checkpoint based on json description .
Args :
checkpoint : tensorflow checkpoint with trained model to
verify
model _ json : path of json file with model description of
the network list... | # Load checkpoint
reader = tf . train . load_checkpoint ( checkpoint )
variable_map = reader . get_variable_to_shape_map ( )
checkpoint_variable_names = variable_map . keys ( )
# Parse JSON file for names
with tf . gfile . Open ( model_json ) as f :
list_model_var = json . load ( f )
net_layer_types = [ ]
net_weigh... |
def binary_to_spin ( linear , quadratic , offset ) :
"""convert linear , quadratic and offset from binary to spin .
Does no checking of vartype . Copies all of the values into new objects .""" | h = { }
J = { }
linear_offset = 0.0
quadratic_offset = 0.0
for u , bias in iteritems ( linear ) :
h [ u ] = .5 * bias
linear_offset += bias
for ( u , v ) , bias in iteritems ( quadratic ) :
J [ ( u , v ) ] = .25 * bias
h [ u ] += .25 * bias
h [ v ] += .25 * bias
quadratic_offset += bias
offset +... |
def _extract_image_urls ( self ) :
"""Retrieves image URLs from the current page""" | resultsPage = self . _chromeDriver . page_source
resultsPageSoup = BeautifulSoup ( resultsPage , 'html.parser' )
images = resultsPageSoup . find_all ( 'div' , class_ = 'rg_meta' )
images = [ json . loads ( image . contents [ 0 ] ) for image in images ]
[ self . _imageURLs . append ( image [ 'ou' ] ) for image in images... |
def is_carrying_minerals ( self ) -> bool :
"""Checks if a worker or MULE is carrying ( gold - ) minerals .""" | return any ( buff . value in self . _proto . buff_ids for buff in { BuffId . CARRYMINERALFIELDMINERALS , BuffId . CARRYHIGHYIELDMINERALFIELDMINERALS } ) |
def renew_session ( self ) :
"""Clears all session data and starts a new session using the same settings as before .
This method can be used to clear session data , e . g . , cookies . Future requests will use a new session initiated
with the same settings and authentication method .""" | logger . debug ( "API session renewed" )
self . session = self . authentication . get_session ( )
self . session . headers . update ( { 'User-Agent' : 'MoneyBird for Python %s' % VERSION , 'Accept' : 'application/json' , } ) |
def unlock ( self ) :
"""Unlock the doors and extend handles where applicable .""" | if self . __lock_state :
data = self . _controller . command ( self . _id , 'door_unlock' , wake_if_asleep = True )
if data [ 'response' ] [ 'result' ] :
self . __lock_state = False
self . __manual_update_time = time . time ( ) |
def update_health_monitor ( self , health_monitor , body = None ) :
"""Updates a load balancer health monitor .""" | return self . put ( self . health_monitor_path % ( health_monitor ) , body = body ) |
def choose_args ( metadata , config ) :
"""Choose database connection arguments .""" | return dict ( connect_args = choose_connect_args ( metadata , config ) , echo = config . echo , max_overflow = config . max_overflow , pool_size = config . pool_size , pool_timeout = config . pool_timeout , ) |
def _explore ( self , pop ) :
"""Exploration phase : Find a set of candidate states based on
the current population .
: param pop : The starting population for this generation .""" | new_pop = set ( pop )
exploration_per_state = self . args . max_exploration // len ( pop )
mutations = [ ]
if self . args . brokers :
mutations . append ( self . _move_partition )
if self . args . leaders :
mutations . append ( self . _move_leadership )
for state in pop :
for _ in range ( exploration_per_st... |
def get_relationships_for_idents ( self , cid , idents ) :
'''Get relationships between ` ` idents ` ` and a ` ` cid ` ` .
Returns a dictionary mapping the identifiers in ` ` idents ` `
to either None , if no relationship label is found between
the identifier and ` ` cid ` ` , or a RelationshipType classifyin... | keys = [ ( cid , ident , ) for ident in idents ]
key_ranges = zip ( keys , keys )
mapping = { }
for k , v in self . kvl . scan ( self . TABLE , * key_ranges ) :
label = self . _label_from_kvlayer ( k , v )
ident = label . other ( cid )
rel_strength = label . rel_strength
mapping [ ident ] = label . rel_... |
def serial_wire_viewer ( jlink_serial , device ) :
"""Implements a Serial Wire Viewer ( SWV ) .
A Serial Wire Viewer ( SWV ) allows us implement real - time logging of output
from a connected device over Serial Wire Output ( SWO ) .
Args :
jlink _ serial ( str ) : the J - Link serial number
device ( str )... | buf = StringIO . StringIO ( )
jlink = pylink . JLink ( log = buf . write , detailed_log = buf . write )
jlink . open ( serial_no = jlink_serial )
# Use Serial Wire Debug as the target interface . Need this in order to use
# Serial Wire Output .
jlink . set_tif ( pylink . enums . JLinkInterfaces . SWD )
jlink . connect ... |
def _initBlockMajorMap ( self ) :
"""Parses / proc / devices to initialize device class - major number map
for block devices .""" | self . _mapMajorDevclass = { }
try :
fp = open ( devicesFile , 'r' )
data = fp . read ( )
fp . close ( )
except :
raise IOError ( 'Failed reading device information from file: %s' % devicesFile )
skip = True
for line in data . splitlines ( ) :
if skip :
if re . match ( 'block.*:' , line , re... |
def _do_get ( cnf , get_path ) :
""": param cnf : Configuration object to print out
: param get _ path : key path given in - - get option
: return : updated Configuration object if no error""" | ( cnf , err ) = API . get ( cnf , get_path )
if cnf is None : # Failed to get the result .
_exit_with_output ( "Failed to get result: err=%s" % err , 1 )
return cnf |
def create_slab_label ( self ) :
"""Returns a label ( str ) for this particular slab based
on composition , coverage and Miller index .""" | if "label" in self . data . keys ( ) :
return self . data [ "label" ]
label = str ( self . miller_index )
ads_strs = list ( self . ads_entries_dict . keys ( ) )
cleaned = self . cleaned_up_slab
label += " %s" % ( cleaned . composition . reduced_composition )
if self . adsorbates :
for ads in ads_strs :
... |
def features ( self ) :
"""lazy fetch and cache features""" | if self . _features is None :
metadata = self . metadata ( )
if "features" in metadata :
self . _features = metadata [ "features" ]
else :
self . _features = [ ]
return self . _features |
def unregister_handle_func ( self , _handle_func_name , topic ) :
"""注销handle _ func""" | handler_list = self . _handle_funcs . get ( topic , [ ] )
for i , h in enumerate ( handler_list ) :
if h is _handle_func_name or h . __name__ == _handle_func_name :
handler_list . pop ( i )
if self . _handle_funcs . get ( topic ) == [ ] :
self . _handle_funcs . pop ( topic ) |
def supports_version_type ( self , version_type ) :
"""Tests if the given version type is supported .
arg : version _ type ( osid . type . Type ) : a version Type
return : ( boolean ) - ` ` true ` ` if the type is supported , ` ` false ` `
otherwise
raise : IllegalState - syntax is not a ` ` VERSION ` `
r... | # Implemented from template for osid . Metadata . supports _ coordinate _ type
if self . _kwargs [ 'syntax' ] not in [ '``VERSION``' ] :
raise errors . IllegalState ( )
return version_type in self . get_version_types |
def free_parameters ( self ) :
"""Returns a dictionary of free parameters for this function
: return : dictionary of free parameters""" | free_parameters = collections . OrderedDict ( [ ( k , v ) for k , v in self . parameters . iteritems ( ) if v . free ] )
return free_parameters |
def phon ( self , cls = 'current' , previousdelimiter = "" , strict = False , correctionhandling = CorrectionHandling . CURRENT ) :
"""See : meth : ` AbstractElement . phon `""" | if cls == 'original' :
correctionhandling = CorrectionHandling . ORIGINAL
# backward compatibility
if correctionhandling in ( CorrectionHandling . CURRENT , CorrectionHandling . EITHER ) :
for e in self :
if isinstance ( e , New ) or isinstance ( e , Current ) :
return previousdelimiter ... |
def switch_to_output ( self , value = False , ** kwargs ) :
"""Switch the pin state to a digital output with the provided starting
value ( True / False for high or low , default is False / low ) .""" | self . direction = digitalio . Direction . OUTPUT
self . value = value |
def _setTypecodeList ( self ) :
"""generates ofwhat content , minOccurs / maxOccurs facet generation .
Dependency instance attribute :
mgContent - - expected to be either a complex definition
with model group content , a model group , or model group
content . TODO : should only support the first two .
loc... | self . logger . debug ( "_setTypecodeList(%r): %s" % ( self . mgContent , self . _item . getItemTrace ( ) ) )
flat = [ ]
content = self . mgContent
# TODO : too much slop permitted here , impossible
# to tell what is going on .
if type ( content ) is not tuple :
mg = content
if not mg . isModelGroup ( ) :
... |
def get ( block_id ) :
"""Processing block detail resource .""" | _url = get_root_url ( )
try :
block = DB . get_block_details ( [ block_id ] ) . __next__ ( )
response = block
response [ 'links' ] = { 'self' : '{}' . format ( request . url ) , 'list' : '{}/processing-blocks' . format ( _url ) , 'home' : '{}' . format ( _url ) }
return block
except IndexError as error ... |
def scrub ( zpool , stop = False , pause = False ) :
'''Scrub a storage pool
zpool : string
Name of storage pool
stop : boolean
If ` ` True ` ` , cancel ongoing scrub
pause : boolean
If ` ` True ` ` , pause ongoing scrub
. . versionadded : : 2018.3.0
. . note : :
Pause is only available on recent ... | # # select correct action
if stop :
action = [ '-s' ]
elif pause :
action = [ '-p' ]
else :
action = None
# # Scrub storage pool
res = __salt__ [ 'cmd.run_all' ] ( __utils__ [ 'zfs.zpool_command' ] ( command = 'scrub' , flags = action , target = zpool , ) , python_shell = False , )
if res [ 'retcode' ] != 0... |
def get_service_packages ( self , ** kwargs ) : # noqa : E501
"""Get all service packages . # noqa : E501
Get information of all service packages for the currently authenticated commercial account . The response is returned in descending order by service package created timestamp , listing first the pending servi... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . get_service_packages_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . get_service_packages_with_http_info ( ** kwargs )
# noqa : E501
return data |
def next ( self ) :
"""Return the next row of a query result set , respecting if cursor was
closed .""" | if self . rows is None :
raise ProgrammingError ( "No result available. " + "execute() or executemany() must be called first." )
elif not self . _closed :
return next ( self . rows )
else :
raise ProgrammingError ( "Cursor closed" ) |
def convert_type ( self , value , spec ) :
"""Some well - educated format guessing .""" | data_type = spec . get ( 'type' , 'string' ) . lower ( ) . strip ( )
if data_type in [ 'bool' , 'boolean' ] :
return value . lower ( ) in BOOL_TRUISH
elif data_type in [ 'int' , 'integer' ] :
try :
return int ( value )
except ( ValueError , TypeError ) :
return None
elif data_type in [ 'floa... |
def validate ( self ) :
"""Validate the whole document""" | if not self . mustValidate :
return True
res = { }
for field in self . validators . keys ( ) :
try :
if isinstance ( self . validators [ field ] , dict ) and field not in self . store :
self . store [ field ] = DocumentStore ( self . collection , validators = self . validators [ field ] , in... |
def remove_in_progress_notifications ( self , master = True ) :
"""Remove all notifications from notifications _ in _ progress
Preserves some specific notifications ( downtime , . . . )
: param master : remove master notifications only if True ( default value )
: type master : bool
: param force : force rem... | for notification in list ( self . notifications_in_progress . values ( ) ) :
if master and notification . contact :
continue
# Do not remove some specific notifications
if notification . type in [ u'DOWNTIMESTART' , u'DOWNTIMEEND' , u'DOWNTIMECANCELLED' , u'CUSTOM' , u'ACKNOWLEDGEMENT' ] :
c... |
def handler ( self , data ) :
'''Function to handle notification data as part of Callback URL handler .
: param str data : data posted to Callback URL by connector .
: return : nothing''' | if isinstance ( data , r . models . Response ) :
self . log . debug ( "data is request object = %s" , str ( data . content ) )
data = data . content
elif isinstance ( data , str ) :
self . log . info ( "data is json string with len %d" , len ( data ) )
if len ( data ) == 0 :
self . log . warn (... |
def save_spectral_lines_ds9 ( rectwv_coeff , debugplot = 0 ) :
"""Save expected location of arc and OH airglow to ds9 region files .
Parameters
rectwv _ coeff : RectWaveCoeff instance
Rectification and wavelength calibration coefficients for the
particular CSU configuration .
debugplot : int
Debugging l... | for spectral_lines , rectified , suffix in zip ( [ 'arc' , 'arc' , 'oh' , 'oh' ] , [ False , True , False , True ] , [ 'rawimage' , 'rectified' , 'rawimage' , 'rectified' ] ) :
output = spectral_lines_to_ds9 ( rectwv_coeff = rectwv_coeff , spectral_lines = spectral_lines , rectified = rectified )
filename = 'ds... |
def _handleBulletWidth ( bulletText , style , maxWidths ) :
"""work out bullet width and adjust maxWidths [ 0 ] if neccessary""" | if bulletText :
if isinstance ( bulletText , basestring ) :
bulletWidth = stringWidth ( bulletText , style . bulletFontName , style . bulletFontSize )
else : # it ' s a list of fragments
bulletWidth = 0
for f in bulletText :
bulletWidth = bulletWidth + stringWidth ( f . text ... |
def register_rp_hook ( r , * args , ** kwargs ) :
"""This is a requests hook to register RP automatically .
You should not use this command manually , this is added automatically
by the SDK .
See requests documentation for details of the signature of this function .
http : / / docs . python - requests . org... | if r . status_code == 409 and 'msrest' in kwargs :
rp_name = _check_rp_not_registered_err ( r )
if rp_name :
session = kwargs [ 'msrest' ] [ 'session' ]
url_prefix = _extract_subscription_url ( r . request . url )
if not _register_rp ( session , url_prefix , rp_name ) :
retur... |
def get_process_mapping ( ) :
"""Try to look up the process tree via Linux ' s / proc""" | with open ( '/proc/{0}/stat' . format ( os . getpid ( ) ) ) as f :
self_tty = f . read ( ) . split ( ) [ STAT_TTY ]
processes = { }
for pid in os . listdir ( '/proc' ) :
if not pid . isdigit ( ) :
continue
try :
stat = '/proc/{0}/stat' . format ( pid )
cmdline = '/proc/{0}/cmdline' .... |
def filter_by ( self , ** kwargs ) :
"""Apply the given filtering criterion to a copy of this Query , using
keyword expressions .""" | query = self . _copy ( )
for field , value in kwargs . items ( ) :
query . domain . append ( ( field , '=' , value ) )
return query |
def dict_values ( src ) :
"""Recursively get values in dict .
Unlike the builtin dict . values ( ) function , this method will descend into
nested dicts , returning all nested values .
Arguments :
src ( dict ) : Source dict .
Returns :
list : List of values .""" | for v in src . values ( ) :
if isinstance ( v , dict ) :
for v in dict_values ( v ) :
yield v
else :
yield v |
def flightmode_colours ( ) :
'''return mapping of flight mode to colours''' | from MAVProxy . modules . lib . grapher import flightmode_colours
mapping = { }
idx = 0
for ( mode , t0 , t1 ) in flightmodes :
if not mode in mapping :
mapping [ mode ] = flightmode_colours [ idx ]
idx += 1
if idx >= len ( flightmode_colours ) :
idx = 0
return mapping |
def var ( ctx , clear_target , clear_all ) :
"""Install variable data to / var / [ lib , cache ] / hfos""" | install_var ( str ( ctx . obj [ 'instance' ] ) , clear_target , clear_all ) |
def H_iso ( x , params ) :
"""Isochrone Hamiltonian = - GM / ( b + sqrt ( b * * 2 + ( r - r0 ) * * 2 ) )""" | # r = ( np . sqrt ( np . sum ( x [ : 3 ] * * 2 ) ) - params [ 2 ] ) * * 2
r = np . sum ( x [ : 3 ] ** 2 )
return 0.5 * np . sum ( x [ 3 : ] ** 2 ) - Grav * params [ 0 ] / ( params [ 1 ] + np . sqrt ( params [ 1 ] ** 2 + r ) ) |
def delete_api_service ( self , name , ** kwargs ) :
"""delete an APIService
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . delete _ api _ service ( name , async _ req = True )
> > > result = thread . get (... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . delete_api_service_with_http_info ( name , ** kwargs )
else :
( data ) = self . delete_api_service_with_http_info ( name , ** kwargs )
return data |
def scope_choices ( self , exclude_internal = True ) :
"""Return list of scope choices .
: param exclude _ internal : Exclude internal scopes or not .
( Default : ` ` True ` ` )
: returns : A list of tuples ( id , scope ) .""" | return [ ( k , scope ) for k , scope in sorted ( self . scopes . items ( ) ) if not exclude_internal or not scope . is_internal ] |
def parse_env_zones ( self ) :
'''returns a list of comma separated zones parsed from the GCE _ ZONE environment variable .
If provided , this will be used to filter the results of the grouped _ instances call''' | import csv
reader = csv . reader ( [ os . environ . get ( 'GCE_ZONE' , "" ) ] , skipinitialspace = True )
zones = [ r for r in reader ]
return [ z for z in zones [ 0 ] ] |
def config ( * args , ** attrs ) :
"""Override configuration""" | attrs . setdefault ( "metavar" , "KEY=VALUE" )
attrs . setdefault ( "multiple" , True )
return option ( config , * args , ** attrs ) |
def _save_rest_method ( self , method_name , api_name , version , method ) :
"""Store Rest api methods in a list for lookup at call time .
The list is self . _ rest _ methods , a list of tuples :
[ ( < compiled _ path > , < path _ pattern > , < method _ dict > ) , . . . ]
where :
< compiled _ path > is a co... | path_pattern = '/' . join ( ( api_name , version , method . get ( 'path' , '' ) ) )
http_method = method . get ( 'httpMethod' , '' ) . lower ( )
for _ , path , methods in self . _rest_methods :
if path == path_pattern :
methods [ http_method ] = method_name , method
break
else :
self . _rest_met... |
def ensure_outdir_exists ( filepath ) :
"""Make dir to dump ' filepath ' if that dir does not exist .
: param filepath : path of file to dump""" | outdir = os . path . dirname ( filepath )
if outdir and not os . path . exists ( outdir ) :
LOGGER . debug ( "Making output dir: %s" , outdir )
os . makedirs ( outdir ) |
def GetPackages ( classification , visibility ) :
"""Gets a list of Blueprint Packages filtered by classification and visibility .
https : / / t3n . zendesk . com / entries / 20411357 - Get - Packages
: param classification : package type filter ( System , Script , Software )
: param visibility : package visi... | r = clc . v1 . API . Call ( 'post' , 'Blueprint/GetPackages' , { 'Classification' : Blueprint . classification_stoi [ classification ] , 'Visibility' : Blueprint . visibility_stoi [ visibility ] } )
if int ( r [ 'StatusCode' ] ) == 0 :
return ( r [ 'Packages' ] ) |
def _subArrayShape ( self ) :
"""Returns the shape of the sub - array .
An empty tuple is returned for regular fields , which have no sub array .""" | fieldName = self . nodeName
fieldDtype = self . _array . dtype . fields [ fieldName ] [ 0 ]
return fieldDtype . shape |
def get_clamav_conf ( filename ) :
"""Initialize clamav configuration .""" | if os . path . isfile ( filename ) :
return ClamavConfig ( filename )
log . warn ( LOG_PLUGIN , "No ClamAV config file found at %r." , filename ) |
def get_namedtuple_factory ( cls , field_mappings , name = "Record" ) :
"""Gets a method that will convert a dictionary to a namedtuple , as defined by
get _ namedtuple ( field _ mappings ) .""" | ntup = cls . get_namedtuple ( field_mappings , name )
return lambda data : ntup ( ** data ) |
def fold_all ( self ) :
"""Folds / unfolds all levels in the editor""" | line_count = self . GetLineCount ( )
expanding = True
# find out if we are folding or unfolding
for line_num in range ( line_count ) :
if self . GetFoldLevel ( line_num ) & stc . STC_FOLDLEVELHEADERFLAG :
expanding = not self . GetFoldExpanded ( line_num )
break
line_num = 0
while line_num < line_co... |
def solve_filter ( expr , vars ) :
"""Filter values on the LHS by evaluating RHS with each value .
Returns any LHS values for which RHS evaluates to a true value .""" | lhs_values , _ = __solve_for_repeated ( expr . lhs , vars )
def lazy_filter ( ) :
for lhs_value in repeated . getvalues ( lhs_values ) :
if solve ( expr . rhs , __nest_scope ( expr . lhs , vars , lhs_value ) ) . value :
yield lhs_value
return Result ( repeated . lazy ( lazy_filter ) , ( ) ) |
def getReffs ( self , level : int = 1 , subreference : CtsReference = None ) -> CtsReferenceSet :
"""CtsReference available at a given level
: param level : Depth required . If not set , should retrieve first encountered level ( 1 based )
: param subreference : Subreference ( optional )
: returns : List of le... | if not subreference and hasattr ( self , "reference" ) :
subreference = self . reference
elif subreference and not isinstance ( subreference , CtsReference ) :
subreference = CtsReference ( subreference )
return self . getValidReff ( level = level , reference = subreference ) |
def _build_native_function_call ( fn ) :
"""If fn can be interpreted and handled as a native function : i . e .
fn is one of the extensions , or fn is a simple lambda closure using one of
the extensions .
fn = tc . extensions . add
fn = lambda x : tc . extensions . add ( 5)
Then , this returns a closure o... | # See if fn is the native function itself
native_function_name = _get_toolkit_function_name_from_function ( fn )
if native_function_name != "" : # yup !
# generate an " identity " argument list
argnames = _get_argument_list_from_toolkit_function_name ( native_function_name )
arglist = [ [ 0 , i ] for i in range... |
def list_namespaced_secret ( self , namespace , ** kwargs ) :
"""list or watch objects of kind Secret
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . list _ namespaced _ secret ( namespace , async _ req = True... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . list_namespaced_secret_with_http_info ( namespace , ** kwargs )
else :
( data ) = self . list_namespaced_secret_with_http_info ( namespace , ** kwargs )
return data |
def keep_recent_datasets ( max_dataset_history , info = None ) :
"""Keep track of the most recent recordings .
Parameters
max _ dataset _ history : int
maximum number of datasets to remember
info : str , optional TODO
path to file
Returns
list of str
paths to most recent datasets ( only if you don '... | history = settings . value ( 'recent_recordings' , [ ] )
if isinstance ( history , str ) :
history = [ history ]
if info is not None and info . filename is not None :
new_dataset = info . filename
if new_dataset in history :
lg . debug ( new_dataset + ' already present, will be replaced' )
h... |
def _execute ( self , stmt , * values ) :
"""Gets a cursor , executes ` stmt ` and closes the cursor ,
fetching one row afterwards and returning its result .""" | c = self . _cursor ( )
try :
return c . execute ( stmt , values ) . fetchone ( )
finally :
c . close ( ) |
def call_proxy ( self , engine , payload , method , analyze_json_error_param , retry_request_substr_variants , stream = False ) :
""": param engine : Система
: param payload : Данные для запроса
: param method : string Может содержать native _ call | tsv | json _ newline
: param analyze _ json _ error _ param... | return self . __api_proxy_call ( engine , payload , method , analyze_json_error_param , retry_request_substr_variants , stream ) |
def AddArguments ( cls , argument_group ) :
"""Adds command line arguments to an argument group .
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports .
Args :
argument _ group ( argparse . _ ArgumentGroup | argparse . Argument... | argument_group . add_argument ( '--analysis' , metavar = 'PLUGIN_LIST' , dest = 'analysis_plugins' , default = '' , action = 'store' , type = str , help = ( 'A comma separated list of analysis plugin names to be loaded ' 'or "--analysis list" to see a list of available plugins.' ) )
arguments = sys . argv [ 1 : ]
argum... |
def get_service_details ( self , service_id ) :
"""Get the details of an individual service and return a ServiceDetails
instance .
Positional arguments :
service _ id : A Darwin LDB service id""" | service_query = self . _soap_client . service [ 'LDBServiceSoap' ] [ 'GetServiceDetails' ]
try :
soap_response = service_query ( serviceID = service_id )
except WebFault :
raise WebServiceError
return ServiceDetails ( soap_response ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.